tina4-nodejs 3.13.161 → 3.13.163
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.
- package/CLAUDE.md +2 -2
- package/package.json +1 -1
- package/packages/cli/dist/bin.js +265 -135
- package/packages/cli/src/commands/test.ts +2 -2
- package/packages/core/dist/index.js +264 -133
- package/packages/core/src/index.ts +1 -1
- package/packages/core/src/mcp.ts +10 -4
- package/packages/core/src/queueBackends/kafkaBackend.ts +56 -10
- package/packages/core/src/server.ts +71 -15
- package/packages/core/src/testing.ts +181 -69
- package/packages/orm/dist/index.js +263 -133
- package/types/core/src/index.d.ts +1 -1
- package/types/core/src/mcp.d.ts +2 -2
- package/types/core/src/testing.d.ts +27 -4
|
@@ -172,7 +172,7 @@ export { MongoSessionHandler } from "./sessionHandlers/mongoHandler.js";
|
|
|
172
172
|
export type { MongoSessionConfig } from "./sessionHandlers/mongoHandler.js";
|
|
173
173
|
export { ValkeySessionHandler } from "./sessionHandlers/valkeyHandler.js";
|
|
174
174
|
export type { ValkeySessionConfig } from "./sessionHandlers/valkeyHandler.js";
|
|
175
|
-
export { tests, expectEqual, expectRaises, expectTrue, expectFalse, runAll, reset } from "./testing.js";
|
|
175
|
+
export { tests, expectEqual, expectRaises, expectTrue, expectFalse, runAll, runAllAsync, reset } from "./testing.js";
|
|
176
176
|
export { TestClient, TestResponse } from "./testClient.js";
|
|
177
177
|
export { Tina4Test, AssertionError as Tina4AssertionError } from "./test.js";
|
|
178
178
|
export type { TestRunResults } from "./test.js";
|
package/packages/core/src/mcp.ts
CHANGED
|
@@ -85,7 +85,10 @@ export interface McpResourceDefinition {
|
|
|
85
85
|
name: string;
|
|
86
86
|
description: string;
|
|
87
87
|
mimeType: string;
|
|
88
|
-
|
|
88
|
+
// Like tool handlers, resource handlers may be sync or async — the dispatch
|
|
89
|
+
// (`_handleResourcesRead`) awaits the return value, so a resource that reads
|
|
90
|
+
// the async Database wrapper serialises its rows, not a pending Promise.
|
|
91
|
+
handler: () => unknown | Promise<unknown>;
|
|
89
92
|
}
|
|
90
93
|
|
|
91
94
|
export interface JsonSchema {
|
|
@@ -502,7 +505,7 @@ export class McpServer {
|
|
|
502
505
|
|
|
503
506
|
registerResource(
|
|
504
507
|
uri: string,
|
|
505
|
-
handler: () => unknown
|
|
508
|
+
handler: () => unknown | Promise<unknown>,
|
|
506
509
|
description = "",
|
|
507
510
|
mimeType = "application/json",
|
|
508
511
|
): void {
|
|
@@ -640,7 +643,7 @@ export class McpServer {
|
|
|
640
643
|
return { resources };
|
|
641
644
|
}
|
|
642
645
|
|
|
643
|
-
private _handleResourcesRead(params: Record<string, unknown>): Record<string, unknown
|
|
646
|
+
private async _handleResourcesRead(params: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
644
647
|
const uri = params.uri as string | undefined;
|
|
645
648
|
if (!uri) {
|
|
646
649
|
throw new Error("Missing resource URI");
|
|
@@ -651,7 +654,10 @@ export class McpServer {
|
|
|
651
654
|
throw new Error(`Unknown resource: ${uri}`);
|
|
652
655
|
}
|
|
653
656
|
|
|
654
|
-
|
|
657
|
+
// Await like `_handleToolsCall`: an async handler's rows, not `{}` from
|
|
658
|
+
// JSON.stringify(Promise), and its rejection becomes a JSON-RPC error
|
|
659
|
+
// rather than an unhandled rejection.
|
|
660
|
+
const result = await resource.handler();
|
|
655
661
|
|
|
656
662
|
let text: string;
|
|
657
663
|
if (typeof result === "string") {
|
|
@@ -160,6 +160,12 @@ const outBytes = new Uint8Array(workerData.sab, 8);
|
|
|
160
160
|
// (test/kafkaErrorCodes.test.ts) can assert the floors.
|
|
161
161
|
const PRODUCE_VERSION = 3;
|
|
162
162
|
const FETCH_VERSION = 4;
|
|
163
|
+
// How long the broker long-polls an empty partition before answering (ms).
|
|
164
|
+
// Deliberately 1000, not tina4-php / tina4-python's 5000: Node's pop() is
|
|
165
|
+
// synchronous (Atomics.wait on this worker), so the long-poll blocks the whole
|
|
166
|
+
// event loop, not one request. The tombstone-skip deadline caps it further while
|
|
167
|
+
// stepping so a stream of tombstones cannot hold pop() past ~1s.
|
|
168
|
+
const FETCH_MAX_WAIT_MS = 1000;
|
|
163
169
|
|
|
164
170
|
let correlationId = 0;
|
|
165
171
|
let brokerSock = null;
|
|
@@ -346,12 +352,13 @@ async function produce(topic, valueBytes) {
|
|
|
346
352
|
}
|
|
347
353
|
|
|
348
354
|
// ── fetch ─────────────────────────────────────────────────────────────────
|
|
349
|
-
function fetchRequest(topic, offset) {
|
|
355
|
+
function fetchRequest(topic, offset, maxWaitMs) {
|
|
356
|
+
if (maxWaitMs === undefined) maxWaitMs = FETCH_MAX_WAIT_MS;
|
|
350
357
|
const topicBuf = Buffer.from(topic, "utf-8");
|
|
351
358
|
const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
|
|
352
359
|
let p = 0;
|
|
353
360
|
buf.writeInt32BE(-1, p); p += 4; // replicaId
|
|
354
|
-
buf.writeInt32BE(
|
|
361
|
+
buf.writeInt32BE(maxWaitMs, p); p += 4; // maxWaitMs (long-poll bound; capped by the tombstone-skip deadline)
|
|
355
362
|
buf.writeInt32BE(1, p); p += 4; // minBytes
|
|
356
363
|
buf.writeInt32BE(1048576, p); p += 4; // maxBytes
|
|
357
364
|
buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
|
|
@@ -364,8 +371,12 @@ function fetchRequest(topic, offset) {
|
|
|
364
371
|
buf.writeInt32BE(1048576, p); p += 4;
|
|
365
372
|
return frame(1, FETCH_VERSION, buf);
|
|
366
373
|
}
|
|
367
|
-
// Decode the
|
|
368
|
-
//
|
|
374
|
+
// Decode the FIRST record of the partition's record-set (the cross-framework
|
|
375
|
+
// contract: only a batch's first record is decoded -- the Tina4 producer writes
|
|
376
|
+
// one record per batch). Returns its value and absolute offset (baseOffset +
|
|
377
|
+
// offsetDelta); a tombstone (null value) comes back with value null and its
|
|
378
|
+
// offset so the caller can step past it. null = no usable record at all (empty /
|
|
379
|
+
// old-format / short response).
|
|
369
380
|
function firstRecord(buf, start, end) {
|
|
370
381
|
let pos = start;
|
|
371
382
|
while (pos + 12 <= end) {
|
|
@@ -381,8 +392,7 @@ function firstRecord(buf, start, end) {
|
|
|
381
392
|
for (let i = 0; i < recordsCount && r < batchEnd; i++) {
|
|
382
393
|
const recLen = readVarint(buf, r);
|
|
383
394
|
let rp = recLen.next;
|
|
384
|
-
|
|
385
|
-
rp += 1;
|
|
395
|
+
rp += 1; // record attributes byte
|
|
386
396
|
rp = readVarint(buf, rp).next; // timestampDelta
|
|
387
397
|
const offDelta = readVarint(buf, rp); rp = offDelta.next;
|
|
388
398
|
const keyLen = readVarint(buf, rp); rp = keyLen.next;
|
|
@@ -394,15 +404,23 @@ function firstRecord(buf, start, end) {
|
|
|
394
404
|
offset: Number(baseOffset) + offDelta.value,
|
|
395
405
|
};
|
|
396
406
|
}
|
|
397
|
-
|
|
407
|
+
// Tombstone (null value) or empty value: hand back a marker carrying its
|
|
408
|
+
// offset instead of null. Returning null here used to mean "no record", so
|
|
409
|
+
// pop() never advanced and re-fetched the tombstone for ever -- nothing
|
|
410
|
+
// after it was delivered. The caller (fetchPastTombstones) steps the
|
|
411
|
+
// offset on and re-fetches.
|
|
412
|
+
return {
|
|
413
|
+
value: null,
|
|
414
|
+
offset: Number(baseOffset) + offDelta.value,
|
|
415
|
+
};
|
|
398
416
|
}
|
|
399
417
|
pos = batchEnd;
|
|
400
418
|
}
|
|
401
419
|
return null;
|
|
402
420
|
}
|
|
403
|
-
async function fetchAt(topic, offset) {
|
|
421
|
+
async function fetchAt(topic, offset, maxWaitMs) {
|
|
404
422
|
const sock = await broker();
|
|
405
|
-
const resp = await rpc(sock, fetchRequest(topic, offset));
|
|
423
|
+
const resp = await rpc(sock, fetchRequest(topic, offset, maxWaitMs));
|
|
406
424
|
let pos = 4; // correlationId
|
|
407
425
|
pos += 4; // throttleTimeMs
|
|
408
426
|
const topicCount = resp.readInt32BE(pos); pos += 4;
|
|
@@ -538,9 +556,37 @@ async function broker() {
|
|
|
538
556
|
// Resume from the committed offset on the FIRST read of a topic in this worker,
|
|
539
557
|
// then advance the in-memory cursor; the committed offset only moves on a
|
|
540
558
|
// commit, so it lags and a crash before commit replays (at-least-once).
|
|
559
|
+
// Fetch from the cursor, stepping past tombstones, until a record with a value
|
|
560
|
+
// arrives, the topic is exhausted, or the deadline passes. A tombstone (null
|
|
561
|
+
// value: Debezium deletes, compacted-topic delete markers) carries no job;
|
|
562
|
+
// returning "nothing" without moving the offset re-fetched it for ever, so
|
|
563
|
+
// nothing after it was ever delivered. The 1 s deadline holds while skipping
|
|
564
|
+
// (the same steady-state bound as tina4-php/tina4-python), and the whole loop
|
|
565
|
+
// stays inside this one worker round-trip (ADR-0022) -- well under
|
|
566
|
+
// CALL_TIMEOUT_MS. Nothing is committed here: acknowledging the next record
|
|
567
|
+
// commits past the skipped tombstones, as before.
|
|
568
|
+
async function fetchPastTombstones(topic) {
|
|
569
|
+
const deadline = Date.now() + 1000;
|
|
570
|
+
let maxWaitMs = FETCH_MAX_WAIT_MS;
|
|
571
|
+
while (true) {
|
|
572
|
+
const offset = offsets[topic];
|
|
573
|
+
const rec = await fetchAt(topic, offset, maxWaitMs);
|
|
574
|
+
if (rec === null || rec.value !== null) return rec; // nothing, or a real record
|
|
575
|
+
// Anti-spin: the decoder reads only a batch's first record, so a tombstone
|
|
576
|
+
// sharing a batch with later records comes back at an offset already passed.
|
|
577
|
+
// That must never loop this fetch.
|
|
578
|
+
const next = rec.offset + 1;
|
|
579
|
+
if (next <= offset) return null;
|
|
580
|
+
offsets[topic] = next;
|
|
581
|
+
const remaining = deadline - Date.now();
|
|
582
|
+
if (remaining <= 0) return null;
|
|
583
|
+
maxWaitMs = remaining;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
541
587
|
async function fetchNext(topic) {
|
|
542
588
|
if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
|
|
543
|
-
const rec = await
|
|
589
|
+
const rec = await fetchPastTombstones(topic);
|
|
544
590
|
if (rec === null) return null;
|
|
545
591
|
offsets[topic] = rec.offset + 1;
|
|
546
592
|
return rec;
|
|
@@ -2388,11 +2388,11 @@ export async function startServer(config?: Tina4Config): Promise<{
|
|
|
2388
2388
|
// promise resolves (a client can then rely on both families being up).
|
|
2389
2389
|
const siblingServers = await startLoopbackSiblings(port, host, dispatch);
|
|
2390
2390
|
|
|
2391
|
-
// Raw TCP services
|
|
2392
|
-
//
|
|
2393
|
-
//
|
|
2394
|
-
//
|
|
2395
|
-
|
|
2391
|
+
// Raw TCP services start LATER, only after the SIGTERM/SIGINT handlers are
|
|
2392
|
+
// armed (see startAllTcpServices below). Binding a port that accepts work
|
|
2393
|
+
// BEFORE graceful shutdown is wired leaves a window in which a signal kills
|
|
2394
|
+
// the process ungracefully (exit 143) instead of draining to exit 0 — and
|
|
2395
|
+
// a client that connects the instant the port opens lands squarely in it.
|
|
2396
2396
|
|
|
2397
2397
|
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
2398
2398
|
const isDebug = isTruthy(process.env.TINA4_DEBUG);
|
|
@@ -2556,9 +2556,11 @@ ${reset}
|
|
|
2556
2556
|
for (const sibling of siblingServers) sibling.closeIdleConnections();
|
|
2557
2557
|
});
|
|
2558
2558
|
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2559
|
+
// The teardown steps a handled signal must run. Pulled out of
|
|
2560
|
+
// gracefulShutdown() so the handler itself stays a thin try/catch/exit
|
|
2561
|
+
// (low cyclomatic complexity) — the drain logic lives here, the
|
|
2562
|
+
// exit-safety contract lives in the caller.
|
|
2563
|
+
const runTeardown = async (signal: string): Promise<void> => {
|
|
2562
2564
|
Log.info(`Received ${signal}, shutting down gracefully...`);
|
|
2563
2565
|
|
|
2564
2566
|
// Drop our identity marker so a later takeover does not match a dead PID.
|
|
@@ -2623,23 +2625,77 @@ ${reset}
|
|
|
2623
2625
|
// without letting exit() actually kill the process (see
|
|
2624
2626
|
// test/gracefulShutdown.test.ts) must not inherit a stale snapshot.
|
|
2625
2627
|
Log.reset();
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2628
|
+
};
|
|
2629
|
+
|
|
2630
|
+
// Best-effort degrade when a teardown step throws: try the logger, and
|
|
2631
|
+
// when logging ITSELF is the failing step, fall back to a raw stderr
|
|
2632
|
+
// write (which never routes through the sink). Never throws.
|
|
2633
|
+
const degradeTeardownFailure = (signal: string, err: unknown): void => {
|
|
2634
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
2635
|
+
try {
|
|
2636
|
+
Log.error(`Teardown step failed during ${signal} shutdown (exiting cleanly): ${detail}`);
|
|
2637
|
+
} catch {
|
|
2638
|
+
try {
|
|
2639
|
+
process.stderr.write(
|
|
2640
|
+
`tina4: teardown step failed during ${signal} shutdown (exiting cleanly): ${detail}\n`,
|
|
2641
|
+
);
|
|
2642
|
+
} catch {
|
|
2643
|
+
/* nothing left to degrade to */
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
};
|
|
2647
|
+
|
|
2648
|
+
const gracefulShutdown = async (signal: string): Promise<void> => {
|
|
2649
|
+
if (shuttingDown) return;
|
|
2650
|
+
shuttingDown = true;
|
|
2651
|
+
|
|
2652
|
+
// Exception-safe teardown (parity with PHP Server::cleanup()/
|
|
2653
|
+
// forceShutdown() and Ruby). A handled SIGTERM/SIGINT MUST drain and
|
|
2654
|
+
// exit 0, never fatal, so NO throw or rejection from any teardown step
|
|
2655
|
+
// may escape this function. The handlers below invoke it as
|
|
2656
|
+
// `void gracefulShutdown(...)`, which discards the promise - an escaping
|
|
2657
|
+
// rejection would surface as an unhandledRejection and Node's default
|
|
2658
|
+
// disposition would exit NON-ZERO, turning a handled signal into exit 1.
|
|
2659
|
+
// So the whole drain runs inside this guard: on any throw we degrade to
|
|
2660
|
+
// a best-effort line and STILL exit 0. `shuttingDown` keeps it idempotent.
|
|
2661
|
+
try {
|
|
2662
|
+
await runTeardown(signal);
|
|
2663
|
+
} catch (err) {
|
|
2664
|
+
degradeTeardownFailure(signal, err);
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2667
|
+
// Exit 0: this process was ASKED to stop. Reached on the clean path AND
|
|
2668
|
+
// after a degraded teardown. 128+signum is what waitpid reports for a
|
|
2669
|
+
// process killed BY a signal, i.e. one that did NOT handle it - it is a
|
|
2670
|
+
// diagnosis, not a target. Gunicorn and Puma both halt 0 on a handled
|
|
2671
|
+
// TERM, and a container exiting 0 is a clean termination rather than a
|
|
2672
|
+
// signal-kill.
|
|
2631
2673
|
process.exit(0);
|
|
2632
2674
|
};
|
|
2633
2675
|
|
|
2634
2676
|
const onSigterm = (): void => {
|
|
2635
|
-
|
|
2677
|
+
// gracefulShutdown is internally exception-safe, so this cannot reject;
|
|
2678
|
+
// the `.catch` is belt-and-braces so the discarded (`void`) promise can
|
|
2679
|
+
// never become an unhandledRejection that exits non-zero on a handled
|
|
2680
|
+
// signal.
|
|
2681
|
+
void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
|
|
2636
2682
|
};
|
|
2637
2683
|
const onSigint = (): void => {
|
|
2638
|
-
void gracefulShutdown("SIGINT");
|
|
2684
|
+
void gracefulShutdown("SIGINT").catch(() => process.exit(0));
|
|
2639
2685
|
};
|
|
2640
2686
|
process.on("SIGTERM", onSigterm);
|
|
2641
2687
|
process.on("SIGINT", onSigint);
|
|
2642
2688
|
|
|
2689
|
+
// Raw TCP services (feature 142, ADR-0102 D1) bind on THIS event loop,
|
|
2690
|
+
// beside the HTTP server — one process serves both the device gateway and
|
|
2691
|
+
// its dashboard. Started HERE, AFTER the shutdown handlers are armed and
|
|
2692
|
+
// still BEFORE resolvePromise (so a client can rely on both families being
|
|
2693
|
+
// up), so a device connecting the instant the port opens can never catch
|
|
2694
|
+
// the process in a state where SIGTERM kills it ungracefully instead of
|
|
2695
|
+
// draining (feature 142's SIGTERM-drain contract). Each binds its own port;
|
|
2696
|
+
// a worker that finds it already bound skips silently (single-owner).
|
|
2697
|
+
await startAllTcpServices(host);
|
|
2698
|
+
|
|
2643
2699
|
const loopWatchdog = startLoopWatchdog();
|
|
2644
2700
|
|
|
2645
2701
|
resolvePromise({
|
|
@@ -21,7 +21,8 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
21
21
|
* return a + b;
|
|
22
22
|
* });
|
|
23
23
|
*
|
|
24
|
-
* runAll();
|
|
24
|
+
* runAll(); // synchronous test functions
|
|
25
|
+
* await runAllAsync(); // async test functions (awaited, with a timeout)
|
|
25
26
|
*
|
|
26
27
|
* The builders are named expect* — DESCRIPTORS that record an expectation for the
|
|
27
28
|
* runner — deliberately distinct from the xUnit assert* on Tina4Test (test.ts),
|
|
@@ -104,46 +105,70 @@ export function tests(
|
|
|
104
105
|
|
|
105
106
|
// ── Runner ─────────────────────────────────────────────────────────
|
|
106
107
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
interface RunOptions {
|
|
109
|
+
quiet?: boolean;
|
|
110
|
+
failfast?: boolean;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface AsyncRunOptions extends RunOptions {
|
|
114
|
+
/** Per-call limit in milliseconds for an async test function (default 30000). */
|
|
115
|
+
timeoutMs?: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Run all registered tests synchronously. Returns the results summary.
|
|
120
|
+
*
|
|
121
|
+
* A test function that returns a Promise (an async function) cannot be judged
|
|
122
|
+
* here: its result is not known yet. It is reported as an ERROR naming
|
|
123
|
+
* `runAllAsync()`, never as a pass. Use `await runAllAsync()` for async tests.
|
|
124
|
+
*/
|
|
125
|
+
export function runAll(options: RunOptions = {}): TestResults {
|
|
111
126
|
const { quiet = false, failfast = false } = options;
|
|
112
127
|
const results: TestResults = { passed: 0, failed: 0, errors: 0, details: [] };
|
|
113
128
|
|
|
114
129
|
for (const entry of registry) {
|
|
115
|
-
if (!quiet) {
|
|
116
|
-
|
|
130
|
+
if (!quiet) console.log(`\n ${entry.name}`);
|
|
131
|
+
for (const assertion of entry.assertions) {
|
|
132
|
+
const label = assertionLabel(assertion, entry.name);
|
|
133
|
+
const ok = record(results, label, quiet, () => judge(assertion, callSync(entry.fn, assertion.args)));
|
|
134
|
+
if (!ok && failfast) {
|
|
135
|
+
printSummary(results, quiet);
|
|
136
|
+
return results;
|
|
137
|
+
}
|
|
117
138
|
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
printSummary(results, quiet);
|
|
142
|
+
return results;
|
|
143
|
+
}
|
|
118
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Run all registered tests, awaiting each test function. Resolves to the
|
|
147
|
+
* results summary.
|
|
148
|
+
*
|
|
149
|
+
* An async function is judged on what it resolves to or rejects with. A call
|
|
150
|
+
* that has not settled after `timeoutMs` (default 30000) is reported as an
|
|
151
|
+
* error, so one stuck test cannot hang the run. `timeoutMs: Infinity` turns the
|
|
152
|
+
* timeout off; any other value must be a positive number of milliseconds no
|
|
153
|
+
* larger than 2147483647 (the largest delay a Node timer accepts).
|
|
154
|
+
*/
|
|
155
|
+
export async function runAllAsync(options: AsyncRunOptions = {}): Promise<TestResults> {
|
|
156
|
+
const { quiet = false, failfast = false, timeoutMs = 30_000 } = options;
|
|
157
|
+
checkTimeout(timeoutMs);
|
|
158
|
+
const results: TestResults = { passed: 0, failed: 0, errors: 0, details: [] };
|
|
159
|
+
|
|
160
|
+
for (const entry of registry) {
|
|
161
|
+
if (!quiet) console.log(`\n ${entry.name}`);
|
|
119
162
|
for (const assertion of entry.assertions) {
|
|
120
163
|
const label = assertionLabel(assertion, entry.name);
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
if (err instanceof TestAssertionError) {
|
|
130
|
-
results.failed++;
|
|
131
|
-
results.details.push({ name: label, status: "failed", message: err.message });
|
|
132
|
-
if (!quiet) {
|
|
133
|
-
console.log(` \x1b[31mx\x1b[0m ${label}: ${err.message}`);
|
|
134
|
-
}
|
|
135
|
-
} else {
|
|
136
|
-
results.errors++;
|
|
137
|
-
const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
|
|
138
|
-
results.details.push({ name: label, status: "error", message: msg });
|
|
139
|
-
if (!quiet) {
|
|
140
|
-
console.log(` \x1b[33m!\x1b[0m ${label}: ${msg}`);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
if (failfast) {
|
|
144
|
-
printSummary(results, quiet);
|
|
145
|
-
return results;
|
|
146
|
-
}
|
|
164
|
+
const outcome = await callAsync(entry.fn, assertion.args, timeoutMs);
|
|
165
|
+
const ok = record(results, label, quiet, () => {
|
|
166
|
+
if (outcome instanceof TestRunError) throw outcome;
|
|
167
|
+
judge(assertion, outcome);
|
|
168
|
+
});
|
|
169
|
+
if (!ok && failfast) {
|
|
170
|
+
printSummary(results, quiet);
|
|
171
|
+
return results;
|
|
147
172
|
}
|
|
148
173
|
}
|
|
149
174
|
}
|
|
@@ -166,52 +191,139 @@ class TestAssertionError extends Error {
|
|
|
166
191
|
}
|
|
167
192
|
}
|
|
168
193
|
|
|
169
|
-
function
|
|
170
|
-
|
|
194
|
+
/** What calling a test function produced: a value, or a thrown error. */
|
|
195
|
+
type Outcome = { threw: false; value: unknown } | { threw: true; error: unknown };
|
|
196
|
+
|
|
197
|
+
/** Raised when a test cannot be judged at all (not a failed assertion). */
|
|
198
|
+
class TestRunError extends Error {
|
|
199
|
+
constructor(message: string) {
|
|
200
|
+
super(message);
|
|
201
|
+
this.name = "TestRunError";
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function isThenable(value: unknown): value is PromiseLike<unknown> {
|
|
206
|
+
return (
|
|
207
|
+
value !== null &&
|
|
208
|
+
(typeof value === "object" || typeof value === "function") &&
|
|
209
|
+
typeof (value as { then?: unknown }).then === "function"
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function callSync(fn: (...args: unknown[]) => unknown, args: unknown[]): Outcome {
|
|
214
|
+
let value: unknown;
|
|
215
|
+
try {
|
|
216
|
+
value = fn(...args);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
return { threw: true, error };
|
|
219
|
+
}
|
|
220
|
+
if (isThenable(value)) {
|
|
221
|
+
// Settle it quietly: its rejection must not surface as an unhandled one.
|
|
222
|
+
Promise.resolve(value).then(undefined, () => undefined);
|
|
223
|
+
throw new TestRunError(
|
|
224
|
+
"returned a Promise (async test function): runAll() cannot judge it, use await runAllAsync()",
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
return { threw: false, value };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Largest delay setTimeout honours; a larger one fires after 1 ms. */
|
|
231
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
232
|
+
|
|
233
|
+
function checkTimeout(timeoutMs: number): void {
|
|
234
|
+
if (timeoutMs === Infinity) return;
|
|
235
|
+
if (!(timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {
|
|
236
|
+
throw new RangeError(
|
|
237
|
+
`timeoutMs must be Infinity or a number of milliseconds in (0, ${MAX_TIMER_MS}], got ${timeoutMs}`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function callAsync(
|
|
243
|
+
fn: (...args: unknown[]) => unknown,
|
|
244
|
+
args: unknown[],
|
|
245
|
+
timeoutMs: number,
|
|
246
|
+
): Promise<Outcome | TestRunError> {
|
|
247
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
248
|
+
try {
|
|
249
|
+
const value = fn(...args);
|
|
250
|
+
if (!isThenable(value)) return { threw: false, value };
|
|
251
|
+
if (timeoutMs === Infinity) return { threw: false, value: await value };
|
|
252
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
253
|
+
timer = setTimeout(
|
|
254
|
+
() => reject(new TestRunError(`did not settle within ${timeoutMs} ms`)),
|
|
255
|
+
timeoutMs,
|
|
256
|
+
);
|
|
257
|
+
});
|
|
258
|
+
return { threw: false, value: await Promise.race([Promise.resolve(value), timeout]) };
|
|
259
|
+
} catch (error) {
|
|
260
|
+
if (error instanceof TestRunError) return error;
|
|
261
|
+
return { threw: true, error };
|
|
262
|
+
} finally {
|
|
263
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Record one assertion's result; returns true when it passed. */
|
|
268
|
+
function record(results: TestResults, label: string, quiet: boolean, check: () => void): boolean {
|
|
269
|
+
try {
|
|
270
|
+
check();
|
|
271
|
+
results.passed++;
|
|
272
|
+
results.details.push({ name: label, status: "passed" });
|
|
273
|
+
if (!quiet) console.log(` \x1b[32m+\x1b[0m ${label}`);
|
|
274
|
+
return true;
|
|
275
|
+
} catch (err) {
|
|
276
|
+
if (err instanceof TestAssertionError) {
|
|
277
|
+
results.failed++;
|
|
278
|
+
results.details.push({ name: label, status: "failed", message: err.message });
|
|
279
|
+
if (!quiet) console.log(` \x1b[31mx\x1b[0m ${label}: ${err.message}`);
|
|
280
|
+
} else {
|
|
281
|
+
results.errors++;
|
|
282
|
+
const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
|
|
283
|
+
results.details.push({ name: label, status: "error", message: msg });
|
|
284
|
+
if (!quiet) console.log(` \x1b[33m!\x1b[0m ${label}: ${msg}`);
|
|
285
|
+
}
|
|
286
|
+
return false;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Judge an expectRaises assertion: the call must have thrown that class. */
|
|
291
|
+
function judgeRaises(assertion: Assertion, outcome: Outcome): void {
|
|
292
|
+
const ExcClass = assertion.exception!;
|
|
293
|
+
if (!outcome.threw) throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
|
|
294
|
+
const err = outcome.error;
|
|
295
|
+
if (err instanceof ExcClass) return;
|
|
296
|
+
throw new TestAssertionError(
|
|
297
|
+
`expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Judge one assertion against what the call produced. */
|
|
302
|
+
function judge(assertion: Assertion, outcome: Outcome): void {
|
|
303
|
+
const { type } = assertion;
|
|
304
|
+
|
|
305
|
+
if (type === "raises") return judgeRaises(assertion, outcome);
|
|
306
|
+
|
|
307
|
+
// Any other assertion: an exception from the function is an error, not a failure.
|
|
308
|
+
if (outcome.threw) throw outcome.error;
|
|
309
|
+
const result = outcome.value;
|
|
171
310
|
|
|
172
311
|
switch (type) {
|
|
173
312
|
case "equal": {
|
|
174
|
-
const result = fn(...args);
|
|
175
313
|
const expected = assertion.expected;
|
|
176
314
|
if (result !== expected) {
|
|
177
315
|
throw new TestAssertionError(
|
|
178
316
|
`expected ${JSON.stringify(expected)}, got ${JSON.stringify(result)}`,
|
|
179
317
|
);
|
|
180
318
|
}
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
case "raises": {
|
|
185
|
-
const ExcClass = assertion.exception!;
|
|
186
|
-
try {
|
|
187
|
-
fn(...args);
|
|
188
|
-
} catch (err) {
|
|
189
|
-
if (err instanceof ExcClass) {
|
|
190
|
-
return; // success
|
|
191
|
-
}
|
|
192
|
-
throw new TestAssertionError(
|
|
193
|
-
`expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`,
|
|
194
|
-
);
|
|
195
|
-
}
|
|
196
|
-
throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
case "true": {
|
|
200
|
-
const result = fn(...args);
|
|
201
|
-
if (!result) {
|
|
202
|
-
throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
|
|
203
|
-
}
|
|
204
|
-
break;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
case "false": {
|
|
208
|
-
const result = fn(...args);
|
|
209
|
-
if (result) {
|
|
210
|
-
throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
|
|
211
|
-
}
|
|
212
|
-
break;
|
|
319
|
+
return;
|
|
213
320
|
}
|
|
214
|
-
|
|
321
|
+
case "true":
|
|
322
|
+
if (!result) throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
|
|
323
|
+
return;
|
|
324
|
+
case "false":
|
|
325
|
+
if (result) throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
|
|
326
|
+
return;
|
|
215
327
|
default:
|
|
216
328
|
throw new Error(`unknown assertion type: ${type}`);
|
|
217
329
|
}
|