@terreno/test 57.18.0 → 57.19.2
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/CHANGELOG.md +1681 -0
- package/README.md +6 -0
- package/dist/assertions/expectAPIError.d.ts +18 -0
- package/dist/assertions/expectAPIError.js +33 -0
- package/dist/assertions/strictResponseProperties.d.ts +14 -0
- package/dist/assertions/strictResponseProperties.js +37 -0
- package/dist/cache/mongoTestCache.js +2 -2
- package/dist/cli/collectFiles.d.ts +38 -0
- package/dist/cli/collectFiles.js +73 -0
- package/dist/cli/testHygiene.d.ts +134 -0
- package/dist/cli/testHygiene.js +357 -0
- package/dist/cli/testHygieneCli.d.ts +2 -0
- package/dist/cli/testHygieneCli.js +5 -0
- package/dist/cli/testHygieneRules.d.ts +58 -0
- package/dist/cli/testHygieneRules.js +517 -0
- package/dist/cli/testShard.d.ts +155 -0
- package/dist/cli/testShard.js +377 -0
- package/dist/cli/testShardCli.d.ts +2 -0
- package/dist/cli/testShardCli.js +5 -0
- package/dist/expo/authTokenStorage.d.ts +76 -0
- package/dist/expo/authTokenStorage.js +160 -0
- package/dist/expo/expoModuleMocks.d.ts +24 -0
- package/dist/expo/expoModuleMocks.js +456 -0
- package/dist/expo/libraryModuleMocks.d.ts +17 -0
- package/dist/expo/libraryModuleMocks.js +347 -0
- package/dist/expo/mockHelpers.d.ts +39 -0
- package/dist/expo/mockHelpers.js +45 -0
- package/dist/expo/mockModuleAliases.d.ts +50 -0
- package/dist/expo/mockModuleAliases.js +174 -0
- package/dist/expo/reactNativeMock.d.ts +39 -0
- package/dist/expo/reactNativeMock.js +421 -0
- package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
- package/dist/expo/registerExpoTestEnvironment.js +163 -0
- package/dist/expo/renderWithTerreno.d.ts +47 -0
- package/dist/expo/renderWithTerreno.js +47 -0
- package/dist/http/authWithToken.d.ts +20 -0
- package/dist/http/authWithToken.js +30 -0
- package/dist/index.d.ts +14 -1
- package/dist/index.js +33 -1
- package/dist/logging/silenceLogs.js +0 -2
- package/dist/mocks/aiSdk.d.ts +77 -0
- package/dist/mocks/aiSdk.js +102 -0
- package/dist/mocks/cloudTasks.d.ts +91 -0
- package/dist/mocks/cloudTasks.js +197 -0
- package/dist/mocks/expoPush.d.ts +53 -0
- package/dist/mocks/expoPush.js +57 -0
- package/dist/mocks/gcs.d.ts +101 -0
- package/dist/mocks/gcs.js +162 -0
- package/dist/mocks/googleAuth.d.ts +69 -0
- package/dist/mocks/googleAuth.js +55 -0
- package/dist/mocks/mockGroup.d.ts +11 -0
- package/dist/mocks/mockGroup.js +21 -0
- package/dist/mocks/notifiers.d.ts +21 -0
- package/dist/mocks/notifiers.js +26 -0
- package/dist/mocks/sendgrid.d.ts +22 -0
- package/dist/mocks/sendgrid.js +32 -0
- package/dist/mocks/twilio.d.ts +72 -0
- package/dist/mocks/twilio.js +64 -0
- package/dist/preload/registerBackendPreload.js +4 -1
- package/dist/time/freezeTime.d.ts +16 -0
- package/dist/time/freezeTime.js +49 -0
- package/dist/transaction/testTransaction.d.ts +43 -6
- package/dist/transaction/testTransaction.js +371 -92
- package/dist/utils/waitUntil.d.ts +22 -0
- package/dist/utils/waitUntil.js +34 -0
- package/package.json +53 -8
- package/src/assertions/expectAPIError.ts +51 -0
- package/src/assertions/strictResponseProperties.ts +42 -0
- package/src/cache/mongoTestCache.ts +2 -2
- package/src/cli/collectFiles.ts +115 -0
- package/src/cli/testHygiene.ts +539 -0
- package/src/cli/testHygieneCli.ts +4 -0
- package/src/cli/testHygieneRules.ts +719 -0
- package/src/cli/testShard.ts +532 -0
- package/src/cli/testShardCli.ts +4 -0
- package/src/expo/authTokenStorage.ts +198 -0
- package/src/expo/expoModuleMocks.ts +503 -0
- package/src/expo/libraryModuleMocks.ts +411 -0
- package/src/expo/mockHelpers.ts +73 -0
- package/src/expo/mockModuleAliases.ts +252 -0
- package/src/expo/reactNativeMock.ts +534 -0
- package/src/expo/registerExpoTestEnvironment.ts +260 -0
- package/src/expo/renderWithTerreno.ts +79 -0
- package/src/http/authWithToken.ts +38 -0
- package/src/index.ts +82 -1
- package/src/logging/silenceLogs.ts +0 -2
- package/src/mocks/aiSdk.ts +199 -0
- package/src/mocks/cloudTasks.ts +323 -0
- package/src/mocks/expoPush.ts +134 -0
- package/src/mocks/gcs.ts +305 -0
- package/src/mocks/googleAuth.ts +136 -0
- package/src/mocks/mockGroup.ts +32 -0
- package/src/mocks/notifiers.ts +36 -0
- package/src/mocks/sendgrid.ts +57 -0
- package/src/mocks/twilio.ts +143 -0
- package/src/preload/registerBackendPreload.ts +4 -1
- package/src/time/freezeTime.ts +61 -0
- package/src/transaction/testTransaction.ts +456 -124
- package/src/utils/waitUntil.ts +47 -0
- package/biome.jsonc +0 -20
- package/bunfig.toml +0 -16
- package/src/cache/mongoTestCache.test.ts +0 -103
- package/src/env/setTerrenoTestEnv.test.ts +0 -26
- package/src/http/authAsUser.test.ts +0 -40
- package/src/http/getBaseServer.test.ts +0 -45
- package/src/logging/setupEnvironment.test.ts +0 -24
- package/src/logging/silenceLogs.test.ts +0 -52
- package/src/logging/testLogger.test.ts +0 -58
- package/src/mocks/sentryBun.test.ts +0 -230
- package/src/mongo/connection.test.ts +0 -43
- package/src/mongo/mongoServer.test.ts +0 -99
- package/src/preload/registerBackendPreload.test.ts +0 -10
- package/src/transaction/testTransaction.test.ts +0 -64
- package/src/utils/helpers.test.ts +0 -46
- package/tsconfig.json +0 -18
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
export interface GoogleAuthMockRequestOptions {
|
|
3
|
+
data?: unknown;
|
|
4
|
+
method?: string;
|
|
5
|
+
url: string;
|
|
6
|
+
[key: string]: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface GoogleAuthMockResponse {
|
|
9
|
+
data: unknown;
|
|
10
|
+
headers: Record<string, string>;
|
|
11
|
+
status: number;
|
|
12
|
+
}
|
|
13
|
+
export interface GoogleAuthMockClient {
|
|
14
|
+
getAccessToken: GoogleAuthMock["getAccessToken"];
|
|
15
|
+
getRequestHeaders: GoogleAuthMock["getRequestHeaders"];
|
|
16
|
+
request: GoogleAuthMock["request"];
|
|
17
|
+
}
|
|
18
|
+
export interface GoogleAuthMockIdTokenPayload {
|
|
19
|
+
aud?: string;
|
|
20
|
+
email?: string;
|
|
21
|
+
email_verified?: boolean;
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
export interface GoogleAuthMockTicket {
|
|
25
|
+
getPayload: () => GoogleAuthMockIdTokenPayload;
|
|
26
|
+
}
|
|
27
|
+
export interface RegisterGoogleAuthMockOptions {
|
|
28
|
+
/** Token `getAccessToken()` returns. Default `"mock-access-token"`. */
|
|
29
|
+
accessToken?: string;
|
|
30
|
+
/** Claims every verified ID token carries (merged with `aud`). Default: a verified email. */
|
|
31
|
+
idTokenPayload?: GoogleAuthMockIdTokenPayload;
|
|
32
|
+
/** Project id `getProjectId()` returns. Default `"mock-project"`. */
|
|
33
|
+
projectId?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface GoogleAuthMock {
|
|
36
|
+
/** `new GoogleAuth(options)` — every instance shares `getClient`, `getAccessToken`, `request`. */
|
|
37
|
+
GoogleAuth: Mock<(options?: Record<string, unknown>) => {
|
|
38
|
+
getAccessToken: GoogleAuthMock["getAccessToken"];
|
|
39
|
+
getClient: GoogleAuthMock["getClient"];
|
|
40
|
+
getProjectId: GoogleAuthMock["getProjectId"];
|
|
41
|
+
request: GoogleAuthMock["request"];
|
|
42
|
+
}>;
|
|
43
|
+
/** `new OAuth2Client(...)` — every instance shares `verifyIdToken`. */
|
|
44
|
+
OAuth2Client: Mock<(...args: unknown[]) => {
|
|
45
|
+
verifyIdToken: GoogleAuthMock["verifyIdToken"];
|
|
46
|
+
}>;
|
|
47
|
+
client: GoogleAuthMockClient;
|
|
48
|
+
getAccessToken: Mock<() => Promise<{
|
|
49
|
+
token: string;
|
|
50
|
+
}>>;
|
|
51
|
+
getClient: Mock<() => Promise<GoogleAuthMockClient>>;
|
|
52
|
+
getProjectId: Mock<() => Promise<string>>;
|
|
53
|
+
getRequestHeaders: Mock<() => Promise<Record<string, string>>>;
|
|
54
|
+
/** Authorized request — resolves `{data: {}, status: 200}`. Override per test. */
|
|
55
|
+
request: Mock<(options: GoogleAuthMockRequestOptions) => Promise<GoogleAuthMockResponse>>;
|
|
56
|
+
/** Accepts any token; the ticket's payload is `idTokenPayload` plus the requested audience. */
|
|
57
|
+
verifyIdToken: Mock<(options: {
|
|
58
|
+
audience?: string | string[];
|
|
59
|
+
idToken: string;
|
|
60
|
+
}) => Promise<GoogleAuthMockTicket>>;
|
|
61
|
+
/** Clears calls and overrides. */
|
|
62
|
+
reset: () => void;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Registers `mock.module("google-auth-library", ...)` covering what Terreno calls: `GoogleAuth`
|
|
66
|
+
* (`getClient().request` / `getAccessToken`, used by Vertex model discovery and the Cloud Tasks
|
|
67
|
+
* REST client) and `OAuth2Client.verifyIdToken` (Cloud Tasks OIDC execute auth).
|
|
68
|
+
*/
|
|
69
|
+
export declare const registerGoogleAuthMock: (options?: RegisterGoogleAuthMockOptions) => GoogleAuthMock;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerGoogleAuthMock = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const mockGroup_1 = require("./mockGroup");
|
|
6
|
+
/**
|
|
7
|
+
* Registers `mock.module("google-auth-library", ...)` covering what Terreno calls: `GoogleAuth`
|
|
8
|
+
* (`getClient().request` / `getAccessToken`, used by Vertex model discovery and the Cloud Tasks
|
|
9
|
+
* REST client) and `OAuth2Client.verifyIdToken` (Cloud Tasks OIDC execute auth).
|
|
10
|
+
*/
|
|
11
|
+
const registerGoogleAuthMock = (options = {}) => {
|
|
12
|
+
const accessToken = options.accessToken ?? "mock-access-token";
|
|
13
|
+
const idTokenPayload = options.idTokenPayload ?? {
|
|
14
|
+
email: "mock-service-account@mock-project.iam.gserviceaccount.com",
|
|
15
|
+
email_verified: true,
|
|
16
|
+
};
|
|
17
|
+
const projectId = options.projectId ?? "mock-project";
|
|
18
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
19
|
+
const getAccessToken = group.fn(async () => ({ token: accessToken }));
|
|
20
|
+
const getRequestHeaders = group.fn(async () => ({ Authorization: `Bearer ${accessToken}` }));
|
|
21
|
+
const request = group.fn(async (_options) => ({
|
|
22
|
+
data: {},
|
|
23
|
+
headers: {},
|
|
24
|
+
status: 200,
|
|
25
|
+
}));
|
|
26
|
+
const client = { getAccessToken, getRequestHeaders, request };
|
|
27
|
+
const getClient = group.fn(async () => client);
|
|
28
|
+
const getProjectId = group.fn(async () => projectId);
|
|
29
|
+
const GoogleAuth = group.fn((_options) => ({
|
|
30
|
+
getAccessToken,
|
|
31
|
+
getClient,
|
|
32
|
+
getProjectId,
|
|
33
|
+
request,
|
|
34
|
+
}));
|
|
35
|
+
const verifyIdToken = group.fn(async ({ audience, }) => {
|
|
36
|
+
const aud = Array.isArray(audience) ? audience[0] : audience;
|
|
37
|
+
return { getPayload: () => ({ ...idTokenPayload, aud }) };
|
|
38
|
+
});
|
|
39
|
+
const OAuth2Client = group.fn((..._args) => ({ verifyIdToken }));
|
|
40
|
+
const moduleExports = { GoogleAuth, OAuth2Client };
|
|
41
|
+
bun_test_1.mock.module("google-auth-library", () => ({ ...moduleExports, default: moduleExports }));
|
|
42
|
+
return {
|
|
43
|
+
client,
|
|
44
|
+
GoogleAuth,
|
|
45
|
+
getAccessToken,
|
|
46
|
+
getClient,
|
|
47
|
+
getProjectId,
|
|
48
|
+
getRequestHeaders,
|
|
49
|
+
OAuth2Client,
|
|
50
|
+
request,
|
|
51
|
+
reset: group.reset,
|
|
52
|
+
verifyIdToken,
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
exports.registerGoogleAuthMock = registerGoogleAuthMock;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
type AnyFunction = (...args: never[]) => unknown;
|
|
3
|
+
export interface MockGroup {
|
|
4
|
+
/** Creates a mock whose default behavior `reset()` restores. */
|
|
5
|
+
fn: <T extends AnyFunction>(implementation: T) => Mock<T>;
|
|
6
|
+
/** Clears every mock's calls and restores its default implementation. */
|
|
7
|
+
reset: () => void;
|
|
8
|
+
}
|
|
9
|
+
/** Tracks a set of SDK mocks so one call resets calls, one-off overrides, and implementations. */
|
|
10
|
+
export declare const createMockGroup: () => MockGroup;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMockGroup = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
/** Tracks a set of SDK mocks so one call resets calls, one-off overrides, and implementations. */
|
|
6
|
+
const createMockGroup = () => {
|
|
7
|
+
const entries = [];
|
|
8
|
+
const fn = (implementation) => {
|
|
9
|
+
const mockFn = (0, bun_test_1.mock)(implementation);
|
|
10
|
+
entries.push({ implementation, mockFn: mockFn });
|
|
11
|
+
return mockFn;
|
|
12
|
+
};
|
|
13
|
+
const reset = () => {
|
|
14
|
+
for (const { implementation, mockFn } of entries) {
|
|
15
|
+
mockFn.mockReset();
|
|
16
|
+
mockFn.mockImplementation(implementation);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
return { fn, reset };
|
|
20
|
+
};
|
|
21
|
+
exports.createMockGroup = createMockGroup;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
type NotifierMock = Mock<(...args: unknown[]) => Promise<void>>;
|
|
3
|
+
export interface TerrenoNotifierMocks {
|
|
4
|
+
sendToGoogleChat: NotifierMock;
|
|
5
|
+
sendToSlack: NotifierMock;
|
|
6
|
+
sendToZoom: NotifierMock;
|
|
7
|
+
/** Clears calls and overrides; the notifiers resolve `undefined` again. */
|
|
8
|
+
reset: () => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Re-registers `@terreno/api` with its real exports plus mocked `sendToSlack`, `sendToZoom`,
|
|
12
|
+
* and `sendToGoogleChat`, so app code that imports them sends nothing and tests can assert the
|
|
13
|
+
* calls. Call it in a preload before app modules load.
|
|
14
|
+
*
|
|
15
|
+
* Only importers of the `@terreno/api` package see the mocks: code inside `@terreno/api` that
|
|
16
|
+
* calls the notifiers through its own modules (for example `wrapScript`) still uses the real
|
|
17
|
+
* ones, which no-op without webhook env vars. `@terreno/api` must be installed; it is loaded at
|
|
18
|
+
* runtime because `@terreno/api` depends on this package.
|
|
19
|
+
*/
|
|
20
|
+
export declare const registerTerrenoNotifierMocks: () => TerrenoNotifierMocks;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerTerrenoNotifierMocks = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const mockGroup_1 = require("./mockGroup");
|
|
6
|
+
/**
|
|
7
|
+
* Re-registers `@terreno/api` with its real exports plus mocked `sendToSlack`, `sendToZoom`,
|
|
8
|
+
* and `sendToGoogleChat`, so app code that imports them sends nothing and tests can assert the
|
|
9
|
+
* calls. Call it in a preload before app modules load.
|
|
10
|
+
*
|
|
11
|
+
* Only importers of the `@terreno/api` package see the mocks: code inside `@terreno/api` that
|
|
12
|
+
* calls the notifiers through its own modules (for example `wrapScript`) still uses the real
|
|
13
|
+
* ones, which no-op without webhook env vars. `@terreno/api` must be installed; it is loaded at
|
|
14
|
+
* runtime because `@terreno/api` depends on this package.
|
|
15
|
+
*/
|
|
16
|
+
const registerTerrenoNotifierMocks = () => {
|
|
17
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
18
|
+
const sendToGoogleChat = group.fn(async (..._args) => { });
|
|
19
|
+
const sendToSlack = group.fn(async (..._args) => { });
|
|
20
|
+
const sendToZoom = group.fn(async (..._args) => { });
|
|
21
|
+
// Runtime-only so @terreno/test compiles without @terreno/api (which depends on it).
|
|
22
|
+
const actual = require("@terreno/api");
|
|
23
|
+
bun_test_1.mock.module("@terreno/api", () => ({ ...actual, sendToGoogleChat, sendToSlack, sendToZoom }));
|
|
24
|
+
return { reset: group.reset, sendToGoogleChat, sendToSlack, sendToZoom };
|
|
25
|
+
};
|
|
26
|
+
exports.registerTerrenoNotifierMocks = registerTerrenoNotifierMocks;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
export interface SendGridMockResponse {
|
|
3
|
+
body: unknown;
|
|
4
|
+
headers: Record<string, string>;
|
|
5
|
+
statusCode: number;
|
|
6
|
+
}
|
|
7
|
+
export type SendGridMockSendResult = [SendGridMockResponse, Record<string, never>];
|
|
8
|
+
export interface SendGridMock {
|
|
9
|
+
/** `send(data)` resolves `[{statusCode: 202, headers: {"x-message-id": ...}}, {}]`. */
|
|
10
|
+
send: Mock<(data: unknown, isMultiple?: boolean) => Promise<SendGridMockSendResult>>;
|
|
11
|
+
setApiKey: Mock<(apiKey: string) => void>;
|
|
12
|
+
/** Every message passed to `send`, flattened when `send` gets an array. */
|
|
13
|
+
getSentMessages: () => Record<string, unknown>[];
|
|
14
|
+
/** Clears calls, overrides, and the message-id counter. */
|
|
15
|
+
reset: () => void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Registers `mock.module("@sendgrid/mail", ...)` with both the CommonJS shape (`send` /
|
|
19
|
+
* `setApiKey` on the module, what `require` returns) and a `default` export (what
|
|
20
|
+
* `import sgMail from "@sendgrid/mail"` reads). `@sendgrid/mail` does not need to be installed.
|
|
21
|
+
*/
|
|
22
|
+
export declare const registerSendGridMock: () => SendGridMock;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerSendGridMock = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const mockGroup_1 = require("./mockGroup");
|
|
6
|
+
/**
|
|
7
|
+
* Registers `mock.module("@sendgrid/mail", ...)` with both the CommonJS shape (`send` /
|
|
8
|
+
* `setApiKey` on the module, what `require` returns) and a `default` export (what
|
|
9
|
+
* `import sgMail from "@sendgrid/mail"` reads). `@sendgrid/mail` does not need to be installed.
|
|
10
|
+
*/
|
|
11
|
+
const registerSendGridMock = () => {
|
|
12
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
13
|
+
let messageCount = 0;
|
|
14
|
+
const send = group.fn(async (_data, _isMultiple) => {
|
|
15
|
+
messageCount += 1;
|
|
16
|
+
const result = [
|
|
17
|
+
{ body: "", headers: { "x-message-id": `mock-sendgrid-${messageCount}` }, statusCode: 202 },
|
|
18
|
+
{},
|
|
19
|
+
];
|
|
20
|
+
return result;
|
|
21
|
+
});
|
|
22
|
+
const setApiKey = group.fn((_apiKey) => { });
|
|
23
|
+
const getSentMessages = () => send.mock.calls.flatMap(([data]) => (Array.isArray(data) ? data : [data]));
|
|
24
|
+
const reset = () => {
|
|
25
|
+
group.reset();
|
|
26
|
+
messageCount = 0;
|
|
27
|
+
};
|
|
28
|
+
const mailService = { send, setApiKey };
|
|
29
|
+
bun_test_1.mock.module("@sendgrid/mail", () => ({ ...mailService, default: mailService }));
|
|
30
|
+
return { getSentMessages, reset, send, setApiKey };
|
|
31
|
+
};
|
|
32
|
+
exports.registerSendGridMock = registerSendGridMock;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
export interface TwilioMessageCreateParams {
|
|
3
|
+
body?: string;
|
|
4
|
+
from?: string;
|
|
5
|
+
messagingServiceSid?: string;
|
|
6
|
+
statusCallback?: string;
|
|
7
|
+
to: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface TwilioMockMessage {
|
|
11
|
+
body?: string;
|
|
12
|
+
from?: string;
|
|
13
|
+
sid: string;
|
|
14
|
+
status: string;
|
|
15
|
+
to: string;
|
|
16
|
+
}
|
|
17
|
+
export interface TwilioMockVerification {
|
|
18
|
+
channel: string;
|
|
19
|
+
sid: string;
|
|
20
|
+
status: string;
|
|
21
|
+
to: string;
|
|
22
|
+
}
|
|
23
|
+
export interface TwilioMockVerificationCheck {
|
|
24
|
+
status: string;
|
|
25
|
+
to: string;
|
|
26
|
+
valid: boolean;
|
|
27
|
+
}
|
|
28
|
+
export interface TwilioMockVerifyService {
|
|
29
|
+
verificationChecks: {
|
|
30
|
+
create: TwilioMock["verificationChecksCreate"];
|
|
31
|
+
};
|
|
32
|
+
verifications: {
|
|
33
|
+
create: TwilioMock["verificationsCreate"];
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export interface TwilioMockClient {
|
|
37
|
+
messages: {
|
|
38
|
+
create: TwilioMock["messagesCreate"];
|
|
39
|
+
};
|
|
40
|
+
verify: {
|
|
41
|
+
v2: {
|
|
42
|
+
services: TwilioMock["verifyServices"];
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export interface TwilioMock {
|
|
47
|
+
/** `twilio(accountSid, authToken)`; also `new Twilio(...)`. Returns the shared `client`. */
|
|
48
|
+
twilio: Mock<(accountSid?: string, authToken?: string) => TwilioMockClient>;
|
|
49
|
+
client: TwilioMockClient;
|
|
50
|
+
/** `client.messages.create` — resolves `{sid: "SMmock…", status: "queued"}`. */
|
|
51
|
+
messagesCreate: Mock<(params: TwilioMessageCreateParams) => Promise<TwilioMockMessage>>;
|
|
52
|
+
/** `client.verify.v2.services(serviceSid)`. */
|
|
53
|
+
verifyServices: Mock<(serviceSid: string) => TwilioMockVerifyService>;
|
|
54
|
+
/** `services(sid).verifications.create` — resolves `status: "pending"`. */
|
|
55
|
+
verificationsCreate: Mock<(params: {
|
|
56
|
+
channel: string;
|
|
57
|
+
to: string;
|
|
58
|
+
}) => Promise<TwilioMockVerification>>;
|
|
59
|
+
/** `services(sid).verificationChecks.create` — approves every code by default. */
|
|
60
|
+
verificationChecksCreate: Mock<(params: {
|
|
61
|
+
code: string;
|
|
62
|
+
to: string;
|
|
63
|
+
}) => Promise<TwilioMockVerificationCheck>>;
|
|
64
|
+
/** Clears calls, overrides, and the sid counter. */
|
|
65
|
+
reset: () => void;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Registers `mock.module("twilio", ...)`. The module is the callable factory, so both
|
|
69
|
+
* `require("twilio")(sid, token)` and `import twilio from "twilio"` work. `twilio` does not need
|
|
70
|
+
* to be installed.
|
|
71
|
+
*/
|
|
72
|
+
export declare const registerTwilioMock: () => TwilioMock;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerTwilioMock = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const mockGroup_1 = require("./mockGroup");
|
|
6
|
+
const padSid = (prefix, count) => `${prefix}mock${String(count).padStart(28, "0")}`;
|
|
7
|
+
/**
|
|
8
|
+
* Registers `mock.module("twilio", ...)`. The module is the callable factory, so both
|
|
9
|
+
* `require("twilio")(sid, token)` and `import twilio from "twilio"` work. `twilio` does not need
|
|
10
|
+
* to be installed.
|
|
11
|
+
*/
|
|
12
|
+
const registerTwilioMock = () => {
|
|
13
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
14
|
+
let sidCount = 0;
|
|
15
|
+
const nextSid = (prefix) => {
|
|
16
|
+
sidCount += 1;
|
|
17
|
+
return padSid(prefix, sidCount);
|
|
18
|
+
};
|
|
19
|
+
const messagesCreate = group.fn(async (params) => ({
|
|
20
|
+
body: params.body,
|
|
21
|
+
from: params.from,
|
|
22
|
+
sid: nextSid("SM"),
|
|
23
|
+
status: "queued",
|
|
24
|
+
to: params.to,
|
|
25
|
+
}));
|
|
26
|
+
const verificationsCreate = group.fn(async (params) => ({
|
|
27
|
+
channel: params.channel,
|
|
28
|
+
sid: nextSid("VE"),
|
|
29
|
+
status: "pending",
|
|
30
|
+
to: params.to,
|
|
31
|
+
}));
|
|
32
|
+
const verificationChecksCreate = group.fn(async (params) => ({
|
|
33
|
+
status: "approved",
|
|
34
|
+
to: params.to,
|
|
35
|
+
valid: true,
|
|
36
|
+
}));
|
|
37
|
+
const service = {
|
|
38
|
+
verificationChecks: { create: verificationChecksCreate },
|
|
39
|
+
verifications: { create: verificationsCreate },
|
|
40
|
+
};
|
|
41
|
+
const verifyServices = group.fn((_serviceSid) => service);
|
|
42
|
+
const client = {
|
|
43
|
+
messages: { create: messagesCreate },
|
|
44
|
+
verify: { v2: { services: verifyServices } },
|
|
45
|
+
};
|
|
46
|
+
const twilio = group.fn((_accountSid, _authToken) => client);
|
|
47
|
+
const reset = () => {
|
|
48
|
+
group.reset();
|
|
49
|
+
sidCount = 0;
|
|
50
|
+
};
|
|
51
|
+
const twilioModule = Object.assign((accountSid, authToken) => twilio(accountSid, authToken), { Twilio: twilio });
|
|
52
|
+
// `__esModule` makes Bun's `require` return the callable itself rather than a namespace.
|
|
53
|
+
bun_test_1.mock.module("twilio", () => Object.assign(twilioModule, { __esModule: true, default: twilioModule }));
|
|
54
|
+
return {
|
|
55
|
+
client,
|
|
56
|
+
messagesCreate,
|
|
57
|
+
reset,
|
|
58
|
+
twilio,
|
|
59
|
+
verificationChecksCreate,
|
|
60
|
+
verificationsCreate,
|
|
61
|
+
verifyServices,
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
exports.registerTwilioMock = registerTwilioMock;
|
|
@@ -131,7 +131,10 @@ const registerSimpleMongoPreload = (options = {}) => {
|
|
|
131
131
|
let uri = process.env.TERRENO_TEST_MONGODB_URI?.trim();
|
|
132
132
|
if (!uri && process.env.TERRENO_TEST_USE_MEMORY_MONGO === "true") {
|
|
133
133
|
const { MongoMemoryServer } = await import("mongodb-memory-server");
|
|
134
|
-
|
|
134
|
+
// A cold mongod start can exceed mongodb-memory-server's 10s default on CI machines.
|
|
135
|
+
memoryMongo = await MongoMemoryServer.create({
|
|
136
|
+
instance: { launchTimeout: (0, mongoServer_1.resolveMongoLaunchTimeoutMs)() },
|
|
137
|
+
});
|
|
135
138
|
uri = memoryMongo.getUri();
|
|
136
139
|
}
|
|
137
140
|
const connectUri = uri ?? defaultLocalMongoUri;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DateTime } from "luxon";
|
|
2
|
+
export type FreezeTimeInput = string | DateTime;
|
|
3
|
+
export interface FreezeTimeOptions {
|
|
4
|
+
/** Restore the previous clock after the current test. Defaults to true. */
|
|
5
|
+
restoreAfterEach?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Freezes the clock at `input` for `Date.now()`, `new Date()`, and Luxon's `DateTime.now()`.
|
|
9
|
+
*
|
|
10
|
+
* Uses Bun's `setSystemTime` and also replaces `Date.now`, so it still wins when a preload has
|
|
11
|
+
* swapped `Date.now` for its own mock. By default it restores the previous clock after the current
|
|
12
|
+
* test (call it in `beforeEach` or inside a test). Returns a restore function for un-freezing
|
|
13
|
+
* earlier; calling it twice is a no-op. Do not mix with direct `setSystemTime` calls in the same
|
|
14
|
+
* test: restoring the last freeze resets the system clock to real time.
|
|
15
|
+
*/
|
|
16
|
+
export declare const freezeTime: (input: FreezeTimeInput, { restoreAfterEach }?: FreezeTimeOptions) => (() => void);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.freezeTime = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const luxon_1 = require("luxon");
|
|
6
|
+
// Instants frozen by calls that have not been restored, oldest first. Restoring re-freezes to the
|
|
7
|
+
// newest remaining entry, so nested freezes unwind in any order.
|
|
8
|
+
const activeFreezes = [];
|
|
9
|
+
const toFrozenDateTime = (input) => {
|
|
10
|
+
const dateTime = typeof input === "string" ? luxon_1.DateTime.fromISO(input, { setZone: true }) : input;
|
|
11
|
+
if (!dateTime.isValid) {
|
|
12
|
+
const invalidInput = typeof input === "string" ? input : String(input.invalidExplanation);
|
|
13
|
+
throw new Error(`freezeTime: invalid date/time "${invalidInput}" (${dateTime.invalidReason})`);
|
|
14
|
+
}
|
|
15
|
+
return dateTime;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Freezes the clock at `input` for `Date.now()`, `new Date()`, and Luxon's `DateTime.now()`.
|
|
19
|
+
*
|
|
20
|
+
* Uses Bun's `setSystemTime` and also replaces `Date.now`, so it still wins when a preload has
|
|
21
|
+
* swapped `Date.now` for its own mock. By default it restores the previous clock after the current
|
|
22
|
+
* test (call it in `beforeEach` or inside a test). Returns a restore function for un-freezing
|
|
23
|
+
* earlier; calling it twice is a no-op. Do not mix with direct `setSystemTime` calls in the same
|
|
24
|
+
* test: restoring the last freeze resets the system clock to real time.
|
|
25
|
+
*/
|
|
26
|
+
const freezeTime = (input, { restoreAfterEach = true } = {}) => {
|
|
27
|
+
const millis = toFrozenDateTime(input).toMillis();
|
|
28
|
+
const entry = { millis };
|
|
29
|
+
const previousDateNow = Date.now;
|
|
30
|
+
activeFreezes.push(entry);
|
|
31
|
+
(0, bun_test_1.setSystemTime)(new Date(millis));
|
|
32
|
+
Date.now = () => millis;
|
|
33
|
+
let isRestored = false;
|
|
34
|
+
const restore = () => {
|
|
35
|
+
if (isRestored) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
isRestored = true;
|
|
39
|
+
Date.now = previousDateNow;
|
|
40
|
+
activeFreezes.splice(activeFreezes.indexOf(entry), 1);
|
|
41
|
+
const newest = activeFreezes.at(-1);
|
|
42
|
+
(0, bun_test_1.setSystemTime)(newest ? new Date(newest.millis) : undefined);
|
|
43
|
+
};
|
|
44
|
+
if (restoreAfterEach) {
|
|
45
|
+
(0, bun_test_1.afterEach)(restore);
|
|
46
|
+
}
|
|
47
|
+
return restore;
|
|
48
|
+
};
|
|
49
|
+
exports.freezeTime = freezeTime;
|
|
@@ -26,9 +26,22 @@
|
|
|
26
26
|
* cause TransientTransactionError / NoSuchTransaction. We solve this with a
|
|
27
27
|
* reentrant async mutex:
|
|
28
28
|
* - Top-level operations (the ones fired by Promise.all) are serialized
|
|
29
|
-
* - Nested operations (e.g. pre-save hooks that do queries)
|
|
30
|
-
*
|
|
31
|
-
*
|
|
29
|
+
* - Nested operations (e.g. pre-save hooks that do queries) run without taking
|
|
30
|
+
* the mutex while the ancestor that owns it is still inside its critical
|
|
31
|
+
* section, preventing deadlocks
|
|
32
|
+
* - AsyncLocalStorage tracks which critical section owns the current async chain
|
|
33
|
+
*
|
|
34
|
+
* Teardown drain: every operation is counted while in flight, and teardown waits
|
|
35
|
+
* for that count to reach zero before aborting. Work a test leaves behind — a
|
|
36
|
+
* fire-and-forget `void AuditLog.create(...)` write, follow-up writes spawned by
|
|
37
|
+
* post-save hooks — would otherwise still be queued when the transaction is
|
|
38
|
+
* aborted, then run against the aborted transaction or, once the session is no
|
|
39
|
+
* longer transactional, commit for real.
|
|
40
|
+
*
|
|
41
|
+
* Test-boundary cancellation: operations still queued on the mutex when the
|
|
42
|
+
* session is discarded reject with {@link TestTransactionOperationCancelledError}
|
|
43
|
+
* instead of running. Use {@link isTestTransactionOperationCancelled} to
|
|
44
|
+
* recognize that error (including when wrapped through `cause`).
|
|
32
45
|
*
|
|
33
46
|
* Limitations:
|
|
34
47
|
* - App code that creates its own sessions (e.g. explicit transactions in
|
|
@@ -38,6 +51,20 @@
|
|
|
38
51
|
* NOT patched. Only Mongoose-level operations are covered.
|
|
39
52
|
*/
|
|
40
53
|
import type { ClientSession } from "mongoose";
|
|
54
|
+
/**
|
|
55
|
+
* Thrown when a queued DB operation is discarded at a test boundary.
|
|
56
|
+
*
|
|
57
|
+
* Rejecting stops the operation's `await` chain so later writes cannot run
|
|
58
|
+
* after the test session is gone. `bun test` reports an unawaited rejection
|
|
59
|
+
* itself (it does not call `process.on("unhandledRejection")` listeners), so a
|
|
60
|
+
* fire-and-forget write that hits this error shows up as a test failure; await
|
|
61
|
+
* the write, or check `isTestTransactionOperationCancelled` where it is caught.
|
|
62
|
+
*/
|
|
63
|
+
export declare class TestTransactionOperationCancelledError extends Error {
|
|
64
|
+
constructor();
|
|
65
|
+
}
|
|
66
|
+
/** True when `error` is a test-boundary cancellation, including wrapped `cause` chains. */
|
|
67
|
+
export declare const isTestTransactionOperationCancelled: (error: unknown) => boolean;
|
|
41
68
|
/** Returns the current test session, or null if not in a test transaction. */
|
|
42
69
|
export declare const getTestSession: () => ClientSession | null;
|
|
43
70
|
/**
|
|
@@ -48,15 +75,24 @@ export declare const getTestSession: () => ClientSession | null;
|
|
|
48
75
|
* explicitly ended (e.g., due to an error).
|
|
49
76
|
*/
|
|
50
77
|
export declare const startTestTransaction: () => Promise<void>;
|
|
78
|
+
export interface AbortTestTransactionOptions {
|
|
79
|
+
/** How long to wait for in-flight and queued operations to settle. Defaults to 3000ms. */
|
|
80
|
+
drainTimeoutMs?: number;
|
|
81
|
+
}
|
|
51
82
|
/**
|
|
52
83
|
* Aborts the current test transaction. Call in afterEach.
|
|
53
84
|
*
|
|
54
|
-
*
|
|
85
|
+
* Waits for in-flight and queued operations to settle first. If they do not
|
|
86
|
+
* settle within the drain budget, the session is quarantined (aborted and
|
|
87
|
+
* ended), queued operations reject with {@link TestTransactionOperationCancelledError},
|
|
88
|
+
* and the drain timeout error is rethrown so the offending test fails.
|
|
89
|
+
*
|
|
90
|
+
* The session is otherwise kept alive (not ended) so it can be reused by
|
|
55
91
|
* the next test. This avoids returning the session to the driver's server
|
|
56
92
|
* session pool, which prevents transaction number mismatches when in-flight
|
|
57
93
|
* operations from a previous test complete after the session has been recycled.
|
|
58
94
|
*/
|
|
59
|
-
export declare const abortTestTransaction: () => Promise<void>;
|
|
95
|
+
export declare const abortTestTransaction: ({ drainTimeoutMs, }?: AbortTestTransactionOptions) => Promise<void>;
|
|
60
96
|
/**
|
|
61
97
|
* Drops the cached test session after an out-of-band mongoose reconnect.
|
|
62
98
|
*
|
|
@@ -79,7 +115,8 @@ export declare const resetTestSessionAfterReconnect: () => Promise<void>;
|
|
|
79
115
|
* - Aggregate.prototype.exec — covers aggregation pipelines
|
|
80
116
|
* - Model.bulkWrite — covers bulk write operations
|
|
81
117
|
* - Model.insertMany — covers bulk inserts (uses native driver, not save)
|
|
82
|
-
* - Model.
|
|
118
|
+
* - Model.create — serializes multi-document creates (forces `ordered: true`) so
|
|
119
|
+
* their saves cannot race each other on the shared session
|
|
83
120
|
* - Model.startSession — returns a no-op wrapper so app-level transactions don't conflict
|
|
84
121
|
* - Collection.prototype (insertOne, updateOne, deleteOne, etc.) — covers native driver
|
|
85
122
|
* operations used by tests that call Model.collection.insertOne() directly
|