@appling/codegen-go 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +5 -0
- package/out/access.js +9 -43
- package/out/index.d.ts +1 -1
- package/out/index.js +129 -217
- package/package.json +7 -6
- package/templates/access/access.go.njk +142 -0
- package/templates/access/check.go.njk +6 -0
- package/templates/access/entity-checks.go.njk +18 -0
- package/templates/access/policy.go.njk +5 -0
- package/templates/application/query.go.njk +9 -0
- package/templates/behavior/action.go.njk +35 -0
- package/templates/behavior/effects/create.go.njk +20 -0
- package/templates/behavior/effects/emit.go.njk +2 -0
- package/templates/behavior/effects/for.go.njk +6 -0
- package/templates/behavior/effects/record.go.njk +20 -0
- package/templates/behavior/effects/set.go.njk +2 -0
- package/templates/behavior/invalid-transition.go.njk +3 -0
- package/templates/behavior/machine.go.njk +13 -0
- package/templates/behavior/transitions.go.njk +13 -0
- package/templates/domain/doc.go.njk +2 -0
- package/templates/domain/entity.go.njk +62 -0
- package/templates/domain/enum.go.njk +13 -0
- package/templates/domain/error.go.njk +3 -0
- package/templates/domain/struct.go.njk +13 -0
- package/templates/go/macros.njk +7 -0
- package/templates/go/ptr.go.njk +3 -0
- package/templates/tests/invariant.go.njk +24 -0
- package/templates/tests/policy.go.njk +19 -0
- package/templates/tests/scenario.go.njk +65 -0
- package/templates/tests/skipped.go.njk +4 -0
- package/templates/tests/transition.go.njk +27 -0
- package/templates/tests/valid-record.go.njk +10 -0
package/out/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { aboutOf } from '@appling/codegen';
|
|
1
3
|
import { coveredByScenarios, scenarioCall, Simulator, throughPath, UNKNOWN } from '@appling/model';
|
|
2
4
|
import { accessFile, accessOf, accessSteps, actorFields, actorFieldType, tenantOf, tenantPaths } from './access.js';
|
|
3
5
|
import { camel, enumConstant, goExpr, goTerm, pascal, PRIMITIVES, qualify } from './golang.js';
|
|
@@ -5,6 +7,7 @@ const DECIMAL = 'github.com/shopspring/decimal';
|
|
|
5
7
|
const OPERATIONS = ['read', 'create', 'update', 'delete'];
|
|
6
8
|
const extension = {
|
|
7
9
|
name: '@appling/codegen-go',
|
|
10
|
+
templates: fileURLToPath(new URL('../templates', import.meta.url)),
|
|
8
11
|
test: ['go', 'test', './...'],
|
|
9
12
|
syncExclude: ['go.sum'],
|
|
10
13
|
prerequisites: [{ name: 'Go', command: ['go', 'version'], expect: /go1\.(2[2-9]|[3-9]\d)/, hint: 'install Go 1.22 or later' }],
|
|
@@ -16,14 +19,14 @@ const extension = {
|
|
|
16
19
|
steps(node, context) {
|
|
17
20
|
switch (node.kind) {
|
|
18
21
|
case 'Module': return [
|
|
19
|
-
goFile(node.qn, 'doc.go', context, new Set(),
|
|
20
|
-
goFile(node.qn, 'support.go', context, new Set(), '
|
|
22
|
+
goFile(node.qn, 'doc.go', context, new Set(), context.render('domain/doc.go.njk', { pkg: pkgOf(node.qn), qn: node.qn })),
|
|
23
|
+
goFile(node.qn, 'support.go', context, new Set(), context.render('go/ptr.go.njk', {}))
|
|
21
24
|
];
|
|
22
25
|
case 'Enum': return [enumSteps(node, context)];
|
|
23
26
|
case 'ValueType': return [structStep(node, context, 'types.go')];
|
|
24
27
|
case 'Entity': return entitySteps(node, context);
|
|
25
28
|
case 'Event': return [structStep(node, context, 'events.go')];
|
|
26
|
-
case 'ErrorDecl': return [goFile(node.module, 'errors.go', context, new Set(['errors']),
|
|
29
|
+
case 'ErrorDecl': return [goFile(node.module, 'errors.go', context, new Set(['errors']), context.render('domain/error.go.njk', { name: errorName(node), qn: node.qn, label: last(node.qn) }))];
|
|
27
30
|
case 'Field': return fieldSteps(node, context);
|
|
28
31
|
case 'Invariant': return [...(validation(node, context) ? [] : [task(`check the invariant "${node.data.label}" in Validate: ${node.props.condition}`)]), ...invariantTestSteps(node, context)];
|
|
29
32
|
case 'Policy': return [...policySteps(node, context), ...policyTestSteps(node, context)];
|
|
@@ -66,51 +69,48 @@ const extension = {
|
|
|
66
69
|
};
|
|
67
70
|
export default extension;
|
|
68
71
|
function enumSteps(node, context) {
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
return goFile(node.module, 'types.go', context, new Set(), `// ${name} is the enum ${node.qn}.\ntype ${name} string\n\nconst (\n${values.join('\n')}\n)`);
|
|
72
|
+
const literals = context.children(node.qn).map(l => ({ constant: pascal(last(l.qn)), value: last(l.qn) }));
|
|
73
|
+
return goFile(node.module, 'types.go', context, new Set(), context.render('domain/enum.go.njk', { name: last(node.qn), qn: node.qn, about: about(node), literals }));
|
|
72
74
|
}
|
|
73
75
|
function structStep(node, context, file) {
|
|
74
76
|
const imports = new Set();
|
|
75
77
|
const scope = goScope(node, context, imports);
|
|
76
|
-
const fields = fieldsOf(node, context).filter(f => !f.data.derived)
|
|
77
|
-
return goFile(node.module, file, context, imports,
|
|
78
|
+
const fields = structFields(fieldsOf(node, context).filter(f => !f.data.derived), scope);
|
|
79
|
+
return goFile(node.module, file, context, imports, context.render('domain/struct.go.njk', { name: last(node.qn), what: node.kind === 'Event' ? 'event' : 'value type', qn: node.qn, about: about(node), fields }));
|
|
80
|
+
}
|
|
81
|
+
function structFields(fields, scope) {
|
|
82
|
+
return fields.map(f => ({ name: pascal(last(f.qn)), type: typeOf(f.data.type, scope), json: last(f.qn) }));
|
|
78
83
|
}
|
|
79
84
|
/** An entity becomes a struct with an ID, a constructor with the defaults, methods for derived fields, and Validate for the invariants. */
|
|
80
85
|
function entitySteps(entity, context) {
|
|
81
86
|
return [entityStep(entity, context), ...guardSteps(entity, context)];
|
|
82
87
|
}
|
|
83
88
|
function entityStep(entity, context) {
|
|
84
|
-
const imports = new Set();
|
|
89
|
+
const imports = new Set(['errors']);
|
|
85
90
|
const name = last(entity.qn);
|
|
86
91
|
const receiver = name.charAt(0).toLowerCase();
|
|
87
92
|
const scope = goScope(entity, context, imports);
|
|
88
93
|
const fields = fieldsOf(entity, context);
|
|
89
94
|
const stored = fields.filter(f => !f.data.derived);
|
|
90
|
-
const lines = [`// ${name} is the entity ${entity.qn}.`, `type ${name} struct {`, '\tID int64 `json:"id"`', ...stored.map(f => `\t${pascal(last(f.qn))} ${typeOf(f.data.type, scope)} \`json:"${last(f.qn)}"\``), '}'];
|
|
91
95
|
const defaults = stored.flatMap(f => {
|
|
92
96
|
const code = defaultValue(f, scope);
|
|
93
|
-
return code ? [
|
|
97
|
+
return code ? [{ name: pascal(last(f.qn)), value: code }] : [];
|
|
94
98
|
});
|
|
95
|
-
|
|
96
|
-
for (const field of fields.filter(f => f.data.derived)) {
|
|
99
|
+
const derived = fields.filter(f => f.data.derived).flatMap(field => {
|
|
97
100
|
const code = goExpr(field.data.derived, { ...scope, self: receiver });
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
101
|
+
return code ? [{ name: pascal(last(field.qn)), qn: field.qn, type: typeOf(field.data.type, scope), code: coerce(code, field) }] : [];
|
|
102
|
+
});
|
|
101
103
|
const checks = context.children(entity.qn).filter(n => n.kind === 'Invariant').flatMap(invariant => {
|
|
102
104
|
const condition = validation(invariant, context);
|
|
103
|
-
return condition ? [
|
|
105
|
+
return condition ? [{ condition, label: String(invariant.data.label) }] : [];
|
|
104
106
|
});
|
|
105
|
-
imports.add('errors');
|
|
106
|
-
lines.push('', `// Validate checks the invariants of ${name}.`, `func (${receiver} *${name}) Validate() error {`, '\tvar errs []error', ...checks, '\treturn errors.Join(errs...)', '}');
|
|
107
107
|
const path = tenantPaths(context).get(entity.qn);
|
|
108
|
-
|
|
109
|
-
const tenant = tenantOf(context);
|
|
108
|
+
const tenant = path && (() => {
|
|
110
109
|
const hops = path.map((_, i) => [receiver, ...path.slice(0, i + 1).map(f => pascal(last(f.qn)))].join('.'));
|
|
111
|
-
|
|
112
|
-
}
|
|
113
|
-
|
|
110
|
+
return { entity: tenantOf(context).data.entity, qn: tenantOf(context).qn, hops, record: hops.at(-1) ?? receiver };
|
|
111
|
+
})();
|
|
112
|
+
const code = context.render('domain/entity.go.njk', { name, qn: entity.qn, about: about(entity), receiver, fields: structFields(stored, scope), defaults, derived, checks, tenant });
|
|
113
|
+
return goFile(entity.module, 'types.go', context, imports, code);
|
|
114
114
|
}
|
|
115
115
|
function fieldSteps(field, context) {
|
|
116
116
|
const owner = context.node(parentOf(field.qn));
|
|
@@ -148,30 +148,26 @@ function actionCode(action, context) {
|
|
|
148
148
|
const self = entity ? camel(last(entity.qn)) : undefined;
|
|
149
149
|
const scope = { ...goScope(action, context, imports), self };
|
|
150
150
|
const tasks = [];
|
|
151
|
-
const body = ['var events []any'];
|
|
152
151
|
const guard = guardOf(action, context);
|
|
153
|
-
if (guard)
|
|
152
|
+
if (guard)
|
|
154
153
|
imports.add('fmt');
|
|
155
|
-
|
|
156
|
-
}
|
|
157
|
-
(action.data.preconditions ?? []).forEach((precondition, i) => {
|
|
154
|
+
const preconditions = (action.data.preconditions ?? []).flatMap((precondition, i) => {
|
|
158
155
|
const condition = goExpr(precondition.condition, scope);
|
|
159
156
|
const text = action.props.preconditions[i];
|
|
160
157
|
if (!condition) {
|
|
161
158
|
tasks.push(task(`check the precondition ${text} in ${last(action.qn)}`));
|
|
162
|
-
return;
|
|
159
|
+
return [];
|
|
163
160
|
}
|
|
164
|
-
const error = precondition.error ? errorName(context.node(precondition.error)) : `errors.New(${JSON.stringify(text)})`;
|
|
165
161
|
if (!precondition.error)
|
|
166
162
|
imports.add('errors');
|
|
167
|
-
|
|
163
|
+
return [{ condition, text, error: precondition.error && errorName(context.node(precondition.error)) }];
|
|
168
164
|
});
|
|
169
165
|
const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
|
|
170
166
|
const creating = storing(action);
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
167
|
+
const body = [
|
|
168
|
+
...(transitions.length && self ? transitionSwitch(transitions, self, last(action.qn), scope, context, tasks, creating) : []),
|
|
169
|
+
...effectBlock(action, self, scope, context, tasks, creating)
|
|
170
|
+
];
|
|
175
171
|
const takesActor = !!guard || enforced(context);
|
|
176
172
|
const params = [
|
|
177
173
|
...(takesActor ? [`actor ${accessIn(scope, 'Actor')}`] : []),
|
|
@@ -179,8 +175,11 @@ function actionCode(action, context) {
|
|
|
179
175
|
...context.children(action.qn).filter(c => c.kind === 'Param').map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`),
|
|
180
176
|
...stores(creating).map(([name, e]) => `${name} func(${typeOf({ $type: 'TypeRef', decl: e.qn }, scope)}) error`)
|
|
181
177
|
];
|
|
182
|
-
const
|
|
183
|
-
|
|
178
|
+
const code = context.render('behavior/action.go.njk', {
|
|
179
|
+
name: last(action.qn), qn: action.qn, about: about(action), params, stores: stores(creating).length > 0, preconditions, body,
|
|
180
|
+
guard: guard && `${guard.name}(${['actor', ...guard.args].join(', ')})`,
|
|
181
|
+
forbidden: guard && accessIn(scope, 'ErrForbidden')
|
|
182
|
+
});
|
|
184
183
|
return { step: goFile(action.module, 'actions.go', context, imports, code), tasks, takesActor, creates: stores(creating).map(([, e]) => e) };
|
|
185
184
|
}
|
|
186
185
|
/**
|
|
@@ -201,13 +200,7 @@ function queryFilterSteps(query, context) {
|
|
|
201
200
|
`${self} ${typeOf({ $type: 'TypeRef', decl: entity.qn }, scope)}`,
|
|
202
201
|
...context.children(query.qn).filter(c => c.kind === 'Param').map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`)
|
|
203
202
|
];
|
|
204
|
-
|
|
205
|
-
`// In${last(query.qn)} reports whether a record is among the results of the query ${query.qn}${params.length > 1 ? ' for the inputs' : ''}.`,
|
|
206
|
-
`func In${last(query.qn)}(${params.join(', ')}) bool {`,
|
|
207
|
-
`\treturn ${condition}`,
|
|
208
|
-
'}'
|
|
209
|
-
].join('\n');
|
|
210
|
-
return [goFile(query.module, 'queries.go', context, imports, code)];
|
|
203
|
+
return [goFile(query.module, 'queries.go', context, imports, context.render('application/query.go.njk', { name: last(query.qn), qn: query.qn, about: about(query), params, condition }))];
|
|
211
204
|
}
|
|
212
205
|
/**
|
|
213
206
|
* The exported check of an element, when one applies. Once the model has any policy, every entity gets
|
|
@@ -265,25 +258,22 @@ function guardSteps(owner, context) {
|
|
|
265
258
|
const tenant = guard.entity && tenantPaths(context).has(guard.entity.qn) ? `${accessIn(scope, 'InTenant')}(actor, ${record})` : undefined;
|
|
266
259
|
const policies = policiesOf(owner, context);
|
|
267
260
|
const call = (policy) => `${policyName(policy, context)}(${args})`;
|
|
268
|
-
|
|
261
|
+
let code;
|
|
269
262
|
if (owner.kind === 'Entity') {
|
|
270
263
|
const name = last(owner.qn);
|
|
271
|
-
|
|
264
|
+
const operations = OPERATIONS.map(op => {
|
|
272
265
|
const covering = policies.filter(p => covers(p, op) && !p.data.fields?.length);
|
|
273
|
-
const parts = covering.length ? [...(tenant ? [tenant] : []), ...covering.map(call)] : ['false'];
|
|
274
|
-
blocks.push([
|
|
275
|
-
`// Can${pascal(op)}${name} reports whether the policies of ${owner.qn} let the actor ${op} the record${covering.length ? '' : `; no policy grants ${op}`}.`,
|
|
276
|
-
`func Can${pascal(op)}${name}(${signature}) bool {`, `\treturn ${parts.join(' && ')}`, '}'
|
|
277
|
-
].join('\n'));
|
|
278
266
|
const fields = [...new Set(policies.filter(p => covers(p, op)).flatMap(p => (p.data.fields ?? [])))];
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
267
|
+
return {
|
|
268
|
+
name: pascal(op), verb: op, granted: covering.length > 0,
|
|
269
|
+
parts: covering.length ? [...(tenant ? [tenant] : []), ...covering.map(call)] : ['false'],
|
|
270
|
+
fields: fields.map(field => ({
|
|
271
|
+
name: pascal(last(field)), field: last(field),
|
|
272
|
+
parts: [`Can${pascal(op)}${name}(${args})`, ...policies.filter(p => covers(p, op) && (p.data.fields ?? []).includes(field)).map(call)]
|
|
273
|
+
}))
|
|
274
|
+
};
|
|
275
|
+
});
|
|
276
|
+
code = context.render('access/entity-checks.go.njk', { entity: name, qn: owner.qn, signature, operations });
|
|
287
277
|
}
|
|
288
278
|
else {
|
|
289
279
|
const op = owner.kind === 'Query' ? 'Read' : 'Update';
|
|
@@ -291,14 +281,14 @@ function guardSteps(owner, context) {
|
|
|
291
281
|
const inherited = entity && owner.kind !== 'UseCase' && enforced(context)
|
|
292
282
|
? [`${entity.module === owner.module ? '' : `${qualifyModule(entity.module, scope)}.`}Can${op}${last(entity.qn)}(actor, ${record})`]
|
|
293
283
|
: tenant ? [tenant] : [];
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
284
|
+
code = context.render('access/check.go.njk', {
|
|
285
|
+
name: guard.name, signature, entity: entity?.qn,
|
|
286
|
+
what: owner.kind === 'Query' ? `read a record through ${owner.qn}` : `run ${owner.qn}`,
|
|
287
|
+
inherited: inherited.length ? (inherited[0] === tenant ? 'tenant' : op.toLowerCase()) : undefined,
|
|
288
|
+
parts: [...inherited, ...policies.map(call)]
|
|
289
|
+
});
|
|
300
290
|
}
|
|
301
|
-
return [goFile(owner.module, 'policies.go', context, imports,
|
|
291
|
+
return [goFile(owner.module, 'policies.go', context, imports, code), accessFile(context, accessOf(context))];
|
|
302
292
|
}
|
|
303
293
|
/** One function per policy, `<owner>Policy<Operations>`, with the arguments of its element's check; false with a task when Go cannot say the condition. */
|
|
304
294
|
function policySteps(policy, context) {
|
|
@@ -307,12 +297,7 @@ function policySteps(policy, context) {
|
|
|
307
297
|
const scope = { ...goScope(policy, context, imports), self: guard.entity && camel(last(guard.entity.qn)), actor: 'actor' };
|
|
308
298
|
const condition = goExpr(policy.data.condition, scope);
|
|
309
299
|
const name = policyName(policy, context);
|
|
310
|
-
const code =
|
|
311
|
-
`// ${name} is the policy ${policy.qn}: ${policy.props.condition}`,
|
|
312
|
-
`func ${name}(${guardSignature(guard, scope)}) bool {`,
|
|
313
|
-
`\treturn ${condition ?? 'false'}`,
|
|
314
|
-
'}'
|
|
315
|
-
].join('\n');
|
|
300
|
+
const code = context.render('access/policy.go.njk', { name, qn: policy.qn, text: policy.props.condition, signature: guardSignature(guard, scope), condition });
|
|
316
301
|
return [goFile(policy.module, 'policies.go', context, imports, code), ...(condition ? [] : [task(`implement the policy ${policy.qn} in ${name}: ${policy.props.condition}`)])];
|
|
317
302
|
}
|
|
318
303
|
function policyName(policy, context) {
|
|
@@ -339,8 +324,7 @@ function transitionSwitch(transitions, self, label, scope, context, tasks, creat
|
|
|
339
324
|
const field = context.node(machine.data.field);
|
|
340
325
|
const enumNode = context.node(field.data.type.decl);
|
|
341
326
|
const state = `${self}.${pascal(last(field.qn))}`;
|
|
342
|
-
const
|
|
343
|
-
for (const transition of transitions) {
|
|
327
|
+
const cases = transitions.map(transition => {
|
|
344
328
|
const from = transition.data.from.map(s => `${state} == ${enumConstant(context.node(`${enumNode.qn}.${s}`), scope)}`).join(' || ');
|
|
345
329
|
let condition = from;
|
|
346
330
|
if (transition.data.guard) {
|
|
@@ -350,15 +334,13 @@ function transitionSwitch(transitions, self, label, scope, context, tasks, creat
|
|
|
350
334
|
else
|
|
351
335
|
tasks.push(task(`check the guard ${transition.props.guard} of ${last(transition.qn)}`));
|
|
352
336
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
}
|
|
337
|
+
const effects = effectBlock(transition, self, scope, context, tasks, creating);
|
|
338
|
+
return { condition, effects, to: enumConstant(context.node(`${enumNode.qn}.${transition.data.to}`), scope) };
|
|
339
|
+
});
|
|
357
340
|
scope.imports.add('fmt');
|
|
358
341
|
scope.imports.add(scope.importOf(machine.module));
|
|
359
342
|
const invalid = machine.module.split('.').pop() === scope.pkg ? 'ErrInvalidTransition' : `${machine.module.split('.').pop()}.ErrInvalidTransition`;
|
|
360
|
-
|
|
361
|
-
return lines;
|
|
343
|
+
return context.render('behavior/transitions.go.njk', { cases, state, label, invalid }).split('\n');
|
|
362
344
|
}
|
|
363
345
|
function storing(action) {
|
|
364
346
|
return { action: last(action.qn), entities: new Map(), updates: new Map(), deletes: new Map() };
|
|
@@ -389,7 +371,7 @@ function effectLines(effect, self, scope, context, tasks, creating) {
|
|
|
389
371
|
}
|
|
390
372
|
const body = effectBlock(effect, self, { ...scope, vars: new Map([...(scope.vars ?? []), [variable, 'other']]) }, context, tasks, creating);
|
|
391
373
|
const used = body.some(l => new RegExp(`\\b${variable}\\b`).test(l));
|
|
392
|
-
return
|
|
374
|
+
return context.render('behavior/effects/for.go.njk', { used, variable, collection: `${self}.${pascal(last(effect.data.collection))}`, body }).split('\n');
|
|
393
375
|
}
|
|
394
376
|
if (effect.kind === 'UpdateEffect' || effect.kind === 'DeleteEffect')
|
|
395
377
|
return recordLines(effect, self, scope, context, tasks, creating);
|
|
@@ -400,7 +382,7 @@ function effectLines(effect, self, scope, context, tasks, creating) {
|
|
|
400
382
|
tasks.push(task(`apply the effect set ${last(field.qn)} = ${effect.props.value}`));
|
|
401
383
|
return [];
|
|
402
384
|
}
|
|
403
|
-
return [`${self}.${pascal(last(field.qn))}
|
|
385
|
+
return [context.render('behavior/effects/set.go.njk', { target: `${self}.${pascal(last(field.qn))}`, value })];
|
|
404
386
|
}
|
|
405
387
|
if (effect.kind === 'EmitEffect') {
|
|
406
388
|
const event = context.node(effect.data.event);
|
|
@@ -420,7 +402,7 @@ function effectLines(effect, self, scope, context, tasks, creating) {
|
|
|
420
402
|
tasks.push(task(`emit ${last(event.qn)} with its fields ${missing.join(', ')}, which the model does not give or Go cannot say`));
|
|
421
403
|
return [];
|
|
422
404
|
}
|
|
423
|
-
return [
|
|
405
|
+
return [context.render('behavior/effects/emit.go.njk', { event: qualify(event, scope), values })];
|
|
424
406
|
}
|
|
425
407
|
if (effect.kind === 'CreateEffect') {
|
|
426
408
|
const entity = context.node(effect.data.entity);
|
|
@@ -450,7 +432,7 @@ function recordLines(effect, self, scope, context, tasks, creating) {
|
|
|
450
432
|
const value = entity && assigned(field, throughPath(set.data.value, entity.qn, target), scope);
|
|
451
433
|
if (!value)
|
|
452
434
|
break;
|
|
453
|
-
sets.push(
|
|
435
|
+
sets.push({ name: pascal(last(field.qn)), value });
|
|
454
436
|
}
|
|
455
437
|
const complete = operation === 'delete' || sets.length === context.children(effect.qn).filter(c => c.kind === 'SetEffect').length;
|
|
456
438
|
if (!creating || !entity || !path || !complete) {
|
|
@@ -458,15 +440,13 @@ function recordLines(effect, self, scope, context, tasks, creating) {
|
|
|
458
440
|
return [];
|
|
459
441
|
}
|
|
460
442
|
(operation === 'update' ? creating.updates : creating.deletes).set(entity.qn, entity);
|
|
461
|
-
const check = enforced(context) ?
|
|
462
|
-
|
|
463
|
-
`\treturn nil, fmt.Errorf("%w: ${creating.action}", ${accessIn(scope, 'ErrForbidden')})`,
|
|
464
|
-
'}'
|
|
465
|
-
] : [];
|
|
466
|
-
if (check.length)
|
|
443
|
+
const check = enforced(context) ? `${entity.module === effect.module ? '' : `${qualifyModule(entity.module, scope)}.`}Can${pascal(operation)}${last(entity.qn)}(actor, ${path})` : undefined;
|
|
444
|
+
if (check)
|
|
467
445
|
scope.imports.add('fmt');
|
|
468
|
-
|
|
469
|
-
|
|
446
|
+
return context.render('behavior/effects/record.go.njk', {
|
|
447
|
+
optional: !!target?.type.endsWith('?'), path, check, action: creating.action, forbidden: check && accessIn(scope, 'ErrForbidden'),
|
|
448
|
+
sets, operation, entity: last(entity.qn)
|
|
449
|
+
}).split('\n');
|
|
470
450
|
}
|
|
471
451
|
/**
|
|
472
452
|
* A create effect in an action: a block that builds the record with `New<Entity>` and the given fields, checks
|
|
@@ -478,7 +458,7 @@ function createLines(effect, entity, scope, context, creating) {
|
|
|
478
458
|
// A named row stays a variable for the effects after it; an unnamed one lives in its own block.
|
|
479
459
|
const variable = effect.data.variable;
|
|
480
460
|
const record = variable ?? 'created';
|
|
481
|
-
const
|
|
461
|
+
const fields = [];
|
|
482
462
|
for (const field of fieldsOf(entity, context).filter(f => !f.data.derived)) {
|
|
483
463
|
const type = field.data.type;
|
|
484
464
|
const expr = given.get(last(field.qn));
|
|
@@ -490,20 +470,17 @@ function createLines(effect, entity, scope, context, creating) {
|
|
|
490
470
|
const value = assigned(field, expr, scope);
|
|
491
471
|
if (!value)
|
|
492
472
|
return undefined;
|
|
493
|
-
|
|
473
|
+
fields.push({ name: pascal(last(field.qn)), value });
|
|
494
474
|
}
|
|
495
475
|
const name = qualify(entity, scope);
|
|
496
476
|
const constructor = name.includes('.') ? name.replace(/\.(\w+)$/, '.New$1') : `New${name}`;
|
|
497
|
-
const check = enforced(context) ?
|
|
498
|
-
|
|
499
|
-
`\treturn nil, fmt.Errorf("%w: ${creating.action}", ${accessIn(scope, 'ErrForbidden')})`,
|
|
500
|
-
'}'
|
|
501
|
-
] : [];
|
|
502
|
-
if (check.length)
|
|
477
|
+
const check = enforced(context) ? `${entity.module === effect.module ? '' : `${qualifyModule(entity.module, scope)}.`}CanCreate${last(entity.qn)}(actor, ${record})` : undefined;
|
|
478
|
+
if (check)
|
|
503
479
|
scope.imports.add('fmt');
|
|
504
480
|
creating.entities.set(entity.qn, entity);
|
|
505
|
-
|
|
506
|
-
|
|
481
|
+
return context.render('behavior/effects/create.go.njk', {
|
|
482
|
+
variable, record, constructor, fields, check, action: creating.action, forbidden: check && accessIn(scope, 'ErrForbidden'), entity: last(entity.qn)
|
|
483
|
+
}).split('\n');
|
|
507
484
|
}
|
|
508
485
|
/** Whether an effect runs in an action, which takes the actor, rather than in a transition on an event. */
|
|
509
486
|
function runByActor(effect, context) {
|
|
@@ -538,7 +515,7 @@ function machineSteps(machine, context) {
|
|
|
538
515
|
const field = context.node(machine.data.field);
|
|
539
516
|
const entity = context.node(parentOf(field.qn));
|
|
540
517
|
const imports = new Set(['errors']);
|
|
541
|
-
const steps = [goFile(machine.module, 'errors.go', context, imports,
|
|
518
|
+
const steps = [goFile(machine.module, 'errors.go', context, imports, context.render('behavior/invalid-transition.go.njk', {}))];
|
|
542
519
|
const byEvent = Map.groupBy(context.children(machine.qn).filter(t => t.kind === 'Transition' && t.data.event), t => t.data.event);
|
|
543
520
|
for (const [eventQn, transitions] of byEvent) {
|
|
544
521
|
const event = context.node(eventQn);
|
|
@@ -550,16 +527,16 @@ function machineSteps(machine, context) {
|
|
|
550
527
|
const handlerImports = new Set();
|
|
551
528
|
const scope = { ...goScope(machine, context, handlerImports), self: `event.${pascal(last(carrier.qn))}` };
|
|
552
529
|
const tasks = [];
|
|
553
|
-
const
|
|
554
|
-
const
|
|
555
|
-
steps.push(goFile(machine.module, 'machines.go', context, handlerImports,
|
|
530
|
+
const lines = transitionSwitch(transitions, scope.self, last(eventQn), scope, context, tasks);
|
|
531
|
+
const code = context.render('behavior/machine.go.njk', { name: `${last(machine.qn)}On${last(eventQn)}`, machine: machine.qn, about: about(machine), event: last(eventQn), type: qualify(event, scope), transitions: lines });
|
|
532
|
+
steps.push(goFile(machine.module, 'machines.go', context, handlerImports, code), ...tasks);
|
|
556
533
|
}
|
|
557
534
|
return steps;
|
|
558
535
|
}
|
|
559
536
|
/** A skipped test per case of a rule in the module's test file; writing its body is a registry task. */
|
|
560
537
|
function testSteps(node, context) {
|
|
561
538
|
const name = testName(node);
|
|
562
|
-
const code =
|
|
539
|
+
const code = context.render('tests/skipped.go.njk', { name, qn: node.qn });
|
|
563
540
|
return [goFile(node.module, `${pkgOf(node.module)}_test.go`, context, new Set(['testing']), code), task(`write the test ${name}`)];
|
|
564
541
|
}
|
|
565
542
|
const POLICY_CASES = ['allows permitted actors', 'denies other actors'];
|
|
@@ -598,24 +575,12 @@ function policyTestSteps(policy, context) {
|
|
|
598
575
|
if (!allowed && !denied)
|
|
599
576
|
return testSteps(policy, context);
|
|
600
577
|
const name = testName(policy);
|
|
601
|
-
const
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
...found.operations.flatMap(op => {
|
|
608
|
-
const check = `Can${pascal(op)}${entityName}`;
|
|
609
|
-
return [
|
|
610
|
-
`\t\tif ${want ? '!' : ''}${check}(actor, ${record}) {`,
|
|
611
|
-
`\t\t\tt.Error(${JSON.stringify(`${check}: want ${want} for ${found.actor.qn}`)})`,
|
|
612
|
-
'\t\t}'
|
|
613
|
-
];
|
|
614
|
-
})
|
|
615
|
-
] : [`\t\tt.Skip(${JSON.stringify(`registry task: ${policy.qn}`)})`]),
|
|
616
|
-
'\t})'
|
|
617
|
-
];
|
|
618
|
-
const code = [`func ${name}(t *testing.T) {`, ...body(POLICY_CASES[0], allowed, true), ...body(POLICY_CASES[1], denied, false), '}'].join('\n');
|
|
578
|
+
const run = (label, found, want) => ({
|
|
579
|
+
label, want, qn: found?.actor.qn,
|
|
580
|
+
actor: found && accessIn(scope, `New${accessOf(context).name(found.actor.qn)}`),
|
|
581
|
+
checks: found?.operations.map(op => `Can${pascal(op)}${last(entity.qn)}`)
|
|
582
|
+
});
|
|
583
|
+
const code = context.render('tests/policy.go.njk', { name, qn: policy.qn, record, valid: valid.name, runs: [run(POLICY_CASES[0], allowed, true), run(POLICY_CASES[1], denied, false)] });
|
|
619
584
|
const missing = [allowed ? undefined : POLICY_CASES[0], denied ? undefined : POLICY_CASES[1]].filter(c => c !== undefined);
|
|
620
585
|
return [
|
|
621
586
|
valid.step,
|
|
@@ -665,29 +630,11 @@ function invariantTestSteps(invariant, context) {
|
|
|
665
630
|
const valid = validRecord(entity, context);
|
|
666
631
|
if (!valid)
|
|
667
632
|
return testSteps(invariant, context);
|
|
668
|
-
const label = JSON.stringify(String(invariant.data.label));
|
|
669
633
|
const violation = violating(invariant, entity, valid.record, context, scope);
|
|
670
634
|
if (violation)
|
|
671
635
|
imports.add('strings');
|
|
672
636
|
const name = testName(invariant);
|
|
673
|
-
const code =
|
|
674
|
-
`func ${name}(t *testing.T) {`,
|
|
675
|
-
'\tt.Run("holds for a valid record", func(t *testing.T) {',
|
|
676
|
-
`\t\tif err := ${valid.name}().Validate(); err != nil {`,
|
|
677
|
-
`\t\t\tt.Fatalf("a valid ${last(entity.qn)}: %v", err)`,
|
|
678
|
-
'\t\t}',
|
|
679
|
-
'\t})',
|
|
680
|
-
'\tt.Run("rejects a violation", func(t *testing.T) {',
|
|
681
|
-
...(violation ? [
|
|
682
|
-
`\t\tx := ${valid.name}()`,
|
|
683
|
-
`\t\t${violation}`,
|
|
684
|
-
`\t\tif err := x.Validate(); err == nil || !strings.Contains(err.Error(), ${label}) {`,
|
|
685
|
-
`\t\t\tt.Fatalf(${JSON.stringify(`${violation}: want the error %q, got %v`)}, ${label}, err)`,
|
|
686
|
-
'\t\t}'
|
|
687
|
-
] : [`\t\tt.Skip(${JSON.stringify(`registry task: ${invariant.qn}`)})`]),
|
|
688
|
-
'\t})',
|
|
689
|
-
'}'
|
|
690
|
-
].join('\n');
|
|
637
|
+
const code = context.render('tests/invariant.go.njk', { name, qn: invariant.qn, valid: valid.name, entity: last(entity.qn), label: String(invariant.data.label), violation });
|
|
691
638
|
return [
|
|
692
639
|
valid.step,
|
|
693
640
|
goFile(invariant.module, `${pkgOf(invariant.module)}_test.go`, context, imports, code),
|
|
@@ -708,29 +655,7 @@ function transitionTestSteps(transition, context) {
|
|
|
708
655
|
const { action, valid, state, from, to, invalid, args, actor, imports } = plan;
|
|
709
656
|
const call = `${last(action.qn)}(${[...(actor ? [actor] : []), 'x', ...args].join(', ')})`;
|
|
710
657
|
const name = testName(transition);
|
|
711
|
-
const code =
|
|
712
|
-
`func ${name}(t *testing.T) {`,
|
|
713
|
-
`\tt.Run("goes from ${from.label} to ${to.label}", func(t *testing.T) {`,
|
|
714
|
-
`\t\tx := ${valid.name}()`,
|
|
715
|
-
`\t\tx.${state} = ${from.go}`,
|
|
716
|
-
`\t\tif _, err := ${call}; err != nil {`,
|
|
717
|
-
`\t\t\tt.Fatalf("${last(action.qn)} from ${from.label}: %v", err)`,
|
|
718
|
-
'\t\t}',
|
|
719
|
-
`\t\tif x.${state} != ${to.go} {`,
|
|
720
|
-
`\t\t\tt.Fatalf("${last(action.qn)} from ${from.label}: want ${to.label}, got %v", x.${state})`,
|
|
721
|
-
'\t\t}',
|
|
722
|
-
'\t})',
|
|
723
|
-
...(invalid ? [
|
|
724
|
-
`\tt.Run("refuses ${invalid.label}", func(t *testing.T) {`,
|
|
725
|
-
`\t\tx := ${valid.name}()`,
|
|
726
|
-
`\t\tx.${state} = ${invalid.go}`,
|
|
727
|
-
`\t\tif _, err := ${call}; !errors.Is(err, ErrInvalidTransition) {`,
|
|
728
|
-
`\t\t\tt.Fatalf("${last(action.qn)} from ${invalid.label}: want ErrInvalidTransition, got %v", err)`,
|
|
729
|
-
'\t\t}',
|
|
730
|
-
'\t})'
|
|
731
|
-
] : []),
|
|
732
|
-
'}'
|
|
733
|
-
].join('\n');
|
|
658
|
+
const code = context.render('tests/transition.go.njk', { name, action: last(action.qn), valid: valid.name, state, from, to, invalid, call });
|
|
734
659
|
if (invalid)
|
|
735
660
|
imports.add('errors');
|
|
736
661
|
return [valid.step, goFile(transition.module, `${pkgOf(transition.module)}_test.go`, context, imports, code)];
|
|
@@ -835,7 +760,7 @@ function validRecord(entity, context) {
|
|
|
835
760
|
const imports = new Set();
|
|
836
761
|
const scope = goScope(entity, context, imports);
|
|
837
762
|
const record = { $type: entity.qn };
|
|
838
|
-
const
|
|
763
|
+
const samples = [];
|
|
839
764
|
for (const field of fieldsOf(entity, context).filter(f => !f.data.derived)) {
|
|
840
765
|
const type = field.data.type;
|
|
841
766
|
const fieldName = last(field.qn);
|
|
@@ -850,16 +775,13 @@ function validRecord(entity, context) {
|
|
|
850
775
|
const sample = goSample(fieldName, type, scope, context);
|
|
851
776
|
record[fieldName] = sample?.value ?? UNKNOWN;
|
|
852
777
|
if (sample)
|
|
853
|
-
|
|
778
|
+
samples.push({ field: pascal(fieldName), value: sample.go });
|
|
854
779
|
}
|
|
855
780
|
}
|
|
856
781
|
const checked = context.children(entity.qn).filter(n => n.kind === 'Invariant' && validation(n, context));
|
|
857
782
|
if (!checked.every(i => simulator(context).evaluate(i.data.condition, { self: record }) === true))
|
|
858
783
|
return undefined;
|
|
859
|
-
const code = [
|
|
860
|
-
`// ${name} returns ${/^[AEIOU]/.test(last(entity.qn)) ? 'an' : 'a'} ${last(entity.qn)} with the defaults of the model and a sample value for every other required field.`,
|
|
861
|
-
`func ${name}() *${last(entity.qn)} {`, `\tx := New${last(entity.qn)}()`, ...lines, '\treturn x', '}'
|
|
862
|
-
].join('\n');
|
|
784
|
+
const code = context.render('tests/valid-record.go.njk', { name, article: /^[AEIOU]/.test(last(entity.qn)) ? 'an' : 'a', entity: last(entity.qn), samples });
|
|
863
785
|
const file = goFile(entity.module, `${pkgOf(entity.module)}_test.go`, context, imports, code);
|
|
864
786
|
const step = { ...file, write: existing => existing?.includes(`\nfunc ${name}() `) ? existing : file.write(existing) };
|
|
865
787
|
return { name, record, step };
|
|
@@ -1032,6 +954,11 @@ function parentOf(qn) {
|
|
|
1032
954
|
function last(qn) {
|
|
1033
955
|
return qn.slice(qn.lastIndexOf('.') + 1);
|
|
1034
956
|
}
|
|
957
|
+
/** A node's `describe` text and annotation as Go comment lines, for a template; empty without a text. */
|
|
958
|
+
function about(node) {
|
|
959
|
+
const text = aboutOf(node);
|
|
960
|
+
return text ? text.split('\n').map(line => line.trimEnd() ? `// ${line.trimEnd()}` : '//').join('\n') : '';
|
|
961
|
+
}
|
|
1035
962
|
function task(what) {
|
|
1036
963
|
return { kind: 'task', what };
|
|
1037
964
|
}
|
|
@@ -1068,22 +995,22 @@ function scenarioSteps(scenario, context) {
|
|
|
1068
995
|
const file = 'scenarios_test.go';
|
|
1069
996
|
const imports = new Set(['testing']);
|
|
1070
997
|
try {
|
|
1071
|
-
const
|
|
998
|
+
const test = scenarioTest(scenario, context, imports);
|
|
1072
999
|
const does = scenario.data.describe ? `: ${String(scenario.data.describe).trim().replace(/\s+/g, ' ')}` : '.';
|
|
1073
|
-
const
|
|
1074
|
-
const helper = goFile(scenario.module, file, context, new Set(), '// ptr returns a pointer to a copy of v, for optional fields.\nfunc ptr[T any](v T) *T { return &v }', true);
|
|
1000
|
+
const helper = goFile(scenario.module, file, context, new Set(), context.render('go/ptr.go.njk', {}), true);
|
|
1075
1001
|
return [
|
|
1076
1002
|
{ ...helper, write: existing => existing?.includes('\nfunc ptr[') ? existing : helper.write(existing) },
|
|
1077
|
-
goFile(scenario.module, file, context, imports,
|
|
1003
|
+
goFile(scenario.module, file, context, imports, context.render('tests/scenario.go.njk', { name, qn: scenario.qn, does, ...test }), true)
|
|
1078
1004
|
];
|
|
1079
1005
|
}
|
|
1080
1006
|
catch (error) {
|
|
1081
1007
|
if (!(error instanceof Unsupported))
|
|
1082
1008
|
throw error;
|
|
1083
|
-
const code =
|
|
1009
|
+
const code = context.render('tests/skipped.go.njk', { name, qn: scenario.qn });
|
|
1084
1010
|
return [goFile(scenario.module, file, context, new Set(['testing']), code, true), task(`write the test ${name}: ${error.message}`)];
|
|
1085
1011
|
}
|
|
1086
1012
|
}
|
|
1013
|
+
/** The data of `tests/scenario.go.njk`. */
|
|
1087
1014
|
function scenarioTest(scenario, context, imports) {
|
|
1088
1015
|
const data = scenario.data;
|
|
1089
1016
|
let result;
|
|
@@ -1108,7 +1035,7 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1108
1035
|
const scope = { ...goScope(scenario, context, imports), pkg: `${pkgOf(scenario.module)}_test`, vars: new Map(), rename: new Map() };
|
|
1109
1036
|
const fixtures = (data.fixtures ?? []);
|
|
1110
1037
|
const reserved = new Set([...GO_NAMES, accessOf(context).pkg, ...context.graph.nodes.filter(n => n.kind === 'Module').map(n => pkgOf(n.qn))]);
|
|
1111
|
-
const
|
|
1038
|
+
const rows = [];
|
|
1112
1039
|
// given: the rows, built as the simulator builds them, each with its own ID so records compare by identity.
|
|
1113
1040
|
fixtures.forEach((fixture, i) => {
|
|
1114
1041
|
const entity = context.node(fixture.entity);
|
|
@@ -1116,7 +1043,8 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1116
1043
|
while (!fixture.name && fixtures.some(f => f.name === variable))
|
|
1117
1044
|
variable = `${variable}_`;
|
|
1118
1045
|
const constructor = qualify(entity, scope).replace(/(\w+)$/, 'New$1');
|
|
1119
|
-
|
|
1046
|
+
const fields = [];
|
|
1047
|
+
rows.push({ variable, constructor, id: i + 1, fields });
|
|
1120
1048
|
const given = new Map((fixture.assignments ?? []).map(a => [a.name, a.value]));
|
|
1121
1049
|
for (const field of fieldsOf(entity, context).filter(f => !f.data.derived)) {
|
|
1122
1050
|
const type = field.data.type;
|
|
@@ -1126,7 +1054,7 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1126
1054
|
const value = valueOf(type, expr, scope);
|
|
1127
1055
|
if (!value)
|
|
1128
1056
|
throw new Unsupported(`the value of ${fieldName} in ${variable} has no Go translation`);
|
|
1129
|
-
|
|
1057
|
+
fields.push({ name: pascal(fieldName), value });
|
|
1130
1058
|
}
|
|
1131
1059
|
else if (field.data.default) {
|
|
1132
1060
|
if (!defaultValue(field, { ...scope, imports: new Set(), self: 'x' }))
|
|
@@ -1135,7 +1063,7 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1135
1063
|
else if (!type.optional && !type.many) {
|
|
1136
1064
|
const sample = goSample(fieldName, type, scope, context);
|
|
1137
1065
|
if (sample)
|
|
1138
|
-
|
|
1066
|
+
fields.push({ name: pascal(fieldName), value: sample.go });
|
|
1139
1067
|
}
|
|
1140
1068
|
}
|
|
1141
1069
|
if (fixture.name) {
|
|
@@ -1146,12 +1074,13 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1146
1074
|
});
|
|
1147
1075
|
// as: the declared actor, or the first one carrying the role, with the given fields.
|
|
1148
1076
|
const persona = data.actor;
|
|
1077
|
+
let actor;
|
|
1149
1078
|
if (persona) {
|
|
1150
1079
|
const named = context.node(persona.persona);
|
|
1151
|
-
const
|
|
1152
|
-
if (!
|
|
1080
|
+
const declared = named.kind === 'Role' ? context.graph.nodes.find(n => n.kind === 'Actor' && (n.data.roles ?? []).includes(named.qn)) : named;
|
|
1081
|
+
if (!declared)
|
|
1153
1082
|
throw new Unsupported(`no declared actor carries the role ${last(named.qn)}`);
|
|
1154
|
-
|
|
1083
|
+
actor = { constructor: accessIn(scope, `New${accessOf(context).name(declared.qn)}`), fields: [], unused: !code.takesActor };
|
|
1155
1084
|
for (const assignment of persona.assignments ?? []) {
|
|
1156
1085
|
const field = actorFields(context).find(f => last(f.qn) === assignment.name);
|
|
1157
1086
|
if (!field || !actorFieldType(field, context, new Set()))
|
|
@@ -1163,10 +1092,8 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1163
1092
|
if (term.null)
|
|
1164
1093
|
continue;
|
|
1165
1094
|
const value = type.decl ? `ptr(${term.value}.ID)` : valueOf({ ...type, optional: true }, assignment.value, scope);
|
|
1166
|
-
|
|
1095
|
+
actor.fields.push({ name: pascal(assignment.name), value: String(value) });
|
|
1167
1096
|
}
|
|
1168
|
-
if (!code.takesActor)
|
|
1169
|
-
lines.push('_ = actor');
|
|
1170
1097
|
scope.actor = 'actor';
|
|
1171
1098
|
if (code.takesActor && enforced(context))
|
|
1172
1099
|
checkedPolicies(target, code.creates, context);
|
|
@@ -1197,42 +1124,34 @@ function scenarioTest(scenario, context, imports) {
|
|
|
1197
1124
|
const label = last(target.qn);
|
|
1198
1125
|
const checks = (data.checks ?? []);
|
|
1199
1126
|
const emits = !data.fails && !data.refused && checks.some(c => c.$type === 'Emitted');
|
|
1200
|
-
|
|
1127
|
+
const test = { rows, actor, result: emits ? 'events' : '_', call: `${qualify(target, scope)}(${args.join(', ')})`, label, refused: undefined, error: undefined, forbidden: undefined, fails: !!data.fails, checks: [] };
|
|
1201
1128
|
// then: the error, the refusal, or the checks on the rows (changed in place) and the emitted events.
|
|
1202
1129
|
if (data.refused) {
|
|
1203
1130
|
imports.add('errors');
|
|
1204
|
-
|
|
1205
|
-
lines.push(`if !errors.Is(err, ${forbidden}) {`, `\tt.Fatalf("${label}: want ${forbidden}, got %v", err)`, '}');
|
|
1131
|
+
test.refused = accessIn(scope, 'ErrForbidden');
|
|
1206
1132
|
}
|
|
1207
1133
|
else if (data.fails) {
|
|
1208
1134
|
const error = data.error ? context.node(data.error) : undefined;
|
|
1209
1135
|
if (error || code.takesActor)
|
|
1210
1136
|
imports.add('errors');
|
|
1211
|
-
if (error)
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
else if (code.takesActor) {
|
|
1216
|
-
lines.push(`if err == nil || errors.Is(err, ${accessIn(scope, 'ErrForbidden')}) {`, `\tt.Fatalf("${label}: want an error, got %v", err)`, '}');
|
|
1217
|
-
}
|
|
1218
|
-
else {
|
|
1219
|
-
lines.push('if err == nil {', `\tt.Fatalf("${label}: want an error, got none")`, '}');
|
|
1220
|
-
}
|
|
1137
|
+
if (error)
|
|
1138
|
+
test.error = `${qualifyModule(error.module, scope)}.${errorName(error)}`;
|
|
1139
|
+
else if (code.takesActor)
|
|
1140
|
+
test.forbidden = accessIn(scope, 'ErrForbidden');
|
|
1221
1141
|
}
|
|
1222
1142
|
else {
|
|
1223
|
-
lines.push('if err != nil {', `\tt.Fatalf("${label}: %v", err)`, '}');
|
|
1224
1143
|
const shown = (scenario.props.checks ?? []);
|
|
1225
|
-
checks.
|
|
1144
|
+
test.checks = checks.map((check, i) => checkData(check, shown[i], scope, context));
|
|
1226
1145
|
}
|
|
1227
|
-
return
|
|
1146
|
+
return test;
|
|
1228
1147
|
}
|
|
1229
|
-
/** An expectation as
|
|
1230
|
-
function
|
|
1148
|
+
/** An expectation as a condition on the rows, an emitted event as the comparisons of its fields. */
|
|
1149
|
+
function checkData(check, shown, scope, context) {
|
|
1231
1150
|
if (check.$type === 'Expectation') {
|
|
1232
1151
|
const condition = goExpr(check.condition, scope);
|
|
1233
1152
|
if (!condition)
|
|
1234
1153
|
throw new Unsupported(`the check ${shown} has no Go translation`);
|
|
1235
|
-
return
|
|
1154
|
+
return { condition, shown };
|
|
1236
1155
|
}
|
|
1237
1156
|
const event = context.node(check.event);
|
|
1238
1157
|
const compared = (check.assignments ?? []).map(a => {
|
|
@@ -1244,17 +1163,10 @@ function checkLines(check, shown, scope, context) {
|
|
|
1244
1163
|
const same = goExpr({ $type: 'BinaryExpr', op: '==', left, right: a.value, type: 'Bool' }, { ...scope, vars: new Map([...scope.vars ?? [], ['got', 'other']]) });
|
|
1245
1164
|
if (!same)
|
|
1246
1165
|
throw new Unsupported(`the field ${a.name} of ${last(event.qn)} in ${shown} has no Go translation`);
|
|
1247
|
-
return same
|
|
1166
|
+
return `(${same})`;
|
|
1248
1167
|
});
|
|
1249
1168
|
scope.imports.add('slices');
|
|
1250
|
-
return
|
|
1251
|
-
'if !slices.ContainsFunc(events, func(event any) bool {',
|
|
1252
|
-
`\t${compared.length ? 'got' : '_'}, ok := event.(${qualify(event, scope)})`,
|
|
1253
|
-
`\treturn ${['ok', ...compared.map(c => `(${c})`)].join(' && ')}`,
|
|
1254
|
-
'}) {',
|
|
1255
|
-
`\tt.Error(${JSON.stringify(`${shown} did not happen`)})`,
|
|
1256
|
-
'}'
|
|
1257
|
-
];
|
|
1169
|
+
return { event: qualify(event, scope), compared, shown };
|
|
1258
1170
|
}
|
|
1259
1171
|
/** A value in Go for a field or an input of the type: lists of records or values as slice literals, the rest as `assigned` says it. */
|
|
1260
1172
|
function valueOf(type, expr, scope) {
|