All files / _testing.ts

100.00% Branches 29/29
100.00% Lines 130/130
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
x1
 
x6
 
 
 
 
 
 
x6
x12
 
x1
 
 
 
 
 
 
x6
x6
x6
x6
x6
x6
 
x6
x6
x6
x6
x6
x6
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
x24
 
x1
 
 
 
x6
x6
x53
x53
x54
x54
x53
x246
x82
x53
x53
x56
x448
x168
x56
x58
x177
x59
x59
x59
x58
x56
x53
x54
x55
x55
x55
x55
x55
x55
x54
x54
x98
x53
x56
x448
x560
x168
x56
x58
x177
x59
x59
x59
x58
x56
x53
x54
x55
x55
x55
x55
x55
x55
x54
x54
x96
x96
x370
x137
x905
x181
x183
x183
x181
x218
x181
x181
x96
x53
 
x6
x6
 
x6
x6
x10
x11
x11
x130
x13
x143
x13
x10
 
x6
x6
x46
x46
x329
x846
x47
x46
x282
x658
x47
x46
x84
x84
x46
x46
 
x6
x6
x49
x49
x49
x49
x49
x49
x49
x49
 
 
 
 
 
 


























































































































































































































// Imports
import type { Nullable, Promisable, rw } from "@libs/typing"
import { command } from "@libs/run/command"
export type { Nullable, Promisable }

/** Alias for `any` that can be used for testing. */
//deno-lint-ignore no-explicit-any
export type testing = any

/** TestingError can be used to test expected error behaviours in tests. */
export class TestingError extends Error {}

/**
 * Available runtimes.
 *
 * Either:
 * - `null` if not checked yet (it is checked the first time a test is run with the corresponding runtime)
 * - `true` if available
 * - `false` if unavailable
 */
export const available = {
  deno: true,
  bun: null,
  node: null,
} as Readonly<Record<runtime, Nullable<boolean>>>

/** Paths to runtimes. */
export const paths = {
  deno: "deno",
  bun: "bun",
  node: "node",
  npx: "npx",
}

/** Runtime. */
export type runtime = "deno" | "bun" | "node"

/** Test options. */
export type options = {
  ignore?: Deno.TestDefinition["ignore"]
  only?: Deno.TestDefinition["only"]
  permissions?: Deno.TestDefinition["permissions"]
  sanitizeResources?: Deno.TestDefinition["sanitizeResources"]
  sanitizeOps?: Deno.TestDefinition["sanitizeOps"]
  sanitizeExit?: Deno.TestDefinition["sanitizeExit"]
}

/** Test runner. */
export type tester = (...runtimes: Array<runtime | "all">) => (name: string, fn: () => Promisable<void>, options?: options) => Promisable<void>

/**
 * Run a test case with selected runtimes using their own test engine.
 *
 * The following runtimes can be used:
 * - `deno` which will use `Deno.test` directly
 * - `bun` which will call `bun test`
 * - `node` which will call `npx tsx --test`
 *
 * All runtimes mentioned above can be selected at once using the `all` keyword.
 *
 * If a runtime is not available on current system, the test will be skipped so developpers do not need to install all runtimes.
 *
 * Dependencies are resolved from `deno info` and are installed using the adequate package manager.
 * This is done only once per test file.
 *
 * When a test case is run on `deno`, default permissions are set to `none` rather than `"inherit"` (they can still be set using the {@link options} parameter).
 *
 * > [!WARNING]
 * > Since runtimes are executed using `Deno.command`, `--allow-run` permission must be specified:
 * > - `deno` is always required
 * > - `bun` is required when `bun` runtime is used
 * > - `node,npx` are required when `node` runtime is used
 *
 * > [!WARNING]
 * > It is currently not possible to use `jsr:` specifiers in runtime other than deno, which is why it is advised to use an import map to alias dependencies.
 * > When publishing on {@link https://jsr.io | jsr.io}, these will be rewritten into fully qualified specifiers (see {@link https://jsr.io/docs/publishing-packages#dependency-manifest | dependency manifest}).
 *
 * @example
 * ```ts
 * import { test, expect } from "./mod.ts"
 *
 * // Run tests on specified runtimes
 * test("all")(name, () => void expect(true))
 * test("deno", "bun", "node")(name, () => void expect(true))
 *
 * // Using custom permissions for deno runtime
 * test("deno")(name, () => expect(globalThis.Deno).toBeDefined(), { permissions: "inherit" })
 * ```
 *
 * @example
 * ```ts
 * import { test, expect } from "./mod.ts"
 *
 * // `skip` and `only` can be used to respectively ignore or restrict a test run to specific cases
 * test.skip()(name, () => void null)
 * ```
 */
export const test = Object.assign(_test.bind(null, "test"), { skip: _test.bind(null, "skip"), only: _test.bind(null, "only") }) as (tester & { skip: tester; only: tester })

/**
 * Run a single test case in multiple runtimes using their own test engine within Deno.
 *
 * If the runtime is not available, the test will be skipped.
 */
function _test(mode: mode, ...runtimes: Array<runtime | "all">): (name: string, fn: () => Promisable<void>, options?: options) => Promisable<void> {
  const global = globalThis as rw
  if (runtimes.includes("all")) {
    runtimes = Object.keys(available) as runtime[]
  }
  if (!runtimes.length) {
    runtimes = ["deno"]
  }
  // Bun runtime
  if ((global.Deno) && (runtimes.includes("bun")) && (available.bun === null)) {
    try {
      command(paths.bun, ["--version"], { stdout: null, stderr: null, sync: true, throw: true })
      Object.assign(available, { bun: true })
    } catch (error) {
      if (error instanceof Deno.errors.NotFound) {
        Object.assign(available, { bun: false })
      } else {
        throw error
      }
    }
  }
  if (global.Bun) {
    return async function (name: string, fn: () => Promisable<void>) {
      try {
        const { test } = await import(`${"bun"}:test`)
        test(name, fn)
      } catch (error) {
        throw error
      }
    }
  }
  // Node runtime
  if ((global.Deno) && (runtimes.includes("node")) && (available.node === null)) {
    try {
      command(paths.node, ["--version"], { stdout: null, stderr: null, sync: true, throw: true })
      command(paths.npx, ["tsx", "--version"], { stdout: null, stderr: null, sync: true, throw: true, winext: ".cmd" })
      Object.assign(available, { node: true })
    } catch (error) {
      if (error instanceof Deno.errors.NotFound) {
        Object.assign(available, { node: false })
      } else {
        throw error
      }
    }
  }
  if (global.process?.versions?.node) {
    return async function (name: string, fn: () => Promisable<void>) {
      try {
        const { test } = await import(`${"node"}:test`)
        test(name, fn)
      } catch (error) {
        throw error
      }
    }
  }
  // Deno runtime
  const filename = caller()
  return function (name: string, fn: () => Promisable<void>, options = { permissions: "none" } as options) {
    for (const runtime of runtimes as runtime[]) {
      const runner = { test: Deno.test, skip: Deno.test.ignore, only: Deno.test.only }[available[runtime as runtime] ? mode : "skip"]
      if ((options as { __norun?: boolean })?.__norun) {
        continue
      }
      runner(`[${runtime.padEnd(4)}] ${name}`, runtime === "deno" ? options : {}, function () {
        return testcase(runtime, filename, name, fn, (options as { __dryrun?: boolean })?.__dryrun)
      })
    }
  }
}

/** Install cache (skip install for tests within the same file).*/
export const cache = new Set<string>() as Set<string>

/** Resolve dependencies using `deno info` and install packages using the adequate package manager. */
export function install([bin, ...args]: string[], filename: string, { winext = "" } = {}) {
  if (cache.has(`${bin}:${filename}`)) {
    return
  }
  const { stdout } = command(paths.deno, ["info", "--json", filename], { stdout: "piped", stderr: null, sync: true, throw: true })
  const { packages, npmPackages: _ } = JSON.parse(stdout)
  command(bin, [...args, ...Object.keys(packages)], { stdout: null, stderr: null, sync: true, throw: true, winext, dryrun: !bin })
  cache.add(`${bin}:${filename}`)
}

/** Run test function for given filename on the specified runtime. */
export async function testcase(runtime: runtime, filename: string, name: string, fn: () => Promisable<void>, dryrun = false) {
  switch (runtime) {
    case "node":
      install([paths.npx, "jsr", "add"], filename, { winext: ".cmd" })
      await command(paths.npx, ["tsx", "--test-reporter", "spec", "--test-name-pattern", name, "--test", filename], { stdout: "piped", stderr: "piped", throw: true, env: { FORCE_COLOR: "true" }, winext: ".cmd", dryrun })
      break
    case "bun":
      install([paths.bun, "x", "jsr", "add"], filename)
      await command(paths.bun, ["test", "--test-name-pattern", name, filename], { stdout: "piped", stderr: "piped", throw: true, env: { FORCE_COLOR: "1" }, dryrun })
      break
    case "deno":
      await fn()
      break
  }
}

/** Retrieve caller test file. */
function caller() {
  const Trace = Error as unknown as { prepareStackTrace: (error: Error, stack: CallSite[]) => unknown }
  const _ = Trace.prepareStackTrace
  Trace.prepareStackTrace = (_, stack) => stack
  const { stack } = new Error()
  Trace.prepareStackTrace = _
  const caller = (stack as unknown as CallSite[])[2]
  return caller.getFileName().replaceAll("\\", "/")
}

/** V8 CallSite (subset). */
type CallSite = { getFileName: () => string }

/** Test runner mode. */
type mode = "test" | "skip" | "only"