typenative 0.4.1 → 0.6.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 (270) hide show
  1. package/.github/workflows/ci.yml +2 -2
  2. package/.github/workflows/npm-publish-github-packages.yml +2 -2
  3. package/CHANGELOG.md +442 -1
  4. package/CONTRIBUTION.md +2 -1
  5. package/README.md +73 -25
  6. package/bin/cli.js +2 -0
  7. package/bin/index.js +75 -5
  8. package/bin/main.js +2 -0
  9. package/bin/node/assert.js +2 -2
  10. package/bin/node/async_hooks.js +1 -1
  11. package/bin/node/buffer.js +16 -5
  12. package/bin/node/child_process.js +7 -7
  13. package/bin/node/cluster.js +3 -3
  14. package/bin/node/core.js +41 -0
  15. package/bin/node/crypto_keys.js +21 -21
  16. package/bin/node/dgram.js +1 -1
  17. package/bin/node/diagnostics_channel.js +3 -3
  18. package/bin/node/dns.js +2 -2
  19. package/bin/node/events.js +18 -13
  20. package/bin/node/fetch.js +2 -2
  21. package/bin/node/fs.js +3 -3
  22. package/bin/node/fs_watch.js +5 -5
  23. package/bin/node/http.js +3 -3
  24. package/bin/node/http2.js +3 -3
  25. package/bin/node/net.js +8 -8
  26. package/bin/node/path.js +17 -3
  27. package/bin/node/process.js +47 -11
  28. package/bin/node/punycode.js +2 -2
  29. package/bin/node/readline.js +1 -1
  30. package/bin/node/registry.js +4 -1
  31. package/bin/node/sqlite.js +6 -6
  32. package/bin/node/stream.js +81 -15
  33. package/bin/node/stream_web.js +10 -10
  34. package/bin/node/system_extra.js +3 -3
  35. package/bin/node/test.js +674 -366
  36. package/bin/node/test_coverage.js +187 -0
  37. package/bin/node/test_report.js +1392 -0
  38. package/bin/node/test_run.js +575 -0
  39. package/bin/node/timers.js +8 -6
  40. package/bin/node/tls.js +5 -5
  41. package/bin/node/url.js +1 -1
  42. package/bin/node/util.js +31 -7
  43. package/bin/node/util_extra.js +7 -7
  44. package/bin/node/webview.js +654 -0
  45. package/bin/node/worker_threads.js +1 -1
  46. package/bin/node/zlib.js +3 -3
  47. package/bin/parse-node.js +6 -2
  48. package/bin/regex_vm.js +2057 -0
  49. package/bin/transpiler.js +32872 -11265
  50. package/bin/typecheck-node.js +2 -1
  51. package/bin/version.js +1 -1
  52. package/conformance.md +515 -345
  53. package/examples/README.md +71 -11
  54. package/examples/angular-templates/README.md +139 -0
  55. package/examples/angular-templates/bench.mjs +173 -0
  56. package/examples/angular-templates/dom-type-globals.d.ts +21 -0
  57. package/examples/angular-templates/dom-type-stubs.ts +21 -0
  58. package/examples/angular-templates/main.ts +135 -0
  59. package/examples/angular-templates/parity.mjs +157 -0
  60. package/examples/angular-templates/run-node.mjs +69 -0
  61. package/examples/angular-templates/vendor/angular/compiler/LICENSE +21 -0
  62. package/examples/desktop-notes/README.md +106 -0
  63. package/examples/desktop-notes/bench.mjs +125 -0
  64. package/examples/desktop-notes/main.ts +131 -0
  65. package/examples/desktop-notes/package-lock.json +726 -0
  66. package/examples/desktop-notes/package.json +9 -0
  67. package/examples/desktop-notes/ui.ts +176 -0
  68. package/examples/dupe-finder/README.md +78 -0
  69. package/examples/dupe-finder/bench.mjs +120 -0
  70. package/examples/dupe-finder/main.ts +87 -0
  71. package/examples/fibonacci/README.md +7 -7
  72. package/examples/hello-world/README.md +6 -6
  73. package/examples/json-server/README.md +19 -18
  74. package/examples/mandelbrot-png/README.md +63 -0
  75. package/examples/mandelbrot-png/bench.mjs +95 -0
  76. package/examples/mandelbrot-png/main.ts +98 -0
  77. package/examples/mandelbrot-png/preview.png +0 -0
  78. package/examples/marked-cli/README.md +160 -0
  79. package/examples/marked-cli/bench.mjs +178 -0
  80. package/examples/marked-cli/main.ts +292 -0
  81. package/examples/marked-cli/parity.mjs +185 -0
  82. package/examples/marked-cli/vendor/marked/LICENSE +44 -0
  83. package/examples/marked-cli/vendor/marked/VENDOR.md +26 -0
  84. package/examples/openai-chat/README.md +148 -0
  85. package/examples/openai-chat/bench.mjs +175 -0
  86. package/examples/openai-chat/main.ts +488 -0
  87. package/examples/react-compiler/README.md +170 -0
  88. package/examples/react-compiler/bench.mjs +181 -0
  89. package/examples/react-compiler/main.ts +158 -0
  90. package/examples/react-compiler/parity.mjs +362 -0
  91. package/examples/react-compiler/run-node.mjs +88 -0
  92. package/examples/react-compiler/vendor/babel/LICENSE +22 -0
  93. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +15 -0
  94. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +51 -0
  95. package/examples/react-compiler/vendor/charcodes/package.json +25 -0
  96. package/examples/react-compiler/vendor/invariant/LICENSE +21 -0
  97. package/examples/react-compiler/vendor/invariant/invariant.cjs +51 -0
  98. package/examples/react-compiler/vendor/invariant/invariant.d.cts +11 -0
  99. package/examples/react-compiler/vendor/invariant/types/LICENSE +21 -0
  100. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +19 -0
  101. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +19 -0
  102. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +19 -0
  103. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +19 -0
  104. package/examples/react-compiler/vendor/js-tokens/LICENSE +21 -0
  105. package/examples/react-compiler/vendor/js-tokens/index.cjs +23 -0
  106. package/examples/react-compiler/vendor/js-tokens/index.d.cts +13 -0
  107. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +20 -0
  108. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +337 -0
  109. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +384 -0
  110. package/examples/react-compiler/vendor/jsesc/types/LICENSE +21 -0
  111. package/examples/react-compiler/vendor/picocolors/LICENSE +15 -0
  112. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +75 -0
  113. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +5 -0
  114. package/examples/react-compiler/vendor/picocolors/types.d.ts +51 -0
  115. package/examples/react-compiler/vendor/react-compiler/LICENSE +21 -0
  116. package/examples/react-compiler/vendor/stubs/babel-core.ts +31 -0
  117. package/examples/react-compiler/vendor/stubs/debug.ts +18 -0
  118. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +13 -0
  119. package/examples/react-compiler/vendor/stubs/pretty-format.ts +18 -0
  120. package/examples/react-compiler/vendor/zod/LICENSE +21 -0
  121. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +9 -0
  122. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +5 -0
  123. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +49 -0
  124. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +48 -0
  125. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +50 -0
  126. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +6 -0
  127. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +126 -0
  128. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +39 -0
  129. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +12 -0
  130. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +78 -0
  131. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +2 -0
  132. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +12 -0
  133. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +12 -0
  134. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +131 -0
  135. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +54 -0
  136. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +12 -0
  137. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +40 -0
  138. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +12 -0
  139. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +76 -0
  140. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +76 -0
  141. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +27 -0
  142. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +27 -0
  143. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +13 -0
  144. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +61 -0
  145. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +38 -0
  146. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +20 -0
  147. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +5 -0
  148. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +8 -0
  149. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +11 -0
  150. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +20 -0
  151. package/examples/react-compiler/vendor.mjs +688 -0
  152. package/examples/todo-cli/README.md +69 -0
  153. package/examples/todo-cli/bench.mjs +89 -0
  154. package/examples/todo-cli/main.ts +92 -0
  155. package/examples/yaml-cli/README.md +146 -0
  156. package/examples/yaml-cli/bench.mjs +265 -0
  157. package/examples/yaml-cli/main.ts +29 -0
  158. package/examples/yaml-cli/parity.mjs +156 -0
  159. package/examples/yaml-cli/vendor/yaml/LICENSE +13 -0
  160. package/examples/yaml-cli/vendor/yaml/VENDOR.md +25 -0
  161. package/govendor/github.com/jchv/go-webview2/LICENSE +22 -0
  162. package/govendor/github.com/jchv/go-webview2/README.md +21 -0
  163. package/govendor/github.com/jchv/go-webview2/common.go +84 -0
  164. package/govendor/github.com/jchv/go-webview2/go.mod +3 -0
  165. package/govendor/github.com/jchv/go-webview2/internal/w32/w32.go +194 -0
  166. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_386.go +14 -0
  167. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_64bit.go +15 -0
  168. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_COLOR.go +8 -0
  169. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.go +9 -0
  170. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_KEY_EVENT_KIND.go +10 -0
  171. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_MOVE_FOCUS_REASON.go +9 -0
  172. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_PHYSICAL_KEY_STATUS.go +10 -0
  173. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_WEB_RESOURCE_CONTEXT.go +23 -0
  174. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventArgs.go +78 -0
  175. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventHandler.go +52 -0
  176. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller.go +132 -0
  177. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller2.go +74 -0
  178. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2CreateCoreWebView2ControllerCompletedHandler.go +48 -0
  179. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventArgs.go +17 -0
  180. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventHandler.go +48 -0
  181. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Settings.go +270 -0
  182. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequest.go +43 -0
  183. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventArgs.go +51 -0
  184. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventHandler.go +48 -0
  185. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceResponse.go +21 -0
  186. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_2.go +21 -0
  187. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_3.go +60 -0
  188. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebViewSettings.go +396 -0
  189. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium.go +361 -0
  190. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_386.go +24 -0
  191. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_amd64.go +22 -0
  192. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_arm64.go +26 -0
  193. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc.go +13 -0
  194. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go17.go +51 -0
  195. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go18.go +16 -0
  196. package/govendor/github.com/jchv/go-webview2/pkg/edge/corewebview2.go +411 -0
  197. package/govendor/github.com/jchv/go-webview2/pkg/edge/guid.go +223 -0
  198. package/govendor/github.com/jchv/go-webview2/webview.go +482 -0
  199. package/govendor/github.com/jchv/go-webview2/webviewloader/README.md +3 -0
  200. package/govendor/github.com/jchv/go-webview2/webviewloader/module.go +153 -0
  201. package/govendor/github.com/jchv/go-webview2/webviewloader/module_386.go +6 -0
  202. package/govendor/github.com/jchv/go-webview2/webviewloader/module_amd64.go +6 -0
  203. package/govendor/github.com/jchv/go-webview2/webviewloader/module_arm64.go +6 -0
  204. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/arm64/WebView2Loader.dll +0 -0
  205. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x64/WebView2Loader.dll +0 -0
  206. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x86/WebView2Loader.dll +0 -0
  207. package/govendor/github.com/jchv/go-winloader/LICENSE.md +7 -0
  208. package/govendor/github.com/jchv/go-winloader/README.md +124 -0
  209. package/govendor/github.com/jchv/go-winloader/common.go +11 -0
  210. package/govendor/github.com/jchv/go-winloader/go.mod +3 -0
  211. package/govendor/github.com/jchv/go-winloader/internal/loader/loader.go +25 -0
  212. package/govendor/github.com/jchv/go-winloader/internal/loader/machine.go +53 -0
  213. package/govendor/github.com/jchv/go-winloader/internal/memloader/cache.go +42 -0
  214. package/govendor/github.com/jchv/go-winloader/internal/memloader/loader.go +253 -0
  215. package/govendor/github.com/jchv/go-winloader/internal/pe/export.go +76 -0
  216. package/govendor/github.com/jchv/go-winloader/internal/pe/format.go +522 -0
  217. package/govendor/github.com/jchv/go-winloader/internal/pe/import.go +106 -0
  218. package/govendor/github.com/jchv/go-winloader/internal/pe/module.go +91 -0
  219. package/govendor/github.com/jchv/go-winloader/internal/pe/reloc.go +177 -0
  220. package/govendor/github.com/jchv/go-winloader/internal/pe/util.go +40 -0
  221. package/govendor/github.com/jchv/go-winloader/internal/vmem/common.go +55 -0
  222. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_other.go +71 -0
  223. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_windows.go +179 -0
  224. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_other.go +17 -0
  225. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_windows.go +73 -0
  226. package/govendor/github.com/jchv/go-winloader/internal/winloader/loader_windows.go +64 -0
  227. package/govendor/github.com/jchv/go-winloader/internal/winloader/machine_windows.go +32 -0
  228. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_386.go +9 -0
  229. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_amd64.go +9 -0
  230. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_arm64.go +9 -0
  231. package/govendor/github.com/jchv/go-winloader/loader_other.go +24 -0
  232. package/govendor/github.com/jchv/go-winloader/loader_windows.go +33 -0
  233. package/govendor/manifest.txt +3 -1
  234. package/package.json +8 -5
  235. package/performance/README.md +195 -0
  236. package/performance/any-dynamic.ts +21 -0
  237. package/performance/any-record-view.ts +20 -0
  238. package/performance/arr-hof.ts +21 -0
  239. package/performance/arr-push-index.ts +15 -0
  240. package/performance/arr-sort.ts +21 -0
  241. package/performance/async-await.ts +24 -0
  242. package/performance/class-dispatch.ts +52 -0
  243. package/performance/events-emit.ts +27 -0
  244. package/performance/exc-throw-rare.ts +25 -0
  245. package/performance/exc-try-catch.ts +26 -0
  246. package/performance/fn-closures.ts +29 -0
  247. package/performance/fn-recursion-tree.ts +31 -0
  248. package/performance/gen-for-of.ts +46 -0
  249. package/performance/json-roundtrip.ts +27 -0
  250. package/performance/map-delete.ts +24 -0
  251. package/performance/map-string-keys.ts +22 -0
  252. package/performance/num-arith-loop.ts +14 -0
  253. package/performance/num-bitwise.ts +21 -0
  254. package/performance/num-mod-int.ts +16 -0
  255. package/performance/num-to-string.ts +16 -0
  256. package/performance/obj-alloc.ts +32 -0
  257. package/performance/regex-exec.ts +29 -0
  258. package/performance/regex-site.ts +28 -0
  259. package/performance/set-ops.ts +20 -0
  260. package/performance/str-char-scan.ts +35 -0
  261. package/performance/str-concat-plus.ts +18 -0
  262. package/performance/str-concat.ts +24 -0
  263. package/performance/str-short-scan.ts +26 -0
  264. package/performance/str-split-join.ts +23 -0
  265. package/performance/str-template.ts +16 -0
  266. package/performance/union-switch.ts +57 -0
  267. package/tsparser/check.go +2 -1
  268. package/tsparser/main.go +5 -0
  269. package/types/typenative-npm.d.ts +193 -4
  270. package/types/typenative.d.ts +138 -41
package/bin/node/test.js CHANGED
@@ -1,10 +1,15 @@
1
1
  // node:test — test / it / describe / suite with hooks, subtests (t.test),
2
- // skip / todo, timeouts, async and callback-style tests, and mock.fn. Tests
3
- // are collected while the program runs and executed one after another once
4
- // the main module has finished (as in Node); the report uses Node's TAP
5
- // reporter, or the spec reporter when stdout is a terminal. A failure sets
6
- // the exit code to 1.
2
+ // skip / todo, timeouts, async and callback-style tests, mocks and snapshots.
3
+ // Tests are collected while the program runs and executed one after another
4
+ // once the main module has finished (as in Node). The runner reports through
5
+ // events (Node's test:start / test:pass / test:fail / …), which the
6
+ // reporters in test_report.ts turn into TAP, spec, dot, junit or lcov text
7
+ // for each --test-reporter / --test-reporter-destination pair. A failure
8
+ // sets the exit code to 1.
7
9
  import { defineClass, defineHelper, defineModule, setResults } from './registry.js';
10
+ import { registerTestReporters } from './test_report.js';
11
+ import { registerTestRun } from './test_run.js';
12
+ import { registerTestCoverage } from './test_coverage.js';
8
13
  const testHelper = `// node:test
9
14
  type TnTestNode struct {
10
15
  name string
@@ -25,25 +30,30 @@ type TnTestNode struct {
25
30
  status string
26
31
  err interface{}
27
32
  failureType string
33
+ failure *TnError
28
34
  duration float64
29
35
  diagnostics []string
30
36
  started bool
31
- headerShown bool
32
37
  ctx *TnTestContext
33
38
  done chan struct{}
39
+ // where test() / describe() was called
40
+ file string
41
+ line float64
42
+ column float64
34
43
  }
35
44
 
36
45
  var tnTestRoot = &TnTestNode{suite: true}
37
46
  var tnTestCurrent = tnTestRoot
38
47
  var tnTestRunning *TnTestNode
39
48
  var tnTestScheduled bool
40
- var tnTestSpec bool
41
- var tnTestTap bool
42
- var tnTestReporter string
43
- var tnTestColor bool
44
- var tnTestStart time.Time
49
+ var tnTestStart float64
45
50
  var tnTestCounts = map[string]int{}
46
- var tnTestFailures []*TnTestNode
51
+
52
+ // Hooks of the optional parts: a run() child sends its events to the parent;
53
+ // coverage and snapshots finish when the run does
54
+ var tnTestChildSink func(e *TnTestEvent)
55
+ var tnTestCoverage func(cfg *tnTestConfig) *TnCoverageSummary
56
+ var tnTestSnapshotsDone func()
47
57
 
48
58
  // TestContext (t)
49
59
  type TnTestContext struct {
@@ -65,7 +75,14 @@ func (t *TnTestContext) Get_fullName() string {
65
75
  }
66
76
  func (t *TnTestContext) Get_mock() *TnMockTracker { return t.mock }
67
77
  func (t *TnTestContext) Get_signal() *TnAbortSignal { return t.signal }
78
+
79
+ // The source file the test was declared in
68
80
  func (t *TnTestContext) Get_filePath() string {
81
+ for n := t.node; n != nil; n = n.parent {
82
+ if n.file != "" {
83
+ return n.file
84
+ }
85
+ }
69
86
  if len(os.Args) > 0 {
70
87
  return os.Args[0]
71
88
  }
@@ -98,8 +115,9 @@ func (t *TnTestContext) plan(n float64, options ...interface{}) {
98
115
  func (t *TnTestContext) runOnly(flag bool) {}
99
116
 
100
117
  // t.test(name, [options], fn): runs the subtest now; resolves when it is done
101
- func (t *TnTestContext) test(args ...interface{}) chan struct{} {
118
+ func (t *TnTestContext) test(file string, line float64, column float64, args ...interface{}) chan struct{} {
102
119
  child := tnTestNew(false, args)
120
+ tnTestLocate(child, file, line, column)
103
121
  child.parent = t.node
104
122
  t.node.children = append(t.node.children, child)
105
123
  t.asserts++
@@ -133,22 +151,22 @@ func tnTestNew(suite bool, args []interface{}) *TnTestNode {
133
151
  n.fn = a
134
152
  continue
135
153
  }
136
- switch s := TnGet(a, "skip").(type) {
154
+ switch s := TnGetValue(a, "skip").(type) {
137
155
  case bool:
138
156
  n.skip = s
139
157
  case string:
140
158
  n.skip, n.skipMsg = true, s
141
159
  }
142
- switch td := TnGet(a, "todo").(type) {
160
+ switch td := TnGetValue(a, "todo").(type) {
143
161
  case bool:
144
162
  n.todo = td
145
163
  case string:
146
164
  n.todo, n.todoMsg = true, td
147
165
  }
148
- if ms, ok := TnGet(a, "timeout").(float64); ok {
166
+ if ms, ok := TnGetValue(a, "timeout").(float64); ok {
149
167
  n.timeoutMs = ms
150
168
  }
151
- if only, ok := TnGet(a, "only").(bool); ok {
169
+ if only, ok := TnGetValue(a, "only").(bool); ok {
152
170
  n.only = only
153
171
  }
154
172
  }
@@ -156,6 +174,14 @@ func tnTestNew(suite bool, args []interface{}) *TnTestNode {
156
174
  return n
157
175
  }
158
176
 
177
+ // The call site (a source path with forward slashes, as the compiler knows it)
178
+ func tnTestLocate(n *TnTestNode, file string, line float64, column float64) {
179
+ if file != "" {
180
+ n.file = filepath.FromSlash(file)
181
+ }
182
+ n.line, n.column = line, column
183
+ }
184
+
159
185
  func tnTestIsFunc(v interface{}) bool {
160
186
  rv := reflect.ValueOf(v)
161
187
  return rv.IsValid() && rv.Kind() == reflect.Func && !rv.IsNil()
@@ -170,8 +196,9 @@ func tnTestDepth(n *TnTestNode) int {
170
196
  }
171
197
 
172
198
  // test() / it(): registered with the enclosing describe (or the running test)
173
- func TnTestRegister(variant string, args ...interface{}) chan struct{} {
199
+ func TnTestRegister(variant string, file string, line float64, column float64, args ...interface{}) chan struct{} {
174
200
  n := tnTestNew(false, args)
201
+ tnTestLocate(n, file, line, column)
175
202
  switch variant {
176
203
  case "skip":
177
204
  n.skip = true
@@ -198,8 +225,9 @@ func TnTestRegister(variant string, args ...interface{}) chan struct{} {
198
225
  }
199
226
 
200
227
  // describe() / suite(): the body runs now and registers the suite's tests
201
- func TnSuiteRegister(variant string, args ...interface{}) chan struct{} {
228
+ func TnSuiteRegister(variant string, file string, line float64, column float64, args ...interface{}) chan struct{} {
202
229
  n := tnTestNew(true, args)
230
+ tnTestLocate(n, file, line, column)
203
231
  switch variant {
204
232
  case "skip":
205
233
  n.skip = true
@@ -247,12 +275,14 @@ func TnTestHook(kind string, fn interface{}, options ...interface{}) {
247
275
  tnTestSchedule()
248
276
  }
249
277
 
250
- // The run starts once the main module has finished (a loop task)
278
+ // The run starts once the main module has finished (a loop task); the
279
+ // reporters are set up by the first test(), as Node does
251
280
  func tnTestSchedule() {
252
281
  if tnTestScheduled {
253
282
  return
254
283
  }
255
284
  tnTestScheduled = true
285
+ tnTestOpenReporters()
256
286
  TnLoopRef()
257
287
  TnLoopPost(func() {
258
288
  TnStartAsync(func() {
@@ -280,7 +310,7 @@ func tnTestInvoke(fn interface{}, ctx *TnTestContext, timeoutMs float64) tnTestO
280
310
  if timeoutMs > 0 && !math.IsInf(timeoutMs, 1) {
281
311
  ms := timeoutMs
282
312
  timer := time.AfterFunc(time.Duration(ms*float64(time.Millisecond)), func() {
283
- settle(tnTestOutcome{err: TnNodeError("Error", "ERR_TEST_FAILURE", "test timed out after "+strconv.FormatFloat(ms, 'f', -1, 64)+"ms"), failed: true, timedOut: true})
313
+ settle(tnTestOutcome{err: "test timed out after " + strconv.FormatFloat(ms, 'f', -1, 64) + "ms", failed: true, timedOut: true})
284
314
  })
285
315
  defer timer.Stop()
286
316
  }
@@ -357,12 +387,21 @@ func tnTestAncestors(n *TnTestNode) []*TnTestNode {
357
387
 
358
388
  // The test runner's flags, from NODE_OPTIONS as Node reads them:
359
389
  // --test-name-pattern / --test-skip-pattern (repeatable, "/re/flags" or a
360
- // plain regular expression), --test-only and --test-reporter
390
+ // plain regular expression), --test-only, --test-reporter /
391
+ // --test-reporter-destination (repeatable, in pairs),
392
+ // --test-update-snapshots and the coverage flags
361
393
  type tnTestConfig struct {
362
- names []*regexp.Regexp
363
- skips []*regexp.Regexp
364
- only bool
365
- reporter string
394
+ names []*regexp.Regexp
395
+ skips []*regexp.Regexp
396
+ only bool
397
+ reporters []string
398
+ destinations []string
399
+ updateSnapshots bool
400
+ coverage bool
401
+ coverageInclude []string
402
+ coverageExclude []string
403
+ // --test-coverage-lines / -branches / -functions (0: no threshold)
404
+ thresholds map[string]float64
366
405
  }
367
406
 
368
407
  func (c *tnTestConfig) active() bool { return len(c.names) > 0 || len(c.skips) > 0 || c.only }
@@ -415,16 +454,21 @@ func tnTestPattern(s string) *regexp.Regexp {
415
454
  return re
416
455
  }
417
456
 
457
+ var tnTestValueFlags = map[string]bool{
458
+ "--test-name-pattern": true, "--test-skip-pattern": true, "--test-reporter": true, "--test-reporter-destination": true,
459
+ "--test-coverage-include": true, "--test-coverage-exclude": true,
460
+ "--test-coverage-lines": true, "--test-coverage-branches": true, "--test-coverage-functions": true,
461
+ }
462
+
418
463
  func tnTestFilters() *tnTestConfig {
419
464
  if tnTestCfg != nil {
420
465
  return tnTestCfg
421
466
  }
422
- c := &tnTestConfig{}
467
+ c := &tnTestConfig{thresholds: map[string]float64{}}
423
468
  words := tnNodeOptionWords(os.Getenv("NODE_OPTIONS"))
424
469
  for i := 0; i < len(words); i++ {
425
470
  name, value, hasValue := strings.Cut(words[i], "=")
426
- takesValue := name == "--test-name-pattern" || name == "--test-skip-pattern" || name == "--test-reporter"
427
- if takesValue && !hasValue && i+1 < len(words) {
471
+ if tnTestValueFlags[name] && !hasValue && i+1 < len(words) {
428
472
  i++
429
473
  value = words[i]
430
474
  }
@@ -436,7 +480,21 @@ func tnTestFilters() *tnTestConfig {
436
480
  case "--test-only":
437
481
  c.only = true
438
482
  case "--test-reporter":
439
- c.reporter = value
483
+ c.reporters = append(c.reporters, value)
484
+ case "--test-reporter-destination":
485
+ c.destinations = append(c.destinations, value)
486
+ case "--test-update-snapshots":
487
+ c.updateSnapshots = true
488
+ case "--experimental-test-coverage":
489
+ c.coverage = true
490
+ case "--test-coverage-include":
491
+ c.coverageInclude = append(c.coverageInclude, value)
492
+ case "--test-coverage-exclude":
493
+ c.coverageExclude = append(c.coverageExclude, value)
494
+ case "--test-coverage-lines", "--test-coverage-branches", "--test-coverage-functions":
495
+ if n, err := strconv.ParseFloat(value, 64); err == nil {
496
+ c.thresholds[strings.TrimPrefix(name, "--test-coverage-")] = n
497
+ }
440
498
  }
441
499
  }
442
500
  tnTestCfg = c
@@ -499,25 +557,137 @@ func tnTestPrune(n *TnTestNode) bool {
499
557
  return len(kept) > 0
500
558
  }
501
559
 
502
- func tnRunRoot() {
503
- tnTestStart = time.Now()
560
+ // --- reporting ---
561
+
562
+ // A reporter and where its text goes
563
+ type tnTestSink struct {
564
+ reporter tnTestReporter
565
+ out *os.File
566
+ file bool
567
+ }
568
+
569
+ func (s *tnTestSink) write(text string) {
570
+ if text != "" {
571
+ s.out.WriteString(text)
572
+ }
573
+ }
574
+
575
+ var tnTestSinks []*tnTestSink
576
+
577
+ // --test-reporter / --test-reporter-destination, paired as Node pairs them
578
+ // (the default: spec on a terminal, else tap, to stdout)
579
+ func tnTestOpenReporters() {
580
+ if tnTestChildSink != nil {
581
+ return
582
+ }
504
583
  cfg := tnTestFilters()
505
- tnTestReporter = cfg.reporter
506
- if tnTestReporter != "spec" && tnTestReporter != "dot" && tnTestReporter != "junit" && tnTestReporter != "tap" {
507
- tnTestReporter = "tap"
584
+ reporters, destinations := cfg.reporters, cfg.destinations
585
+ if len(reporters) == 0 && len(destinations) == 0 {
586
+ reporters = []string{"tap"}
508
587
  if TnIsTTY(os.Stdout) {
509
- tnTestReporter = "spec"
588
+ reporters = []string{"spec"}
589
+ }
590
+ }
591
+ if len(reporters) == 1 && len(destinations) == 0 {
592
+ destinations = []string{"stdout"}
593
+ }
594
+ if len(destinations) != len(reporters) {
595
+ received := make([]interface{}, len(reporters))
596
+ for i, r := range reporters {
597
+ received[i] = r
598
+ }
599
+ panic(TnNodeError("TypeError", "ERR_INVALID_ARG_VALUE", "The argument '--test-reporter' must match the number of specified '--test-reporter-destination'. Received "+TnInspect(received)))
600
+ }
601
+ for i, name := range reporters {
602
+ sink := &tnTestSink{}
603
+ colors := tnTestColorsOn()
604
+ switch destinations[i] {
605
+ case "stdout":
606
+ sink.out = os.Stdout
607
+ case "stderr":
608
+ sink.out = os.Stderr
609
+ default:
610
+ path := destinations[i]
611
+ os.MkdirAll(filepath.Dir(path), 0o755)
612
+ f, err := os.Create(path)
613
+ if err != nil {
614
+ panic(TnNodeError("Error", "ENOENT", err.Error()))
615
+ }
616
+ sink.out, sink.file, colors = f, true, false
617
+ }
618
+ sink.reporter = tnNewTestReporter(name, colors)
619
+ if sink.reporter == nil {
620
+ cwd, _ := os.Getwd()
621
+ panic(TnNodeError("Error", "ERR_MODULE_NOT_FOUND", "Cannot find package '"+name+"' imported from "+cwd))
622
+ }
623
+ tnTestSinks = append(tnTestSinks, sink)
624
+ }
625
+ }
626
+
627
+ func tnTestEmit(e *TnTestEvent) {
628
+ if tnTestChildSink != nil {
629
+ tnTestChildSink(e)
630
+ return
631
+ }
632
+ for _, s := range tnTestSinks {
633
+ s.write(s.reporter.report(e))
634
+ }
635
+ }
636
+
637
+ func tnTestNumber(n *TnTestNode) int {
638
+ if n.parent != nil {
639
+ for i, c := range n.parent.children {
640
+ if c == n {
641
+ return i + 1
642
+ }
510
643
  }
511
644
  }
512
- tnTestSpec = tnTestReporter == "spec"
513
- tnTestTap = tnTestReporter == "tap"
514
- tnTestColor = (tnTestSpec || tnTestReporter == "dot") && TnIsTTY(os.Stdout) && os.Getenv("NO_COLOR") == ""
515
- if tnTestTap {
516
- fmt.Println("TAP version 13")
645
+ return 1
646
+ }
647
+
648
+ func tnTestEventFor(kind string, n *TnTestNode, depth int) *TnTestEvent {
649
+ d := &TnTestEventData{name: n.name, nesting: float64(depth), file: n.file, line: n.line, column: n.column}
650
+ if kind != "test:start" {
651
+ d.testNumber = float64(tnTestNumber(n))
652
+ kindName := "test"
653
+ if n.suite {
654
+ kindName = "suite"
655
+ }
656
+ d.details = &TnTestEventDetails{duration_ms: math.Round(n.duration*1e6) / 1e6, type_: kindName, passed: n.status != "fail"}
657
+ if n.err != nil {
658
+ if n.failure == nil {
659
+ n.failure = tnTestFailure(n.err, n.failureType)
660
+ }
661
+ d.details.error_ = n.failure
662
+ }
663
+ if n.skip {
664
+ d.skip = true
665
+ if n.skipMsg != "" {
666
+ d.skip = n.skipMsg
667
+ }
668
+ } else if n.todo {
669
+ d.todo = true
670
+ if n.todoMsg != "" {
671
+ d.todo = n.todoMsg
672
+ }
673
+ }
517
674
  }
518
- if tnTestReporter == "junit" {
519
- fmt.Println("<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>")
520
- fmt.Println("<testsuites>")
675
+ return &TnTestEvent{type_: kind, data: d}
676
+ }
677
+
678
+ func tnTestNote(nesting int, message string, level string, n *TnTestNode) *TnTestEvent {
679
+ d := &TnTestEventData{nesting: float64(nesting), message: message, level: level}
680
+ if n != nil {
681
+ d.file, d.line, d.column = n.file, n.line, n.column
682
+ }
683
+ return &TnTestEvent{type_: "test:diagnostic", data: d}
684
+ }
685
+
686
+ func tnRunRoot() {
687
+ tnTestStart = tnTestNow()
688
+ cfg := tnTestFilters()
689
+ for _, s := range tnTestSinks {
690
+ s.write(s.reporter.begin())
521
691
  }
522
692
  root := tnTestRoot
523
693
  if cfg.active() {
@@ -538,16 +708,12 @@ func tnRunRoot() {
538
708
 
539
709
  func tnRunTestNode(n *TnTestNode, depth int) {
540
710
  n.started = true
541
- tnTestShowParents(n)
542
- indent := strings.Repeat(" ", depth)
543
- if tnTestTap {
544
- fmt.Println(indent + "# Subtest: " + n.name)
545
- }
711
+ tnTestEmit(tnTestEventFor("test:start", n, depth))
546
712
  // .only without --test-only: Node's notice, as the test's diagnostic
547
713
  if n.only && !tnTestFilters().only {
548
714
  n.diagnostics = append(n.diagnostics, "'only' and 'runOnly' require the --test-only command-line option.")
549
715
  }
550
- start := time.Now()
716
+ start := tnTestNow()
551
717
  ctx := &TnTestContext{node: n, mock: TnNewMockTracker(), signal: TnNewAbortSignal()}
552
718
  n.ctx = ctx
553
719
  defer func() {
@@ -609,12 +775,12 @@ func tnRunTestNode(n *TnTestNode, depth int) {
609
775
  n.failureType = "testCodeFailure"
610
776
  }
611
777
  } else if ctx.planSet && ctx.planned != ctx.asserts {
612
- n.err = TnNodeError("Error", "ERR_TEST_FAILURE", "plan expected "+strconv.FormatFloat(ctx.planned, 'f', -1, 64)+" assertions but received "+strconv.FormatFloat(ctx.asserts, 'f', -1, 64))
778
+ n.err = "plan expected " + strconv.FormatFloat(ctx.planned, 'f', -1, 64) + " assertions but received " + strconv.FormatFloat(ctx.asserts, 'f', -1, 64)
613
779
  n.failureType = "testCodeFailure"
614
780
  }
615
781
  tnTestRunning = prev
616
782
  }
617
- n.duration = float64(time.Since(start).Nanoseconds()) / 1e6
783
+ n.duration = tnTestNow() - start
618
784
  switch {
619
785
  case n.skip:
620
786
  n.status = "skip"
@@ -624,23 +790,20 @@ func tnRunTestNode(n *TnTestNode, depth int) {
624
790
  n.status = "fail"
625
791
  default:
626
792
  n.status = "pass"
627
- for _, child := range n.children {
628
- if child.status == "fail" {
629
- n.status = "fail"
630
- failed := 0
631
- for _, c := range n.children {
632
- if c.status == "fail" {
633
- failed++
634
- }
635
- }
636
- noun := "subtest"
637
- if failed > 1 {
638
- noun = "subtests"
639
- }
640
- n.err = TnNodeError("Error", "ERR_TEST_FAILURE", strconv.Itoa(failed)+" "+noun+" failed")
641
- n.failureType = "subtestsFailed"
642
- break
793
+ failed := 0
794
+ for _, c := range n.children {
795
+ if c.status == "fail" {
796
+ failed++
797
+ }
798
+ }
799
+ if failed > 0 {
800
+ n.status = "fail"
801
+ noun := "subtest"
802
+ if failed > 1 {
803
+ noun = "subtests"
643
804
  }
805
+ n.err = strconv.Itoa(failed) + " " + noun + " failed"
806
+ n.failureType = "subtestsFailed"
644
807
  }
645
808
  }
646
809
  if n.suite {
@@ -656,9 +819,6 @@ func tnRunTestNode(n *TnTestNode, depth int) {
656
819
  } else {
657
820
  tnTestCounts["fail"]++
658
821
  }
659
- if n.failureType != "subtestsFailed" {
660
- tnTestFailures = append(tnTestFailures, n)
661
- }
662
822
  case "skip":
663
823
  tnTestCounts["skipped"]++
664
824
  case "todo":
@@ -668,314 +828,69 @@ func tnRunTestNode(n *TnTestNode, depth int) {
668
828
  tnTestReport(n, depth)
669
829
  }
670
830
 
671
- // Spec reporter: a parent's ▶ line comes before its first child's output
672
- func tnTestShowParents(n *TnTestNode) {
673
- if !tnTestSpec {
674
- return
675
- }
676
- chain := tnTestAncestors(n)
677
- for i, p := range chain {
678
- if p.parent == nil || p.headerShown {
679
- continue
680
- }
681
- p.headerShown = true
682
- fmt.Println(strings.Repeat(" ", i-1) + "\\u25b6 " + p.name)
683
- }
684
- }
685
-
686
- func tnTestColorize(code string, s string) string {
687
- if !tnTestColor {
688
- return s
689
- }
690
- return "\\x1b[" + code + "m" + s + "\\x1b[39m"
691
- }
692
-
693
- func tnTestDuration(ms float64) string {
694
- return strconv.FormatFloat(math.Round(ms*1e6)/1e6, 'f', -1, 64)
695
- }
696
-
697
- func tnTestErrorField(err interface{}, key string) interface{} {
698
- if e, ok := err.(*TnError); ok {
699
- if key == "message" {
700
- return e.message
701
- }
702
- if key == "code" {
703
- if e.code != "" {
704
- return e.code
705
- }
706
- }
707
- if key == "name" {
708
- return e.Get_name()
709
- }
710
- return e.prop(key)
711
- }
712
- if key == "message" {
713
- return TnJSString(err)
714
- }
715
- return nil
716
- }
717
-
718
- func tnTestYamlString(s string, indent string) string {
719
- if strings.Contains(s, "\\n") {
720
- lines := strings.Split(s, "\\n")
721
- for i, l := range lines {
722
- lines[i] = indent + " " + l
723
- }
724
- return "|-\\n" + strings.Join(lines, "\\n")
725
- }
726
- return "'" + strings.ReplaceAll(s, "'", "''") + "'"
727
- }
728
-
831
+ // A finished test's events: complete, its subtests' plan, pass / fail, diagnostics
729
832
  func tnTestReport(n *TnTestNode, depth int) {
730
- switch tnTestReporter {
731
- case "spec":
732
- tnTestReportSpec(n, depth)
733
- return
734
- case "dot":
735
- mark := "."
736
- if n.status == "fail" {
737
- mark = tnTestColorize("31", "X")
738
- }
739
- fmt.Print(mark)
740
- return
741
- case "junit":
742
- return
743
- }
744
- indent := strings.Repeat(" ", depth)
833
+ tnTestEmit(tnTestEventFor("test:complete", n, depth))
745
834
  if len(n.children) > 0 {
746
- fmt.Println(indent + " 1.." + strconv.Itoa(len(n.children)))
747
- }
748
- number := 1
749
- if n.parent != nil {
750
- for i, c := range n.parent.children {
751
- if c == n {
752
- number = i + 1
753
- }
754
- }
755
- }
756
- line := "ok"
757
- if n.status == "fail" {
758
- line = "not ok"
759
- }
760
- line = indent + line + " " + strconv.Itoa(number) + " - " + n.name
761
- switch n.status {
762
- case "skip":
763
- line += " # SKIP"
764
- if n.skipMsg != "" {
765
- line += " " + n.skipMsg
766
- }
767
- case "todo":
768
- line += " # TODO"
769
- if n.todoMsg != "" {
770
- line += " " + n.todoMsg
771
- }
772
- }
773
- fmt.Println(line)
774
- fmt.Println(indent + " ---")
775
- fmt.Println(indent + " duration_ms: " + tnTestDuration(n.duration))
776
- kind := "test"
777
- if n.suite {
778
- kind = "suite"
779
- }
780
- fmt.Println(indent + " type: '" + kind + "'")
781
- if n.status == "fail" || (n.status == "todo" && n.err != nil) {
782
- fmt.Println(indent + " failureType: '" + n.failureType + "'")
783
- msg := TnJSString(tnTestErrorField(n.err, "message"))
784
- if e, ok := n.err.(*TnError); ok && e.Get_name() == "AssertionError" && !strings.HasSuffix(msg, "\\n") && strings.Contains(msg, "\\n") {
785
- msg += "\\n"
786
- }
787
- fmt.Println(indent + " error: " + tnTestYamlString(msg, indent))
788
- code, _ := tnTestErrorField(n.err, "code").(string)
789
- if code == "" {
790
- code = "ERR_TEST_FAILURE"
791
- }
792
- fmt.Println(indent + " code: '" + code + "'")
793
- if e, isTnErr := n.err.(*TnError); isTnErr && n.failureType == "testCodeFailure" && e.Get_name() == "AssertionError" {
794
- fmt.Println(indent + " name: '" + TnJSString(tnTestErrorField(n.err, "name")) + "'")
795
- for _, key := range []string{"expected", "actual", "operator"} {
796
- if e, ok := n.err.(*TnError); ok {
797
- if v, has := e.props[key]; has {
798
- fmt.Println(indent + " " + key + ": " + TnInspect(v))
799
- }
800
- }
801
- }
802
- }
803
- }
804
- fmt.Println(indent + " ...")
805
- for _, d := range n.diagnostics {
806
- fmt.Println(indent + "# " + d)
835
+ tnTestEmit(&TnTestEvent{type_: "test:plan", data: &TnTestEventData{nesting: float64(depth + 1), count: float64(len(n.children)), file: n.file, line: n.line, column: n.column}})
807
836
  }
808
- }
809
-
810
- func tnTestReportSpec(n *TnTestNode, depth int) {
811
- indent := strings.Repeat(" ", depth)
812
- dur := " (" + tnTestDuration(n.duration) + "ms)"
813
- var line string
814
- switch n.status {
815
- case "pass":
816
- line = tnTestColorize("32", "\\u2714 "+n.name+dur)
817
- case "fail":
818
- line = tnTestColorize("31", "\\u2716 "+n.name+dur)
819
- case "skip":
820
- msg := "SKIP"
821
- if n.skipMsg != "" {
822
- msg = n.skipMsg
823
- }
824
- line = tnTestColorize("90", "\\ufe63 "+n.name+dur+" # "+msg)
825
- case "todo":
826
- msg := "TODO"
827
- if n.todoMsg != "" {
828
- msg = n.todoMsg
829
- }
830
- mark := "\\u2714 "
831
- if n.err != nil {
832
- mark = "\\u2716 "
833
- }
834
- line = tnTestColorize("33", mark+n.name+dur+" # "+msg)
837
+ kind := "test:pass"
838
+ if n.err != nil && !n.skip {
839
+ kind = "test:fail"
835
840
  }
836
- fmt.Println(indent + line)
841
+ tnTestEmit(tnTestEventFor(kind, n, depth))
837
842
  for _, d := range n.diagnostics {
838
- fmt.Println(indent + tnTestColorize("34", "\\u2139 "+d))
843
+ tnTestEmit(tnTestNote(depth, d, "info", n))
839
844
  }
840
845
  }
841
846
 
842
- // dot: the failures after the line of dots, in the spec reporter's format
843
- func tnTestFailureLines(n *TnTestNode) {
844
- fmt.Println("\\n" + tnTestColorize("31", "\\u2716 "+n.name+" ("+tnTestDuration(n.duration)+"ms)"))
845
- name := TnJSString(tnTestErrorField(n.err, "name"))
846
- head := name
847
- if code, ok := tnTestErrorField(n.err, "code").(string); ok && code != "" {
848
- head += " [" + code + "]"
849
- }
850
- for _, l := range strings.Split(head+": "+TnJSString(tnTestErrorField(n.err, "message")), "\\n") {
851
- fmt.Println(" " + l)
852
- }
853
- }
854
-
855
- func tnXMLEscape(s string, attr bool) string {
856
- s = strings.ReplaceAll(s, "&", "&amp;")
857
- s = strings.ReplaceAll(s, "<", "&lt;")
858
- if attr {
859
- s = strings.ReplaceAll(s, "\\"", "&quot;")
860
- s = strings.ReplaceAll(s, "\\n", "")
861
- }
862
- return s
863
- }
864
-
865
- // junit: Node's layout (testcase / testsuite elements, diagnostics and the
866
- // counters as comments); failure bodies show the error, without a stack
867
- func tnTestJunit(n *TnTestNode, depth int) {
868
- indent := strings.Repeat("\\t", depth+1)
869
- dur := strconv.FormatFloat(n.duration/1000, 'f', 6, 64)
870
- if n.suite {
871
- tests, failures, skipped := 0, 0, 0
872
- for _, c := range n.children {
873
- if !c.suite {
874
- tests++
875
- if c.status == "fail" {
876
- failures++
877
- }
878
- if c.status == "skip" || c.status == "todo" {
879
- skipped++
880
- }
881
- }
882
- }
883
- host, _ := os.Hostname()
884
- fmt.Printf("%s<testsuite name=\\"%s\\" time=\\"%s\\" disabled=\\"0\\" errors=\\"0\\" tests=\\"%d\\" failures=\\"%d\\" skipped=\\"%d\\" hostname=\\"%s\\">\\n", indent, tnXMLEscape(n.name, true), dur, tests, failures, skipped, tnXMLEscape(host, true))
885
- for _, c := range n.children {
886
- tnTestJunit(c, depth+1)
887
- }
888
- fmt.Println(indent + "</testsuite>")
889
- } else {
890
- open := fmt.Sprintf("%s<testcase name=\\"%s\\" time=\\"%s\\" classname=\\"test\\"", indent, tnXMLEscape(n.name, true), dur)
891
- switch {
892
- case n.status == "fail":
893
- msg := tnXMLEscape(TnJSString(tnTestErrorField(n.err, "message")), true)
894
- fmt.Printf("%s failure=\\"%s\\">\\n", open, msg)
895
- fmt.Printf("%s\\t<failure type=\\"%s\\" message=\\"%s\\">\\n", indent, n.failureType, msg)
896
- // Node wraps the error in an ERR_TEST_FAILURE whose cause it is
897
- cause := strings.ReplaceAll(TnInspect(n.err), "\\n", "\\n ")
898
- raw := strings.TrimSuffix(TnJSString(tnTestErrorField(n.err, "message")), "\\n")
899
- fmt.Println(tnXMLEscape("[Error [ERR_TEST_FAILURE]: "+raw+"\\n] {\\n code: 'ERR_TEST_FAILURE',\\n failureType: '"+n.failureType+"',\\n cause: "+cause+"\\n}", false))
900
- fmt.Println(indent + "\\t</failure>")
901
- fmt.Println(indent + "</testcase>")
902
- case n.status == "skip" || n.status == "todo":
903
- kind := "skipped"
904
- msg := n.skipMsg
905
- if n.status == "todo" {
906
- kind, msg = "todo", n.todoMsg
907
- }
908
- if msg == "" {
909
- msg = "true"
910
- }
911
- fmt.Println(open + ">")
912
- fmt.Printf("%s\\t<skipped type=\\"%s\\" message=\\"%s\\"/>\\n", indent, kind, tnXMLEscape(msg, true))
913
- fmt.Println(indent + "</testcase>")
914
- default:
915
- fmt.Println(open + "/>")
916
- }
917
- for _, c := range n.children {
918
- tnTestJunit(c, depth+1)
919
- }
920
- }
921
- for _, d := range n.diagnostics {
922
- fmt.Println(indent + "<!-- " + d + " -->")
923
- }
847
+ func tnTestDuration(ms float64) string {
848
+ return strconv.FormatFloat(math.Round(ms*1e6)/1e6, 'f', -1, 64)
924
849
  }
925
850
 
851
+ // The root's report: the plan, the counters as diagnostics, coverage, the summary
926
852
  func tnTestFinish() {
853
+ cfg := tnTestFilters()
854
+ duration := tnTestNow() - tnTestStart
927
855
  stats := []string{"tests", "suites", "pass", "fail", "cancelled", "skipped", "todo"}
928
- duration := "duration_ms " + tnTestDuration(float64(time.Since(tnTestStart).Nanoseconds())/1e6)
929
- switch tnTestReporter {
930
- case "dot":
931
- fmt.Println()
932
- if len(tnTestFailures) > 0 {
933
- fmt.Println("\\n" + tnTestColorize("31", "Failed tests:"))
934
- for _, n := range tnTestFailures {
935
- tnTestFailureLines(n)
936
- }
937
- }
938
- tnTestExitCode()
939
- return
940
- case "junit":
941
- for _, n := range tnTestRoot.children {
942
- tnTestJunit(n, 0)
943
- }
856
+ if tnTestChildSink == nil {
857
+ tnTestEmit(&TnTestEvent{type_: "test:plan", data: &TnTestEventData{count: float64(len(tnTestRoot.children))}})
944
858
  for _, key := range stats {
945
- fmt.Println("\\t<!-- " + key + " " + strconv.Itoa(tnTestCounts[key]) + " -->")
859
+ tnTestEmit(tnTestNote(0, key+" "+strconv.Itoa(tnTestCounts[key]), "info", nil))
860
+ }
861
+ tnTestEmit(tnTestNote(0, "duration_ms "+tnTestDuration(duration), "info", nil))
862
+ }
863
+ success := tnTestCounts["fail"] == 0 && tnTestCounts["cancelled"] == 0
864
+ if cfg.coverage && tnTestCoverage != nil {
865
+ if summary := tnTestCoverage(cfg); summary != nil {
866
+ totals := map[string]float64{"line": summary.totals.coveredLinePercent, "branch": summary.totals.coveredBranchPercent, "function": summary.totals.coveredFunctionPercent}
867
+ for _, kind := range []string{"lines", "branches", "functions"} {
868
+ threshold, set := cfg.thresholds[kind]
869
+ name := map[string]string{"lines": "line", "branches": "branch", "functions": "function"}[kind]
870
+ if set && totals[name] < threshold {
871
+ success = false
872
+ tnTestEmit(tnTestNote(0, "Error: "+strconv.FormatFloat(totals[name], 'f', 2, 64)+"% "+name+" coverage does not meet threshold of "+TnNumStr(threshold)+"%.", "error", nil))
873
+ }
874
+ }
875
+ tnTestEmit(&TnTestEvent{type_: "test:coverage", data: &TnTestEventData{summary: summary}})
946
876
  }
947
- fmt.Println("\\t<!-- " + duration + " -->")
948
- fmt.Println("</testsuites>")
949
- tnTestExitCode()
950
- return
951
877
  }
952
- if tnTestTap {
953
- fmt.Println("1.." + strconv.Itoa(len(tnTestRoot.children)))
878
+ if tnTestSnapshotsDone != nil {
879
+ tnTestSnapshotsDone()
954
880
  }
955
- for _, key := range stats {
956
- line := key + " " + strconv.Itoa(tnTestCounts[key])
957
- if tnTestSpec {
958
- fmt.Println(tnTestColorize("34", "\\u2139 "+line))
959
- } else {
960
- fmt.Println("# " + line)
961
- }
881
+ counts := &TnTestCounts{
882
+ tests: float64(tnTestCounts["tests"]), failed: float64(tnTestCounts["fail"]), passed: float64(tnTestCounts["pass"]),
883
+ cancelled: float64(tnTestCounts["cancelled"]), skipped: float64(tnTestCounts["skipped"]), todo: float64(tnTestCounts["todo"]),
884
+ topLevel: float64(len(tnTestRoot.children)), suites: float64(tnTestCounts["suites"]),
962
885
  }
963
- if tnTestSpec {
964
- fmt.Println(tnTestColorize("34", "\\u2139 "+duration))
965
- if len(tnTestFailures) > 0 {
966
- fmt.Println("\\n" + tnTestColorize("31", "\\u2716 failing tests:"))
967
- for _, n := range tnTestFailures {
968
- tnTestFailureLines(n)
969
- }
886
+ tnTestEmit(&TnTestEvent{type_: "test:summary", data: &TnTestEventData{success: success, counts: counts, duration_ms: math.Round(duration*1e6) / 1e6}})
887
+ for _, s := range tnTestSinks {
888
+ s.write(s.reporter.end())
889
+ if s.file {
890
+ s.out.Close()
970
891
  }
971
- } else {
972
- fmt.Println("# " + duration)
973
892
  }
974
- tnTestExitCode()
975
- }
976
-
977
- func tnTestExitCode() {
978
- if tnTestCounts["fail"] > 0 || tnTestCounts["cancelled"] > 0 {
893
+ if !success {
979
894
  TnSetExitCode(1)
980
895
  }
981
896
  }
@@ -996,6 +911,8 @@ type TnMockFunctionContext struct {
996
911
  impl interface{}
997
912
  original interface{}
998
913
  once map[int]interface{}
914
+ // mock.method & co.: puts the original back where the mock was
915
+ unmock func()
999
916
  }
1000
917
 
1001
918
  func (m *TnMockFunctionContext) Get_calls() []*TnMockCall { return m.calls }
@@ -1009,7 +926,13 @@ func (m *TnMockFunctionContext) mockImplementationOnce(fn interface{}, onCall ..
1009
926
  }
1010
927
  m.once[index] = fn
1011
928
  }
1012
- func (m *TnMockFunctionContext) restore() { m.impl = m.original }
929
+ func (m *TnMockFunctionContext) restore() {
930
+ m.impl = m.original
931
+ if m.unmock != nil {
932
+ m.unmock()
933
+ m.unmock = nil
934
+ }
935
+ }
1013
936
 
1014
937
  var tnMocks = map[uintptr]*TnMockFunctionContext{}
1015
938
 
@@ -1051,7 +974,7 @@ func (m *TnMockTimers) enable(options ...interface{}) {
1051
974
  apis := map[string]bool{"setTimeout": true, "setInterval": true, "setImmediate": true, "Date": true}
1052
975
  m.now = 0
1053
976
  if len(options) > 0 && options[0] != nil {
1054
- switch list := TnGet(options[0], "apis").(type) {
977
+ switch list := TnGetValue(options[0], "apis").(type) {
1055
978
  case []string:
1056
979
  apis = map[string]bool{}
1057
980
  for _, a := range list {
@@ -1063,7 +986,7 @@ func (m *TnMockTimers) enable(options ...interface{}) {
1063
986
  apis[fmt.Sprint(a)] = true
1064
987
  }
1065
988
  }
1066
- switch now := TnGet(options[0], "now").(type) {
989
+ switch now := TnGetValue(options[0], "now").(type) {
1067
990
  case float64:
1068
991
  m.now = now
1069
992
  case time.Time:
@@ -1235,6 +1158,134 @@ func TnMockFnEmpty(tracker *TnMockTracker) func(...interface{}) interface{} {
1235
1158
  return TnMockFn(tracker, func(args ...interface{}) interface{} { return nil })
1236
1159
  }
1237
1160
 
1161
+ // The implementation argument of mock.method / getter / setter (options objects aside)
1162
+ func tnMockImplementation(rest []interface{}) interface{} {
1163
+ for _, r := range rest {
1164
+ if tnTestIsFunc(r) {
1165
+ return r
1166
+ }
1167
+ }
1168
+ return nil
1169
+ }
1170
+
1171
+ func tnMockNotAMethod(name string) *TnError {
1172
+ return TnNodeError("TypeError", "ERR_INVALID_ARG_VALUE", "The argument 'methodName' must be a method. Received '"+name+"'")
1173
+ }
1174
+
1175
+ // mock.method(object, name, implementation?) on a function-valued field (an
1176
+ // object literal's method or accessor): the field holds the mock until restore()
1177
+ func TnMockMethod[F any](tracker *TnMockTracker, name string, slot *F, rest ...interface{}) F {
1178
+ original := *slot
1179
+ if !tnTestIsFunc(original) {
1180
+ panic(tnMockNotAMethod(name))
1181
+ }
1182
+ fn := TnMockFn(tracker, original)
1183
+ ctx := tnMocks[tnFuncID(fn)]
1184
+ if impl := tnMockImplementation(rest); impl != nil {
1185
+ ctx.impl = impl
1186
+ }
1187
+ *slot = fn
1188
+ ctx.unmock = func() { *slot = original }
1189
+ return fn
1190
+ }
1191
+
1192
+ // mock.method on a class instance: the method's override slot holds the mock
1193
+ // (the method calls it while it is set); original is the method's own body
1194
+ func TnMockSlot[F any](tracker *TnMockTracker, slot *F, original F, rest ...interface{}) F {
1195
+ fn := TnMockFn(tracker, original)
1196
+ ctx := tnMocks[tnFuncID(fn)]
1197
+ if impl := tnMockImplementation(rest); impl != nil {
1198
+ ctx.impl = impl
1199
+ }
1200
+ *slot = fn
1201
+ ctx.unmock = func() {
1202
+ var none F
1203
+ *slot = none
1204
+ }
1205
+ return fn
1206
+ }
1207
+
1208
+ // mock.method(console, 'log') & co.: calls of a namespace's function check
1209
+ // for a mock by name (TnMockedCall)
1210
+ var tnMockedGlobals = map[string]*TnMockFunctionContext{}
1211
+
1212
+ func TnMockGlobal(tracker *TnMockTracker, key string, rest ...interface{}) func(...interface{}) interface{} {
1213
+ ctx := &TnMockFunctionContext{once: map[int]interface{}{}, impl: tnMockImplementation(rest)}
1214
+ tracker.mocks = append(tracker.mocks, ctx)
1215
+ tnMockedGlobals[key] = ctx
1216
+ ctx.unmock = func() {
1217
+ if tnMockedGlobals[key] == ctx {
1218
+ delete(tnMockedGlobals, key)
1219
+ }
1220
+ }
1221
+ fn := func(args ...interface{}) interface{} {
1222
+ return tnMockedCallVia(ctx, args, func() interface{} { return nil })
1223
+ }
1224
+ tnMocks[tnFuncID(fn)] = ctx
1225
+ return fn
1226
+ }
1227
+
1228
+ func tnMockedCallVia(ctx *TnMockFunctionContext, args []interface{}, original func() interface{}) interface{} {
1229
+ call := &TnMockCall{arguments: args}
1230
+ impl := ctx.impl
1231
+ if once, ok := ctx.once[len(ctx.calls)]; ok {
1232
+ impl = once
1233
+ delete(ctx.once, len(ctx.calls))
1234
+ }
1235
+ ctx.calls = append(ctx.calls, call)
1236
+ defer func() {
1237
+ if r := recover(); r != nil {
1238
+ call.error_ = r
1239
+ panic(r)
1240
+ }
1241
+ }()
1242
+ var result interface{}
1243
+ if impl == nil {
1244
+ result = original()
1245
+ } else {
1246
+ result = TnInvoke(impl, args...)
1247
+ }
1248
+ call.result = result
1249
+ return result
1250
+ }
1251
+
1252
+ // A call of a namespace function that a mock may replace (args evaluate only then)
1253
+ func TnMockedCall[R any](key string, args func() []interface{}, original func() R) R {
1254
+ ctx, mocked := tnMockedGlobals[key]
1255
+ if !mocked {
1256
+ return original()
1257
+ }
1258
+ result := tnMockedCallVia(ctx, args(), func() interface{} { return original() })
1259
+ if r, ok := result.(R); ok {
1260
+ return r
1261
+ }
1262
+ var zero R
1263
+ if result == nil {
1264
+ return zero
1265
+ }
1266
+ return tnInvokeArg(result, reflect.TypeOf(&zero).Elem()).Interface().(R)
1267
+ }
1268
+
1269
+ func TnMockedCallVoid(key string, args func() []interface{}, original func()) {
1270
+ ctx, mocked := tnMockedGlobals[key]
1271
+ if !mocked {
1272
+ original()
1273
+ return
1274
+ }
1275
+ tnMockedCallVia(ctx, args(), func() interface{} {
1276
+ original()
1277
+ return nil
1278
+ })
1279
+ }
1280
+
1281
+ // console.log.mock: the record of a namespace function's mock
1282
+ func TnMockedContext(key string) *TnMockFunctionContext {
1283
+ if ctx, ok := tnMockedGlobals[key]; ok {
1284
+ return ctx
1285
+ }
1286
+ panic(TnNodeError("TypeError", "", "not a mock function"))
1287
+ }
1288
+
1238
1289
  // fn.mock: the call record of a mock function
1239
1290
  func TnMockOf(fn interface{}) *TnMockFunctionContext {
1240
1291
  if ctx, ok := tnMocks[tnFuncID(fn)]; ok {
@@ -1258,20 +1309,252 @@ func (t *TnMockTracker) restoreAll() {
1258
1309
  m.restore()
1259
1310
  }
1260
1311
  }`;
1312
+ const snapshotHelper = `// node:test snapshots: t.assert.snapshot (one <test file>.snapshot file per
1313
+ // test file, Node's format) and t.assert.fileSnapshot; --test-update-snapshots
1314
+ // writes them, otherwise they are compared
1315
+ const tnSnapshotTip = "Missing snapshots can be generated by rerunning the command with the --test-update-snapshots flag."
1316
+
1317
+ type tnSnapshotFile struct {
1318
+ path string
1319
+ snapshots map[string]string
1320
+ counts map[string]int
1321
+ loaded bool
1322
+ }
1323
+
1324
+ var tnSnapshotFiles = map[string]*tnSnapshotFile{}
1325
+ var tnSnapshotOrder []*tnSnapshotFile
1326
+ var tnSnapshotSerializers []interface{}
1327
+ var tnSnapshotResolve interface{}
1328
+
1329
+ func init() {
1330
+ tnTestSnapshotsDone = tnSnapshotWriteAll
1331
+ }
1332
+
1333
+ // snapshot.setDefaultSnapshotSerializers / setResolveSnapshotPath
1334
+ func TnSetDefaultSnapshotSerializers(list interface{}) { tnSnapshotSerializers = tnTestList(list) }
1335
+ func TnSetResolveSnapshotPath(fn interface{}) { tnSnapshotResolve = fn }
1336
+
1337
+ func tnSnapshotEscape(s string) string {
1338
+ s = strings.ReplaceAll(s, "\\\\", "\\\\\\\\")
1339
+ s = strings.ReplaceAll(s, "\`", "\\\\\`")
1340
+ return strings.ReplaceAll(s, "\${", "\\\\\${")
1341
+ }
1342
+
1343
+ func tnSnapshotUnescape(s string) string {
1344
+ var b strings.Builder
1345
+ for i := 0; i < len(s); i++ {
1346
+ if s[i] == '\\\\' && i+1 < len(s) {
1347
+ i++
1348
+ }
1349
+ b.WriteByte(s[i])
1350
+ }
1351
+ return b.String()
1352
+ }
1353
+
1354
+ func tnSnapshotState(msg string, file string) *TnError {
1355
+ e := tnMockTimersState(msg)
1356
+ e.props["filename"] = file
1357
+ return e
1358
+ }
1359
+
1360
+ func tnSnapshotFor(testFile string) *tnSnapshotFile {
1361
+ if f, ok := tnSnapshotFiles[testFile]; ok {
1362
+ return f
1363
+ }
1364
+ path := testFile + ".snapshot"
1365
+ if tnSnapshotResolve != nil {
1366
+ resolved, ok := TnInvoke(tnSnapshotResolve, testFile).(string)
1367
+ if !ok {
1368
+ panic(tnSnapshotState("Invalid snapshot filename.", ""))
1369
+ }
1370
+ path = resolved
1371
+ }
1372
+ f := &tnSnapshotFile{path: path, snapshots: map[string]string{}, counts: map[string]int{}, loaded: tnTestFilters().updateSnapshots}
1373
+ tnSnapshotFiles[testFile] = f
1374
+ tnSnapshotOrder = append(tnSnapshotOrder, f)
1375
+ return f
1376
+ }
1377
+
1378
+ func (f *tnSnapshotFile) nextID(name string) string {
1379
+ count := f.counts[name]
1380
+ if count == 0 {
1381
+ count = 1
1382
+ }
1383
+ f.counts[name] = count + 1
1384
+ return name + " " + strconv.Itoa(count)
1385
+ }
1386
+
1387
+ // exports[\`name 1\`] = \`value\`; entries, keeping the values escaped as written
1388
+ func tnSnapshotParse(src string) (map[string]string, bool) {
1389
+ out := map[string]string{}
1390
+ i := 0
1391
+ literal := func() (string, bool) {
1392
+ start := i
1393
+ for i < len(src) {
1394
+ switch src[i] {
1395
+ case '\\\\':
1396
+ i += 2
1397
+ continue
1398
+ case '\`':
1399
+ text := src[start:i]
1400
+ i++
1401
+ return text, true
1402
+ }
1403
+ i++
1404
+ }
1405
+ return "", false
1406
+ }
1407
+ for {
1408
+ at := strings.Index(src[i:], "exports[\`")
1409
+ if at < 0 {
1410
+ return out, true
1411
+ }
1412
+ i += at + len("exports[\`")
1413
+ key, ok := literal()
1414
+ if !ok || !strings.HasPrefix(src[i:], "] = \`") {
1415
+ return nil, false
1416
+ }
1417
+ i += len("] = \`")
1418
+ value, ok := literal()
1419
+ if !ok {
1420
+ return nil, false
1421
+ }
1422
+ out[tnSnapshotUnescape(key)] = value
1423
+ }
1424
+ }
1425
+
1426
+ func (f *tnSnapshotFile) read() {
1427
+ if f.loaded {
1428
+ return
1429
+ }
1430
+ data, err := os.ReadFile(f.path)
1431
+ msg := "Cannot read snapshot file '" + f.path + ".'"
1432
+ if err != nil {
1433
+ if os.IsNotExist(err) {
1434
+ msg += " " + tnSnapshotTip
1435
+ }
1436
+ panic(tnSnapshotState(msg, f.path))
1437
+ }
1438
+ snapshots, ok := tnSnapshotParse(string(data))
1439
+ if !ok {
1440
+ panic(tnSnapshotState(msg, f.path))
1441
+ }
1442
+ f.snapshots = snapshots
1443
+ f.loaded = true
1444
+ }
1445
+
1446
+ // The serializers (default: JSON.stringify(value, null, 2)), then String()
1447
+ func tnSnapshotSerialize(value interface{}, options []interface{}) string {
1448
+ serializers := tnSnapshotSerializers
1449
+ if len(options) > 0 && options[0] != nil {
1450
+ if list := TnGet(options[0], "serializers"); list != nil {
1451
+ serializers = tnTestList(list)
1452
+ }
1453
+ }
1454
+ if len(serializers) == 0 {
1455
+ return TnJSONStringify(value, " ")
1456
+ }
1457
+ for _, fn := range serializers {
1458
+ value = TnInvoke(fn, value)
1459
+ }
1460
+ return tnTestStr(value)
1461
+ }
1462
+
1463
+ func (a *TnTestAssert) snapshot(value interface{}, options ...interface{}) {
1464
+ a.ctx.asserts++
1465
+ file := tnSnapshotFor(a.ctx.Get_filePath())
1466
+ serialized := "\\n" + tnSnapshotEscape(tnSnapshotSerialize(value, options)) + "\\n"
1467
+ id := file.nextID(a.ctx.Get_fullName())
1468
+ if tnTestFilters().updateSnapshots {
1469
+ file.snapshots[id] = serialized
1470
+ return
1471
+ }
1472
+ file.read()
1473
+ expected, ok := file.snapshots[id]
1474
+ if !ok {
1475
+ e := tnSnapshotState("Snapshot '"+id+"' not found in '"+file.path+".' "+tnSnapshotTip, file.path)
1476
+ e.props["snapshot"] = id
1477
+ panic(e)
1478
+ }
1479
+ TnAssertStrictEqual(serialized, expected)
1480
+ }
1481
+
1482
+ func (a *TnTestAssert) fileSnapshot(value interface{}, path string, options ...interface{}) {
1483
+ a.ctx.asserts++
1484
+ serialized := tnSnapshotSerialize(value, options)
1485
+ if tnTestFilters().updateSnapshots {
1486
+ os.MkdirAll(filepath.Dir(path), 0o755)
1487
+ if err := os.WriteFile(path, []byte(serialized), 0o644); err != nil {
1488
+ panic(tnSnapshotState("Cannot write snapshot file '"+path+".'", path))
1489
+ }
1490
+ return
1491
+ }
1492
+ data, err := os.ReadFile(path)
1493
+ if err != nil {
1494
+ msg := "Cannot read snapshot file '" + path + ".'"
1495
+ if os.IsNotExist(err) {
1496
+ msg += " " + tnSnapshotTip
1497
+ }
1498
+ panic(tnSnapshotState(msg, path))
1499
+ }
1500
+ TnAssertStrictEqual(serialized, string(data))
1501
+ }
1502
+
1503
+ // --test-update-snapshots: each snapshot file, its entries sorted by name
1504
+ func tnSnapshotWriteAll() {
1505
+ if !tnTestFilters().updateSnapshots {
1506
+ return
1507
+ }
1508
+ for _, f := range tnSnapshotOrder {
1509
+ keys := make([]string, 0, len(f.snapshots))
1510
+ for k := range f.snapshots {
1511
+ keys = append(keys, k)
1512
+ }
1513
+ sort.Strings(keys)
1514
+ entries := make([]string, len(keys))
1515
+ for i, k := range keys {
1516
+ entries[i] = "exports[\`" + tnSnapshotEscape(k) + "\`] = \`" + f.snapshots[k] + "\`;\\n"
1517
+ }
1518
+ os.MkdirAll(filepath.Dir(f.path), 0o755)
1519
+ if err := os.WriteFile(f.path, []byte(strings.Join(entries, "\\n")), 0o644); err != nil {
1520
+ fmt.Fprintln(os.Stderr, "Cannot write snapshot file '"+f.path+".'")
1521
+ TnSetExitCode(1)
1522
+ }
1523
+ }
1524
+ }`;
1261
1525
  function eventFn(nodes) {
1262
1526
  void nodes;
1263
1527
  return ['*TnTestContext', 'func(...interface{})'];
1264
1528
  }
1265
1529
  export function registerTest(r) {
1266
1530
  defineModule(r, 'test');
1267
- defineHelper(r, 'nodeTest', ['fmt', 'math', 'os', 'reflect', 'regexp', 'strconv', 'strings', 'time'], ['eventLoop', 'promise', 'nodeInvoke', 'dynamic', 'nodeEvents', 'nodeProcess', 'nodeUtil', 'error', 'timerWait', 'clock'], testHelper);
1531
+ defineHelper(r, 'nodeTest', ['fmt', 'math', 'os', 'path/filepath', 'reflect', 'regexp', 'strconv', 'strings', 'time'], ['eventLoop', 'promise', 'nodeInvoke', 'dynamic', 'nodeEvents', 'nodeProcess', 'nodeUtil', 'error', 'timerWait', 'clock', 'nodeTestReport', 'nodeTestClock@os'], testHelper);
1532
+ defineHelper(r, 'nodeTestSnapshot', ['fmt', 'os', 'path/filepath', 'sort', 'strconv', 'strings'], ['nodeTest', 'nodeAssert', 'jsonStringify'], snapshotHelper);
1533
+ registerTestReporters(r);
1534
+ registerTestRun(r);
1535
+ registerTestCoverage(r);
1268
1536
  const use = () => r.helper('nodeTest');
1537
+ // "file", line, column of a test() call: where Node's reports point
1538
+ const site = (c) => {
1539
+ const position = r.callSite(c.site);
1540
+ return `${JSON.stringify(position.file)}, ${position.line}, ${position.column}`;
1541
+ };
1269
1542
  defineClass(r, 'test.TestContext', '*TnTestContext', 'class', 'skip=; todo=; diagnostic=; plan=; runOnly=; test=chan struct{}; before=; after=; beforeEach=; afterEach=', '', 'name=string; fullName=string; mock=*TnMockTracker; signal=*TnAbortSignal; filePath=string; assert=*TnTestAssert', '');
1543
+ r.methods['test.TestContext#test'] = (c) => {
1544
+ use();
1545
+ return `${c.recv}.test(${site(c)}${c.args.length > 0 ? ', ' : ''}${c.args.join(', ')})`;
1546
+ };
1270
1547
  r.classes['test.SuiteContext'] = r.classes['test.TestContext'];
1271
1548
  defineClass(r, 'test.MockTracker', '*TnMockTracker', 'class', 'reset=; restoreAll=', '', 'timers=*TnMockTimers', '');
1272
1549
  defineClass(r, 'test.MockTimers', '*TnMockTimers', 'class', 'enable=; tick=; runAll=; setTime=; reset=', '', '', '');
1273
1550
  // t.assert.x(...): node:assert's x, counted for t.plan()
1274
- defineClass(r, 'test.TestContextAssert', '*TnTestAssert', 'class', '', '', '', '');
1551
+ defineClass(r, 'test.TestContextAssert', '*TnTestAssert', 'class', 'snapshot=; fileSnapshot=', '', '', '');
1552
+ for (const name of ['snapshot', 'fileSnapshot']) {
1553
+ r.methods[`test.TestContextAssert#${name}`] = (c) => {
1554
+ r.helper('nodeTestSnapshot');
1555
+ return `${c.recv}.${name}(${c.args.join(', ')})`;
1556
+ };
1557
+ }
1275
1558
  const assertNames = ['ok', 'equal', 'notEqual', 'strictEqual', 'notStrictEqual', 'deepEqual', 'notDeepEqual', 'deepStrictEqual', 'notDeepStrictEqual', 'throws', 'doesNotThrow', 'rejects', 'doesNotReject', 'match', 'doesNotMatch', 'fail', 'ifError'];
1276
1559
  for (const name of assertNames) {
1277
1560
  const key = `test.TestContextAssert#${name}`;
@@ -1294,7 +1577,7 @@ export function registerTest(r) {
1294
1577
  const register = (name, goFn, variant) => {
1295
1578
  r.functions[`test.${name}`] = (c) => {
1296
1579
  use();
1297
- return `${goFn}(${JSON.stringify(variant)}${c.args.length > 0 ? ', ' : ''}${c.args.join(', ')})`;
1580
+ return `${goFn}(${JSON.stringify(variant)}, ${site(c)}${c.args.length > 0 ? ', ' : ''}${c.args.join(', ')})`;
1298
1581
  };
1299
1582
  r.results[`test.${name}`] = 'chan struct{}';
1300
1583
  r.paramTypers[`test.${name}`] = eventFn;
@@ -1323,6 +1606,18 @@ export function registerTest(r) {
1323
1606
  };
1324
1607
  r.paramTypers[`test.${hook}`] = eventFn;
1325
1608
  }
1609
+ // snapshot.setDefaultSnapshotSerializers / setResolveSnapshotPath
1610
+ r.namespaces['test.default.snapshot'] = 'test.snapshot';
1611
+ r.objects['test.snapshot'] = true;
1612
+ r.functions['test.snapshot.setDefaultSnapshotSerializers'] = (c) => {
1613
+ r.helper('nodeTestSnapshot');
1614
+ return `TnSetDefaultSnapshotSerializers(${c.args[0]})`;
1615
+ };
1616
+ r.functions['test.snapshot.setResolveSnapshotPath'] = (c) => {
1617
+ r.helper('nodeTestSnapshot');
1618
+ return `TnSetResolveSnapshotPath(${c.args[0]})`;
1619
+ };
1620
+ r.paramTypers['test.snapshot.setResolveSnapshotPath'] = (_n) => ['string'];
1326
1621
  // mock.fn(original?, implementation?) / t.mock.fn(...)
1327
1622
  r.values['test.mock'] = (_c) => {
1328
1623
  use();
@@ -1342,6 +1637,19 @@ export function registerTest(r) {
1342
1637
  return `TnMockFn(TnMock, ${c.args.join(', ')})`;
1343
1638
  };
1344
1639
  r.typers['test.mock.fn'] = (c) => (c.nodes.length === 0 || !c.types[0] ? 'func(...interface{}) interface{}' : c.types[0]);
1640
+ // mock.method(object, name, implementation?, options?) / getter / setter
1641
+ for (const kind of ['method', 'getter', 'setter']) {
1642
+ r.methods[`test.MockTracker#${kind}`] = (c) => {
1643
+ use();
1644
+ return r.mockMember(c, c.recv, kind);
1645
+ };
1646
+ r.functions[`test.mock.${kind}`] = (c) => {
1647
+ use();
1648
+ return r.mockMember(c, 'TnMock', kind);
1649
+ };
1650
+ r.typers[`test.MockTracker#${kind}`] = (c) => r.mockMemberType(c, kind);
1651
+ r.typers[`test.mock.${kind}`] = r.typers[`test.MockTracker#${kind}`];
1652
+ }
1345
1653
  for (const method of ['reset', 'restoreAll']) {
1346
1654
  r.functions[`test.mock.${method}`] = (_c) => {
1347
1655
  use();