sf-flow-coverage 0.2.0 → 0.4.0

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +142 -17
  3. package/lib/commands/flowcov/gate.d.ts +1 -0
  4. package/lib/commands/flowcov/gate.js +15 -2
  5. package/lib/commands/flowcov/gate.js.map +1 -1
  6. package/lib/commands/flowcov/readiness.js +25 -3
  7. package/lib/commands/flowcov/readiness.js.map +1 -1
  8. package/lib/commands/flowcov/transform.d.ts +15 -0
  9. package/lib/commands/flowcov/transform.js +78 -0
  10. package/lib/commands/flowcov/transform.js.map +1 -0
  11. package/lib/core/apexTemplate.d.ts +16 -1
  12. package/lib/core/apexTemplate.js +462 -104
  13. package/lib/core/apexTemplate.js.map +1 -1
  14. package/lib/core/conditions.d.ts +107 -0
  15. package/lib/core/conditions.js +481 -0
  16. package/lib/core/conditions.js.map +1 -0
  17. package/lib/core/coverageCheck.d.ts +8 -0
  18. package/lib/core/coverageCheck.js +12 -0
  19. package/lib/core/coverageCheck.js.map +1 -0
  20. package/lib/core/coverageFormats.d.ts +7 -0
  21. package/lib/core/coverageFormats.js +77 -0
  22. package/lib/core/coverageFormats.js.map +1 -0
  23. package/lib/core/criteria.d.ts +40 -0
  24. package/lib/core/criteria.js +262 -0
  25. package/lib/core/criteria.js.map +1 -0
  26. package/lib/core/elementCoverage.d.ts +9 -0
  27. package/lib/core/elementCoverage.js +27 -0
  28. package/lib/core/elementCoverage.js.map +1 -0
  29. package/lib/core/flowElementLines.d.ts +13 -0
  30. package/lib/core/flowElementLines.js +44 -0
  31. package/lib/core/flowElementLines.js.map +1 -0
  32. package/lib/core/flowFingerprint.d.ts +37 -0
  33. package/lib/core/flowFingerprint.js +142 -0
  34. package/lib/core/flowFingerprint.js.map +1 -0
  35. package/lib/core/flowGraph.d.ts +144 -0
  36. package/lib/core/flowGraph.js +279 -0
  37. package/lib/core/flowGraph.js.map +1 -0
  38. package/lib/core/flowSettings.d.ts +16 -0
  39. package/lib/core/flowSettings.js +49 -0
  40. package/lib/core/flowSettings.js.map +1 -0
  41. package/lib/core/flowTypes.d.ts +6 -0
  42. package/lib/core/flowTypes.js +17 -0
  43. package/lib/core/flowTypes.js.map +1 -1
  44. package/lib/core/flowValues.d.ts +14 -0
  45. package/lib/core/flowValues.js +43 -0
  46. package/lib/core/flowValues.js.map +1 -0
  47. package/lib/core/flowXml.d.ts +1 -1
  48. package/lib/core/flowXml.js +6 -39
  49. package/lib/core/flowXml.js.map +1 -1
  50. package/lib/core/formula.d.ts +48 -0
  51. package/lib/core/formula.js +227 -0
  52. package/lib/core/formula.js.map +1 -0
  53. package/lib/core/gate.d.ts +10 -1
  54. package/lib/core/gate.js +64 -7
  55. package/lib/core/gate.js.map +1 -1
  56. package/lib/core/orgCoverageSource.d.ts +9 -0
  57. package/lib/core/orgCoverageSource.js +68 -12
  58. package/lib/core/orgCoverageSource.js.map +1 -1
  59. package/lib/core/readiness.d.ts +5 -0
  60. package/lib/core/readiness.js +24 -10
  61. package/lib/core/readiness.js.map +1 -1
  62. package/lib/core/requiredFields.d.ts +53 -3
  63. package/lib/core/requiredFields.js +158 -10
  64. package/lib/core/requiredFields.js.map +1 -1
  65. package/lib/core/scaffold.js +50 -4
  66. package/lib/core/scaffold.js.map +1 -1
  67. package/lib/core/toolingQuery.d.ts +5 -0
  68. package/lib/core/toolingQuery.js +9 -1
  69. package/lib/core/toolingQuery.js.map +1 -1
  70. package/lib/core/transform.d.ts +36 -0
  71. package/lib/core/transform.js +62 -0
  72. package/lib/core/transform.js.map +1 -0
  73. package/lib/core/types.d.ts +79 -1
  74. package/lib/index.d.ts +6 -1
  75. package/lib/index.js +3 -1
  76. package/lib/index.js.map +1 -1
  77. package/messages/flowcov.gate.md +19 -1
  78. package/messages/flowcov.readiness.md +4 -2
  79. package/messages/flowcov.scaffold.md +5 -1
  80. package/messages/flowcov.transform.md +33 -0
  81. package/oclif.manifest.json +113 -4
  82. package/package.json +1 -1
@@ -1,4 +1,9 @@
1
+ import { entryCondition, negate } from './conditions.js';
2
+ import { solveCriteria } from './criteria.js';
3
+ import { walkFlow, } from './flowGraph.js';
4
+ import { isProcessBuilder, PROCESS_BUILDER_ADVICE, processTypeLabel } from './flowTypes.js';
1
5
  import { escapeApexString } from './flowXml.js';
6
+ import { canInsertParent, EXISTING_RECORD_IDS, MAX_PARENT_DEPTH } from './requiredFields.js';
2
7
  const MAX_CLASS_NAME = 40;
3
8
  const CLASS_SUFFIX = '_FlowTest';
4
9
  const INDENT = ' ';
@@ -55,55 +60,188 @@ function header(flow, description) {
55
60
  '@IsTest',
56
61
  ];
57
62
  }
58
- function isSimpleField(field) {
59
- return /^[A-Za-z][A-Za-z0-9_]*$/.test(field);
60
- }
61
- /**
62
- * Entry-criteria filters the generator can satisfy: `EqualTo` a literal, and `IsNull false`
63
- * when the org describe gives a value for the field.
64
- */
65
- function resolveCriteria(filters, object, fieldValues) {
66
- const settable = [];
67
- const handled = new Set();
68
- for (const filter of filters) {
69
- if (!isSimpleField(filter.field))
70
- continue;
71
- let apexValue;
72
- if (filter.operator === 'EqualTo')
73
- apexValue = filter.apexValue;
74
- else if (filter.operator === 'IsNull' && filter.rawValue === 'false')
75
- apexValue = fieldValues[object]?.[filter.field];
76
- if (apexValue === undefined)
77
- continue;
78
- settable.push({ field: filter.field, apexValue });
79
- handled.add(filter);
80
- }
81
- return { settable, handled };
63
+ /** What the criteria solver knows about the record an insert or an update test builds. */
64
+ function criteriaContext(object, values, required, context) {
65
+ return {
66
+ object,
67
+ context,
68
+ inserted: knownRequired(object, required) ?? {},
69
+ fieldValues: values.fieldValues[object] ?? {},
70
+ changedValues: values.changedValues[object] ?? {},
71
+ relationships: values.relationships[object] ?? {},
72
+ lookups: values.lookups[object] ?? {},
73
+ parentFieldValues: (parent) => values.fieldValues[parent] ?? {},
74
+ };
82
75
  }
83
- function criteriaTodos(flow, handled) {
84
- const todos = [];
85
- for (const filter of flow.filters) {
86
- if (handled.has(filter))
87
- continue;
88
- const value = filter.rawValue === undefined ? '' : ` ${filter.rawValue}`;
89
- todos.push(`// TODO: entry criteria: ${filter.field} ${filter.operator}${value}`);
90
- }
91
- if (flow.filterFormula)
92
- todos.push(`// TODO: entry criteria formula: ${flow.filterFormula.replace(/\s+/g, ' ')}`);
93
- if (flow.filterLogic && !['and', 'or'].includes(flow.filterLogic.toLowerCase())) {
94
- todos.push(`// TODO: entry criteria logic: ${flow.filterLogic}`);
76
+ /** Plans field values that meet the Flow's entry criteria for an insert or an update test. */
77
+ function planCriteria(flow, object, values, required, context) {
78
+ const plan = solveCriteria(entryCondition(flow), criteriaContext(object, values, required, context));
79
+ for (const [parent, fields] of plan.parents) {
80
+ const known = values.parentFields.get(parent) ?? new Map();
81
+ for (const [field, value] of fields)
82
+ if (!known.has(field))
83
+ known.set(field, value);
84
+ values.parentFields.set(parent, known);
95
85
  }
96
- return todos;
86
+ return plan;
97
87
  }
88
+ const criteriaTodos = (plan) => plan.unmet.map((u) => `// TODO: ${u.label}: ${u.text}`);
98
89
  /** Described required fields win over the built-in list for standard objects. */
99
90
  function knownRequired(object, required) {
100
91
  return required[object] ?? REQUIRED_FIELDS[object];
101
92
  }
102
- function recordFields(object, criteria, required) {
93
+ function recordFieldValues(object, criteria, required) {
103
94
  const fields = new Map(Object.entries(knownRequired(object, required) ?? {}));
104
- for (const assignment of criteria)
105
- fields.set(assignment.field, assignment.apexValue);
106
- return [...fields].map(([field, value]) => `${field} = ${value}`);
95
+ for (const [field, value] of criteria)
96
+ fields.set(field, value);
97
+ return fields;
98
+ }
99
+ function recordFields(object, criteria, required) {
100
+ return [...recordFieldValues(object, criteria, required)].map(([field, value]) => `${field} = ${value}`);
101
+ }
102
+ /**
103
+ * What the test knows about the record's fields when the Flow runs: the values it sets, what the
104
+ * describe says a new record holds in the fields it doesn't set (except `unknown` fields), and,
105
+ * in an update, the values before it (`$Record__Prior`).
106
+ */
107
+ function fieldState(values, unset, unknown = new Set(), prior) {
108
+ const state = new Map();
109
+ for (const [field, value] of Object.entries(unset)) {
110
+ if (!unknown.has(field))
111
+ state.set(`$Record.${field}`, value);
112
+ }
113
+ // `null /* TODO: set a ... Id */` leaves the field empty.
114
+ const apex = (value) => (/^null\b/.test(value) ? null : value);
115
+ for (const [field, value] of values)
116
+ state.set(`$Record.${field}`, apex(value));
117
+ if (prior) {
118
+ for (const [field, value] of Object.entries(unset))
119
+ state.set(`$Record__Prior.${field}`, value);
120
+ for (const [field, value] of prior)
121
+ state.set(`$Record__Prior.${field}`, apex(value));
122
+ }
123
+ return state;
124
+ }
125
+ /** Standard objects that hold data a test must create to have any; custom objects always do. */
126
+ const DATA_OBJECTS = new Set([
127
+ 'Account',
128
+ 'Asset',
129
+ 'Campaign',
130
+ 'CampaignMember',
131
+ 'Case',
132
+ 'Contact',
133
+ 'Contract',
134
+ 'Event',
135
+ 'Lead',
136
+ 'Opportunity',
137
+ 'OpportunityLineItem',
138
+ 'Order',
139
+ 'OrderItem',
140
+ 'Quote',
141
+ 'Task',
142
+ ]);
143
+ /** Apex tests see no org data, so a lookup on data the test doesn't insert finds nothing. */
144
+ const isDataObject = (object) => object.endsWith('__c') || DATA_OBJECTS.has(object);
145
+ function errorText(message) {
146
+ // Merge fields in the message vary per record; match the text before the first one.
147
+ const fixed = message?.split('{!')[0].trim();
148
+ return fixed ? fixed : undefined;
149
+ }
150
+ /**
151
+ * Assertions on records the Flow creates and links back to the record (a field set to
152
+ * `$Record.Id`): one of them exists with the literal values the Flow sets.
153
+ */
154
+ function createdChecks(creates, variable, i2) {
155
+ const lines = [];
156
+ creates.forEach((create, index) => {
157
+ const link = create.fields.find((f) => f.value.apexValue === undefined && f.value.rawValue === '$Record.Id');
158
+ if (!link) {
159
+ lines.push(`${i2}// TODO: ${create.element} creates a ${create.object}; assert it`);
160
+ return;
161
+ }
162
+ const literal = create.fields.filter((f) => f !== link && f.value.apexValue !== undefined);
163
+ const message = `'${escapeApexString(create.element)} should create a ${create.object}'`;
164
+ const query = `[SELECT Id${literal.map((f) => `, ${f.field}`).join('')} FROM ${create.object} WHERE ${link.field} = :${variable}.Id]`;
165
+ if (literal.length === 0) {
166
+ lines.push(`${i2}Assert.isFalse(${query}.isEmpty(), ${message});`);
167
+ return;
168
+ }
169
+ // Look for a match rather than count, so records other automation creates don't fail the test.
170
+ const found = `found${index + 1}`;
171
+ const record = `created${index + 1}`;
172
+ const matches = literal.map((f) => `${record}.${f.field} == ${f.value.apexValue}`).join(' && ');
173
+ lines.push(`${i2}Boolean ${found} = false;`, `${i2}for (${create.object} ${record} : ${query}) {`, `${i2}${INDENT}${found} = ${found} || (${matches});`, `${i2}}`, `${i2}Assert.isTrue(${found}, ${message});`);
174
+ });
175
+ return lines;
176
+ }
177
+ /**
178
+ * Turns a walk of the Flow into the test's DML and checks: an expected custom error, assertions
179
+ * on the fields the Flow is certain to set and the records it is certain to create, and
180
+ * commented assertions for what it does only on a branch the test can't predict. Undefined when
181
+ * the walk gives nothing to check.
182
+ */
183
+ function flowChecks(walk, object, variable, dml, i2) {
184
+ const i3 = INDENT.repeat(3);
185
+ if (walk.customError) {
186
+ const message = errorText(walk.customError.message);
187
+ return {
188
+ dml: [
189
+ `${i2}Test.startTest();`,
190
+ `${i2}try {`,
191
+ `${i3}${dml} ${variable};`,
192
+ `${i3}Assert.fail('${escapeApexString(walk.customError.element)} should block this save with a custom error');`,
193
+ `${i2}} catch (DmlException e) {`,
194
+ message
195
+ ? `${i3}Assert.isTrue(e.getMessage().contains('${escapeApexString(message)}'), e.getMessage());`
196
+ : `${i3}Assert.isNotNull(e.getMessage(), 'The custom error should have a message');`,
197
+ `${i2}}`,
198
+ `${i2}Test.stopTest();`,
199
+ ],
200
+ after: [],
201
+ };
202
+ }
203
+ const maybe = new Set((walk.undecided?.outcomes ?? []).flatMap((o) => o.writes.map((w) => w.field)));
204
+ const certain = new Map();
205
+ for (const write of walk.writes)
206
+ certain.set(write.field, write);
207
+ const lines = [];
208
+ for (const [field, write] of certain) {
209
+ const value = write.value.apexValue;
210
+ if (value !== undefined && !maybe.has(field)) {
211
+ lines.push(`${i2}Assert.areEqual(${value}, result.${field}, '${escapeApexString(write.element)} should set ${field}');`);
212
+ }
213
+ else {
214
+ const reason = maybe.has(field) ? ', and a later branch may change it' : '';
215
+ lines.push(`${i2}// TODO: ${write.element} sets ${field} to ${write.value.rawValue ?? 'a value'}${reason}; assert it`);
216
+ }
217
+ }
218
+ const created = createdChecks(walk.creates ?? [], variable, i2);
219
+ const later = [];
220
+ for (const outcome of walk.undecided?.outcomes ?? []) {
221
+ later.push(`${i2}// TODO: when ${walk.undecided?.element} takes "${outcome.label}", the Flow also:`);
222
+ for (const write of outcome.writes) {
223
+ later.push(write.value.apexValue === undefined
224
+ ? `${i2}// sets ${write.field} to ${write.value.rawValue ?? 'a value'} (${write.element})`
225
+ : `${i2}// Assert.areEqual(${write.value.apexValue}, result.${write.field}, '${escapeApexString(write.element)} should set ${write.field}');`);
226
+ }
227
+ for (const create of outcome.creates)
228
+ later.push(`${i2}// creates a ${create.object} (${create.element})`);
229
+ if (outcome.customError)
230
+ later.push(`${i2}// can block the save with a custom error`);
231
+ }
232
+ if (lines.length + created.length + later.length === 0)
233
+ return undefined;
234
+ const fields = [...new Set([...certain.keys(), ...maybe])];
235
+ const requery = fields.length > 0
236
+ ? [
237
+ `${i2}${object} result = [SELECT Id${fields.map((f) => `, ${f}`).join('')} FROM ${object} WHERE Id = :${variable}.Id];`,
238
+ ]
239
+ : [];
240
+ return {
241
+ dml: [`${i2}Test.startTest();`, `${i2}${dml} ${variable};`, `${i2}Test.stopTest();`],
242
+ // What the Flow is certain to do first, then what it does only on other branches.
243
+ after: [...requery, ...lines, ...created, ...later],
244
+ };
107
245
  }
108
246
  function newRecord(object, variable, fields, indent, required) {
109
247
  const lines = [];
@@ -119,74 +257,143 @@ function newRecord(object, variable, fields, indent, required) {
119
257
  lines.push(`${indent}// TODO: set the required fields for ${object}`);
120
258
  return lines;
121
259
  }
122
- function recordMethods(flow, required, fieldValues) {
260
+ /** Every field the Flow can write on the triggering record, anywhere in its elements. */
261
+ function fieldsTheFlowWrites(flow) {
262
+ return new Set(Object.values(flow.graph?.nodes ?? {}).flatMap((node) => node.kind === 'write' ? node.writes.map((w) => w.field) : []));
263
+ }
264
+ /**
265
+ * When the walk ends in a custom error, a plan that also takes the other way at the last
266
+ * decision that led there, so a second test can save without the error. Undefined when the
267
+ * generator can't meet that decision's opposite.
268
+ */
269
+ function planWithoutError(flow, walk, plan, ctx) {
270
+ if (!walk?.customError)
271
+ return undefined;
272
+ const last = [...(walk.decisions ?? [])].reverse().find((d) => d.rule);
273
+ if (!last?.rule || !flow.graph)
274
+ return undefined;
275
+ const avoided = solveCriteria(negate(last.rule.condition), ctx, plan);
276
+ return avoided.unmet.length === plan.unmet.length ? avoided : undefined;
277
+ }
278
+ function recordMethods(flow, required, values, parentObjects) {
123
279
  const object = flow.object;
124
280
  // A fixed name avoids Apex reserved words (`case`, `order`, `group`) that object names produce.
125
281
  const variable = 'testRecord';
126
- const { settable, handled } = resolveCriteria(flow.filters, object, fieldValues);
127
- const todos = criteriaTodos(flow, handled);
128
282
  const i2 = INDENT.repeat(2);
129
- const requery = (assertion) => [
130
- `${i2}${object} result = [SELECT Id FROM ${object} WHERE Id = :${variable}.Id];`,
131
- `${i2}// TODO: query and assert the fields this Flow sets`,
132
- `${i2}${assertion}`,
133
- ];
283
+ const unset = values.unsetValues[object] ?? {};
284
+ const emptyObject = (o) => isDataObject(o) && o !== object && !parentObjects.has(o);
285
+ const walkFor = (state) => flow.graph ? walkFlow(flow.graph, state, { emptyObject }) : undefined;
134
286
  const method = (name, body) => [
135
287
  `${INDENT}@IsTest`,
136
288
  `${INDENT}static void ${name}() {`,
137
289
  ...body,
138
290
  `${INDENT}}`,
139
291
  ];
140
- const createBody = () => [
141
- ...newRecord(object, variable, recordFields(object, settable, required), i2, required),
142
- ...todos.map((t) => `${i2}${t}`),
143
- '',
144
- `${i2}Test.startTest();`,
145
- `${i2}insert ${variable};`,
146
- `${i2}Test.stopTest();`,
147
- '',
148
- ...requery(`Assert.isNotNull(result.Id, 'The ${object} should be saved');`),
149
- ];
150
- const updateBody = () => {
151
- const lines = [
152
- ...newRecord(object, variable, recordFields(object, [], required), i2, required),
292
+ const defaultChecks = (dml, assertion) => ({
293
+ dml: [`${i2}Test.startTest();`, `${i2}${dml} ${variable};`, `${i2}Test.stopTest();`],
294
+ after: [
295
+ `${i2}${object} result = [SELECT Id FROM ${object} WHERE Id = :${variable}.Id];`,
296
+ `${i2}// TODO: query and assert the fields this Flow sets`,
297
+ `${i2}${assertion}`,
298
+ ],
299
+ });
300
+ const checksOf = (walk, dml, assertion) => (walk && flowChecks(walk, object, variable, dml, i2)) ?? defaultChecks(dml, assertion);
301
+ /** A create test for a plan, and the walk of the Flow it leads to (when the criteria are met). */
302
+ const create = (plan) => {
303
+ const todos = criteriaTodos(plan);
304
+ const walk = todos.length === 0 ? walkFor(fieldState(recordFieldValues(object, plan.set, required), unset)) : undefined;
305
+ const checks = checksOf(walk, 'insert', `Assert.isNotNull(result.Id, 'The ${object} should be saved');`);
306
+ return {
307
+ walk,
308
+ body: [
309
+ ...newRecord(object, variable, recordFields(object, plan.set, required), i2, required),
310
+ ...todos.map((t) => `${i2}${t}`),
311
+ '',
312
+ ...checks.dml,
313
+ ...(checks.after.length > 0 ? ['', ...checks.after] : []),
314
+ ],
315
+ };
316
+ };
317
+ /** An update test for a plan: the insert sets prior values, the update sets the rest. */
318
+ const update = (plan) => {
319
+ const todos = criteriaTodos(plan);
320
+ const inserted = recordFieldValues(object, plan.prior, required);
321
+ const fields = new Map(inserted);
322
+ const changes = [];
323
+ // Skip values the insert already set: assigning them again wouldn't change the record.
324
+ for (const [field, value] of plan.set) {
325
+ fields.set(field, value);
326
+ if (inserted.get(field) !== value)
327
+ changes.push(`${i2}${variable}.${field} = ${value};`);
328
+ }
329
+ changes.push(...todos.map((t) => `${i2}${t}`));
330
+ if (plan.set.size === 0 && todos.length === 0)
331
+ changes.push(`${i2}// TODO: change the fields this Flow reacts to`);
332
+ // When the Flow also runs on create, the insert may already have set the fields it writes.
333
+ const unknown = flow.recordTriggerType === 'CreateAndUpdate' ? fieldsTheFlowWrites(flow) : new Set();
334
+ const changesField = [...plan.set].some(([field, value]) => inserted.get(field) !== value);
335
+ const walk = todos.length === 0 && changesField ? walkFor(fieldState(fields, unset, unknown, inserted)) : undefined;
336
+ const checks = checksOf(walk, 'update', `Assert.isNotNull(result.Id, 'The ${object} should still exist');`);
337
+ const [start, ...dml] = checks.dml;
338
+ return {
339
+ walk,
340
+ body: [
341
+ ...newRecord(object, variable, recordFields(object, plan.prior, required), i2, required),
342
+ `${i2}insert ${variable};`,
343
+ '',
344
+ start,
345
+ ...changes,
346
+ ...dml,
347
+ ...(checks.after.length > 0 ? ['', ...checks.after] : []),
348
+ ],
349
+ };
350
+ };
351
+ /** The test methods for one kind of save, plus one that avoids a custom error when it can. */
352
+ const methods = (name, context) => {
353
+ const plan = planCriteria(flow, object, values, required, context);
354
+ const build = context === 'insert' ? create : update;
355
+ const first = build(plan);
356
+ const ctx = criteriaContext(object, values, required, context);
357
+ const avoided = planWithoutError(flow, first.walk, plan, ctx);
358
+ const second = avoided && build(avoided);
359
+ if (!second || second.walk?.customError)
360
+ return method(name, first.body);
361
+ return [...method(name, first.body), '', ...method(`${name}WithoutError`, second.body)];
362
+ };
363
+ const deleteBody = () => {
364
+ const plan = planCriteria(flow, object, values, required, 'insert');
365
+ const todos = criteriaTodos(plan);
366
+ const fields = recordFieldValues(object, plan.set, required);
367
+ const walk = todos.length === 0 ? walkFor(fieldState(fields, unset)) : undefined;
368
+ const blocked = walk?.customError
369
+ ? flowChecks({ writes: [], customError: walk.customError }, object, variable, 'delete', i2)
370
+ : undefined;
371
+ return [
372
+ ...newRecord(object, variable, recordFields(object, plan.set, required), i2, required),
373
+ ...todos.map((t) => `${i2}${t}`),
153
374
  `${i2}insert ${variable};`,
154
375
  '',
155
- `${i2}Test.startTest();`,
376
+ ...(blocked
377
+ ? blocked.dml
378
+ : [
379
+ `${i2}Test.startTest();`,
380
+ `${i2}delete ${variable};`,
381
+ `${i2}Test.stopTest();`,
382
+ '',
383
+ `${i2}// TODO: assert what this Flow does when the record is deleted`,
384
+ `${i2}Assert.areEqual(0, [SELECT COUNT() FROM ${object} WHERE Id = :${variable}.Id], 'The ${object} should be deleted');`,
385
+ ]),
156
386
  ];
157
- const inserted = knownRequired(object, required) ?? {};
158
- // Skip values the insert already set: assigning them again wouldn't change the record.
159
- for (const { field, apexValue } of settable) {
160
- if (inserted[field] !== apexValue)
161
- lines.push(`${i2}${variable}.${field} = ${apexValue};`);
162
- }
163
- lines.push(...todos.map((t) => `${i2}${t}`));
164
- if (settable.length === 0 && todos.length === 0)
165
- lines.push(`${i2}// TODO: change the fields this Flow reacts to`);
166
- lines.push(`${i2}update ${variable};`, `${i2}Test.stopTest();`, '');
167
- return [...lines, ...requery(`Assert.isNotNull(result.Id, 'The ${object} should still exist');`)];
168
387
  };
169
- const deleteBody = () => [
170
- ...newRecord(object, variable, recordFields(object, settable, required), i2, required),
171
- ...todos.map((t) => `${i2}${t}`),
172
- `${i2}insert ${variable};`,
173
- '',
174
- `${i2}Test.startTest();`,
175
- `${i2}delete ${variable};`,
176
- `${i2}Test.stopTest();`,
177
- '',
178
- `${i2}// TODO: assert what this Flow does when the record is deleted`,
179
- `${i2}Assert.areEqual(0, [SELECT COUNT() FROM ${object} WHERE Id = :${variable}.Id], 'The ${object} should be deleted');`,
180
- ];
181
388
  switch (flow.recordTriggerType) {
182
389
  case 'Update':
183
- return method('runsFlowOnUpdate', updateBody());
390
+ return methods('runsFlowOnUpdate', 'update');
184
391
  case 'CreateAndUpdate':
185
- return [...method('runsFlowOnCreate', createBody()), '', ...method('runsFlowOnUpdate', updateBody())];
392
+ return [...methods('runsFlowOnCreate', 'insert'), '', ...methods('runsFlowOnUpdate', 'update')];
186
393
  case 'Delete':
187
394
  return method('runsFlowOnDelete', deleteBody());
188
395
  default:
189
- return method('runsFlowOnCreate', createBody());
396
+ return methods('runsFlowOnCreate', 'insert');
190
397
  }
191
398
  }
192
399
  function inputValue(variable) {
@@ -225,14 +432,14 @@ function inputValue(variable) {
225
432
  return 'null';
226
433
  }
227
434
  }
228
- function interviewMethod(flow, name, notes, required) {
435
+ function interviewMethod(flow, name, notes, required, walkOutputs = false) {
229
436
  const i2 = INDENT.repeat(2);
230
437
  const lines = [`${INDENT}@IsTest`, `${INDENT}static void ${name}() {`, ...notes.map((n) => `${i2}// ${n}`)];
231
438
  lines.push(`${i2}Map<String, Object> inputs = new Map<String, Object>();`);
232
439
  for (const variable of flow.variables.filter((v) => v.isInput)) {
233
440
  if (variable.dataType === 'SObject' && variable.objectType && !variable.isCollection) {
234
441
  const local = `${camel(variable.name) || 'input'}Input`;
235
- lines.push(...newRecord(variable.objectType, local, recordFields(variable.objectType, [], required), i2, required));
442
+ lines.push(...newRecord(variable.objectType, local, recordFields(variable.objectType, new Map(), required), i2, required));
236
443
  lines.push(`${i2}insert ${local};`, `${i2}inputs.put('${escapeApexString(variable.name)}', ${local});`);
237
444
  }
238
445
  else {
@@ -240,23 +447,65 @@ function interviewMethod(flow, name, notes, required) {
240
447
  lines.push(`${i2}inputs.put('${escapeApexString(variable.name)}', ${inputValue(variable)}); // TODO: ${type}${variable.isCollection ? ' collection' : ''}`);
241
448
  }
242
449
  }
243
- lines.push('', `${i2}Test.startTest();`, `${i2}Flow.Interview interview = Flow.Interview.createInterview('${escapeApexString(flow.name)}', inputs);`, `${i2}interview.start();`, `${i2}Test.stopTest();`, '', `${i2}// TODO: assert what this Flow does`);
450
+ lines.push('', `${i2}Test.startTest();`, `${i2}Flow.Interview interview = Flow.Interview.createInterview('${escapeApexString(flow.name)}', inputs);`, `${i2}interview.start();`, `${i2}Test.stopTest();`, '');
451
+ const known = walkOutputs ? outputValues(flow) : new Map();
452
+ const checks = [];
244
453
  for (const variable of flow.variables.filter((v) => v.isOutput)) {
245
- lines.push(`${i2}Object ${camel(variable.name) || 'output'}Output = interview.getVariableValue('${escapeApexString(variable.name)}');`);
454
+ const name = escapeApexString(variable.name);
455
+ const write = known.get(variable.name);
456
+ checks.push(write
457
+ ? `${i2}Assert.areEqual(${write.value.apexValue}, interview.getVariableValue('${name}'), '${escapeApexString(write.element)} should set ${name}');`
458
+ : `${i2}Object ${camel(variable.name) || 'output'}Output = interview.getVariableValue('${name}');`);
246
459
  }
247
- lines.push(`${i2}Assert.isNotNull(interview, 'The Flow interview should run');`, `${INDENT}}`);
460
+ if (known.size === 0)
461
+ lines.push(`${i2}// TODO: assert what this Flow does`);
462
+ lines.push(...checks);
463
+ if (known.size === 0)
464
+ lines.push(`${i2}Assert.isNotNull(interview, 'The Flow interview should run');`);
465
+ lines.push(`${INDENT}}`);
248
466
  return lines;
249
467
  }
250
- function platformEventMethod(flow, required, fieldValues) {
468
+ /**
469
+ * Output variables an autolaunched Flow is certain to set to a literal, for the inputs the test
470
+ * passes (the placeholder values in `inputValue`).
471
+ */
472
+ function outputValues(flow) {
473
+ if (!flow.graph)
474
+ return new Map();
475
+ const state = new Map();
476
+ const inputObjects = new Set();
477
+ for (const variable of flow.variables.filter((v) => v.isInput)) {
478
+ if (variable.dataType === 'SObject' && variable.objectType)
479
+ inputObjects.add(variable.objectType);
480
+ else if (!variable.isCollection) {
481
+ const value = inputValue(variable);
482
+ state.set(variable.name, value === 'null' ? null : value);
483
+ }
484
+ }
485
+ const walk = walkFlow(flow.graph, state, { emptyObject: (o) => isDataObject(o) && !inputObjects.has(o) });
486
+ if (walk.customError)
487
+ return new Map();
488
+ const maybe = new Set((walk.undecided?.outcomes ?? []).flatMap((o) => o.variables.map((v) => v.variable)));
489
+ const known = new Map();
490
+ for (const write of walk.variables ?? []) {
491
+ if (write.value.apexValue === undefined || maybe.has(write.variable))
492
+ known.delete(write.variable);
493
+ else
494
+ known.set(write.variable, write);
495
+ }
496
+ const outputs = new Set(flow.variables.filter((v) => v.isOutput).map((v) => v.name));
497
+ return new Map([...known].filter(([name]) => outputs.has(name)));
498
+ }
499
+ function platformEventMethod(flow, required, values) {
251
500
  const event = flow.object;
252
501
  const i2 = INDENT.repeat(2);
253
- const { settable, handled } = resolveCriteria(flow.filters, event, fieldValues);
502
+ const plan = planCriteria(flow, event, values, required, 'insert');
254
503
  return [
255
504
  `${INDENT}@IsTest`,
256
505
  `${INDENT}static void runsFlowOnEvent() {`,
257
- ...newRecord(event, 'testEvent', recordFields(event, settable, required), i2, required).filter((l) => !l.includes('TODO: set the required')),
506
+ ...newRecord(event, 'testEvent', recordFields(event, plan.set, required), i2, required).filter((l) => !l.includes('TODO: set the required')),
258
507
  `${i2}// TODO: set the event fields this Flow reads`,
259
- ...criteriaTodos(flow, handled).map((t) => `${i2}${t}`),
508
+ ...criteriaTodos(plan).map((t) => `${i2}${t}`),
260
509
  '',
261
510
  `${i2}Test.startTest();`,
262
511
  `${i2}EventBus.publish(testEvent);`,
@@ -270,10 +519,12 @@ function platformEventMethod(flow, required, fieldValues) {
270
519
  }
271
520
  function processMethod(flow) {
272
521
  const i2 = INDENT.repeat(2);
522
+ const advice = PROCESS_BUILDER_ADVICE.split(/(?<=\.) /).map((sentence) => `${i2}// ${sentence}`);
273
523
  return [
274
524
  `${INDENT}@IsTest`,
275
525
  `${INDENT}static void runsProcess() {`,
276
- `${i2}// TODO: ${flow.processType ?? 'This'} processes start when a record changes or an event fires.`,
526
+ ...(isProcessBuilder(flow.processType) ? advice : []),
527
+ `${i2}// TODO: ${flow.processType ? processTypeLabel(flow.processType) : 'These'} processes start when a record changes or an event fires.`,
277
528
  `${i2}// Insert or update a record that meets this process's criteria between startTest and stopTest.`,
278
529
  `${i2}Test.startTest();`,
279
530
  `${i2}Test.stopTest();`,
@@ -283,10 +534,116 @@ function processMethod(flow) {
283
534
  `${INDENT}}`,
284
535
  ];
285
536
  }
537
+ /**
538
+ * Fills lookup fields with an Id: an existing record's (the running user, the standard price
539
+ * book), or a parent record's the test inserts when the describe gives the parent's required
540
+ * fields. Other lookups keep their TODO.
541
+ */
542
+ function resolveLookups(options) {
543
+ const required = { ...options.requiredFields };
544
+ const fieldValues = { ...options.fieldValues };
545
+ const parents = new Map();
546
+ const lookupValue = (target, source) => {
547
+ if (target in EXISTING_RECORD_IDS)
548
+ return EXISTING_RECORD_IDS[target];
549
+ // Setup data a test can read without inserting: the org's default business hours, and a
550
+ // record type of the object when the describe shows it has any besides Master.
551
+ if (target === 'BusinessHours')
552
+ return '[SELECT Id FROM BusinessHours WHERE IsDefault = true LIMIT 1].Id';
553
+ if (target === 'RecordType') {
554
+ return (options.recordTypes?.[source] ?? 0) > 1
555
+ ? `[SELECT Id FROM RecordType WHERE SobjectType = '${source}' AND IsActive = true LIMIT 1].Id`
556
+ : undefined;
557
+ }
558
+ if (!canInsertParent(target) || !options.requiredFields?.[target])
559
+ return undefined;
560
+ const variable = `${camel(target) || 'record'}Parent`;
561
+ parents.set(variable, target);
562
+ return `${variable}.Id`;
563
+ };
564
+ for (const [object, fields] of Object.entries(options.lookups ?? {})) {
565
+ for (const [field, target] of Object.entries(fields)) {
566
+ const value = lookupValue(target, object);
567
+ if (value === undefined)
568
+ continue;
569
+ if (required[object] && field in required[object])
570
+ required[object] = { ...required[object], [field]: value };
571
+ fieldValues[object] = { ...fieldValues[object], [field]: value };
572
+ }
573
+ }
574
+ return { required, fieldValues, parents };
575
+ }
576
+ const METHOD_START = /^\s+static void \w+\(\) \{$/;
577
+ const PARENT_ID = /\b(\w+Parent)\.Id\b/g;
578
+ /**
579
+ * Inserts each parent record a test method uses at the top of that method, with the parents
580
+ * those parents need inserted first. A parent gets its own required fields and the fields the
581
+ * criteria need on it. A lookup back into its own chain (a cycle), or past
582
+ * `MAX_PARENT_DEPTH`, keeps its TODO.
583
+ */
584
+ function withParentInserts(lines, parents, required, original, parentFields) {
585
+ if (parents.size === 0)
586
+ return lines;
587
+ const i2 = INDENT.repeat(2);
588
+ const referenced = (text) => [...new Set([...text.matchAll(PARENT_ID)].map((m) => m[1]))].filter((v) => parents.has(v));
589
+ const insertParents = (variables) => {
590
+ const out = [];
591
+ const done = new Set();
592
+ const visit = (variable, chain) => {
593
+ if (done.has(variable))
594
+ return;
595
+ const object = parents.get(variable);
596
+ const here = [...chain, variable];
597
+ const fields = recordFieldValues(object, parentFields.get(object) ?? new Map(), required);
598
+ for (const [field, value] of fields) {
599
+ const refs = referenced(value);
600
+ if (refs.some((r) => here.includes(r)) || (refs.length > 0 && here.length >= MAX_PARENT_DEPTH)) {
601
+ fields.set(field, original[object]?.[field] ?? 'null /* TODO: set this lookup */');
602
+ }
603
+ }
604
+ for (const dependency of referenced([...fields.values()].join('\n')))
605
+ visit(dependency, here);
606
+ done.add(variable);
607
+ out.push(...newRecord(object, variable, [...fields].map(([f, v]) => `${f} = ${v}`), i2, required), `${i2}insert ${variable};`);
608
+ };
609
+ for (const variable of variables)
610
+ visit(variable, []);
611
+ return out;
612
+ };
613
+ const out = [];
614
+ for (let i = 0; i < lines.length; i++) {
615
+ out.push(lines[i]);
616
+ if (!METHOD_START.test(lines[i]))
617
+ continue;
618
+ const used = referenced(lines.slice(i + 1, lines.indexOf(`${INDENT}}`, i)).join('\n'));
619
+ if (used.length > 0)
620
+ out.push(...insertParents(used), '');
621
+ }
622
+ return out;
623
+ }
624
+ /** `unsetValues`, with `nullWhenUnset` fields added as empty. */
625
+ function unsetValuesOf(options) {
626
+ const unset = {};
627
+ for (const [object, fields] of Object.entries(options.nullWhenUnset ?? {})) {
628
+ unset[object] = Object.fromEntries(fields.map((field) => [field, null]));
629
+ }
630
+ for (const [object, values] of Object.entries(options.unsetValues ?? {})) {
631
+ unset[object] = { ...unset[object], ...values };
632
+ }
633
+ return unset;
634
+ }
286
635
  /** Generates a starter Apex test class for a Flow from its metadata. */
287
636
  export function generateApexTest(flow, options = {}) {
288
- const required = options.requiredFields ?? {};
289
- const fieldValues = options.fieldValues ?? {};
637
+ const lookups = resolveLookups(options);
638
+ const required = lookups.required;
639
+ const values = {
640
+ fieldValues: lookups.fieldValues,
641
+ changedValues: options.changedValues ?? {},
642
+ unsetValues: unsetValuesOf(options),
643
+ relationships: options.relationships ?? {},
644
+ lookups: options.lookups ?? {},
645
+ parentFields: new Map(),
646
+ };
290
647
  const className = apexTestClassName(flow.name);
291
648
  const kind = flowKind(flow);
292
649
  let description;
@@ -294,11 +651,11 @@ export function generateApexTest(flow, options = {}) {
294
651
  switch (kind) {
295
652
  case 'record':
296
653
  description = `Record-triggered on ${flow.object} (${flow.recordTriggerType ?? 'Create'}, ${flow.triggerType}).`;
297
- methods = recordMethods(flow, required, fieldValues);
654
+ methods = recordMethods(flow, required, values, new Set(lookups.parents.values()));
298
655
  break;
299
656
  case 'platformEvent':
300
657
  description = `Triggered by the platform event ${flow.object}.`;
301
- methods = platformEventMethod(flow, required, fieldValues);
658
+ methods = platformEventMethod(flow, required, values);
302
659
  break;
303
660
  case 'scheduled':
304
661
  description = 'Schedule-triggered. Apex tests cannot fire the schedule, so this test starts the Flow directly.';
@@ -311,12 +668,13 @@ export function generateApexTest(flow, options = {}) {
311
668
  break;
312
669
  case 'autolaunched':
313
670
  description = 'Autolaunched (no trigger).';
314
- methods = interviewMethod(flow, 'runsFlow', [], required);
671
+ methods = interviewMethod(flow, 'runsFlow', [], required, true);
315
672
  break;
316
673
  default:
317
674
  description = `Process type ${flow.processType ?? 'unknown'}.`;
318
675
  methods = processMethod(flow);
319
676
  }
677
+ methods = withParentInserts(methods, lookups.parents, required, options.requiredFields ?? {}, values.parentFields);
320
678
  const body = [...header(flow, description), `private class ${className} {`, ...methods, '}', ''].join('\n');
321
679
  return { className, body, kind };
322
680
  }