sf-flow-coverage 0.3.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 (77) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +117 -19
  3. package/lib/commands/flowcov/gate.js +3 -1
  4. package/lib/commands/flowcov/gate.js.map +1 -1
  5. package/lib/commands/flowcov/readiness.js +25 -3
  6. package/lib/commands/flowcov/readiness.js.map +1 -1
  7. package/lib/commands/flowcov/transform.d.ts +15 -0
  8. package/lib/commands/flowcov/transform.js +78 -0
  9. package/lib/commands/flowcov/transform.js.map +1 -0
  10. package/lib/core/apexTemplate.d.ts +11 -2
  11. package/lib/core/apexTemplate.js +307 -199
  12. package/lib/core/apexTemplate.js.map +1 -1
  13. package/lib/core/conditions.d.ts +107 -0
  14. package/lib/core/conditions.js +481 -0
  15. package/lib/core/conditions.js.map +1 -0
  16. package/lib/core/coverageCheck.d.ts +8 -0
  17. package/lib/core/coverageCheck.js +12 -0
  18. package/lib/core/coverageCheck.js.map +1 -0
  19. package/lib/core/coverageFormats.d.ts +7 -0
  20. package/lib/core/coverageFormats.js +77 -0
  21. package/lib/core/coverageFormats.js.map +1 -0
  22. package/lib/core/criteria.d.ts +40 -0
  23. package/lib/core/criteria.js +262 -0
  24. package/lib/core/criteria.js.map +1 -0
  25. package/lib/core/elementCoverage.d.ts +9 -0
  26. package/lib/core/elementCoverage.js +27 -0
  27. package/lib/core/elementCoverage.js.map +1 -0
  28. package/lib/core/flowElementLines.d.ts +13 -0
  29. package/lib/core/flowElementLines.js +44 -0
  30. package/lib/core/flowElementLines.js.map +1 -0
  31. package/lib/core/flowFingerprint.d.ts +10 -0
  32. package/lib/core/flowFingerprint.js +14 -0
  33. package/lib/core/flowFingerprint.js.map +1 -1
  34. package/lib/core/flowGraph.d.ts +63 -13
  35. package/lib/core/flowGraph.js +125 -134
  36. package/lib/core/flowGraph.js.map +1 -1
  37. package/lib/core/flowSettings.d.ts +16 -0
  38. package/lib/core/flowSettings.js +49 -0
  39. package/lib/core/flowSettings.js.map +1 -0
  40. package/lib/core/flowTypes.d.ts +6 -0
  41. package/lib/core/flowTypes.js +17 -0
  42. package/lib/core/flowTypes.js.map +1 -1
  43. package/lib/core/formula.d.ts +48 -0
  44. package/lib/core/formula.js +227 -0
  45. package/lib/core/formula.js.map +1 -0
  46. package/lib/core/gate.js +19 -1
  47. package/lib/core/gate.js.map +1 -1
  48. package/lib/core/orgCoverageSource.d.ts +3 -0
  49. package/lib/core/orgCoverageSource.js +26 -5
  50. package/lib/core/orgCoverageSource.js.map +1 -1
  51. package/lib/core/readiness.d.ts +5 -0
  52. package/lib/core/readiness.js +24 -10
  53. package/lib/core/readiness.js.map +1 -1
  54. package/lib/core/requiredFields.d.ts +29 -7
  55. package/lib/core/requiredFields.js +60 -19
  56. package/lib/core/requiredFields.js.map +1 -1
  57. package/lib/core/scaffold.js +30 -11
  58. package/lib/core/scaffold.js.map +1 -1
  59. package/lib/core/toolingQuery.d.ts +5 -0
  60. package/lib/core/toolingQuery.js +9 -1
  61. package/lib/core/toolingQuery.js.map +1 -1
  62. package/lib/core/transform.d.ts +36 -0
  63. package/lib/core/transform.js +62 -0
  64. package/lib/core/transform.js.map +1 -0
  65. package/lib/core/types.d.ts +52 -2
  66. package/lib/index.d.ts +6 -1
  67. package/lib/index.js +3 -1
  68. package/lib/index.js.map +1 -1
  69. package/messages/flowcov.gate.md +3 -1
  70. package/messages/flowcov.readiness.md +4 -2
  71. package/messages/flowcov.scaffold.md +4 -2
  72. package/messages/flowcov.transform.md +33 -0
  73. package/oclif.manifest.json +98 -4
  74. package/package.json +1 -1
  75. package/lib/core/filterFormula.d.ts +0 -10
  76. package/lib/core/filterFormula.js +0 -153
  77. package/lib/core/filterFormula.js.map +0 -1
@@ -1,7 +1,9 @@
1
- import { parseFilterFormula } from './filterFormula.js';
2
- import { walkFlow } from './flowGraph.js';
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';
3
5
  import { escapeApexString } from './flowXml.js';
4
- import { canInsertParent, EXISTING_RECORD_IDS } from './requiredFields.js';
6
+ import { canInsertParent, EXISTING_RECORD_IDS, MAX_PARENT_DEPTH } from './requiredFields.js';
5
7
  const MAX_CLASS_NAME = 40;
6
8
  const CLASS_SUFFIX = '_FlowTest';
7
9
  const INDENT = ' ';
@@ -58,153 +60,125 @@ function header(flow, description) {
58
60
  '@IsTest',
59
61
  ];
60
62
  }
61
- function isSimpleField(field) {
62
- return /^[A-Za-z][A-Za-z0-9_]*$/.test(field);
63
- }
64
- const BOUND_STEPS = {
65
- GreaterThan: 1,
66
- GreaterThanOrEqualTo: 0,
67
- LessThan: -1,
68
- LessThanOrEqualTo: 0,
69
- };
70
- const NUMBER = /^-?\d+(\.\d+)?$/;
71
- const DATE = 'Date.valueOf(';
72
- const DATETIME = 'Datetime.valueOfGmt(';
73
- /** A value past (or at) a comparison bound: numbers step by 1, dates by a day, datetimes by a second. */
74
- function boundValue(apexValue, step) {
75
- if (apexValue === undefined)
76
- return undefined;
77
- if (NUMBER.test(apexValue))
78
- return String(Number((Number(apexValue) + step).toFixed(10)));
79
- if (!apexValue.startsWith(DATE) && !apexValue.startsWith(DATETIME))
80
- return undefined;
81
- if (step === 0)
82
- return apexValue;
83
- return apexValue.startsWith(DATE) ? `${apexValue}.addDays(${step})` : `${apexValue}.addSeconds(${step})`;
84
- }
85
- /** A value that meets one filter on its own, or undefined when the generator can't make one. */
86
- function filterValue(filter, object, values) {
87
- const { operator, apexValue } = filter;
88
- if (operator === 'EqualTo')
89
- return apexValue;
90
- if (operator === 'IsNull' && filter.rawValue === 'false')
91
- return values.fieldValues[object]?.[filter.field];
92
- if (operator in BOUND_STEPS)
93
- return boundValue(apexValue, BOUND_STEPS[operator]);
94
- // A string contains, starts with, and ends with itself.
95
- if (['Contains', 'StartsWith', 'EndsWith'].includes(operator) && apexValue?.startsWith("'"))
96
- return apexValue;
97
- return undefined;
98
- }
99
- /**
100
- * Entry-criteria filters the generator can satisfy: `EqualTo`, comparisons, and string matches
101
- * against a literal; `IsNull false` when the org describe gives a value for the field; and, in
102
- * an update, `IsChanged true` when the describe gives a second value (or another filter already
103
- * sets the field) and `IsChanged false` when no other filter sets the field.
104
- */
105
- function resolveCriteria(filters, object, values, context) {
106
- const settable = [];
107
- const handled = new Set();
108
- const changed = [];
109
- for (const filter of filters) {
110
- if (!isSimpleField(filter.field))
111
- continue;
112
- if (filter.operator === 'IsChanged') {
113
- if (context === 'update')
114
- changed.push(filter);
115
- continue;
116
- }
117
- const apexValue = filterValue(filter, object, values);
118
- if (apexValue === undefined)
119
- continue;
120
- settable.push({ field: filter.field, apexValue });
121
- handled.add(filter);
122
- }
123
- // After the other filters, so a field they already set in the update counts as changed.
124
- for (const filter of changed) {
125
- const alreadySet = settable.some((s) => s.field === filter.field);
126
- if (filter.rawValue !== 'true') {
127
- // `IsChanged false` holds as long as nothing else sets the field.
128
- if (filter.rawValue === 'false' && !alreadySet)
129
- handled.add(filter);
130
- continue;
131
- }
132
- if (!alreadySet) {
133
- const apexValue = values.changedValues[object]?.[filter.field];
134
- if (apexValue === undefined)
135
- continue;
136
- settable.push({ field: filter.field, apexValue });
137
- }
138
- handled.add(filter);
139
- }
140
- 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
+ };
141
75
  }
142
- function criteriaTodos(flow, handled) {
143
- const todos = [];
144
- for (const filter of flow.filters) {
145
- if (handled.has(filter))
146
- continue;
147
- if (filter.formulaTerm !== undefined) {
148
- todos.push(`// TODO: entry criteria formula term: ${filter.formulaTerm.replace(/\s+/g, ' ')}`);
149
- continue;
150
- }
151
- const value = filter.rawValue === undefined ? '' : ` ${filter.rawValue}`;
152
- todos.push(`// TODO: entry criteria: ${filter.field} ${filter.operator}${value}`);
153
- }
154
- if (flow.filterFormula)
155
- todos.push(`// TODO: entry criteria formula: ${flow.filterFormula.replace(/\s+/g, ' ')}`);
156
- if (flow.filterLogic && !['and', 'or'].includes(flow.filterLogic.toLowerCase())) {
157
- 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);
158
85
  }
159
- return todos;
160
- }
161
- /**
162
- * Reads a simple entry-criteria formula into filters the generator can meet, so only the terms
163
- * it can't read stay TODOs. Other formulas stay a single TODO.
164
- */
165
- function withFormulaFilters(flow) {
166
- const filters = flow.filterFormula ? parseFilterFormula(flow.filterFormula) : undefined;
167
- if (!filters)
168
- return flow;
169
- return { ...flow, filters: [...flow.filters, ...filters], filterFormula: undefined };
86
+ return plan;
170
87
  }
88
+ const criteriaTodos = (plan) => plan.unmet.map((u) => `// TODO: ${u.label}: ${u.text}`);
171
89
  /** Described required fields win over the built-in list for standard objects. */
172
90
  function knownRequired(object, required) {
173
91
  return required[object] ?? REQUIRED_FIELDS[object];
174
92
  }
175
93
  function recordFieldValues(object, criteria, required) {
176
94
  const fields = new Map(Object.entries(knownRequired(object, required) ?? {}));
177
- for (const assignment of criteria)
178
- fields.set(assignment.field, assignment.apexValue);
95
+ for (const [field, value] of criteria)
96
+ fields.set(field, value);
179
97
  return fields;
180
98
  }
181
99
  function recordFields(object, criteria, required) {
182
100
  return [...recordFieldValues(object, criteria, required)].map(([field, value]) => `${field} = ${value}`);
183
101
  }
184
102
  /**
185
- * What the test knows about the record's fields when the Flow runs: the values it sets, empty
186
- * for fields the describe says stay empty, and nothing for `unknown` fields.
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`).
187
106
  */
188
- function fieldState(values, nullWhenUnset, unknown = new Set()) {
107
+ function fieldState(values, unset, unknown = new Set(), prior) {
189
108
  const state = new Map();
190
- for (const field of nullWhenUnset)
109
+ for (const [field, value] of Object.entries(unset)) {
191
110
  if (!unknown.has(field))
192
- state.set(field, null);
193
- for (const [field, value] of values) {
194
- // `null /* TODO: set a ... Id */` leaves the field empty.
195
- state.set(field, /^null\b/.test(value) ? null : value);
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));
196
122
  }
197
123
  return state;
198
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);
199
145
  function errorText(message) {
200
146
  // Merge fields in the message vary per record; match the text before the first one.
201
147
  const fixed = message?.split('{!')[0].trim();
202
148
  return fixed ? fixed : undefined;
203
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
+ }
204
177
  /**
205
178
  * Turns a walk of the Flow into the test's DML and checks: an expected custom error, assertions
206
- * on the fields the Flow is certain to set, and commented assertions for fields it sets only on
207
- * a branch the test can't predict. Undefined when the walk gives nothing to check.
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.
208
182
  */
209
183
  function flowChecks(walk, object, variable, dml, i2) {
210
184
  const i3 = INDENT.repeat(3);
@@ -241,25 +215,32 @@ function flowChecks(walk, object, variable, dml, i2) {
241
215
  lines.push(`${i2}// TODO: ${write.element} sets ${field} to ${write.value.rawValue ?? 'a value'}${reason}; assert it`);
242
216
  }
243
217
  }
218
+ const created = createdChecks(walk.creates ?? [], variable, i2);
219
+ const later = [];
244
220
  for (const outcome of walk.undecided?.outcomes ?? []) {
245
- lines.push(`${i2}// TODO: when ${walk.undecided?.element} takes "${outcome.label}", the Flow also:`);
221
+ later.push(`${i2}// TODO: when ${walk.undecided?.element} takes "${outcome.label}", the Flow also:`);
246
222
  for (const write of outcome.writes) {
247
- lines.push(write.value.apexValue === undefined
223
+ later.push(write.value.apexValue === undefined
248
224
  ? `${i2}// sets ${write.field} to ${write.value.rawValue ?? 'a value'} (${write.element})`
249
225
  : `${i2}// Assert.areEqual(${write.value.apexValue}, result.${write.field}, '${escapeApexString(write.element)} should set ${write.field}');`);
250
226
  }
227
+ for (const create of outcome.creates)
228
+ later.push(`${i2}// creates a ${create.object} (${create.element})`);
251
229
  if (outcome.customError)
252
- lines.push(`${i2}// can block the save with a custom error`);
230
+ later.push(`${i2}// can block the save with a custom error`);
253
231
  }
254
- if (lines.length === 0)
232
+ if (lines.length + created.length + later.length === 0)
255
233
  return undefined;
256
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
+ : [];
257
240
  return {
258
241
  dml: [`${i2}Test.startTest();`, `${i2}${dml} ${variable};`, `${i2}Test.stopTest();`],
259
- after: [
260
- `${i2}${object} result = [SELECT Id, ${fields.join(', ')} FROM ${object} WHERE Id = :${variable}.Id];`,
261
- ...lines,
262
- ],
242
+ // What the Flow is certain to do first, then what it does only on other branches.
243
+ after: [...requery, ...lines, ...created, ...later],
263
244
  };
264
245
  }
265
246
  function newRecord(object, variable, fields, indent, required) {
@@ -280,14 +261,28 @@ function newRecord(object, variable, fields, indent, required) {
280
261
  function fieldsTheFlowWrites(flow) {
281
262
  return new Set(Object.values(flow.graph?.nodes ?? {}).flatMap((node) => node.kind === 'write' ? node.writes.map((w) => w.field) : []));
282
263
  }
283
- function recordMethods(flow, required, values) {
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) {
284
279
  const object = flow.object;
285
280
  // A fixed name avoids Apex reserved words (`case`, `order`, `group`) that object names produce.
286
281
  const variable = 'testRecord';
287
- const { settable, handled } = resolveCriteria(flow.filters, object, values, 'insert');
288
- const todos = criteriaTodos(flow, handled);
289
282
  const i2 = INDENT.repeat(2);
290
- const nullWhenUnset = values.nullWhenUnset[object] ?? [];
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;
291
286
  const method = (name, body) => [
292
287
  `${INDENT}@IsTest`,
293
288
  `${INDENT}static void ${name}() {`,
@@ -302,56 +297,79 @@ function recordMethods(flow, required, values) {
302
297
  `${i2}${assertion}`,
303
298
  ],
304
299
  });
305
- /** Checks from walking the Flow, when the test is sure to meet its entry criteria. */
306
- const checksFor = (criteriaMet, state, dml) => criteriaMet && flow.graph ? flowChecks(walkFlow(flow.graph, state), object, variable, dml, i2) : undefined;
307
- const createBody = () => {
308
- const fields = recordFieldValues(object, settable, required);
309
- const checks = checksFor(todos.length === 0, fieldState(fields, nullWhenUnset), 'insert') ??
310
- defaultChecks('insert', `Assert.isNotNull(result.Id, 'The ${object} should be saved');`);
311
- return [
312
- ...newRecord(object, variable, recordFields(object, settable, required), i2, required),
313
- ...todos.map((t) => `${i2}${t}`),
314
- '',
315
- ...checks.dml,
316
- ...(checks.after.length > 0 ? ['', ...checks.after] : []),
317
- ];
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
+ };
318
316
  };
319
- const updateBody = () => {
320
- const update = resolveCriteria(flow.filters, object, values, 'update');
321
- const updateTodos = criteriaTodos(flow, update.handled);
322
- const lines = [
323
- ...newRecord(object, variable, recordFields(object, [], required), i2, required),
324
- `${i2}insert ${variable};`,
325
- '',
326
- ];
327
- const inserted = knownRequired(object, required) ?? {};
328
- const fields = recordFieldValues(object, [], required);
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);
329
322
  const changes = [];
330
323
  // Skip values the insert already set: assigning them again wouldn't change the record.
331
- for (const { field, apexValue } of update.settable) {
332
- fields.set(field, apexValue);
333
- if (inserted[field] !== apexValue)
334
- changes.push(`${i2}${variable}.${field} = ${apexValue};`);
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};`);
335
328
  }
336
- changes.push(...updateTodos.map((t) => `${i2}${t}`));
337
- if (update.settable.length === 0 && updateTodos.length === 0)
329
+ changes.push(...todos.map((t) => `${i2}${t}`));
330
+ if (plan.set.size === 0 && todos.length === 0)
338
331
  changes.push(`${i2}// TODO: change the fields this Flow reacts to`);
339
332
  // When the Flow also runs on create, the insert may already have set the fields it writes.
340
333
  const unknown = flow.recordTriggerType === 'CreateAndUpdate' ? fieldsTheFlowWrites(flow) : new Set();
341
- const changesField = update.settable.some(({ field, apexValue }) => inserted[field] !== apexValue);
342
- const checks = checksFor(updateTodos.length === 0 && changesField, fieldState(fields, nullWhenUnset, unknown), 'update') ??
343
- defaultChecks('update', `Assert.isNotNull(result.Id, 'The ${object} should still exist');`);
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');`);
344
337
  const [start, ...dml] = checks.dml;
345
- return [...lines, start, ...changes, ...dml, ...(checks.after.length > 0 ? ['', ...checks.after] : [])];
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)];
346
362
  };
347
363
  const deleteBody = () => {
348
- const fields = recordFieldValues(object, settable, required);
349
- const walk = todos.length === 0 && flow.graph ? walkFlow(flow.graph, fieldState(fields, nullWhenUnset)) : undefined;
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;
350
368
  const blocked = walk?.customError
351
369
  ? flowChecks({ writes: [], customError: walk.customError }, object, variable, 'delete', i2)
352
370
  : undefined;
353
371
  return [
354
- ...newRecord(object, variable, recordFields(object, settable, required), i2, required),
372
+ ...newRecord(object, variable, recordFields(object, plan.set, required), i2, required),
355
373
  ...todos.map((t) => `${i2}${t}`),
356
374
  `${i2}insert ${variable};`,
357
375
  '',
@@ -369,13 +387,13 @@ function recordMethods(flow, required, values) {
369
387
  };
370
388
  switch (flow.recordTriggerType) {
371
389
  case 'Update':
372
- return method('runsFlowOnUpdate', updateBody());
390
+ return methods('runsFlowOnUpdate', 'update');
373
391
  case 'CreateAndUpdate':
374
- return [...method('runsFlowOnCreate', createBody()), '', ...method('runsFlowOnUpdate', updateBody())];
392
+ return [...methods('runsFlowOnCreate', 'insert'), '', ...methods('runsFlowOnUpdate', 'update')];
375
393
  case 'Delete':
376
394
  return method('runsFlowOnDelete', deleteBody());
377
395
  default:
378
- return method('runsFlowOnCreate', createBody());
396
+ return methods('runsFlowOnCreate', 'insert');
379
397
  }
380
398
  }
381
399
  function inputValue(variable) {
@@ -414,14 +432,14 @@ function inputValue(variable) {
414
432
  return 'null';
415
433
  }
416
434
  }
417
- function interviewMethod(flow, name, notes, required) {
435
+ function interviewMethod(flow, name, notes, required, walkOutputs = false) {
418
436
  const i2 = INDENT.repeat(2);
419
437
  const lines = [`${INDENT}@IsTest`, `${INDENT}static void ${name}() {`, ...notes.map((n) => `${i2}// ${n}`)];
420
438
  lines.push(`${i2}Map<String, Object> inputs = new Map<String, Object>();`);
421
439
  for (const variable of flow.variables.filter((v) => v.isInput)) {
422
440
  if (variable.dataType === 'SObject' && variable.objectType && !variable.isCollection) {
423
441
  const local = `${camel(variable.name) || 'input'}Input`;
424
- 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));
425
443
  lines.push(`${i2}insert ${local};`, `${i2}inputs.put('${escapeApexString(variable.name)}', ${local});`);
426
444
  }
427
445
  else {
@@ -429,23 +447,65 @@ function interviewMethod(flow, name, notes, required) {
429
447
  lines.push(`${i2}inputs.put('${escapeApexString(variable.name)}', ${inputValue(variable)}); // TODO: ${type}${variable.isCollection ? ' collection' : ''}`);
430
448
  }
431
449
  }
432
- 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 = [];
433
453
  for (const variable of flow.variables.filter((v) => v.isOutput)) {
434
- 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}');`);
435
459
  }
436
- 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}}`);
437
466
  return lines;
438
467
  }
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
+ }
439
499
  function platformEventMethod(flow, required, values) {
440
500
  const event = flow.object;
441
501
  const i2 = INDENT.repeat(2);
442
- const { settable, handled } = resolveCriteria(flow.filters, event, values, 'insert');
502
+ const plan = planCriteria(flow, event, values, required, 'insert');
443
503
  return [
444
504
  `${INDENT}@IsTest`,
445
505
  `${INDENT}static void runsFlowOnEvent() {`,
446
- ...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')),
447
507
  `${i2}// TODO: set the event fields this Flow reads`,
448
- ...criteriaTodos(flow, handled).map((t) => `${i2}${t}`),
508
+ ...criteriaTodos(plan).map((t) => `${i2}${t}`),
449
509
  '',
450
510
  `${i2}Test.startTest();`,
451
511
  `${i2}EventBus.publish(testEvent);`,
@@ -459,10 +519,12 @@ function platformEventMethod(flow, required, values) {
459
519
  }
460
520
  function processMethod(flow) {
461
521
  const i2 = INDENT.repeat(2);
522
+ const advice = PROCESS_BUILDER_ADVICE.split(/(?<=\.) /).map((sentence) => `${i2}// ${sentence}`);
462
523
  return [
463
524
  `${INDENT}@IsTest`,
464
525
  `${INDENT}static void runsProcess() {`,
465
- `${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.`,
466
528
  `${i2}// Insert or update a record that meets this process's criteria between startTest and stopTest.`,
467
529
  `${i2}Test.startTest();`,
468
530
  `${i2}Test.stopTest();`,
@@ -481,9 +543,18 @@ function resolveLookups(options) {
481
543
  const required = { ...options.requiredFields };
482
544
  const fieldValues = { ...options.fieldValues };
483
545
  const parents = new Map();
484
- const lookupValue = (target) => {
546
+ const lookupValue = (target, source) => {
485
547
  if (target in EXISTING_RECORD_IDS)
486
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
+ }
487
558
  if (!canInsertParent(target) || !options.requiredFields?.[target])
488
559
  return undefined;
489
560
  const variable = `${camel(target) || 'record'}Parent`;
@@ -492,7 +563,7 @@ function resolveLookups(options) {
492
563
  };
493
564
  for (const [object, fields] of Object.entries(options.lookups ?? {})) {
494
565
  for (const [field, target] of Object.entries(fields)) {
495
- const value = lookupValue(target);
566
+ const value = lookupValue(target, object);
496
567
  if (value === undefined)
497
568
  continue;
498
569
  if (required[object] && field in required[object])
@@ -503,38 +574,75 @@ function resolveLookups(options) {
503
574
  return { required, fieldValues, parents };
504
575
  }
505
576
  const METHOD_START = /^\s+static void \w+\(\) \{$/;
577
+ const PARENT_ID = /\b(\w+Parent)\.Id\b/g;
506
578
  /**
507
- * Inserts each parent record a test method uses at the top of that method. Parents get their
508
- * own required fields from the describe; their lookups stay TODOs (one level deep).
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.
509
583
  */
510
- function withParentInserts(lines, parents, required) {
584
+ function withParentInserts(lines, parents, required, original, parentFields) {
511
585
  if (parents.size === 0)
512
586
  return lines;
513
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
+ };
514
613
  const out = [];
515
614
  for (let i = 0; i < lines.length; i++) {
516
615
  out.push(lines[i]);
517
616
  if (!METHOD_START.test(lines[i]))
518
617
  continue;
519
- const body = lines.slice(i + 1, lines.indexOf(`${INDENT}}`, i)).join('\n');
520
- const used = [...parents].filter(([variable]) => new RegExp(`\\b${variable}\\.Id\\b`).test(body));
521
- for (const [variable, object] of used) {
522
- out.push(...newRecord(object, variable, recordFields(object, [], required), i2, required), `${i2}insert ${variable};`);
523
- }
618
+ const used = referenced(lines.slice(i + 1, lines.indexOf(`${INDENT}}`, i)).join('\n'));
524
619
  if (used.length > 0)
525
- out.push('');
620
+ out.push(...insertParents(used), '');
526
621
  }
527
622
  return out;
528
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
+ }
529
635
  /** Generates a starter Apex test class for a Flow from its metadata. */
530
- export function generateApexTest(source, options = {}) {
531
- const flow = withFormulaFilters(source);
636
+ export function generateApexTest(flow, options = {}) {
532
637
  const lookups = resolveLookups(options);
533
638
  const required = lookups.required;
534
639
  const values = {
535
640
  fieldValues: lookups.fieldValues,
536
641
  changedValues: options.changedValues ?? {},
537
- nullWhenUnset: options.nullWhenUnset ?? {},
642
+ unsetValues: unsetValuesOf(options),
643
+ relationships: options.relationships ?? {},
644
+ lookups: options.lookups ?? {},
645
+ parentFields: new Map(),
538
646
  };
539
647
  const className = apexTestClassName(flow.name);
540
648
  const kind = flowKind(flow);
@@ -543,7 +651,7 @@ export function generateApexTest(source, options = {}) {
543
651
  switch (kind) {
544
652
  case 'record':
545
653
  description = `Record-triggered on ${flow.object} (${flow.recordTriggerType ?? 'Create'}, ${flow.triggerType}).`;
546
- methods = recordMethods(flow, required, values);
654
+ methods = recordMethods(flow, required, values, new Set(lookups.parents.values()));
547
655
  break;
548
656
  case 'platformEvent':
549
657
  description = `Triggered by the platform event ${flow.object}.`;
@@ -560,13 +668,13 @@ export function generateApexTest(source, options = {}) {
560
668
  break;
561
669
  case 'autolaunched':
562
670
  description = 'Autolaunched (no trigger).';
563
- methods = interviewMethod(flow, 'runsFlow', [], required);
671
+ methods = interviewMethod(flow, 'runsFlow', [], required, true);
564
672
  break;
565
673
  default:
566
674
  description = `Process type ${flow.processType ?? 'unknown'}.`;
567
675
  methods = processMethod(flow);
568
676
  }
569
- methods = withParentInserts(methods, lookups.parents, options.requiredFields ?? {});
677
+ methods = withParentInserts(methods, lookups.parents, required, options.requiredFields ?? {}, values.parentFields);
570
678
  const body = [...header(flow, description), `private class ${className} {`, ...methods, '}', ''].join('\n');
571
679
  return { className, body, kind };
572
680
  }