Open History to see the last commit
1/**
2 * An oracle enforces its laws only in the tests that run. This rule reports
3 * the edits that stop a law from running while every test still passes:
4 *
5 * - `.only` on a test or suite, which silences every other law in the file.
6 * - `.skip`, `.todo`, or Playwright's `.fixme` on a test or suite that has a
7 * body, inline or passed by name. An empty body is a placeholder that
8 * disables nothing, such as the test that a replay registers when it does
9 * not select its property.
10 * - A test that skips itself through its context, as in `ctx.skip()`.
11 * - `.skipIf(condition)` or `.runIf(condition)`, unless the call is
12 * `.skipIf(oracleReplayRequested())` or `.skipIf(oracleReplaySkips(...))`.
13 * A replay may stand a test aside, and nothing else may switch an oracle
14 * test off. The shared helpers in oracle-config are false in an ordinary
15 * run, so no condition built from them can turn a test off there.
16 * - A test modifier passed around as a value, as in
17 * `const run = replaying ? it.skip : it`. The rule cannot see what such an
18 * alias switches off. `oracleReplayTest(test, property)` selects a replay.
19 * - A test registered under a condition, or after an early `return`, unless
20 * the condition is a shared replay helper and the test registers when the
21 * helper is false, as in `if (!oracleReplayRequested())`. Each helper is
22 * false in an ordinary run, so such a test runs there. An early `throw`
23 * fails the run loudly, and `continue` filters a loop's data, so neither
24 * guards a registration. A registration made through `oracleReplayTest`
25 * or `oracleCalibrationTest`, directly or through a constant bound to its
26 * result, or through a renamed import such as `import { it as vitestIt }`,
27 * is checked as a registration of its test.
28 * - Playwright's runtime `test.skip()` or `test.fixme()` inside a test,
29 * unless its condition is `browserName !== '<browser>'`: a control that
30 * only one browser supports.
31 * - A generated property limited to one run that pins no history: a literal
32 * `numRuns` of 1 or 0, or a base of 1 passed to the run helpers. One random
33 * history is not a generated property. A witness pins its history with a
34 * recorded `path` (a literal, or a failure's `counterexamplePath`) or with
35 * a seed that is a number literal or a constant bound to one. A replay from
36 * configuration takes its options from `oraclePropertyOptions`, which
37 * returns one run for a path replay.
38 * - A literal run count above 1 that pins no history. It does not scale with
39 * `TANSTACK_DB_ORACLE_RUNS_MULTIPLIER`, so `oracleRuns` must wrap it.
40 * - A private replay variable: a `process.env` read whose name ends in
41 * `_SEED`, `_PATH`, `_PROPERTY`, or `_RUNS`, other than the shared
42 * `TANSTACK_DB_ORACLE_SEED`, `TANSTACK_DB_ORACLE_PATH`, and
43 * `TANSTACK_DB_ORACLE_PROPERTY`. The replay manifest, the guarded replay
44 * runner, and the retired-variable check see only the shared variables.
45 *
46 * The rule has no inline exception. A known gap is pinned with `it.fails` on
47 * a fixed seed, not skipped.
48 *
49 * The rule cannot see a run count lowered to any value above 1, a run count
50 * or seed held in a variable that is not a constant bound to a number, a call
51 * to a local helper that registers tests under a condition, or a table built
52 * by a function that returns different items in different runs. Reviewers
53 * still check those.
54 */
55
56import {
57 aliasModifiers,
58 calleeChain,
59 conditionalModifiers,
60 disablingModifiers,
61 findVariable,
62 isFunction,
63 isSharedHelperCall,
64 isTestRoot,
65 registrationMembers,
66 selectionHelpers,
67 testRoots,
68} from '../registration.js'
69
70const replayConditions = new Set([`oracleReplayRequested`, `oracleReplaySkips`])
71// oracle-config implements replay selection, so its options may carry a
72// replay path from configuration.
73const replaySelectionModule =
74 /(^|[/\\])packages[/\\]db[/\\]tests[/\\]oracle-config\.ts$/
75// The variables that select a replay. Any other variable whose name ends
76// in one of these suffixes is a private replay selection.
77const sharedReplayVariables = new Set([
78 `TANSTACK_DB_ORACLE_PATH`,
79 `TANSTACK_DB_ORACLE_PROPERTY`,
80 `TANSTACK_DB_ORACLE_SEED`,
81])
82const replayVariableName = /_(PATH|PROPERTY|RUNS|SEED)$/
83const runHelpers = new Set([
84 `oraclePropertyOptions`,
85 `oracleRandomParameters`,
86 `oracleRuns`,
87])
88
89/** A test body that runs something: a named function or a non-empty one. */
90function hasBody(body) {
91 if (!isFunction(body)) return true
92 return body.body.type !== `BlockStatement` || body.body.body.length > 0
93}
94
95function isStringLike(node) {
96 return (
97 node.type === `TemplateLiteral` ||
98 (node.type === `Literal` && typeof node.value === `string`)
99 )
100}
101
102/** The `skipIf` or `runIf` call in a callee chain, if there is one. */
103function registrationCondition(callee) {
104 let node = callee
105 while (node.type === `CallExpression` || node.type === `MemberExpression`) {
106 if (
107 node.type === `CallExpression` &&
108 node.callee.type === `MemberExpression` &&
109 conditionalModifiers.has(node.callee.property.name)
110 ) {
111 return { name: node.callee.property.name, args: node.arguments }
112 }
113 node = node.type === `CallExpression` ? node.callee : node.object
114 }
115 return undefined
116}
117
118/** Exactly `.skipIf(<shared replay condition>)`, not negated. */
119function isReplaySelection({ name, args }, sourceCode) {
120 return (
121 name === `skipIf` &&
122 args.length === 1 &&
123 isSharedHelperCall(args[0], replayConditions, sourceCode)
124 )
125}
126
127/**
128 * Whether a statement always returns from its function. A `throw` fails the
129 * run loudly, and `continue` or `break` skips one item of a loop's data, as
130 * `.filter` would, so neither guards a registration.
131 */
132function returns(statement) {
133 if (statement === null || statement === undefined) return false
134 if (statement.type === `ReturnStatement`) return true
135 if (statement.type === `BlockStatement`) {
136 return returns(statement.body.at(-1))
137 }
138 if (statement.type === `IfStatement`) {
139 return returns(statement.consequent) && returns(statement.alternate)
140 }
141 return false
142}
143
144function isEmptyArray(node) {
145 return node?.type === `ArrayExpression` && node.elements.length === 0
146}
147
148/**
149 * The conditions that decide which items a loop's iterable or an `.each()`
150 * table holds, each with the value under which the items register. A branch
151 * that is `[]` registers nothing, a `.filter` callback that reads
152 * `process.env` filters by environment, and a constant is read through to
153 * its initializer.
154 */
155function iterableConditions(node, sourceCode, seen = new Set()) {
156 if (node === null || node === undefined || seen.has(node)) return []
157 seen.add(node)
158 if (node.type === `Identifier`) {
159 const definition = findVariable(sourceCode.getScope(node), node.name)
160 ?.defs[0]
161 return definition?.type === `Variable` && definition.parent.kind === `const`
162 ? iterableConditions(definition.node.init, sourceCode, seen)
163 : []
164 }
165 if (node.type === `ConditionalExpression`) {
166 const conditions = []
167 if (isEmptyArray(node.alternate)) {
168 conditions.push({ test: node.test, registersWhen: true })
169 } else if (isEmptyArray(node.consequent)) {
170 conditions.push({ test: node.test, registersWhen: false })
171 }
172 return [
173 ...conditions,
174 ...iterableConditions(node.consequent, sourceCode, seen),
175 ...iterableConditions(node.alternate, sourceCode, seen),
176 ]
177 }
178 if (node.type === `LogicalExpression`) {
179 return [
180 {
181 test: node.left,
182 registersWhen: node.operator === `&&` ? true : undefined,
183 },
184 ...iterableConditions(node.right, sourceCode, seen),
185 ]
186 }
187 if (
188 node.type === `CallExpression` &&
189 node.callee.type === `MemberExpression` &&
190 node.callee.property.name === `filter`
191 ) {
192 const [callback] = node.arguments
193 const readsEnvironment =
194 callback !== undefined &&
195 /process\.env/.test(sourceCode.getText(callback))
196 return [
197 ...(readsEnvironment
198 ? [{ test: callback, registersWhen: undefined }]
199 : []),
200 ...iterableConditions(node.callee.object, sourceCode, seen),
201 ]
202 }
203 return []
204}
205
206/** The table of an `.each(table)` call in a registration's callee chain. */
207function eachTable(callee) {
208 let node = callee
209 while (node.type === `CallExpression` || node.type === `MemberExpression`) {
210 if (
211 node.type === `CallExpression` &&
212 node.callee.type === `MemberExpression` &&
213 node.callee.property.name === `each`
214 ) {
215 return node.arguments[0]
216 }
217 node = node.type === `CallExpression` ? node.callee : node.object
218 }
219 return undefined
220}
221
222/**
223 * The conditions that decide whether `node` runs, each with the value that
224 * the condition must have for `node` to run: every enclosing `if`,
225 * conditional, or logical branch, and every earlier `if` in an enclosing
226 * block that returns. `registersWhen` is undefined when no single value
227 * decides it, as for `??`.
228 */
229function guardingConditions(node, sourceCode) {
230 const conditions = []
231 let child = node
232 for (let parent = node.parent; parent; parent = parent.parent) {
233 if (parent.type === `ForOfStatement` && child === parent.body) {
234 conditions.push(...iterableConditions(parent.right, sourceCode))
235 }
236 if (
237 (parent.type === `IfStatement` ||
238 parent.type === `ConditionalExpression`) &&
239 child !== parent.test
240 ) {
241 conditions.push({
242 test: parent.test,
243 registersWhen: child === parent.consequent,
244 })
245 } else if (parent.type === `LogicalExpression` && child === parent.right) {
246 conditions.push({
247 test: parent.left,
248 registersWhen:
249 parent.operator === `&&`
250 ? true
251 : parent.operator === `||`
252 ? false
253 : undefined,
254 })
255 } else if (
256 parent.type === `BlockStatement` ||
257 parent.type === `Program` ||
258 parent.type === `SwitchCase`
259 ) {
260 const body =
261 parent.type === `SwitchCase` ? parent.consequent : parent.body
262 for (const statement of body.slice(0, body.indexOf(child))) {
263 if (statement.type === `IfStatement` && returns(statement.consequent)) {
264 conditions.push({ test: statement.test, registersWhen: false })
265 }
266 }
267 }
268 child = parent
269 }
270 return conditions
271}
272
273/**
274 * Whether a guard keeps a registration in every ordinary run. Each shared
275 * replay helper is false in an ordinary run, so the registration must run
276 * when the helper is false: under `!helper()`, in the `else` branch of
277 * `helper()`, or after `if (helper()) return`. A registration that runs only
278 * when a helper is true would run only during a replay.
279 */
280function keepsOrdinaryRun({ test, registersWhen }, sourceCode) {
281 if (registersWhen === undefined) return false
282 const negated = test.type === `UnaryExpression` && test.operator === `!`
283 const helper = negated ? test.argument : test
284 if (!isSharedHelperCall(helper, replayConditions, sourceCode)) return false
285 return negated ? registersWhen : !registersWhen
286}
287
288/** A `path` that a witness recorded: a literal, or a failure's path. */
289function isRecordedPath(node) {
290 if (node.type === `TemplateLiteral`) return node.expressions.length === 0
291 if (node.type === `Literal`) return typeof node.value === `string`
292 return (
293 node.type === `MemberExpression` &&
294 !node.computed &&
295 node.property.name === `counterexamplePath`
296 )
297}
298
299/** Playwright's `browserName !== '<browser>'`. */
300function isBrowserCondition(node) {
301 return (
302 node.type === `BinaryExpression` &&
303 node.operator === `!==` &&
304 node.left.type === `Identifier` &&
305 node.left.name === `browserName` &&
306 isStringLike(node.right)
307 )
308}
309
310/**
311 * Whether a `.skip`, `.todo`, or `.fixme` call switches off a body that runs
312 * something. A test registration passes `(name, body)`, and a todo passes
313 * only its name. Playwright's runtime form passes `(condition, reason)`,
314 * `(condition)`, or nothing, and skips the test that it runs in.
315 */
316function disablesBody(args) {
317 const [first, second] = args
318 if (first === undefined) return true
319 if (second === undefined && isStringLike(first)) return false
320 if (second === undefined || isStringLike(second)) {
321 return !isBrowserCondition(first)
322 }
323 return hasBody(second)
324}
325
326/** A numeric literal at most 1: the run counts that check one history or none. */
327function isSingleRunLiteral(node) {
328 return (
329 node?.type === `Literal` &&
330 typeof node.value === `number` &&
331 node.value <= 1
332 )
333}
334
335function isNumberLiteral(node) {
336 if (node?.type === `UnaryExpression` && node.operator === `-`) {
337 return isNumberLiteral(node.argument)
338 }
339 return node?.type === `Literal` && typeof node.value === `number`
340}
341
342function isProcessEnv(node) {
343 return (
344 node?.type === `MemberExpression` &&
345 !node.computed &&
346 node.object.type === `Identifier` &&
347 node.object.name === `process` &&
348 node.property.name === `env`
349 )
350}
351
352/** The name in `process.env.NAME` or `process.env['NAME']`. */
353function environmentKey(node) {
354 if (!isProcessEnv(node.object)) return undefined
355 if (!node.computed) return node.property.name
356 return node.property.type === `Literal` &&
357 typeof node.property.value === `string`
358 ? node.property.value
359 : undefined
360}
361
362function isPrivateReplayVariable(name) {
363 return replayVariableName.test(name) && !sharedReplayVariables.has(name)
364}
365
366/** The number literal that `node` is, or that a constant `node` names. */
367function constantNumber(node, sourceCode) {
368 if (isNumberLiteral(node)) return node
369 if (node?.type !== `Identifier`) return undefined
370 const definition = findVariable(sourceCode.getScope(node), node.name)?.defs[0]
371 return definition?.type === `Variable` &&
372 definition.parent.kind === `const` &&
373 isNumberLiteral(definition.node.init)
374 ? definition.node.init
375 : undefined
376}
377
378/** A number literal, or a constant bound to one. */
379function isFixedSeed(node, sourceCode) {
380 return constantNumber(node, sourceCode) !== undefined
381}
382
383function propertyName(property) {
384 if (property.type !== `Property` || property.computed) return undefined
385 return property.key.type === `Identifier`
386 ? property.key.name
387 : property.key.value
388}
389
390/**
391 * A one-run object pins its history when it replays a `path` or passes a
392 * fixed seed. An object that an `expect` matcher compares holds an observed
393 * run count, and `fc.sample` draws examples without running a property.
394 */
395function isPinnedOrObservation(object, sourceCode) {
396 const option = (name) =>
397 object.properties.find((property) => propertyName(property) === name)
398 const path = option(`path`)
399 if (path !== undefined && isRecordedPath(path.value)) return true
400 const seed = option(`seed`)
401 if (seed !== undefined && isFixedSeed(seed.value, sourceCode)) return true
402 const { parent } = object
403 if (parent.type !== `CallExpression` || !parent.arguments.includes(object)) {
404 return false
405 }
406 const { root, names } = calleeChain(parent.callee)
407 return root === `expect` || (root === `fc` && names[0] === `sample`)
408}
409
410/**
411 * Whether a call skips the test that it runs in through the test context,
412 * as in `it('law', (ctx) => { ctx.skip() })`.
413 */
414function isContextSkip(node, sourceCode) {
415 const { callee } = node
416 if (
417 callee.type !== `MemberExpression` ||
418 callee.property.type !== `Identifier` ||
419 callee.property.name !== `skip` ||
420 callee.object.type !== `Identifier`
421 ) {
422 return false
423 }
424 // Resolve the binding, so a context captured by a nested callback counts
425 // and an unrelated variable of the same name does not.
426 const definition = findVariable(sourceCode.getScope(node), callee.object.name)
427 ?.defs[0]
428 if (definition?.type !== `Parameter`) return false
429 const fn = definition.node
430 if (fn.params[0] !== definition.name) return false
431 const registration = fn.parent
432 return (
433 registration.type === `CallExpression` &&
434 registration.arguments.includes(fn) &&
435 isTestRoot(calleeChain(registration.callee).rootNode, sourceCode)
436 )
437}
438
439/**
440 * Whether a test function is passed around as a value: assigned, collected,
441 * returned, or passed to any call except a shared selection helper.
442 */
443function isPassedAsValue(node) {
444 const { parent } = node
445 switch (parent.type) {
446 case `VariableDeclarator`:
447 return parent.init === node
448 case `AssignmentExpression`:
449 return parent.right === node
450 case `ArrayExpression`:
451 case `ReturnStatement`:
452 case `SpreadElement`:
453 return true
454 case `Property`:
455 return parent.value === node && parent.parent.type === `ObjectExpression`
456 case `ConditionalExpression`:
457 return parent.test !== node
458 case `LogicalExpression`:
459 return true
460 case `ArrowFunctionExpression`:
461 return parent.body === node
462 case `CallExpression`:
463 return (
464 parent.arguments.includes(node) &&
465 !(
466 parent.callee.type === `Identifier` &&
467 selectionHelpers.has(parent.callee.name) &&
468 parent.arguments[0] === node
469 )
470 )
471 default:
472 return false
473 }
474}
475
476/** @type {import('eslint').Rule.RuleModule} */
477export default {
478 meta: {
479 type: `problem`,
480 docs: {
481 description: `Report oracle tests that stop running: .only, a skipped body, a switch-off condition, or one unpinned run.`,
482 },
483 schema: [],
484 messages: {
485 only: `\`.only\` runs only this test, so every other law in the file stops running. Remove it before committing.`,
486 skip: `\`.{{name}}\` stops this test from enforcing its law. Remove it. To keep a known gap visible, pin a failing history with \`it.fails\` and a fixed seed.`,
487 conditional: `\`.{{name}}\` can switch this test off in ordinary runs. Only \`.skipIf(oracleReplayRequested())\` or \`.skipIf(oracleReplaySkips(property))\` may switch an oracle test off, so that a replay can stand it aside. Remove the condition.`,
488 alias: `\`.{{name}}\` is passed around as a value, so the rule cannot see what it switches off. Call it directly, or select a replay with \`oracleReplayTest(test, property)\` from oracle-config.`,
489 aliasTest: `\`{{name}}\` is passed around as a value, so the rule cannot see what it registers or switches off. Call it directly, or select a replay with \`oracleReplayTest({{name}}, property)\` from oracle-config.`,
490 guarded: `This test registers only under a condition, so it can stop running in ordinary runs. Register it unconditionally. A replay selection uses \`oracleReplayRequested()\` or \`oracleReplaySkips(property)\` from oracle-config, or \`oracleReplayTest(test, property)\`.`,
491 singleRun: `A generated property with one run that pins no history checks one random history. Pass a base run count to oracleRuns or oraclePropertyOptions, which also selects a replay. A witness passes a recorded \`path\` or a seed that is a number literal or a constant.`,
492 replayVariable: `\`{{name}}\` selects a replay or a run count outside the shared variables, so the replay manifest, the guarded replay runner, and the retired-variable check cannot see it. Take the options from \`oraclePropertyOptions\` or \`oracleRandomParameters\` in oracle-config, which read TANSTACK_DB_ORACLE_SEED, TANSTACK_DB_ORACLE_PATH, and TANSTACK_DB_ORACLE_PROPERTY, and scale run counts with \`oracleRuns\`.`,
493 literalRuns: `A literal run count does not scale with TANSTACK_DB_ORACLE_RUNS_MULTIPLIER. Wrap it in oracleRuns, or pass it to oraclePropertyOptions.`,
494 },
495 },
496 create(context) {
497 const { sourceCode } = context
498
499 /** Whether `node` is the value of a `numRuns` option that a replay pins. */
500 function isPinnedRunCount(node) {
501 const { parent } = node
502 return (
503 parent.type === `Property` &&
504 propertyName(parent) === `numRuns` &&
505 parent.parent.type === `ObjectExpression` &&
506 isPinnedOrObservation(parent.parent, sourceCode)
507 )
508 }
509
510 return {
511 CallExpression(node) {
512 // A curried call such as `fcTest.prop(arbs)(name, fn)` is reported
513 // once, at the outermost call, which holds the test body.
514 if (
515 node.parent.type === `CallExpression` &&
516 node.parent.callee === node
517 ) {
518 return
519 }
520 if (isContextSkip(node, sourceCode)) {
521 context.report({ node, messageId: `skip`, data: { name: `skip` } })
522 return
523 }
524 const { root, rootNode, names } = calleeChain(node.callee)
525 if (runHelpers.has(root) && names.length === 0) {
526 if (
527 isSingleRunLiteral(constantNumber(node.arguments[0], sourceCode)) &&
528 !isPinnedRunCount(node)
529 ) {
530 context.report({ node: node.arguments[0], messageId: `singleRun` })
531 }
532 return
533 }
534 if (
535 !isTestRoot(rootNode, sourceCode) ||
536 !names.every((member) => registrationMembers.has(member))
537 ) {
538 return
539 }
540 const unguarded = [
541 ...guardingConditions(node, sourceCode),
542 ...iterableConditions(eachTable(node.callee), sourceCode),
543 ].every((condition) => keepsOrdinaryRun(condition, sourceCode))
544 if (!unguarded) {
545 context.report({ node, messageId: `guarded` })
546 return
547 }
548 if (names.includes(`only`)) {
549 context.report({ node: node.callee, messageId: `only` })
550 return
551 }
552 const conditional = registrationCondition(node.callee)
553 if (conditional !== undefined) {
554 if (!isReplaySelection(conditional, sourceCode)) {
555 context.report({
556 node,
557 messageId: `conditional`,
558 data: { name: conditional.name },
559 })
560 }
561 return
562 }
563 const disabled = names.find((name) => disablingModifiers.has(name))
564 if (disabled !== undefined && disablesBody(node.arguments)) {
565 context.report({ node, messageId: `skip`, data: { name: disabled } })
566 }
567 },
568 Identifier(node) {
569 if (!testRoots.has(node.name) || !isPassedAsValue(node)) return
570 // A local variable or parameter that shares a test function's name
571 // is not that function.
572 const definition = findVariable(sourceCode.getScope(node), node.name)
573 ?.defs[0]
574 if (definition !== undefined && definition.type !== `ImportBinding`) {
575 return
576 }
577 context.report({
578 node,
579 messageId: `aliasTest`,
580 data: { name: node.name },
581 })
582 },
583 MemberExpression(node) {
584 const variable = environmentKey(node)
585 if (
586 variable !== undefined &&
587 isPrivateReplayVariable(variable) &&
588 !replaySelectionModule.test(context.filename)
589 ) {
590 context.report({
591 node,
592 messageId: `replayVariable`,
593 data: { name: variable },
594 })
595 }
596 // Report a chain such as `fcTest.skip` or `it.skip.prop` once, at its
597 // outermost member, when nothing calls it.
598 if (
599 node.parent.type === `MemberExpression` &&
600 node.parent.object === node
601 ) {
602 return
603 }
604 if (
605 node.parent.type === `CallExpression` &&
606 node.parent.callee === node
607 ) {
608 return
609 }
610 const { rootNode, names } = calleeChain(node)
611 const name = names.find((member) => aliasModifiers.has(member))
612 if (isTestRoot(rootNode, sourceCode) && name !== undefined) {
613 context.report({ node, messageId: `alias`, data: { name } })
614 }
615 },
616 VariableDeclarator(node) {
617 if (
618 node.id.type !== `ObjectPattern` ||
619 !isProcessEnv(node.init) ||
620 replaySelectionModule.test(context.filename)
621 ) {
622 return
623 }
624 for (const property of node.id.properties) {
625 const name =
626 property.type === `Property` ? propertyName(property) : undefined
627 if (name !== undefined && isPrivateReplayVariable(name)) {
628 context.report({
629 node: property,
630 messageId: `replayVariable`,
631 data: { name },
632 })
633 }
634 }
635 },
636 Property(node) {
637 if (
638 replaySelectionModule.test(context.filename) ||
639 propertyName(node) !== `numRuns`
640 ) {
641 return
642 }
643 // A constant bound to a number literal counts as that literal.
644 const count = constantNumber(node.value, sourceCode)
645 if (count === undefined || isPinnedRunCount(node.value)) return
646 context.report({
647 node,
648 messageId: isSingleRunLiteral(count) ? `singleRun` : `literalRuns`,
649 })
650 },
651 }
652 },
653}