sf-flow-coverage 0.3.0 → 0.4.1

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