sf-flow-coverage 0.2.0 → 0.3.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 (39) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +30 -3
  3. package/lib/commands/flowcov/gate.d.ts +1 -0
  4. package/lib/commands/flowcov/gate.js +12 -1
  5. package/lib/commands/flowcov/gate.js.map +1 -1
  6. package/lib/core/apexTemplate.d.ts +8 -2
  7. package/lib/core/apexTemplate.js +304 -54
  8. package/lib/core/apexTemplate.js.map +1 -1
  9. package/lib/core/filterFormula.d.ts +10 -0
  10. package/lib/core/filterFormula.js +153 -0
  11. package/lib/core/filterFormula.js.map +1 -0
  12. package/lib/core/flowFingerprint.d.ts +27 -0
  13. package/lib/core/flowFingerprint.js +128 -0
  14. package/lib/core/flowFingerprint.js.map +1 -0
  15. package/lib/core/flowGraph.d.ts +94 -0
  16. package/lib/core/flowGraph.js +288 -0
  17. package/lib/core/flowGraph.js.map +1 -0
  18. package/lib/core/flowValues.d.ts +14 -0
  19. package/lib/core/flowValues.js +43 -0
  20. package/lib/core/flowValues.js.map +1 -0
  21. package/lib/core/flowXml.d.ts +1 -1
  22. package/lib/core/flowXml.js +6 -39
  23. package/lib/core/flowXml.js.map +1 -1
  24. package/lib/core/gate.d.ts +10 -1
  25. package/lib/core/gate.js +45 -6
  26. package/lib/core/gate.js.map +1 -1
  27. package/lib/core/orgCoverageSource.d.ts +6 -0
  28. package/lib/core/orgCoverageSource.js +43 -8
  29. package/lib/core/orgCoverageSource.js.map +1 -1
  30. package/lib/core/requiredFields.d.ts +30 -2
  31. package/lib/core/requiredFields.js +114 -7
  32. package/lib/core/requiredFields.js.map +1 -1
  33. package/lib/core/scaffold.js +31 -4
  34. package/lib/core/scaffold.js.map +1 -1
  35. package/lib/core/types.d.ts +29 -1
  36. package/messages/flowcov.gate.md +16 -0
  37. package/messages/flowcov.scaffold.md +3 -1
  38. package/oclif.manifest.json +18 -3
  39. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.0](https://github.com/mcarvin8/sf-flow-coverage/compare/v0.2.0...v0.3.0) (2026-11-20)
4
+
5
+
6
+ ### Features
7
+
8
+ * **gate:** compare changed Flows with the org version via --content-check ([#9](https://github.com/mcarvin8/sf-flow-coverage/issues/9)) ([841c417](https://github.com/mcarvin8/sf-flow-coverage/commit/841c4170e361a0669727b851823ecfe4d00b9a0d))
9
+ * **gate:** fail Flows whose org version was likely deployed inactive ([#7](https://github.com/mcarvin8/sf-flow-coverage/issues/7)) ([5564801](https://github.com/mcarvin8/sf-flow-coverage/commit/55648016d9be109bdc853ef300d70d6c33bb117e))
10
+ * **scaffold:** assert what record-triggered Flows do ([#13](https://github.com/mcarvin8/sf-flow-coverage/issues/13)) ([9ef29b5](https://github.com/mcarvin8/sf-flow-coverage/commit/9ef29b5245b6f25d660005231b3e94907c32a2ed))
11
+ * **scaffold:** insert parent records for required and criteria lookups ([#12](https://github.com/mcarvin8/sf-flow-coverage/issues/12)) ([cc57296](https://github.com/mcarvin8/sf-flow-coverage/commit/cc57296d58439531b5f2f2963e2da02ddc158484))
12
+ * **scaffold:** meet comparison, string, and IsChanged entry criteria ([#10](https://github.com/mcarvin8/sf-flow-coverage/issues/10)) ([5451dbb](https://github.com/mcarvin8/sf-flow-coverage/commit/5451dbb66921d59ad00812ed18c060dfeb1c992e))
13
+ * **scaffold:** meet simple entry-criteria formulas ([#11](https://github.com/mcarvin8/sf-flow-coverage/issues/11)) ([1a5b8e4](https://github.com/mcarvin8/sf-flow-coverage/commit/1a5b8e4257462e51092077d9746dcc6ad3af1e9d))
14
+
3
15
  ## [0.2.0](https://github.com/mcarvin8/sf-flow-coverage/compare/v0.1.0...v0.2.0) (2026-11-20)
4
16
 
5
17
 
package/README.md CHANGED
@@ -4,6 +4,7 @@
4
4
  [![Downloads/week](https://img.shields.io/npm/dw/sf-flow-coverage.svg)](https://npmjs.org/package/sf-flow-coverage)
5
5
  [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://raw.githubusercontent.com/mcarvin8/sf-flow-coverage/refs/heads/main/LICENSE.md)
6
6
  [![codecov](https://codecov.io/gh/mcarvin8/sf-flow-coverage/graph/badge.svg?token=7R49P3RQ47)](https://codecov.io/gh/mcarvin8/sf-flow-coverage)
7
+ [![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fmcarvin8%2Fsf-flow-coverage%2Fmain)](https://dashboard.stryker-mutator.io/reports/github.com/mcarvin8/sf-flow-coverage/main)
7
8
 
8
9
  Get your Salesforce org ready to deploy Flows as active.
9
10
 
@@ -112,13 +113,16 @@ Require Apex test coverage for every Flow a pull request changes.
112
113
  ```
113
114
  USAGE
114
115
  $ sf flowcov gate -o <value> [--json] [--flags-dir <value>] [--api-version <value>] [--from <value> | --flow
115
- <value>...] [--to <value>] [-d <value>] [--min-element-coverage <value>]
116
+ <value>...] [--to <value>] [-d <value>] [--min-element-coverage <value>] [--content-check warn|fail|off]
116
117
 
117
118
  FLAGS
118
119
  -d, --project-dir=<value> [default: .] Git repository to read changed Flows from.
119
120
  -o, --target-org=<value> (required) Username or alias of the target org. Not required if the `target-org`
120
121
  configuration variable is already set.
121
122
  --api-version=<value> Override the api version used for api requests made by this command
123
+ --content-check=<option> [default: warn] What to do when a changed Flow's content differs from the org's
124
+ version.
125
+ <options: warn|fail|off>
122
126
  --flow=<value>... Flow API name to check. Use instead of --from to skip git.
123
127
  --from=<value> Git ref the pull request merges into (the gate compares from the merge base of
124
128
  this ref).
@@ -140,6 +144,15 @@ DESCRIPTION
140
144
  with `sf apex run test --code-coverage` before running the gate. Without `--code-coverage`, Salesforce records no Flow
141
145
  coverage. Flows that don't count toward deploy-as-active (screen Flows, inactive Flows) are skipped.
142
146
 
147
+ The gate also fails a Flow when the org has no active version of it, or when its active version is older than its
148
+ latest version. Both usually mean the branch was deployed inactive, so the org's coverage doesn't belong to the
149
+ version in the pull request.
150
+
151
+ With --from, the gate also compares each changed Flow at --to with the org's version: process type, start trigger and
152
+ entry criteria, and the names of its elements and resources. A difference usually means the branch wasn't deployed to
153
+ the org. By default this is a warning; use --content-check to fail instead, or to skip the comparison. The comparison
154
+ doesn't look inside elements, so it can miss a change that only edits an existing element.
155
+
143
156
  Exits with code 1 when any Flow fails.
144
157
 
145
158
  EXAMPLES
@@ -151,9 +164,19 @@ EXAMPLES
151
164
 
152
165
  $ sf flowcov gate --target-org ci-sandbox --from origin/main --min-element-coverage 60
153
166
 
167
+ Fail when the org runs a different version of a changed Flow than the branch:
168
+
169
+ $ sf flowcov gate --target-org ci-sandbox --from origin/main --content-check fail
170
+
154
171
  Check named Flows without git:
155
172
 
156
173
  $ sf flowcov gate --target-org ci-sandbox --flow Account_After_Save --flow Close_Cases
174
+
175
+ FLAG DESCRIPTIONS
176
+ --content-check=warn|fail|off What to do when a changed Flow's content differs from the org's version.
177
+
178
+ "warn" prints a warning, "fail" fails a Flow that would otherwise pass, and "off" skips the comparison (and its one
179
+ Tooling API query per Flow). Only applies with --from.
157
180
  ```
158
181
 
159
182
  _See code: [src/commands/flowcov/gate.ts](https://github.com/mcarvin8/sf-flow-coverage/blob/main/src/commands/flowcov/gate.ts)_
@@ -241,8 +264,12 @@ DESCRIPTION
241
264
  record-triggered Flows get a record built from the trigger object and entry criteria, autolaunched Flows are started
242
265
  with Flow.Interview and their input variables, and platform event Flows publish the event. When a target org is
243
266
  available (--target-org or a default org), the command describes each object the test creates and fills in its
244
- required fields and any fields the entry criteria require to be set (IsNull false). The generated tests have TODOs for
245
- anything it can't fill in and placeholder assertions.
267
+ required fields, the fields the entry criteria need, and parent records for required lookups.
268
+
269
+ For record-triggered Flows, the command follows the Flow's elements for the record the test creates. It asserts the
270
+ fields the Flow is certain to set, and when the Flow is certain to stop the save with a custom error, the test expects
271
+ that error. Fields the Flow sets only on a decision outcome the command can't predict get commented-out assertions.
272
+ The generated tests have TODOs for anything the command can't fill in.
246
273
 
247
274
  Only Apex tests count toward deploying Flows as active, so this command generates Apex, not Flow Builder tests.
248
275
 
@@ -12,6 +12,7 @@ export default class FlowcovGate extends SfCommand<GateResult> {
12
12
  flow: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
13
  'project-dir': import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
14
14
  'min-element-coverage': import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
15
+ 'content-check': import("@oclif/core/interfaces").OptionFlag<"fail" | "off" | "warn", import("@oclif/core/interfaces").CustomOptions>;
15
16
  };
16
17
  run(): Promise<GateResult>;
17
18
  }
@@ -37,6 +37,12 @@ export default class FlowcovGate extends SfCommand {
37
37
  min: 0,
38
38
  max: 100,
39
39
  }),
40
+ 'content-check': Flags.option({
41
+ summary: messages.getMessage('flags.content-check.summary'),
42
+ description: messages.getMessage('flags.content-check.description'),
43
+ options: ['warn', 'fail', 'off'],
44
+ default: 'warn',
45
+ })(),
40
46
  };
41
47
  async run() {
42
48
  const { flags } = await this.parse(FlowcovGate);
@@ -59,6 +65,7 @@ export default class FlowcovGate extends SfCommand {
59
65
  source: new OrgCoverageSource(toolingQuery(connection)),
60
66
  candidates,
61
67
  minElementCoverage: flags['min-element-coverage'],
68
+ contentCheck: flags['content-check'],
62
69
  });
63
70
  this.table({
64
71
  data: result.flows.map((f) => ({
@@ -68,12 +75,16 @@ export default class FlowcovGate extends SfCommand {
68
75
  Reason: f.reason,
69
76
  })),
70
77
  });
78
+ for (const flow of result.flows) {
79
+ for (const warning of flow.warnings ?? [])
80
+ this.warn(`${flow.flowName}: ${warning}`);
81
+ }
71
82
  if (result.passed) {
72
83
  this.logSuccess(`Flow coverage gate passed for ${result.flows.length} Flow(s).`);
73
84
  }
74
85
  else {
75
86
  const failed = result.flows.filter((f) => f.status === 'fail').length;
76
- this.warn(`Flow coverage gate failed: ${failed} Flow(s) need Apex test coverage.`);
87
+ this.warn(`Flow coverage gate failed for ${failed} Flow(s). See the Reason column.`);
77
88
  process.exitCode = 1;
78
89
  }
79
90
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"gate.js","sourceRoot":"","sources":["../../../src/commands/flowcov/gate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAE/D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAsB,MAAM,oBAAoB,CAAC;AAC3F,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG1D,QAAQ,CAAC,kCAAkC,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7D,MAAM,QAAQ,GAAG,QAAQ,CAAC,YAAY,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAC;AAE3E,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,SAAqB;IACrD,MAAM,CAAmB,OAAO,GAAG,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;IAClE,MAAM,CAAmB,WAAW,GAAG,QAAQ,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;IAC1E,MAAM,CAAmB,QAAQ,GAAG,QAAQ,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;IAErE,MAAM,CAAmB,KAAK,GAAG;QACtC,YAAY,EAAE,KAAK,CAAC,WAAW,EAAE;QACjC,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE;QACpC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC;YACjB,OAAO,EAAE,QAAQ,CAAC,UAAU,CAAC,oBAAoB,CAAC;YAClD,SAAS,EAAE,CAAC,MAAM,CAAC;SACpB,CAAC;QACF,E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,CAAC,CAAC,sBAAsB,GAAG;gBAChG,MAAM,EAAE,CAAC,CAAC,MAAM;aACjB,CAAC,CAAC;SACJ,CAAC,CAAC;QAEH,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;YAChC,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,QAAQ,IAAI,EAAE;gBAAE,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC,CAAC;QACvF,CAAC;QAED,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAClB,IAAI,CAAC,UAAU,CAAC,iCAAiC,MAAM,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,CAAC;QACnF,CAAC;aAAM,CAAC;YACN,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,CAAC;YACtE,IAAI,CAAC,IAAI,CAAC,iCAAiC,MAAM,kCAAkC,CAAC,CAAC;YACrF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"}
@@ -1,4 +1,4 @@
1
- import type { RequiredFieldMap } from './requiredFields.js';
1
+ import { type RequiredFieldMap } from './requiredFields.js';
2
2
  import type { FlowMetadata } from './types.js';
3
3
  export type GeneratedApexTest = {
4
4
  className: string;
@@ -14,7 +14,13 @@ export type GenerateOptions = {
14
14
  requiredFields?: RequiredFieldMap;
15
15
  /** A value for every field the org describe can fill, per object. Used to meet `IsNull false` entry criteria. */
16
16
  fieldValues?: RequiredFieldMap;
17
+ /** A second value per field, different from `fieldValues`. Used to meet `IsChanged true` entry criteria. */
18
+ changedValues?: RequiredFieldMap;
19
+ /** The object each lookup field points to, per object. Fills required and `IsNull false` lookups. */
20
+ lookups?: Record<string, Record<string, string>>;
21
+ /** Fields that stay empty when a test doesn't set them, per object. Lets assertions follow the Flow's decisions. */
22
+ nullWhenUnset?: Record<string, string[]>;
17
23
  };
18
24
  /** Generates a starter Apex test class for a Flow from its metadata. */
19
- export declare function generateApexTest(flow: FlowMetadata, options?: GenerateOptions): GeneratedApexTest;
25
+ export declare function generateApexTest(source: FlowMetadata, options?: GenerateOptions): GeneratedApexTest;
20
26
  export declare function apexClassMetaXml(apiVersion: string): string;
@@ -1,4 +1,7 @@
1
+ import { parseFilterFormula } from './filterFormula.js';
2
+ import { walkFlow } from './flowGraph.js';
1
3
  import { escapeApexString } from './flowXml.js';
4
+ import { canInsertParent, EXISTING_RECORD_IDS } from './requiredFields.js';
2
5
  const MAX_CLASS_NAME = 40;
3
6
  const CLASS_SUFFIX = '_FlowTest';
4
7
  const INDENT = ' ';
@@ -58,26 +61,82 @@ function header(flow, description) {
58
61
  function isSimpleField(field) {
59
62
  return /^[A-Za-z][A-Za-z0-9_]*$/.test(field);
60
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
+ }
61
99
  /**
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.
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.
64
104
  */
65
- function resolveCriteria(filters, object, fieldValues) {
105
+ function resolveCriteria(filters, object, values, context) {
66
106
  const settable = [];
67
107
  const handled = new Set();
108
+ const changed = [];
68
109
  for (const filter of filters) {
69
110
  if (!isSimpleField(filter.field))
70
111
  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];
112
+ if (filter.operator === 'IsChanged') {
113
+ if (context === 'update')
114
+ changed.push(filter);
115
+ continue;
116
+ }
117
+ const apexValue = filterValue(filter, object, values);
76
118
  if (apexValue === undefined)
77
119
  continue;
78
120
  settable.push({ field: filter.field, apexValue });
79
121
  handled.add(filter);
80
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
+ }
81
140
  return { settable, handled };
82
141
  }
83
142
  function criteriaTodos(flow, handled) {
@@ -85,6 +144,10 @@ function criteriaTodos(flow, handled) {
85
144
  for (const filter of flow.filters) {
86
145
  if (handled.has(filter))
87
146
  continue;
147
+ if (filter.formulaTerm !== undefined) {
148
+ todos.push(`// TODO: entry criteria formula term: ${filter.formulaTerm.replace(/\s+/g, ' ')}`);
149
+ continue;
150
+ }
88
151
  const value = filter.rawValue === undefined ? '' : ` ${filter.rawValue}`;
89
152
  todos.push(`// TODO: entry criteria: ${filter.field} ${filter.operator}${value}`);
90
153
  }
@@ -95,15 +158,109 @@ function criteriaTodos(flow, handled) {
95
158
  }
96
159
  return todos;
97
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 };
170
+ }
98
171
  /** Described required fields win over the built-in list for standard objects. */
99
172
  function knownRequired(object, required) {
100
173
  return required[object] ?? REQUIRED_FIELDS[object];
101
174
  }
102
- function recordFields(object, criteria, required) {
175
+ function recordFieldValues(object, criteria, required) {
103
176
  const fields = new Map(Object.entries(knownRequired(object, required) ?? {}));
104
177
  for (const assignment of criteria)
105
178
  fields.set(assignment.field, assignment.apexValue);
106
- return [...fields].map(([field, value]) => `${field} = ${value}`);
179
+ return fields;
180
+ }
181
+ function recordFields(object, criteria, required) {
182
+ return [...recordFieldValues(object, criteria, required)].map(([field, value]) => `${field} = ${value}`);
183
+ }
184
+ /**
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.
187
+ */
188
+ function fieldState(values, nullWhenUnset, unknown = new Set()) {
189
+ const state = new Map();
190
+ for (const field of nullWhenUnset)
191
+ 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);
196
+ }
197
+ return state;
198
+ }
199
+ function errorText(message) {
200
+ // Merge fields in the message vary per record; match the text before the first one.
201
+ const fixed = message?.split('{!')[0].trim();
202
+ return fixed ? fixed : undefined;
203
+ }
204
+ /**
205
+ * 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.
208
+ */
209
+ function flowChecks(walk, object, variable, dml, i2) {
210
+ const i3 = INDENT.repeat(3);
211
+ if (walk.customError) {
212
+ const message = errorText(walk.customError.message);
213
+ return {
214
+ dml: [
215
+ `${i2}Test.startTest();`,
216
+ `${i2}try {`,
217
+ `${i3}${dml} ${variable};`,
218
+ `${i3}Assert.fail('${escapeApexString(walk.customError.element)} should block this save with a custom error');`,
219
+ `${i2}} catch (DmlException e) {`,
220
+ message
221
+ ? `${i3}Assert.isTrue(e.getMessage().contains('${escapeApexString(message)}'), e.getMessage());`
222
+ : `${i3}Assert.isNotNull(e.getMessage(), 'The custom error should have a message');`,
223
+ `${i2}}`,
224
+ `${i2}Test.stopTest();`,
225
+ ],
226
+ after: [],
227
+ };
228
+ }
229
+ const maybe = new Set((walk.undecided?.outcomes ?? []).flatMap((o) => o.writes.map((w) => w.field)));
230
+ const certain = new Map();
231
+ for (const write of walk.writes)
232
+ certain.set(write.field, write);
233
+ const lines = [];
234
+ for (const [field, write] of certain) {
235
+ const value = write.value.apexValue;
236
+ if (value !== undefined && !maybe.has(field)) {
237
+ lines.push(`${i2}Assert.areEqual(${value}, result.${field}, '${escapeApexString(write.element)} should set ${field}');`);
238
+ }
239
+ else {
240
+ const reason = maybe.has(field) ? ', and a later branch may change it' : '';
241
+ lines.push(`${i2}// TODO: ${write.element} sets ${field} to ${write.value.rawValue ?? 'a value'}${reason}; assert it`);
242
+ }
243
+ }
244
+ for (const outcome of walk.undecided?.outcomes ?? []) {
245
+ lines.push(`${i2}// TODO: when ${walk.undecided?.element} takes "${outcome.label}", the Flow also:`);
246
+ for (const write of outcome.writes) {
247
+ lines.push(write.value.apexValue === undefined
248
+ ? `${i2}// sets ${write.field} to ${write.value.rawValue ?? 'a value'} (${write.element})`
249
+ : `${i2}// Assert.areEqual(${write.value.apexValue}, result.${write.field}, '${escapeApexString(write.element)} should set ${write.field}');`);
250
+ }
251
+ if (outcome.customError)
252
+ lines.push(`${i2}// can block the save with a custom error`);
253
+ }
254
+ if (lines.length === 0)
255
+ return undefined;
256
+ const fields = [...new Set([...certain.keys(), ...maybe])];
257
+ return {
258
+ 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
+ ],
263
+ };
107
264
  }
108
265
  function newRecord(object, variable, fields, indent, required) {
109
266
  const lines = [];
@@ -119,65 +276,97 @@ function newRecord(object, variable, fields, indent, required) {
119
276
  lines.push(`${indent}// TODO: set the required fields for ${object}`);
120
277
  return lines;
121
278
  }
122
- function recordMethods(flow, required, fieldValues) {
279
+ /** Every field the Flow can write on the triggering record, anywhere in its elements. */
280
+ function fieldsTheFlowWrites(flow) {
281
+ return new Set(Object.values(flow.graph?.nodes ?? {}).flatMap((node) => node.kind === 'write' ? node.writes.map((w) => w.field) : []));
282
+ }
283
+ function recordMethods(flow, required, values) {
123
284
  const object = flow.object;
124
285
  // A fixed name avoids Apex reserved words (`case`, `order`, `group`) that object names produce.
125
286
  const variable = 'testRecord';
126
- const { settable, handled } = resolveCriteria(flow.filters, object, fieldValues);
287
+ const { settable, handled } = resolveCriteria(flow.filters, object, values, 'insert');
127
288
  const todos = criteriaTodos(flow, handled);
128
289
  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
- ];
290
+ const nullWhenUnset = values.nullWhenUnset[object] ?? [];
134
291
  const method = (name, body) => [
135
292
  `${INDENT}@IsTest`,
136
293
  `${INDENT}static void ${name}() {`,
137
294
  ...body,
138
295
  `${INDENT}}`,
139
296
  ];
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
- ];
297
+ const defaultChecks = (dml, assertion) => ({
298
+ dml: [`${i2}Test.startTest();`, `${i2}${dml} ${variable};`, `${i2}Test.stopTest();`],
299
+ after: [
300
+ `${i2}${object} result = [SELECT Id FROM ${object} WHERE Id = :${variable}.Id];`,
301
+ `${i2}// TODO: query and assert the fields this Flow sets`,
302
+ `${i2}${assertion}`,
303
+ ],
304
+ });
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
+ ];
318
+ };
150
319
  const updateBody = () => {
320
+ const update = resolveCriteria(flow.filters, object, values, 'update');
321
+ const updateTodos = criteriaTodos(flow, update.handled);
151
322
  const lines = [
152
323
  ...newRecord(object, variable, recordFields(object, [], required), i2, required),
153
324
  `${i2}insert ${variable};`,
154
325
  '',
155
- `${i2}Test.startTest();`,
156
326
  ];
157
327
  const inserted = knownRequired(object, required) ?? {};
328
+ const fields = recordFieldValues(object, [], required);
329
+ const changes = [];
158
330
  // Skip values the insert already set: assigning them again wouldn't change the record.
159
- for (const { field, apexValue } of settable) {
331
+ for (const { field, apexValue } of update.settable) {
332
+ fields.set(field, apexValue);
160
333
  if (inserted[field] !== apexValue)
161
- lines.push(`${i2}${variable}.${field} = ${apexValue};`);
334
+ changes.push(`${i2}${variable}.${field} = ${apexValue};`);
162
335
  }
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');`)];
336
+ changes.push(...updateTodos.map((t) => `${i2}${t}`));
337
+ if (update.settable.length === 0 && updateTodos.length === 0)
338
+ changes.push(`${i2}// TODO: change the fields this Flow reacts to`);
339
+ // When the Flow also runs on create, the insert may already have set the fields it writes.
340
+ 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');`);
344
+ const [start, ...dml] = checks.dml;
345
+ return [...lines, start, ...changes, ...dml, ...(checks.after.length > 0 ? ['', ...checks.after] : [])];
346
+ };
347
+ const deleteBody = () => {
348
+ const fields = recordFieldValues(object, settable, required);
349
+ const walk = todos.length === 0 && flow.graph ? walkFlow(flow.graph, fieldState(fields, nullWhenUnset)) : undefined;
350
+ const blocked = walk?.customError
351
+ ? flowChecks({ writes: [], customError: walk.customError }, object, variable, 'delete', i2)
352
+ : undefined;
353
+ return [
354
+ ...newRecord(object, variable, recordFields(object, settable, required), i2, required),
355
+ ...todos.map((t) => `${i2}${t}`),
356
+ `${i2}insert ${variable};`,
357
+ '',
358
+ ...(blocked
359
+ ? blocked.dml
360
+ : [
361
+ `${i2}Test.startTest();`,
362
+ `${i2}delete ${variable};`,
363
+ `${i2}Test.stopTest();`,
364
+ '',
365
+ `${i2}// TODO: assert what this Flow does when the record is deleted`,
366
+ `${i2}Assert.areEqual(0, [SELECT COUNT() FROM ${object} WHERE Id = :${variable}.Id], 'The ${object} should be deleted');`,
367
+ ]),
368
+ ];
168
369
  };
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
370
  switch (flow.recordTriggerType) {
182
371
  case 'Update':
183
372
  return method('runsFlowOnUpdate', updateBody());
@@ -247,10 +436,10 @@ function interviewMethod(flow, name, notes, required) {
247
436
  lines.push(`${i2}Assert.isNotNull(interview, 'The Flow interview should run');`, `${INDENT}}`);
248
437
  return lines;
249
438
  }
250
- function platformEventMethod(flow, required, fieldValues) {
439
+ function platformEventMethod(flow, required, values) {
251
440
  const event = flow.object;
252
441
  const i2 = INDENT.repeat(2);
253
- const { settable, handled } = resolveCriteria(flow.filters, event, fieldValues);
442
+ const { settable, handled } = resolveCriteria(flow.filters, event, values, 'insert');
254
443
  return [
255
444
  `${INDENT}@IsTest`,
256
445
  `${INDENT}static void runsFlowOnEvent() {`,
@@ -283,10 +472,70 @@ function processMethod(flow) {
283
472
  `${INDENT}}`,
284
473
  ];
285
474
  }
475
+ /**
476
+ * Fills lookup fields with an Id: an existing record's (the running user, the standard price
477
+ * book), or a parent record's the test inserts when the describe gives the parent's required
478
+ * fields. Other lookups keep their TODO.
479
+ */
480
+ function resolveLookups(options) {
481
+ const required = { ...options.requiredFields };
482
+ const fieldValues = { ...options.fieldValues };
483
+ const parents = new Map();
484
+ const lookupValue = (target) => {
485
+ if (target in EXISTING_RECORD_IDS)
486
+ return EXISTING_RECORD_IDS[target];
487
+ if (!canInsertParent(target) || !options.requiredFields?.[target])
488
+ return undefined;
489
+ const variable = `${camel(target) || 'record'}Parent`;
490
+ parents.set(variable, target);
491
+ return `${variable}.Id`;
492
+ };
493
+ for (const [object, fields] of Object.entries(options.lookups ?? {})) {
494
+ for (const [field, target] of Object.entries(fields)) {
495
+ const value = lookupValue(target);
496
+ if (value === undefined)
497
+ continue;
498
+ if (required[object] && field in required[object])
499
+ required[object] = { ...required[object], [field]: value };
500
+ fieldValues[object] = { ...fieldValues[object], [field]: value };
501
+ }
502
+ }
503
+ return { required, fieldValues, parents };
504
+ }
505
+ const METHOD_START = /^\s+static void \w+\(\) \{$/;
506
+ /**
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).
509
+ */
510
+ function withParentInserts(lines, parents, required) {
511
+ if (parents.size === 0)
512
+ return lines;
513
+ const i2 = INDENT.repeat(2);
514
+ const out = [];
515
+ for (let i = 0; i < lines.length; i++) {
516
+ out.push(lines[i]);
517
+ if (!METHOD_START.test(lines[i]))
518
+ 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
+ }
524
+ if (used.length > 0)
525
+ out.push('');
526
+ }
527
+ return out;
528
+ }
286
529
  /** Generates a starter Apex test class for a Flow from its metadata. */
287
- export function generateApexTest(flow, options = {}) {
288
- const required = options.requiredFields ?? {};
289
- const fieldValues = options.fieldValues ?? {};
530
+ export function generateApexTest(source, options = {}) {
531
+ const flow = withFormulaFilters(source);
532
+ const lookups = resolveLookups(options);
533
+ const required = lookups.required;
534
+ const values = {
535
+ fieldValues: lookups.fieldValues,
536
+ changedValues: options.changedValues ?? {},
537
+ nullWhenUnset: options.nullWhenUnset ?? {},
538
+ };
290
539
  const className = apexTestClassName(flow.name);
291
540
  const kind = flowKind(flow);
292
541
  let description;
@@ -294,11 +543,11 @@ export function generateApexTest(flow, options = {}) {
294
543
  switch (kind) {
295
544
  case 'record':
296
545
  description = `Record-triggered on ${flow.object} (${flow.recordTriggerType ?? 'Create'}, ${flow.triggerType}).`;
297
- methods = recordMethods(flow, required, fieldValues);
546
+ methods = recordMethods(flow, required, values);
298
547
  break;
299
548
  case 'platformEvent':
300
549
  description = `Triggered by the platform event ${flow.object}.`;
301
- methods = platformEventMethod(flow, required, fieldValues);
550
+ methods = platformEventMethod(flow, required, values);
302
551
  break;
303
552
  case 'scheduled':
304
553
  description = 'Schedule-triggered. Apex tests cannot fire the schedule, so this test starts the Flow directly.';
@@ -317,6 +566,7 @@ export function generateApexTest(flow, options = {}) {
317
566
  description = `Process type ${flow.processType ?? 'unknown'}.`;
318
567
  methods = processMethod(flow);
319
568
  }
569
+ methods = withParentInserts(methods, lookups.parents, options.requiredFields ?? {});
320
570
  const body = [...header(flow, description), `private class ${className} {`, ...methods, '}', ''].join('\n');
321
571
  return { className, body, kind };
322
572
  }