Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

no-unit-test.test.js

460 lines17.3 KB

1import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { describe, it } from 'vitest'
5import { RuleTester } from 'eslint'
6import tsParser from '@typescript-eslint/parser'
7import noUnitTest from './rules/no-unit-test.js'
8​
9RuleTester.describe = describe
10RuleTester.it = it
11​
12// Companion modules on disk, so that the rule resolves real imports.
13const root = mkdtempSync(join(tmpdir(), `oracle-no-unit-test-`))
14const tests = join(root, `tests`)
15mkdirSync(join(root, `src`), { recursive: true })
16mkdirSync(tests, { recursive: true })
17writeFileSync(
18 join(tests, `history-oracle.ts`),
19 `import { declareOracle } from './oracle-config.js'
20function checkHistory(history) { return history }
21function modelHistory(history) { return history }
22declareOracle({ check: [checkHistory], model: [modelHistory] })
23export async function runHistory(history) { return checkHistory(history) }
24export function fixture() { return [] }
25export { modelHistory }
26// Every caller here passes work that runs the check, but an importer passes
27// its own work.
28export async function withCleanup(work) { return work() }
29export class Relation { add() {} }
30declareOracle({ check: [Relation] })
31it('checks with cleanup', () => withCleanup(() => runHistory([])))
32`,
34writeFileSync(
35 join(tests, `history-reexport.ts`),
36 `export { runHistory as replayHistory } from './history-oracle.js'
37export * from './history-oracle.js'
38`,
40writeFileSync(
41 join(root, `src`, `production.ts`),
42 `import { declareOracle } from '../tests/oracle-config.js'
43function compile(x) { return x }
44declareOracle({ check: [compile] })
45export { compile }
46`,
48writeFileSync(join(root, `package.json`), JSON.stringify({ name: `published` }))
49// A private package, such as an end-to-end suite, keeps its oracle in src/.
50const suite = join(root, `suite`)
51mkdirSync(join(suite, `src`), { recursive: true })
52writeFileSync(
53 join(suite, `package.json`),
54 JSON.stringify({ name: `suite`, private: true }),
56writeFileSync(
57 join(suite, `src`, `laws-oracle.ts`),
58 `import { declareOracle } from './oracle-config.js'
59export function checkLaws(observation) { return observation }
60declareOracle({ check: [checkLaws] })
61`,
63const filename = join(tests, `subject-oracle.test.ts`)
64const suiteFilename = join(suite, `src`, `pages-oracle.suite.ts`)
65​
66const header = `import { declareOracle } from './oracle-config.js'
67function checkHistory(history) { return history }
68function modelHistory(history) { return history }
69declareOracle({ check: [checkHistory], model: [modelHistory] })
71​
72const fcImport = `import { fc, test as fcTest } from '@fast-check/vitest'\n`
73​
74const ruleTester = new RuleTester({
75 languageOptions: { parser: tsParser, sourceType: `module` },
76})
77​
78ruleTester.run(`oracle/no-unit-test`, noUnitTest, {
79 valid: [
80 // A generated property reaches the declared check.
81 {
82 code: `${header}fcTest.prop([history])('checks generated histories', (h) => checkHistory(h))`,
83 filename,
84 },
85 // A fixed history reaches the check through a driver.
86 {
87 code: `${header}async function run(h) { await checkHistory(h) }
88it('retains a row after an update', async () => { await run([{ type: 'update' }]) })`,
89 filename,
90 },
91 // A driver held in a constant, and a body passed by name.
92 {
93 code: `${header}const run = (h) => checkHistory(h)
94const replay = () => run([])
95it('replays the pinned history', replay)`,
96 filename,
97 },
98 // A model pin reaches the declared model.
99 {
100 code: `${header}it('keeps an empty diff pending', () => { expect(modelHistory([])).toEqual([]) })`,
101 filename,
102 },
103 // A table of fixed histories.
104 {
105 code: `${header}it.each(cases)('checks %s', (c) => checkHistory(c))`,
106 filename,
107 },
108 // A calibration witness reaches the check through the selection helper.
109 {
110 code: `import { declareOracle, oracleCalibrationTest } from './oracle-config.js'
111function checkHistory(history) { return history }
112declareOracle({ check: [checkHistory] })
113oracleCalibrationTest(it, 'p', 'fault')('rejects the hostile mutant', () => checkHistory(bad))`,
114 filename,
115 },
116 // A class model.
117 {
118 code: `import { declareOracle } from './oracle-config.js'
119class Model { step() {} }
120function checkHistory(h) { return h }
121declareOracle({ check: [checkHistory], model: [Model] })
122it('steps the model', () => { new Model().step() })`,
123 filename,
124 },
125 // A companion module declares the check, and its driver reaches it.
126 {
127 code: `import { runHistory } from './history-oracle.js'
128it('checks a fixed history', () => runHistory([]))`,
129 filename,
130 },
131 // A re-export and an export star keep the reach.
132 {
133 code: `import { replayHistory, modelHistory } from './history-reexport.js'
134it('replays', () => replayHistory([]))
135it('pins the model', () => modelHistory([]))`,
136 filename,
137 },
138 // A private package's src/ is test code, so the rule follows it.
139 {
140 code: `import { checkLaws } from './laws-oracle.js'
141it('checks the page laws', () => checkLaws([]))`,
142 filename: suiteFilename,
143 },
144 // A test of the shared oracle machinery checks no law.
145 {
146 code: `import { readOracleRunConfig } from './oracle-config.js'
147it('rejects a retired variable', () => expect(() => readOracleRunConfig({})).toThrow())`,
148 filename: join(tests, `oracle-config.test.ts`),
149 },
150 // A helper that registers the property its caller passes in.
151 {
152 code: `${header}function serializerProp(name, check) {
153 fcTest.prop([value])(name, check)
155serializerProp('round-trips a value', (v) => checkHistory(v))
156serializerProp('round-trips an array', (v) => checkHistory([v]))`,
157 filename,
158 },
159 // A grammar calibration reaches the declared grammar.
160 {
161 code: `import { declareOracle } from './oracle-config.js'
162const historyGrammar = fc.array(action)
163function checkHistory(h) { return h }
164declareOracle({ check: [checkHistory], grammar: [historyGrammar] })
165it('reaches every action kind', () => { expect(kinds(fc.sample(historyGrammar, 200))).toEqual(allKinds) })`,
166 filename,
167 },
168 // A generated property is its own check, with or without a declaration.
169 {
170 code: `${fcImport}fcTest.prop([fc.integer(), fc.integer()])('compares antisymmetrically', (a, b) => {
171 expect(Math.sign(compare(a, b))).toBe(-Math.sign(compare(b, a)))
172})`,
173 filename,
174 },
175 {
176 code: `${fcImport}it('round-trips every value', () => {
177 fc.assert(fc.property(fc.string(), (value) => expect(decode(encode(value))).toBe(value)))
178})`,
179 filename,
180 },
181 // A property defined elsewhere, and a helper whose callers pass laws.
182 {
183 code: `${fcImport}const roundTrip = fc.property(fc.string(), (value) => decode(encode(value)) === value)
184it('round-trips', () => fc.assert(roundTrip))
185function utilsProperty(name, arbitraries, check) { fcTest.prop(arbitraries)(name, check) }
186utilsProperty('is reflexive', [fc.anything()], (x) => expect(isEqual(x, x)).toBe(true))
187utilsProperty('is symmetric', [fc.anything(), fc.anything()], (x, y) => expect(isEqual(x, y)).toBe(isEqual(y, x)))`,
188 filename,
189 },
190 // A registration that passes named arbitraries and a named predicate.
191 {
192 code: `${fcImport}const arbitraries = [fc.integer(), fc.string()]
193async function checkCampaign(id, name) { expect(await publish(id, name)).toBe(name) }
194const checkPolicy = async (id) => expect(await persist(id)).toBe(id)
195fcTest.prop(arbitraries)('publishes generated commits', checkCampaign)
196fcTest.prop(arbitraries)('persists generated commits', checkPolicy)`,
197 filename,
198 },
199 // A table row that calls a declared check.
200 {
201 code: `${header}it.each([{ name: 'stale', reject: () => checkHistory(stale) }])('rejects $name', ({ reject }) => expect(reject).toThrow())`,
202 filename,
203 },
204 // A named property predicate that reads its input.
205 {
206 code: `${fcImport}function roundTrips(value) { expect(decode(encode(value))).toBe(value) }
207it('round-trips every value', () => fc.assert(fc.property(fc.string(), roundTrips)))`,
208 filename,
209 },
210 // An exported class declared as a check in its home module.
211 {
212 code: `import { Relation } from './history-oracle.js'
213it('adds a row', () => { new Relation().add() })`,
214 filename,
215 },
216 // A type-level test that compares with a declared type model.
217 {
218 code: `import { declareOracle } from './oracle-config.js'
219type PublishedValueFor<T> = T extends { id: unknown } ? T & { $key: string } : T
220declareOracle({ typeModel: [\`PublishedValueFor\`] })
221type PublishedRow = PublishedValueFor<Row>
222test('publishes row roots', () => {
223 expectTypeOf(rowOf(query)).toEqualTypeOf<PublishedValueFor<Row>>()
224})
225test('publishes a named row root', () => {
226 expectTypeOf(rowOf(query)).toEqualTypeOf<PublishedRow>()
227})`,
228 filename,
229 },
230 // declareOracle can come from the dependency-free oracle-declaration module.
231 {
232 code: `import { declareOracle } from './oracle-declaration.js'
233function checkHistory(history) { return history }
234declareOracle({ check: [checkHistory] })
235it('checks a fixed history', () => checkHistory([]))`,
236 filename,
237 },
238 // A coverage calibration reads a Set that grammar-driven tests fill with
239 // the model's predictions.
240 {
241 code: `${header}const covered = new Set()
242it.each(cases)('runs %s', (c) => { covered.add(modelHistory(c)); checkHistory(c) })
243it('covers every outcome', () => expect([...covered]).toEqual(['a', 'b']))`,
244 filename,
245 },
246 // A placeholder registered during a replay runs nothing.
247 {
248 code: `it.skip('runs only when its replay property is selected', () => {})`,
249 filename,
250 },
251 // A suite and a Playwright step are not tests.
252 {
253 code: `${header}describe('suite', () => {
254 test('runs a browser history', async () => { await test.step('open', async () => {}); checkHistory([]) })
255})`,
256 filename,
257 },
258 // A file with no tests needs no declaration.
259 { code: `export function fixture() { return [] }`, filename },
260 ],
261 invalid: [
262 // The reported failure: production compared with a hand-written value.
263 {
264 code: `${header}import { compileExpression } from '../src/compiler.js'
265fcTest.prop([history])('checks generated histories', (h) => checkHistory(h))
266it('handles a simple table reference', () => {
267 expect(compileExpression(ref)(row)).toEqual({ id: 1 })
268})`,
269 filename,
270 errors: [{ messageId: `unitTest`, line: 7 }],
271 },
272 // A unit test registered through a selection helper's result, or
273 // through a renamed import, is still a test.
274 {
275 code: `${header}import { oracleReplayTest } from './oracle-config.js'
276import { it as vitestIt } from 'vitest'
277const fixedCase = oracleReplayTest(vitestIt)
278fixedCase('checks', () => checkHistory([]))
279fixedCase('compiles', () => expect(compile(1)).toBe(1))
280vitestIt('compiles again', () => expect(compile(2)).toBe(2))`,
281 filename,
282 errors: [
283 { messageId: `unitTest`, line: 9 },
284 { messageId: `unitTest`, line: 10 },
285 ],
286 },
287 // A file with tests and no declaration gets one report.
288 {
289 code: `import { compile } from '../src/compiler.js'
290it('a', () => expect(compile(1)).toBe(1))
291it('b', () => expect(compile(2)).toBe(2))`,
292 filename,
293 errors: [{ messageId: `undeclared`, line: 2 }],
294 },
295 // A local function named declareOracle declares nothing.
296 {
297 code: `function declareOracle() {}
298function checkHistory(h) { return h }
299declareOracle({ check: [checkHistory] })
300it('checks', () => checkHistory([]))`,
301 filename,
302 errors: [{ messageId: `undeclared` }],
303 },
304 // A production module declares no oracle part, even when it calls the
305 // helper, so the rule does not follow it.
306 {
307 code: `${header}import { compile } from '../src/production.js'
308it('checks', () => checkHistory([]))
309it('compiles', () => expect(compile(1)).toBe(1))`,
310 filename,
311 errors: [{ messageId: `unitTest`, line: 7 }],
312 },
313 // A local binding that shadows the check is not the check.
314 {
315 code: `${header}it('checks', () => { const checkHistory = (x) => x; expect(checkHistory(1)).toBe(1) })`,
316 filename,
317 errors: [{ messageId: `unitTest` }],
318 },
319 // A helper that only uses itself reaches nothing.
320 {
321 code: `${header}function loop(n) { return n === 0 ? 0 : loop(n - 1) }
322it('counts down', () => expect(loop(3)).toBe(0))`,
323 filename,
324 errors: [{ messageId: `unitTest` }],
325 },
326 // A type annotation runs nothing, so it does not reach the check.
327 {
328 code: `${header}it('types', () => { const check: typeof checkHistory | undefined = undefined; expect(check).toBeUndefined() })`,
329 filename,
330 errors: [{ messageId: `unitTest` }],
331 },
332 // A companion module's fixture does not reach its check.
333 {
334 code: `import { runHistory, fixture } from './history-oracle.js'
335it('checks a fixed history', () => runHistory([]))
336it('builds a fixture', () => expect(fixture()).toEqual([]))`,
337 filename,
338 errors: [{ messageId: `unitTest`, line: 3 }],
339 },
340 // One caller that passes a unit test makes the helper's test a unit test.
341 {
342 code: `${header}const serializerProp = (name, check) => {
343 fcTest.prop([value])(name, check)
345serializerProp('round-trips a value', (v) => checkHistory(v))
346serializerProp('encodes a date', () => expect(encode(date)).toBe('x'))`,
347 filename,
348 errors: [{ messageId: `unitTest`, line: 6 }],
349 },
350 // A helper that nothing calls by name passes nothing the rule can see.
351 {
352 code: `${header}export function register(name, check) { it(name, check) }`,
353 filename,
354 errors: [{ messageId: `unitTest` }],
355 },
356 // A property over constants, or one that ignores its input, checks
357 // written values.
358 {
359 code: `${fcImport}fcTest.prop([fc.constant(1)])('compiles one', (n) => expect(compile(n)).toBe(1))`,
360 filename,
361 errors: [{ messageId: `undeclared` }],
362 },
363 {
364 code: `${fcImport}fcTest.prop([fc.integer()])('encodes a date', () => expect(encode(date)).toBe('x'))`,
365 filename,
366 errors: [{ messageId: `undeclared` }],
367 },
368 {
369 code: `${fcImport}it('encodes a date', () => {
370 fc.assert(fc.property(fc.integer(), () => expect(encode(date)).toBe('x')))
371})`,
372 filename,
373 errors: [{ messageId: `undeclared` }],
374 },
375 {
376 code: `${header}${fcImport}function utilsProperty(name, arbitraries, check) { fcTest.prop(arbitraries)(name, check) }
377utilsProperty('is reflexive', [fc.anything()], (x) => expect(isEqual(x, x)).toBe(true))
378utilsProperty('encodes a date', [fc.integer()], () => expect(encode(date)).toBe('x'))
379it('checks', () => checkHistory([]))`,
380 filename,
381 errors: [{ messageId: `unitTest`, line: 6 }],
382 },
383 // A named predicate that ignores its input checks one written value.
384 {
385 code: `${fcImport}function encodesDate() { expect(encode(date)).toBe('x') }
386fcTest.prop([fc.integer()])('encodes a date', encodesDate)`,
387 filename,
388 errors: [{ messageId: `undeclared` }],
389 },
390 // A table of written values reaches nothing.
391 {
392 code: `${header}it.each([[1, 2]])('adds %i', (a, b) => expect(add(a, b)).toBe(3))`,
393 filename,
394 errors: [{ messageId: `unitTest` }],
395 },
396 // Iterating the declared grammar's cells does not reach it: the body must.
397 {
398 code: `import { declareOracle } from './oracle-config.js'
399const cells = [{ a: 1 }]
400function checkHistory(h) { return h }
401declareOracle({ check: [checkHistory], grammar: [cells] })
402it.each(cells)('handles $a', ({ a }) => expect(compile(a)).toBe(1))`,
403 filename,
404 errors: [{ messageId: `unitTest` }],
405 },
406 // An imported helper that reaches a part only through its home module's
407 // arguments does not reach one for the importer.
408 {
409 code: `import { withCleanup } from './history-oracle.js'
410it('compiles', () => withCleanup(() => expect(compile(1)).toBe(1)))`,
411 filename,
412 errors: [{ messageId: `undeclared` }],
413 },
414 // A named property predicate that ignores its input checks one value.
415 {
416 code: `${fcImport}const ignores = () => expect(encode(date)).toBe('x')
417it('encodes a date', () => {
418 fc.assert(fc.property(fc.integer(), ignores))
419})`,
420 filename,
421 errors: [{ messageId: `undeclared` }],
422 },
423 // A type test that names no type model, and a name that is not a type.
424 {
425 code: `import { declareOracle } from './oracle-config.js'
426type PublishedValueFor<T> = T
427declareOracle({ typeModel: ['PublishedValueFor', 'MissingModel'] })
428test('publishes row roots', () => {
429 expectTypeOf(rowOf(query)).toEqualTypeOf<PublishedValueFor<Row>>()
430})
431test('keeps a number', () => {
432 expectTypeOf(valueOf(query)).toEqualTypeOf<number>()
433})`,
434 filename,
435 errors: [
436 { messageId: `unknownTypeModel`, line: 3 },
437 { messageId: `unitTest`, line: 7 },
438 ],
439 },
440 // A Set filled with written values carries no declared part.
441 {
442 code: `${header}const seen = new Set()
443it('records', () => { seen.add('a') })
444it('reads', () => expect([...seen]).toEqual(['a']))`,
445 filename,
446 errors: [
447 { messageId: `unitTest`, line: 6 },
448 { messageId: `unitTest`, line: 7 },
449 ],
450 },
451 // A test inside a suite and a test passed a timeout are still tests.
452 {
453 code: `${header}describe('suite', () => {
454 it('a', () => expect(1).toBe(1), 1000)
455})`,
456 filename,
457 errors: [{ messageId: `unitTest` }],
458 },
459 ],
460})