@yaks/testing 0.0.0-stage → 0.2.36

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 (93) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +427 -2
  3. package/_dist/assert.d.ts +40 -0
  4. package/_dist/assert.d.ts.map +1 -0
  5. package/_dist/choose.d.ts +39 -0
  6. package/_dist/choose.d.ts.map +1 -0
  7. package/_dist/clock.d.ts +8 -0
  8. package/_dist/clock.d.ts.map +1 -0
  9. package/_dist/deps.d.ts +113 -0
  10. package/_dist/deps.d.ts.map +1 -0
  11. package/_dist/examples.d.ts +69 -0
  12. package/_dist/examples.d.ts.map +1 -0
  13. package/_dist/find.d.ts +23 -0
  14. package/_dist/find.d.ts.map +1 -0
  15. package/_dist/kept.d.ts +27 -0
  16. package/_dist/kept.d.ts.map +1 -0
  17. package/_dist/lend.d.ts +15 -0
  18. package/_dist/lend.d.ts.map +1 -0
  19. package/_dist/main.d.ts +2 -0
  20. package/_dist/main.d.ts.map +1 -0
  21. package/_dist/mod.d.ts +45 -0
  22. package/_dist/mod.d.ts.map +1 -0
  23. package/_dist/names.d.ts +31 -0
  24. package/_dist/names.d.ts.map +1 -0
  25. package/_dist/own.d.ts +25 -0
  26. package/_dist/own.d.ts.map +1 -0
  27. package/_dist/reads.d.ts +8 -0
  28. package/_dist/reads.d.ts.map +1 -0
  29. package/_dist/suite.d.ts +82 -0
  30. package/_dist/suite.d.ts.map +1 -0
  31. package/_dist/typist.d.ts +24 -0
  32. package/_dist/typist.d.ts.map +1 -0
  33. package/_dist/wait.d.ts +21 -0
  34. package/_dist/wait.d.ts.map +1 -0
  35. package/assert.js +114 -0
  36. package/assert.js.map +1 -0
  37. package/assert.ts +143 -0
  38. package/choose.js +197 -0
  39. package/choose.js.map +1 -0
  40. package/choose.ts +327 -0
  41. package/clock.js +45 -0
  42. package/clock.js.map +1 -0
  43. package/clock.ts +60 -0
  44. package/deno.json +1 -0
  45. package/deps.js +868 -0
  46. package/deps.js.map +1 -0
  47. package/deps.ts +1004 -0
  48. package/drive.js +43 -0
  49. package/drive.js.map +1 -0
  50. package/drive.ts +41 -0
  51. package/examples.js +279 -0
  52. package/examples.js.map +1 -0
  53. package/examples.ts +380 -0
  54. package/find.js +86 -0
  55. package/find.js.map +1 -0
  56. package/find.ts +102 -0
  57. package/kept.js +128 -0
  58. package/kept.js.map +1 -0
  59. package/kept.ts +146 -0
  60. package/lend.js +30 -0
  61. package/lend.js.map +1 -0
  62. package/lend.ts +31 -0
  63. package/load.js +106 -0
  64. package/load.js.map +1 -0
  65. package/load.ts +139 -0
  66. package/main.js +214 -0
  67. package/main.js.map +1 -0
  68. package/main.ts +217 -0
  69. package/mod.js +45 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +55 -0
  72. package/names.js +209 -0
  73. package/names.js.map +1 -0
  74. package/names.ts +204 -0
  75. package/own.js +109 -0
  76. package/own.js.map +1 -0
  77. package/own.ts +136 -0
  78. package/package.json +56 -4
  79. package/reads.js +88 -0
  80. package/reads.js.map +1 -0
  81. package/reads.ts +98 -0
  82. package/run.js +306 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +405 -0
  85. package/suite.js +191 -0
  86. package/suite.js.map +1 -0
  87. package/suite.ts +224 -0
  88. package/typist.js +74 -0
  89. package/typist.js.map +1 -0
  90. package/typist.ts +79 -0
  91. package/wait.js +34 -0
  92. package/wait.js.map +1 -0
  93. package/wait.ts +60 -0
package/run.ts ADDED
@@ -0,0 +1,405 @@
1
+ import * as system from '@yaks/process/system'
2
+ // Runs collected tests one at a time, in the order they were declared, and
3
+ // says how each went in the lines `deno test` prints (`name ... ok (12ms)`),
4
+ // which what watches a run reads.
5
+ import { threadtime } from '@yaks/benchmark'
6
+ import { own } from './own.js'
7
+ import { closing, left, type Test, unkept } from './suite.js'
8
+
9
+ /** How one test went. */
10
+ export type Outcome = {
11
+ test: Omit<Test, 'body'>
12
+ ok: boolean
13
+ skipped: boolean
14
+ ms: number
15
+ /** CPU milliseconds: all this process's threads and its reaped children. */
16
+ cpu: number
17
+ errors: unknown[]
18
+ }
19
+
20
+ // The runner's own clock and timers, as the runtime made them: a test that
21
+ // replaced the globals still ends at its deadline and is timed on the real
22
+ // clock.
23
+ let now = performance.now.bind(performance)
24
+ let later = setTimeout
25
+ let cancel = clearTimeout
26
+
27
+ /// took(0.25) -> '250µs'
28
+ /// took(12.4) -> '12ms'
29
+ /// took(1500) -> '1s'
30
+ /// took(152_000) -> '2m32s'
31
+ /** A duration as `deno test` prints one. */
32
+ export let took = (ms: number) =>
33
+ ms < 1
34
+ ? `${Math.round(ms * 1000)}µs`
35
+ : ms < 1000
36
+ ? `${Math.round(ms)}ms`
37
+ : ms < 60_000
38
+ ? `${Math.floor(ms / 1000)}s`
39
+ : `${Math.floor(ms / 60_000)}m${Math.floor(ms % 60_000 / 1000)}s`
40
+
41
+ // A rejection nobody handled, or an error nobody caught, fails the test
42
+ // running when it surfaces, which is the nearest a single runtime can place
43
+ // it: often the test that left it, sometimes the one after.
44
+ //
45
+ // Each file has its own global error events, as a runtime of its own would:
46
+ // what it listens for on the global `error` and `unhandledrejection` events,
47
+ // by listener or by `onerror` and `onunhandledrejection`, hears a copy of
48
+ // each, and one it cancels is handled, not stray. The runner hears the event
49
+ // first and cancels it, so the runtime never ends over it. A file's listeners
50
+ // end with it.
51
+ let stray: unknown[] = []
52
+ let events = new EventTarget()
53
+ let pass = (e: Event, copy: Event, error: unknown) => {
54
+ e.preventDefault()
55
+ if (events.dispatchEvent(copy)) stray.push(error)
56
+ }
57
+ globalThis.addEventListener?.('unhandledrejection', (e) => {
58
+ let { promise, reason } = e
59
+ pass(
60
+ e,
61
+ new PromiseRejectionEvent(e.type, { promise, reason, cancelable: true }),
62
+ reason,
63
+ )
64
+ })
65
+ globalThis.addEventListener?.('error', (e) => {
66
+ let { message, filename, lineno, colno, error } = e
67
+ pass(
68
+ e,
69
+ new ErrorEvent(e.type, {
70
+ message,
71
+ filename,
72
+ lineno,
73
+ colno,
74
+ error,
75
+ cancelable: true,
76
+ }),
77
+ error,
78
+ )
79
+ })
80
+ let TYPES = ['error', 'unhandledrejection']
81
+ let target = globalThis as unknown as EventTarget
82
+ let { addEventListener: add, removeEventListener: remove } = target
83
+ if (add) {
84
+ target.addEventListener = function (type, listener, options) {
85
+ TYPES.includes(type)
86
+ ? events.addEventListener(type, listener, options)
87
+ : add.call(this ?? target, type, listener, options)
88
+ }
89
+ target.removeEventListener = function (type, listener, options) {
90
+ TYPES.includes(type)
91
+ ? events.removeEventListener(type, listener, options)
92
+ : remove.call(this ?? target, type, listener, options)
93
+ }
94
+ let handlers = new Map<string, EventListener | null>()
95
+ for (let type of TYPES) {
96
+ Object.defineProperty(globalThis, `on${type}`, {
97
+ configurable: true,
98
+ enumerable: true,
99
+ get: () => handlers.get(type) ?? null,
100
+ set: (handler: EventListener | null) => {
101
+ let was = handlers.get(type)
102
+ if (was) events.removeEventListener(type, was)
103
+ handlers.set(type, handler)
104
+ if (handler) events.addEventListener(type, handler)
105
+ },
106
+ })
107
+ }
108
+ }
109
+
110
+ /** Gives the file loaded next its own global error events: what the one
111
+ * before listened for there hears no more. */
112
+ export let apart = () => {
113
+ events = new EventTarget()
114
+ for (let type of TYPES) {
115
+ if (`on${type}` in globalThis) Reflect.set(globalThis, `on${type}`, null)
116
+ }
117
+ }
118
+
119
+ /** Runs one test, failing it once `timeout` passes without an end. */
120
+ export let one = async (
121
+ test: Test,
122
+ timeout: number,
123
+ cpu: () => number | undefined = threadtime,
124
+ ): Promise<Outcome> => {
125
+ let { body, ...reported } = test
126
+ if (test.skip) {
127
+ return {
128
+ test: reported,
129
+ ok: true,
130
+ skipped: true,
131
+ ms: 0,
132
+ cpu: 0,
133
+ errors: [],
134
+ }
135
+ }
136
+ let timer: ReturnType<typeof later> | undefined
137
+ let errors: unknown[] = []
138
+ // The deadline is set before the clock starts: a test's time is its own,
139
+ // not the runner's, and a runtime's first timer costs a third of a
140
+ // millisecond, which the first test to await would otherwise pay.
141
+ //
142
+ // It counts the test's own time: the wall clock less what the box kept
143
+ // this runtime, and every process it started, waiting for a CPU
144
+ // (./own.ts). A test that hangs waits for no CPU, so it fails as soon on a
145
+ // busy box as on an idle one. The clock is read each second, and first
146
+ // looks then, so a test that ends sooner never pays for a look.
147
+ let late = new Promise((_, no) => {
148
+ let spent = own(system.pid, { every: 500, time: now })
149
+ let check = () => {
150
+ let left = timeout - spent()
151
+ if (left > 0) timer = later(check, Math.min(left, 1000))
152
+ else {
153
+ no(
154
+ new Error(
155
+ `the test did not end within ${timeout}ms of its own time`,
156
+ ),
157
+ )
158
+ }
159
+ }
160
+ timer = later(check, Math.min(timeout, 1000))
161
+ })
162
+ let from = cpu()
163
+ if (from === undefined) {
164
+ cancel(timer)
165
+ throw new Error('CPU accounting is unavailable')
166
+ }
167
+ let start = now()
168
+ let ms = 0
169
+ try {
170
+ await Promise.race([closing(body), late])
171
+ } catch (error) {
172
+ errors.push(error)
173
+ } finally {
174
+ ms = now() - start
175
+ cancel(timer)
176
+ }
177
+ let to = cpu()
178
+ if (to === undefined) throw new Error('CPU accounting is unavailable')
179
+ let used = to - from
180
+ errors.push(...stray.splice(0))
181
+ return {
182
+ test: reported,
183
+ ok: !errors.length,
184
+ skipped: false,
185
+ ms,
186
+ cpu: used,
187
+ errors,
188
+ }
189
+ }
190
+
191
+ /// at('a_test.ts') -> './a_test.ts'
192
+ /// at('/tmp/a_test.ts') -> '/tmp/a_test.ts'
193
+ /** A file as a run names it: from the checkout, or whole outside it. */
194
+ export let at = (path: string) => path.startsWith('/') ? path : `./${path}`
195
+
196
+ let bytes = new TextEncoder()
197
+ let say = (text: string) => {
198
+ let b = bytes.encode(text)
199
+ while (b.length) b = b.subarray(system.stdout.writeSync(b))
200
+ }
201
+ let colored = system.stdout.isTerminal() && !system.env.get('NO_COLOR')
202
+ let paint = (code: number, text: string) =>
203
+ colored ? `\x1b[${code}m${text}\x1b[0m` : text
204
+
205
+ /** How a test went, said after its name: `ok (12ms)`. */
206
+ export let how = (o: Outcome) =>
207
+ `${
208
+ o.skipped
209
+ ? paint(33, 'ignored')
210
+ : o.ok
211
+ ? paint(32, 'ok')
212
+ : paint(31, 'FAILED')
213
+ } ${paint(90, `(${took(o.ms)})`)}\n`
214
+
215
+ /// running(9, 'a_test.ts', 12.4) -> 'running 9 tests from ./a_test.ts (loaded in 12ms)'
216
+ /** A file's header: how many of its tests run, and what loading it took. */
217
+ export let running = (count: number, path: string, loaded: number) =>
218
+ `running ${count} tests from ${at(path)} (loaded in ${took(loaded)})`
219
+
220
+ /**
221
+ * Runs the tests of one file, `loaded` being what loading it took. A test's
222
+ * name is said as it starts and how it went ends the line, so what watches a
223
+ * run knows which test it waits on. A failure's errors follow at once, `brief`
224
+ * unless `verbose`: a runtime that dies later, before its closing report, has
225
+ * still said why each test failed.
226
+ */
227
+ export let file = async (
228
+ path: string,
229
+ tests: Test[],
230
+ timeout: number,
231
+ loaded = 0,
232
+ verbose = false,
233
+ ): Promise<Outcome[]> => {
234
+ if (!tests.length) return []
235
+ say(paint(90, `${running(tests.length, path, loaded)}\n`))
236
+ let out: Outcome[] = []
237
+ for (let t of tests) {
238
+ say(`${t.name} ... `)
239
+ let o = await one(t, timeout)
240
+ say(how(o))
241
+ if (!o.ok) say(`${told(o, verbose)}\n`)
242
+ out.push(o)
243
+ }
244
+ return out
245
+ }
246
+
247
+ /** Ends the file `file` ran last (./suite.ts `afterAll`) as one more test of
248
+ * it, `<path> ends`. The watchdog sees the active cleanup before it starts. */
249
+ export let end = async (
250
+ path: string,
251
+ timeout: number,
252
+ verbose = false,
253
+ ): Promise<Outcome[]> => {
254
+ let body = left()
255
+ if (!body) return []
256
+ let name = `${path} ends`
257
+ say(`settling ${name}\n`)
258
+ let o = await one({ name, body, tags: [], skip: false, file: path }, timeout)
259
+ if (o.ok) return []
260
+ say(`${name} ... ${how(o)}${told(o, verbose)}\n`)
261
+ return [o]
262
+ }
263
+
264
+ /** Ends what the runtime kept across files (./suite.ts `kept`), as one more
265
+ * test of the file that asked last, `<path> releases`, said only when it
266
+ * fails. The watchdog sees the active cleanup before it starts. */
267
+ export let release = async (
268
+ timeout: number,
269
+ verbose = false,
270
+ ): Promise<Outcome[]> => {
271
+ let asked = unkept()
272
+ if (!asked) return []
273
+ let name = `${asked.file} releases`
274
+ say(`settling ${name}\n`)
275
+ let o = await one(
276
+ { name, body: asked.body, tags: [], skip: false, file: asked.file },
277
+ timeout,
278
+ )
279
+ if (o.ok) return []
280
+ say(`${name} ... ${how(o)}${told(o, verbose)}\n`)
281
+ return [o]
282
+ }
283
+
284
+ /** What a run took, in milliseconds: the whole of it, its planning and its
285
+ * loading, each file's load and each test that ran, with what of it the test
286
+ * spent on a CPU (`cpu`); each file it remembered as passed, by its key
287
+ * (./deps.ts), so a caller holding the run to more than passing can take a
288
+ * pass back; and how many tests it skipped and files it left out as
289
+ * unchanged since they passed. */
290
+ export type Times = {
291
+ wall: number
292
+ planned: number
293
+ loading: number
294
+ loads: Record<string, number>
295
+ remembered: Record<string, string>
296
+ ignored: number
297
+ left: number
298
+ tests: {
299
+ file: string
300
+ name: string
301
+ ms: number
302
+ cpu: number
303
+ ok: boolean
304
+ }[]
305
+ }
306
+
307
+ /** A run's times, as `--times` writes them: skipped tests took nothing. */
308
+ export let timed = (
309
+ outcomes: Outcome[],
310
+ run: Omit<Times, 'tests' | 'ignored'>,
311
+ ): Times => ({
312
+ ...run,
313
+ ignored: outcomes.filter((o) => o.skipped).length,
314
+ tests: outcomes.filter((o) => !o.skipped).map((o) => ({
315
+ file: o.test.file,
316
+ name: o.test.name,
317
+ ms: o.ms,
318
+ cpu: o.cpu,
319
+ ok: o.ok,
320
+ })),
321
+ })
322
+
323
+ let shown = (error: unknown) =>
324
+ error instanceof Error ? error.stack ?? String(error) : system.inspect(error)
325
+
326
+ // This package's own modules: the runner's frames sit under every test's,
327
+ // and an assertion's or a wait's atop the line that called it.
328
+ let RUNNER = ['run', 'suite', 'main', 'load', 'assert', 'wait']
329
+ .map((m) => new URL(`./${m}.ts`, import.meta.url).href)
330
+
331
+ /** The most of one error the closing report says, unless `--verbose`. */
332
+ export let LINES = 30
333
+
334
+ /// brief('Error: no\n\n\n at f (file:///r/a_test.ts:2:1)\n at g (ext:core/x.js:1:1)', 'file:///r/') -> 'Error: no\n\n at f (a_test.ts:2:1)'
335
+ /// brief('a\nb\nc', 'file:///r/', 2) -> 'a\nb\n… 1 more line (--verbose says it whole)'
336
+ /**
337
+ * An error as the closing report says it: its stack holds only the frames in
338
+ * the checkout `root`, from it, and no more than one blank line in a row;
339
+ * then it is cut to `lines`. A frame in a dependency, the runtime or this
340
+ * package is never where a test failed, and its call site in the checkout
341
+ * stays.
342
+ */
343
+ export let brief = (text: string, root: string, lines = LINES) => {
344
+ let kept = text.split('\n').filter((l, i, all) =>
345
+ /^\s+at /.test(l)
346
+ ? l.includes(root) && !RUNNER.some((m) => l.includes(m))
347
+ : l.trim() || all[i - 1]?.trim()
348
+ ).map((l) => l.replaceAll(root, ''))
349
+ let more = kept.length - lines
350
+ return more > 0
351
+ ? [
352
+ ...kept.slice(0, lines),
353
+ `… ${more} more line${more == 1 ? '' : 's'} (--verbose says it whole)`,
354
+ ].join('\n')
355
+ : kept.join('\n')
356
+ }
357
+
358
+ /** A failure's errors, a line each: whole when `verbose`, else `brief`. */
359
+ let told = (o: Outcome, verbose: boolean) => {
360
+ let root = `file://${system.cwd()}/`
361
+ return o.errors.map((e) => `${verbose ? shown(e) : brief(shown(e), root)}\n`)
362
+ .join('')
363
+ }
364
+
365
+ /**
366
+ * The closing report: every failure with its errors, then the counts and the
367
+ * files left out as unchanged since they passed. Each error is `brief`;
368
+ * `verbose` says each whole, then names the failures again and what the run
369
+ * spent before its first test and loading its files.
370
+ */
371
+ export let summary = (
372
+ outcomes: Outcome[],
373
+ ms: number,
374
+ { left = 0, planned = 0, loading = 0 } = {},
375
+ verbose = false,
376
+ ) => {
377
+ let failed = outcomes.filter((o) => !o.ok)
378
+ let passed = outcomes.filter((o) => o.ok && !o.skipped).length
379
+ let ignored = outcomes.filter((o) => o.skipped).length
380
+ let text = ''
381
+ if (failed.length) {
382
+ text += `\n${paint(31, 'ERRORS')}\n\n`
383
+ for (let o of failed) {
384
+ text += `${o.test.name} => ${at(o.test.file)}\n${told(o, verbose)}\n`
385
+ }
386
+ if (verbose) {
387
+ text += `${paint(31, 'FAILURES')}\n\n`
388
+ for (let o of failed) text += `${o.test.name} => ${at(o.test.file)}\n`
389
+ }
390
+ }
391
+ text += `\n${failed.length ? paint(31, 'FAILED') : paint(32, 'ok')} | ${
392
+ [
393
+ `${passed} passed`,
394
+ `${failed.length} failed`,
395
+ ...ignored ? [`${ignored} ignored`] : [],
396
+ ...left ? [`${left} unchanged since they passed`] : [],
397
+ ].join(' | ')
398
+ } ${paint(90, `(${took(ms)})`)}\n`
399
+ if (verbose) {
400
+ text += `${
401
+ paint(90, `planned in ${took(planned)}, loaded in ${took(loading)}`)
402
+ }\n`
403
+ }
404
+ say(text)
405
+ }
package/suite.js ADDED
@@ -0,0 +1,191 @@
1
+ // The words a test module declares its tests in, and the list they land in.
2
+ // A module only declares: the runner (./main.ts) collects what every module
3
+ // it loads declares and runs the lot in one runtime. A module loaded by
4
+ // anything else, `deno test` or an editor, hands each test to Deno.test.
5
+ import * as assertions from "./assert.js";
6
+ let tests;
7
+ let file = '';
8
+ // Whether a stack has been read since the module now loading was named.
9
+ let mapped = false;
10
+ /** Starts collecting: every test declared from now on lands in the list
11
+ * returned, instead of going to Deno.test. */ export let collect = ()=>tests = [];
12
+ /** Names the module whose declarations follow, and opens its scope
13
+ * (`afterAll`). */ export let from = (path)=>{
14
+ file = path;
15
+ mapped = false;
16
+ leaving = tests ? [] : undefined;
17
+ };
18
+ /**
19
+ * Declares a test: a name, a body that throws or rejects to fail, and the
20
+ * tags a run can pick it by.
21
+ *
22
+ * ```ts ignore
23
+ * test('two and two', () => equal(2 + 2, 4))
24
+ * test('the whole shop', async () => ok(await shop()), { tags: ['kernel'] })
25
+ * ```
26
+ */ export let test = (name, body, { tags = [], skip = false } = {})=>{
27
+ if (tests) {
28
+ // The first stack read that holds a module's frame reads the module's
29
+ // source map, half a millisecond, once. A module declares from its own
30
+ // frame, so the map is read here, in its load, rather than by whichever
31
+ // of its tests first reports an error.
32
+ mapped ||= !!Error().stack;
33
+ tests.push({
34
+ name,
35
+ body,
36
+ tags,
37
+ skip,
38
+ file
39
+ });
40
+ } else {
41
+ globalThis.Deno?.test({
42
+ name,
43
+ ignore: skip,
44
+ fn: ()=>closing(body)
45
+ });
46
+ }
47
+ };
48
+ // What the running test asked to have done once it ends (`cleanup`), and
49
+ // what the file the runner loaded last asked to have done once its tests
50
+ // have run (`afterAll`).
51
+ let ending;
52
+ let leaving;
53
+ /**
54
+ * Asks for `done` once the running test ends, before its time is taken, so
55
+ * a test pays for closing what it opened and leaves nothing running into
56
+ * the next one. Outside a test, it is the file's (`afterAll`). Outside the
57
+ * runner and any test it does nothing, and answers false.
58
+ *
59
+ * ```ts ignore
60
+ * let fixture = () => {
61
+ * let db = open()
62
+ * cleanup(() => db.close())
63
+ * return db
64
+ * }
65
+ * ```
66
+ */ export let cleanup = (done)=>{
67
+ let scope = ending ?? leaving;
68
+ scope?.push(done);
69
+ return !!scope;
70
+ };
71
+ /**
72
+ * Asks for `done` once the file the runner loaded last has run its tests,
73
+ * whichever of them asks. A runtime keeps every module it loads, and what a
74
+ * module holds: a kernel a file opened for its tests would otherwise run on,
75
+ * holding every store it made, beside every file the runtime loads after.
76
+ * Outside the runner it does nothing, and answers false.
77
+ *
78
+ * ```ts ignore
79
+ * let shared: Promise<Kernel> | undefined
80
+ * let kernel = () => {
81
+ * if (!shared) afterAll(async () => (await shared)?.close())
82
+ * return shared ??= boot()
83
+ * }
84
+ * ```
85
+ */ export let afterAll = (done)=>{
86
+ leaving?.push(done);
87
+ return !!leaving;
88
+ };
89
+ // What files asked the runtime to keep until it needs their memory back
90
+ // (`kept`), and the file that asked last.
91
+ let keeping = [];
92
+ let keeper = '';
93
+ /**
94
+ * Asks for `done` once the runtime needs back the memory a fixture holds
95
+ * (./main.ts `full`), rather than once the file that made it ends: a fixture
96
+ * that costs more to make than to keep (a kernel, say) serves every file
97
+ * after it until then. Outside the runner it does nothing, and answers false.
98
+ *
99
+ * ```ts ignore
100
+ * let shared: Promise<Kernel> | undefined
101
+ * let kernel = () => {
102
+ * if (!shared) kept(async () => (await shared)?.close())
103
+ * return shared ??= boot()
104
+ * }
105
+ * ```
106
+ */ export let kept = (done)=>{
107
+ if (!tests) return false;
108
+ keeping.push(done);
109
+ keeper = file;
110
+ return true;
111
+ };
112
+ /** What the runtime kept (`kept`), run last asked first, with the file that
113
+ * asked last; none when it keeps nothing. The runtime keeps nothing after. */ export let unkept = ()=>{
114
+ let asked = keeping;
115
+ keeping = [];
116
+ return asked.length ? {
117
+ file: keeper,
118
+ body: ()=>settle(asked)
119
+ } : undefined;
120
+ };
121
+ /** What the file the runner loaded last asked for with `afterAll`, run last
122
+ * asked first; none when it asked for nothing. The scope closes: the file
123
+ * asks for no more. */ export let left = ()=>{
124
+ let asked = leaving;
125
+ leaving = undefined;
126
+ return asked?.length ? ()=>settle(asked) : undefined;
127
+ };
128
+ /** Runs a test's body, then what it asked to have done once it ends, last
129
+ * asked first. A body's failure is the test's; else the first cleanup's. */ export let closing = async (body)=>{
130
+ let was = ending;
131
+ let asked = ending = [];
132
+ let failed;
133
+ try {
134
+ await body();
135
+ } catch (error) {
136
+ failed = {
137
+ error
138
+ };
139
+ } finally{
140
+ ending = was;
141
+ }
142
+ await settle(asked, failed);
143
+ };
144
+ // Runs what a scope asked for, last asked first: the scope's failure, or else
145
+ // the first of theirs, is thrown once all have run.
146
+ let settle = async (asked, failed)=>{
147
+ for (let done of asked.reverse()){
148
+ try {
149
+ await done();
150
+ } catch (error) {
151
+ failed ??= {
152
+ error
153
+ };
154
+ }
155
+ }
156
+ if (failed) throw failed.error;
157
+ };
158
+ /**
159
+ * Declares a group of tests under one name, each clause named after it and
160
+ * carrying its tags. A body that throws declares a failing test instead.
161
+ *
162
+ * ```ts ignore
163
+ * suite('sum', ({ it, equal }) => {
164
+ * it('adds', () => equal(sum([1, 2]), 3))
165
+ * it('of nothing is zero', () => equal(sum([]), 0))
166
+ * })
167
+ * ```
168
+ */ export let suite = (name, body, options = {})=>{
169
+ let it = Object.assign((what, fn, more = {})=>test(`${name} › ${what}`, fn, {
170
+ tags: [
171
+ ...options.tags ?? [],
172
+ ...more.tags ?? []
173
+ ],
174
+ skip: options.skip || more.skip
175
+ }), {
176
+ skip: (what, fn)=>it(what, fn, {
177
+ skip: true
178
+ })
179
+ });
180
+ try {
181
+ body({
182
+ ...assertions,
183
+ it
184
+ });
185
+ } catch (error) {
186
+ test(`${name} › declares its tests`, ()=>{
187
+ throw error;
188
+ }, options);
189
+ }
190
+ };
191
+ //# sourceMappingURL=suite.js.map
package/suite.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suite.js","sources":["./suite.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,yEAAyE;AACzE,YAAY,8BAA6B;AAczC,IAAI;AACJ,IAAI,OAAO;AACX,wEAAwE;AACxE,IAAI,SAAS;AAEb;4CAC4C,GAC5C,OAAO,IAAI,UAAU,IAAc,QAAQ,EAAE,CAAA;AAE7C;iBACiB,GACjB,OAAO,IAAI,OAAO,CAAC;EACjB,OAAO;EACP,SAAS;EACT,UAAU,QAAQ,EAAE,GAAG;AACzB,EAAC;AAED;;;;;;;;CAQC,GACD,OAAO,IAAI,OAAO,CAChB,MACA,MACA,EAAE,OAAO,EAAE,EAAE,OAAO,KAAK,EAAW,GAAG,CAAC,CAAC;EAEzC,IAAI,OAAO;IACT,sEAAsE;IACtE,uEAAuE;IACvE,wEAAwE;IACxE,uCAAuC;IACvC,WAAW,CAAC,CAAC,QAAQ,KAAK;IAC1B,MAAM,IAAI,CAAC;MAAE;MAAM;MAAM;MAAM;MAAM;IA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