@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,91 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
import supertest from "supertest";
|
|
4
|
+
/** protobuf Timestamp / Duration as `@google-cloud/tasks` accepts them. */
|
|
5
|
+
export interface CloudTasksTime {
|
|
6
|
+
nanos?: number | null;
|
|
7
|
+
seconds?: number | string | null;
|
|
8
|
+
}
|
|
9
|
+
export interface CloudTasksHttpRequest {
|
|
10
|
+
/** Base64 string (what the REST surface sends) or raw bytes. */
|
|
11
|
+
body?: string | Uint8Array | null;
|
|
12
|
+
headers?: Record<string, string> | null;
|
|
13
|
+
/** `"POST"` or the numeric `protos.google.cloud.tasks.v2.HttpMethod` value. */
|
|
14
|
+
httpMethod?: string | number | null;
|
|
15
|
+
oidcToken?: {
|
|
16
|
+
audience?: string | null;
|
|
17
|
+
serviceAccountEmail?: string | null;
|
|
18
|
+
} | null;
|
|
19
|
+
url?: string | null;
|
|
20
|
+
}
|
|
21
|
+
export interface CloudTasksTask {
|
|
22
|
+
dispatchDeadline?: CloudTasksTime | null;
|
|
23
|
+
httpRequest?: CloudTasksHttpRequest | null;
|
|
24
|
+
name?: string | null;
|
|
25
|
+
scheduleTime?: CloudTasksTime | null;
|
|
26
|
+
}
|
|
27
|
+
export interface CloudTasksCreateTaskRequest {
|
|
28
|
+
parent?: string | null;
|
|
29
|
+
task?: CloudTasksTask | null;
|
|
30
|
+
}
|
|
31
|
+
/** A task the mock accepted, with its body decoded. */
|
|
32
|
+
export interface EnqueuedCloudTask {
|
|
33
|
+
/** Body parsed as JSON; the decoded string when it is not JSON; undefined when absent. */
|
|
34
|
+
body: unknown;
|
|
35
|
+
headers: Record<string, string>;
|
|
36
|
+
httpMethod: string;
|
|
37
|
+
name: string;
|
|
38
|
+
parent: string;
|
|
39
|
+
/** The decoded body text before JSON parsing. */
|
|
40
|
+
rawBody?: string;
|
|
41
|
+
request: CloudTasksCreateTaskRequest;
|
|
42
|
+
url?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface DrainCloudTasksOptions {
|
|
45
|
+
app: express.Application;
|
|
46
|
+
/** Exact status every dispatch must return, `"2xx"` (default), or `"any"` to skip the check. */
|
|
47
|
+
expectStatus?: number | "2xx" | "any";
|
|
48
|
+
/** Only dispatch matching tasks; the rest stay enqueued. */
|
|
49
|
+
filter?: (task: EnqueuedCloudTask) => boolean;
|
|
50
|
+
/** Extra request headers (e.g. an auth header your execute route checks). */
|
|
51
|
+
headers?: Record<string, string> | ((task: EnqueuedCloudTask) => Record<string, string>);
|
|
52
|
+
/** Rounds to drain tasks enqueued by dispatched tasks. Default 10; throws if work remains. */
|
|
53
|
+
maxRounds?: number;
|
|
54
|
+
/** Request path. Default: the path and query of the task's `httpRequest.url`. */
|
|
55
|
+
path?: string | ((task: EnqueuedCloudTask) => string);
|
|
56
|
+
}
|
|
57
|
+
export interface DrainedCloudTask {
|
|
58
|
+
response: supertest.Response;
|
|
59
|
+
task: EnqueuedCloudTask;
|
|
60
|
+
}
|
|
61
|
+
export interface CloudTasksMockClient {
|
|
62
|
+
createTask: Mock<(request: CloudTasksCreateTaskRequest) => Promise<[CloudTasksTask & {
|
|
63
|
+
name: string;
|
|
64
|
+
}]>>;
|
|
65
|
+
deleteTask: Mock<(request: {
|
|
66
|
+
name?: string | null;
|
|
67
|
+
}) => Promise<[Record<string, never>]>>;
|
|
68
|
+
queuePath: Mock<(project: string, location: string, queue: string) => string>;
|
|
69
|
+
}
|
|
70
|
+
export interface CloudTasksMock extends CloudTasksMockClient {
|
|
71
|
+
/** Constructor registered as `CloudTasksClient`; every instance is `client`. */
|
|
72
|
+
CloudTasksClient: Mock<() => CloudTasksMockClient>;
|
|
73
|
+
client: CloudTasksMockClient;
|
|
74
|
+
/** Dispatches enqueued tasks to `app` with supertest, in enqueue order. */
|
|
75
|
+
drainTasks: (options: DrainCloudTasksOptions) => Promise<DrainedCloudTask[]>;
|
|
76
|
+
/** Tasks created and not yet drained or deleted. */
|
|
77
|
+
getEnqueuedTasks: () => EnqueuedCloudTask[];
|
|
78
|
+
/** Clears calls, drained state, and overrides. */
|
|
79
|
+
reset: () => void;
|
|
80
|
+
}
|
|
81
|
+
/** Decodes a Cloud Tasks HTTP body (base64 string or bytes) and parses it as JSON when it can. */
|
|
82
|
+
export declare const decodeCloudTaskBody: (body: string | Uint8Array | null | undefined) => {
|
|
83
|
+
body: unknown;
|
|
84
|
+
rawBody?: string;
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Registers `mock.module("@google-cloud/tasks", ...)`. Call once (e.g. in a preload), call
|
|
88
|
+
* `reset()` in `beforeEach`, and inject nothing: code that does `new CloudTasksClient()` gets
|
|
89
|
+
* the shared `client`. `@google-cloud/tasks` does not need to be installed.
|
|
90
|
+
*/
|
|
91
|
+
export declare const registerCloudTasksMock: () => CloudTasksMock;
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.registerCloudTasksMock = exports.decodeCloudTaskBody = void 0;
|
|
7
|
+
const bun_test_1 = require("bun:test");
|
|
8
|
+
const supertest_1 = __importDefault(require("supertest"));
|
|
9
|
+
const mockGroup_1 = require("./mockGroup");
|
|
10
|
+
const HTTP_METHODS_BY_NUMBER = {
|
|
11
|
+
1: "POST",
|
|
12
|
+
2: "GET",
|
|
13
|
+
3: "HEAD",
|
|
14
|
+
4: "PUT",
|
|
15
|
+
5: "DELETE",
|
|
16
|
+
6: "PATCH",
|
|
17
|
+
7: "OPTIONS",
|
|
18
|
+
};
|
|
19
|
+
const SUPPORTED_METHODS = new Set([
|
|
20
|
+
"delete",
|
|
21
|
+
"get",
|
|
22
|
+
"head",
|
|
23
|
+
"options",
|
|
24
|
+
"patch",
|
|
25
|
+
"post",
|
|
26
|
+
"put",
|
|
27
|
+
]);
|
|
28
|
+
const CLOUD_TASKS_PROTOS = {
|
|
29
|
+
google: {
|
|
30
|
+
cloud: {
|
|
31
|
+
tasks: {
|
|
32
|
+
v2: {
|
|
33
|
+
HttpMethod: {
|
|
34
|
+
DELETE: 5,
|
|
35
|
+
GET: 2,
|
|
36
|
+
HEAD: 3,
|
|
37
|
+
HTTP_METHOD_UNSPECIFIED: 0,
|
|
38
|
+
OPTIONS: 7,
|
|
39
|
+
PATCH: 6,
|
|
40
|
+
POST: 1,
|
|
41
|
+
PUT: 4,
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
/** Decodes a Cloud Tasks HTTP body (base64 string or bytes) and parses it as JSON when it can. */
|
|
49
|
+
const decodeCloudTaskBody = (body) => {
|
|
50
|
+
if (body === null || body === undefined) {
|
|
51
|
+
return { body: undefined };
|
|
52
|
+
}
|
|
53
|
+
const rawBody = typeof body === "string"
|
|
54
|
+
? Buffer.from(body, "base64").toString("utf8")
|
|
55
|
+
: Buffer.from(body).toString("utf8");
|
|
56
|
+
try {
|
|
57
|
+
return { body: JSON.parse(rawBody), rawBody };
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return { body: rawBody, rawBody };
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
exports.decodeCloudTaskBody = decodeCloudTaskBody;
|
|
64
|
+
const resolveHttpMethod = (httpMethod) => {
|
|
65
|
+
if (typeof httpMethod === "number") {
|
|
66
|
+
return HTTP_METHODS_BY_NUMBER[httpMethod] ?? "POST";
|
|
67
|
+
}
|
|
68
|
+
return httpMethod ? httpMethod.toUpperCase() : "POST";
|
|
69
|
+
};
|
|
70
|
+
const defaultTaskName = (parent, index) => `${parent}/tasks/mock-task-${index + 1}`;
|
|
71
|
+
const toEnqueuedTask = (request, index) => {
|
|
72
|
+
const parent = request.parent ?? "";
|
|
73
|
+
const httpRequest = request.task?.httpRequest ?? undefined;
|
|
74
|
+
return {
|
|
75
|
+
...(0, exports.decodeCloudTaskBody)(httpRequest?.body),
|
|
76
|
+
headers: { ...(httpRequest?.headers ?? {}) },
|
|
77
|
+
httpMethod: resolveHttpMethod(httpRequest?.httpMethod),
|
|
78
|
+
name: request.task?.name ?? defaultTaskName(parent, index),
|
|
79
|
+
parent,
|
|
80
|
+
request,
|
|
81
|
+
url: httpRequest?.url ?? undefined,
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
const resolveTaskPath = (task, path) => {
|
|
85
|
+
if (typeof path === "function") {
|
|
86
|
+
return path(task);
|
|
87
|
+
}
|
|
88
|
+
if (path) {
|
|
89
|
+
return path;
|
|
90
|
+
}
|
|
91
|
+
if (!task.url) {
|
|
92
|
+
throw new Error(`Cloud task ${task.name} has no httpRequest.url; pass drainTasks({path})`);
|
|
93
|
+
}
|
|
94
|
+
const url = new URL(task.url, "http://localhost");
|
|
95
|
+
return `${url.pathname}${url.search}`;
|
|
96
|
+
};
|
|
97
|
+
const assertStatus = (task, response, expectStatus) => {
|
|
98
|
+
if (expectStatus === "any") {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const isExpected = expectStatus === "2xx"
|
|
102
|
+
? response.status >= 200 && response.status < 300
|
|
103
|
+
: response.status === expectStatus;
|
|
104
|
+
if (!isExpected) {
|
|
105
|
+
throw new Error(`Cloud task ${task.name} returned ${response.status} (expected ${expectStatus}): ${JSON.stringify(response.body)}`);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const dispatchTask = async ({ options, task, }) => {
|
|
109
|
+
const path = resolveTaskPath(task, options.path);
|
|
110
|
+
const extraHeaders = typeof options.headers === "function" ? options.headers(task) : (options.headers ?? {});
|
|
111
|
+
const method = task.httpMethod.toLowerCase();
|
|
112
|
+
if (!SUPPORTED_METHODS.has(method)) {
|
|
113
|
+
throw new Error(`Cloud task ${task.name} uses unsupported method ${task.httpMethod}`);
|
|
114
|
+
}
|
|
115
|
+
const agent = (0, supertest_1.default)(options.app);
|
|
116
|
+
const start = agent[method].bind(agent);
|
|
117
|
+
const headers = { ...task.headers, ...extraHeaders };
|
|
118
|
+
const hasContentType = Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
|
|
119
|
+
if (!hasContentType && task.rawBody !== undefined && task.body !== task.rawBody) {
|
|
120
|
+
headers["Content-Type"] = "application/json";
|
|
121
|
+
}
|
|
122
|
+
const request = start(path).set(headers);
|
|
123
|
+
if (task.rawBody === undefined) {
|
|
124
|
+
return request;
|
|
125
|
+
}
|
|
126
|
+
return request.send(task.rawBody);
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Registers `mock.module("@google-cloud/tasks", ...)`. Call once (e.g. in a preload), call
|
|
130
|
+
* `reset()` in `beforeEach`, and inject nothing: code that does `new CloudTasksClient()` gets
|
|
131
|
+
* the shared `client`. `@google-cloud/tasks` does not need to be installed.
|
|
132
|
+
*/
|
|
133
|
+
const registerCloudTasksMock = () => {
|
|
134
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
135
|
+
const consumed = new Set();
|
|
136
|
+
const createTask = group.fn(async (request) => {
|
|
137
|
+
const index = createTask.mock.calls.length - 1;
|
|
138
|
+
const name = request.task?.name ?? defaultTaskName(request.parent ?? "", index);
|
|
139
|
+
return [{ ...(request.task ?? {}), name }];
|
|
140
|
+
});
|
|
141
|
+
const getEnqueuedEntries = () => createTask.mock.calls
|
|
142
|
+
.map(([request], index) => ({ index, task: toEnqueuedTask(request, index) }))
|
|
143
|
+
.filter(({ index }) => !consumed.has(index));
|
|
144
|
+
const deleteTask = group.fn(async (request) => {
|
|
145
|
+
for (const entry of getEnqueuedEntries()) {
|
|
146
|
+
if (entry.task.name === request.name) {
|
|
147
|
+
consumed.add(entry.index);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return [{}];
|
|
151
|
+
});
|
|
152
|
+
const queuePath = group.fn((project, location, queue) => `projects/${project}/locations/${location}/queues/${queue}`);
|
|
153
|
+
const client = { createTask, deleteTask, queuePath };
|
|
154
|
+
const CloudTasksClient = group.fn(() => client);
|
|
155
|
+
const drainTasks = async (options) => {
|
|
156
|
+
const maxRounds = options.maxRounds ?? 10;
|
|
157
|
+
const expectStatus = options.expectStatus ?? "2xx";
|
|
158
|
+
const matches = () => getEnqueuedEntries().filter(({ task }) => (options.filter ? options.filter(task) : true));
|
|
159
|
+
const drained = [];
|
|
160
|
+
for (let round = 0;; round += 1) {
|
|
161
|
+
const batch = matches();
|
|
162
|
+
if (batch.length === 0) {
|
|
163
|
+
return drained;
|
|
164
|
+
}
|
|
165
|
+
if (round >= maxRounds) {
|
|
166
|
+
throw new Error(`drainTasks stopped after ${maxRounds} rounds with ${batch.length} task(s) still enqueued`);
|
|
167
|
+
}
|
|
168
|
+
for (const { index, task } of batch) {
|
|
169
|
+
consumed.add(index);
|
|
170
|
+
const response = await dispatchTask({ options, task });
|
|
171
|
+
assertStatus(task, response, expectStatus);
|
|
172
|
+
drained.push({ response, task });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
const reset = () => {
|
|
177
|
+
group.reset();
|
|
178
|
+
consumed.clear();
|
|
179
|
+
};
|
|
180
|
+
const moduleExports = {
|
|
181
|
+
CloudTasksClient,
|
|
182
|
+
protos: CLOUD_TASKS_PROTOS,
|
|
183
|
+
v2: { CloudTasksClient },
|
|
184
|
+
};
|
|
185
|
+
bun_test_1.mock.module("@google-cloud/tasks", () => ({ ...moduleExports, default: moduleExports }));
|
|
186
|
+
return {
|
|
187
|
+
CloudTasksClient,
|
|
188
|
+
client,
|
|
189
|
+
createTask,
|
|
190
|
+
deleteTask,
|
|
191
|
+
drainTasks,
|
|
192
|
+
getEnqueuedTasks: () => getEnqueuedEntries().map(({ task }) => task),
|
|
193
|
+
queuePath,
|
|
194
|
+
reset,
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
exports.registerCloudTasksMock = registerCloudTasksMock;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
export interface ExpoMockPushMessage {
|
|
3
|
+
body?: string;
|
|
4
|
+
data?: Record<string, unknown>;
|
|
5
|
+
title?: string;
|
|
6
|
+
to: string | string[];
|
|
7
|
+
[key: string]: unknown;
|
|
8
|
+
}
|
|
9
|
+
export interface ExpoMockPushTicket {
|
|
10
|
+
details?: Record<string, unknown>;
|
|
11
|
+
id?: string;
|
|
12
|
+
message?: string;
|
|
13
|
+
status: "ok" | "error";
|
|
14
|
+
}
|
|
15
|
+
export interface ExpoMockPushReceipt {
|
|
16
|
+
details?: Record<string, unknown>;
|
|
17
|
+
message?: string;
|
|
18
|
+
status: "ok" | "error";
|
|
19
|
+
}
|
|
20
|
+
export interface ExpoMockClient {
|
|
21
|
+
chunkPushNotificationReceiptIds: ExpoPushMock["chunkPushNotificationReceiptIds"];
|
|
22
|
+
chunkPushNotifications: ExpoPushMock["chunkPushNotifications"];
|
|
23
|
+
getPushNotificationReceiptsAsync: ExpoPushMock["getPushNotificationReceiptsAsync"];
|
|
24
|
+
sendPushNotificationsAsync: ExpoPushMock["sendPushNotificationsAsync"];
|
|
25
|
+
}
|
|
26
|
+
export interface ExpoPushMock {
|
|
27
|
+
/** `new Expo(options)` — every instance is the shared `client`. Has static `isExpoPushToken`. */
|
|
28
|
+
Expo: Mock<(options?: {
|
|
29
|
+
accessToken?: string;
|
|
30
|
+
}) => ExpoMockClient> & {
|
|
31
|
+
isExpoPushToken: ExpoPushMock["isExpoPushToken"];
|
|
32
|
+
};
|
|
33
|
+
client: ExpoMockClient;
|
|
34
|
+
/** Accepts `ExponentPushToken[...]`, `ExpoPushToken[...]`, and bare UUID device ids. */
|
|
35
|
+
isExpoPushToken: Mock<(token: unknown) => boolean>;
|
|
36
|
+
/** Splits into chunks of 100 messages, Expo's per-request limit. */
|
|
37
|
+
chunkPushNotifications: Mock<(messages: ExpoMockPushMessage[]) => ExpoMockPushMessage[][]>;
|
|
38
|
+
/** Splits into chunks of 300 ids, Expo's per-request limit. */
|
|
39
|
+
chunkPushNotificationReceiptIds: Mock<(receiptIds: string[]) => string[][]>;
|
|
40
|
+
/** Resolves one `{status: "ok", id}` ticket per recipient. */
|
|
41
|
+
sendPushNotificationsAsync: Mock<(messages: ExpoMockPushMessage[]) => Promise<ExpoMockPushTicket[]>>;
|
|
42
|
+
/** Resolves `{status: "ok"}` for every requested receipt id. */
|
|
43
|
+
getPushNotificationReceiptsAsync: Mock<(receiptIds: string[]) => Promise<Record<string, ExpoMockPushReceipt>>>;
|
|
44
|
+
/** Every message passed to `sendPushNotificationsAsync`, in order. */
|
|
45
|
+
getSentMessages: () => ExpoMockPushMessage[];
|
|
46
|
+
/** Clears calls, overrides, and the ticket counter. */
|
|
47
|
+
reset: () => void;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Registers `mock.module("expo-server-sdk", ...)` exporting `Expo` (named and default).
|
|
51
|
+
* `expo-server-sdk` does not need to be installed.
|
|
52
|
+
*/
|
|
53
|
+
export declare const registerExpoPushMock: () => ExpoPushMock;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerExpoPushMock = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const mockGroup_1 = require("./mockGroup");
|
|
6
|
+
const EXPO_TOKEN_PATTERN = /^Expo(nent)?PushToken\[.+\]$/;
|
|
7
|
+
const UUID_PATTERN = /^[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}$/i;
|
|
8
|
+
const chunk = (items, size) => {
|
|
9
|
+
const chunks = [];
|
|
10
|
+
for (let start = 0; start < items.length; start += size) {
|
|
11
|
+
chunks.push(items.slice(start, start + size));
|
|
12
|
+
}
|
|
13
|
+
return chunks;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Registers `mock.module("expo-server-sdk", ...)` exporting `Expo` (named and default).
|
|
17
|
+
* `expo-server-sdk` does not need to be installed.
|
|
18
|
+
*/
|
|
19
|
+
const registerExpoPushMock = () => {
|
|
20
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
21
|
+
let ticketCount = 0;
|
|
22
|
+
const isExpoPushToken = group.fn((token) => typeof token === "string" && (EXPO_TOKEN_PATTERN.test(token) || UUID_PATTERN.test(token)));
|
|
23
|
+
const chunkPushNotifications = group.fn((messages) => chunk(messages, 100));
|
|
24
|
+
const chunkPushNotificationReceiptIds = group.fn((receiptIds) => chunk(receiptIds, 300));
|
|
25
|
+
const sendPushNotificationsAsync = group.fn(async (messages) => messages
|
|
26
|
+
.flatMap((message) => (Array.isArray(message.to) ? message.to : [message.to]))
|
|
27
|
+
.map(() => {
|
|
28
|
+
ticketCount += 1;
|
|
29
|
+
return { id: `mock-ticket-${ticketCount}`, status: "ok" };
|
|
30
|
+
}));
|
|
31
|
+
const getPushNotificationReceiptsAsync = group.fn(async (receiptIds) => Object.fromEntries(receiptIds.map((id) => [id, { status: "ok" }])));
|
|
32
|
+
const client = {
|
|
33
|
+
chunkPushNotificationReceiptIds,
|
|
34
|
+
chunkPushNotifications,
|
|
35
|
+
getPushNotificationReceiptsAsync,
|
|
36
|
+
sendPushNotificationsAsync,
|
|
37
|
+
};
|
|
38
|
+
const Expo = Object.assign(group.fn((_options) => client), { isExpoPushToken });
|
|
39
|
+
const getSentMessages = () => sendPushNotificationsAsync.mock.calls.flatMap(([messages]) => messages);
|
|
40
|
+
const reset = () => {
|
|
41
|
+
group.reset();
|
|
42
|
+
ticketCount = 0;
|
|
43
|
+
};
|
|
44
|
+
bun_test_1.mock.module("expo-server-sdk", () => ({ default: Expo, Expo }));
|
|
45
|
+
return {
|
|
46
|
+
chunkPushNotificationReceiptIds,
|
|
47
|
+
chunkPushNotifications,
|
|
48
|
+
client,
|
|
49
|
+
Expo,
|
|
50
|
+
getPushNotificationReceiptsAsync,
|
|
51
|
+
getSentMessages,
|
|
52
|
+
isExpoPushToken,
|
|
53
|
+
reset,
|
|
54
|
+
sendPushNotificationsAsync,
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
exports.registerExpoPushMock = registerExpoPushMock;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type Mock } from "bun:test";
|
|
2
|
+
import { Readable, Writable } from "node:stream";
|
|
3
|
+
export type GcsObjectMetadata = Record<string, unknown>;
|
|
4
|
+
export interface GcsStoredObject {
|
|
5
|
+
contents: Buffer;
|
|
6
|
+
metadata: GcsObjectMetadata;
|
|
7
|
+
}
|
|
8
|
+
export interface GcsSaveOptions {
|
|
9
|
+
contentType?: string;
|
|
10
|
+
metadata?: GcsObjectMetadata;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
13
|
+
export interface GcsGetFilesQuery {
|
|
14
|
+
delimiter?: string;
|
|
15
|
+
prefix?: string;
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
/** A file handle from `bucket.file(name)`. Its methods are the shared `fileMocks`. */
|
|
19
|
+
export interface GcsMockFile {
|
|
20
|
+
bucket: GcsMockBucket;
|
|
21
|
+
createReadStream: GcsFileMocks["createReadStream"];
|
|
22
|
+
createWriteStream: GcsFileMocks["createWriteStream"];
|
|
23
|
+
delete: GcsFileMocks["delete"];
|
|
24
|
+
download: GcsFileMocks["download"];
|
|
25
|
+
exists: GcsFileMocks["exists"];
|
|
26
|
+
getMetadata: GcsFileMocks["getMetadata"];
|
|
27
|
+
getSignedUrl: GcsFileMocks["getSignedUrl"];
|
|
28
|
+
/** Current stored metadata, or `{}` when the object does not exist. */
|
|
29
|
+
readonly metadata: GcsObjectMetadata;
|
|
30
|
+
name: string;
|
|
31
|
+
publicUrl: () => string;
|
|
32
|
+
save: GcsFileMocks["save"];
|
|
33
|
+
setMetadata: GcsFileMocks["setMetadata"];
|
|
34
|
+
}
|
|
35
|
+
export interface GcsMockBucket {
|
|
36
|
+
deleteFiles: GcsMock["deleteFiles"];
|
|
37
|
+
file: GcsMock["file"];
|
|
38
|
+
getFiles: GcsMock["getFiles"];
|
|
39
|
+
name: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Shared across every file handle; each call runs with `this` bound to the file. Assert with
|
|
43
|
+
* `fileMocks.save.mock.contexts[0].name` or `gcs.file.mock.calls` when the path matters.
|
|
44
|
+
*/
|
|
45
|
+
export interface GcsFileMocks {
|
|
46
|
+
createReadStream: Mock<(this: GcsMockFile) => Readable>;
|
|
47
|
+
createWriteStream: Mock<(this: GcsMockFile, options?: GcsSaveOptions) => Writable>;
|
|
48
|
+
delete: Mock<(this: GcsMockFile, options?: {
|
|
49
|
+
ignoreNotFound?: boolean;
|
|
50
|
+
}) => Promise<[unknown]>>;
|
|
51
|
+
download: Mock<(this: GcsMockFile) => Promise<[Buffer]>>;
|
|
52
|
+
exists: Mock<(this: GcsMockFile) => Promise<[boolean]>>;
|
|
53
|
+
getMetadata: Mock<(this: GcsMockFile) => Promise<[GcsObjectMetadata]>>;
|
|
54
|
+
getSignedUrl: Mock<(this: GcsMockFile, config?: Record<string, unknown>) => Promise<[string]>>;
|
|
55
|
+
save: Mock<(this: GcsMockFile, data: string | Uint8Array, options?: GcsSaveOptions) => Promise<void>>;
|
|
56
|
+
setMetadata: Mock<(this: GcsMockFile, metadata: GcsObjectMetadata) => Promise<[GcsObjectMetadata]>>;
|
|
57
|
+
}
|
|
58
|
+
export interface GcsMock {
|
|
59
|
+
/** `new Storage(options)` — every instance is the shared `storage`. */
|
|
60
|
+
Storage: Mock<(options?: Record<string, unknown>) => {
|
|
61
|
+
bucket: GcsMock["bucket"];
|
|
62
|
+
}>;
|
|
63
|
+
storage: {
|
|
64
|
+
bucket: GcsMock["bucket"];
|
|
65
|
+
};
|
|
66
|
+
/** `storage.bucket(name)`. */
|
|
67
|
+
bucket: Mock<(name: string) => GcsMockBucket>;
|
|
68
|
+
/** `bucket.file(name)` — `this` is the bucket. */
|
|
69
|
+
file: Mock<(this: GcsMockBucket, name: string) => GcsMockFile>;
|
|
70
|
+
/** `bucket.getFiles(query)` — resolves `[files, null, {prefixes}]` like the real API. */
|
|
71
|
+
getFiles: Mock<(this: GcsMockBucket, query?: GcsGetFilesQuery) => Promise<[GcsMockFile[], null, {
|
|
72
|
+
prefixes: string[];
|
|
73
|
+
}]>>;
|
|
74
|
+
/** `bucket.deleteFiles({prefix})`. */
|
|
75
|
+
deleteFiles: Mock<(this: GcsMockBucket, query?: {
|
|
76
|
+
prefix?: string;
|
|
77
|
+
}) => Promise<void>>;
|
|
78
|
+
fileMocks: GcsFileMocks;
|
|
79
|
+
/** Reads an object from the in-memory store. */
|
|
80
|
+
getObject: (params: {
|
|
81
|
+
bucket: string;
|
|
82
|
+
name: string;
|
|
83
|
+
}) => GcsStoredObject | undefined;
|
|
84
|
+
/** Every stored object key as `bucket/name`, sorted. */
|
|
85
|
+
listObjects: () => string[];
|
|
86
|
+
/** Seeds an object without going through the mocks (no calls are recorded). */
|
|
87
|
+
putObject: (params: {
|
|
88
|
+
bucket: string;
|
|
89
|
+
contentType?: string;
|
|
90
|
+
contents: string | Uint8Array;
|
|
91
|
+
name: string;
|
|
92
|
+
}) => void;
|
|
93
|
+
/** Clears calls, overrides, and the in-memory store. */
|
|
94
|
+
reset: () => void;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Registers `mock.module("@google-cloud/storage", ...)` backed by an in-memory object store, so
|
|
98
|
+
* uploads can be downloaded, listed, streamed, and deleted again. Missing objects reject with a
|
|
99
|
+
* `code: 404` error the way GCS does. `@google-cloud/storage` does not need to be installed.
|
|
100
|
+
*/
|
|
101
|
+
export declare const registerGcsMock: () => GcsMock;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerGcsMock = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const node_stream_1 = require("node:stream");
|
|
6
|
+
const luxon_1 = require("luxon");
|
|
7
|
+
const mockGroup_1 = require("./mockGroup");
|
|
8
|
+
const objectKey = (bucket, name) => `${bucket}/${name}`;
|
|
9
|
+
const notFoundError = (bucket, name) => Object.assign(new Error(`No such object: ${bucket}/${name}`), { code: 404 });
|
|
10
|
+
const toBuffer = (data) => typeof data === "string" ? Buffer.from(data) : Buffer.from(data);
|
|
11
|
+
/**
|
|
12
|
+
* Registers `mock.module("@google-cloud/storage", ...)` backed by an in-memory object store, so
|
|
13
|
+
* uploads can be downloaded, listed, streamed, and deleted again. Missing objects reject with a
|
|
14
|
+
* `code: 404` error the way GCS does. `@google-cloud/storage` does not need to be installed.
|
|
15
|
+
*/
|
|
16
|
+
const registerGcsMock = () => {
|
|
17
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
18
|
+
const objects = new Map();
|
|
19
|
+
const store = ({ bucket, contents, name, options, }) => {
|
|
20
|
+
const contentType = options?.contentType ?? options?.metadata?.contentType;
|
|
21
|
+
objects.set(objectKey(bucket, name), {
|
|
22
|
+
contents,
|
|
23
|
+
metadata: {
|
|
24
|
+
...(options?.metadata ?? {}),
|
|
25
|
+
bucket,
|
|
26
|
+
contentType,
|
|
27
|
+
name,
|
|
28
|
+
size: String(contents.length),
|
|
29
|
+
updated: luxon_1.DateTime.utc().toISO(),
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
const requireObject = (file) => {
|
|
34
|
+
const stored = objects.get(objectKey(file.bucket.name, file.name));
|
|
35
|
+
if (!stored) {
|
|
36
|
+
throw notFoundError(file.bucket.name, file.name);
|
|
37
|
+
}
|
|
38
|
+
return stored;
|
|
39
|
+
};
|
|
40
|
+
const fileMocks = {
|
|
41
|
+
createReadStream: group.fn(function () {
|
|
42
|
+
const stored = objects.get(objectKey(this.bucket.name, this.name));
|
|
43
|
+
if (!stored) {
|
|
44
|
+
const error = notFoundError(this.bucket.name, this.name);
|
|
45
|
+
return new node_stream_1.Readable({
|
|
46
|
+
read() {
|
|
47
|
+
this.destroy(error);
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return node_stream_1.Readable.from([stored.contents]);
|
|
52
|
+
}),
|
|
53
|
+
createWriteStream: group.fn(function (options) {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
return new node_stream_1.Writable({
|
|
56
|
+
final: (callback) => {
|
|
57
|
+
store({
|
|
58
|
+
bucket: this.bucket.name,
|
|
59
|
+
contents: Buffer.concat(chunks),
|
|
60
|
+
name: this.name,
|
|
61
|
+
options,
|
|
62
|
+
});
|
|
63
|
+
callback();
|
|
64
|
+
},
|
|
65
|
+
write: (chunkData, _encoding, callback) => {
|
|
66
|
+
chunks.push(toBuffer(chunkData));
|
|
67
|
+
callback();
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}),
|
|
71
|
+
delete: group.fn(async function (options) {
|
|
72
|
+
const deleted = objects.delete(objectKey(this.bucket.name, this.name));
|
|
73
|
+
if (!deleted && !options?.ignoreNotFound) {
|
|
74
|
+
throw notFoundError(this.bucket.name, this.name);
|
|
75
|
+
}
|
|
76
|
+
return [{}];
|
|
77
|
+
}),
|
|
78
|
+
download: group.fn(async function () {
|
|
79
|
+
return [Buffer.from(requireObject(this).contents)];
|
|
80
|
+
}),
|
|
81
|
+
exists: group.fn(async function () {
|
|
82
|
+
return [objects.has(objectKey(this.bucket.name, this.name))];
|
|
83
|
+
}),
|
|
84
|
+
getMetadata: group.fn(async function () {
|
|
85
|
+
return [{ ...requireObject(this).metadata }];
|
|
86
|
+
}),
|
|
87
|
+
getSignedUrl: group.fn(async function (_config) {
|
|
88
|
+
return [
|
|
89
|
+
`https://storage.googleapis.com/${this.bucket.name}/${encodeURI(this.name)}?X-Goog-Signature=mock`,
|
|
90
|
+
];
|
|
91
|
+
}),
|
|
92
|
+
save: group.fn(async function (data, options) {
|
|
93
|
+
store({ bucket: this.bucket.name, contents: toBuffer(data), name: this.name, options });
|
|
94
|
+
}),
|
|
95
|
+
setMetadata: group.fn(async function (metadata) {
|
|
96
|
+
const stored = requireObject(this);
|
|
97
|
+
stored.metadata = { ...stored.metadata, ...metadata };
|
|
98
|
+
return [{ ...stored.metadata }];
|
|
99
|
+
}),
|
|
100
|
+
};
|
|
101
|
+
const createFile = (bucket, name) => ({
|
|
102
|
+
bucket,
|
|
103
|
+
...fileMocks,
|
|
104
|
+
get metadata() {
|
|
105
|
+
return objects.get(objectKey(bucket.name, name))?.metadata ?? {};
|
|
106
|
+
},
|
|
107
|
+
name,
|
|
108
|
+
publicUrl: () => `https://storage.googleapis.com/${bucket.name}/${encodeURI(name)}`,
|
|
109
|
+
});
|
|
110
|
+
const namesInBucket = (bucketName, prefix) => [...objects.keys()]
|
|
111
|
+
.filter((key) => key.startsWith(`${bucketName}/${prefix}`))
|
|
112
|
+
.map((key) => key.slice(bucketName.length + 1))
|
|
113
|
+
.sort();
|
|
114
|
+
const file = group.fn(function (name) {
|
|
115
|
+
return createFile(this, name);
|
|
116
|
+
});
|
|
117
|
+
const getFiles = group.fn(async function (query) {
|
|
118
|
+
const prefix = query?.prefix ?? "";
|
|
119
|
+
const delimiter = query?.delimiter;
|
|
120
|
+
const files = [];
|
|
121
|
+
const prefixes = new Set();
|
|
122
|
+
for (const name of namesInBucket(this.name, prefix)) {
|
|
123
|
+
const rest = name.slice(prefix.length);
|
|
124
|
+
const delimiterIndex = delimiter ? rest.indexOf(delimiter) : -1;
|
|
125
|
+
if (delimiter && delimiterIndex >= 0) {
|
|
126
|
+
prefixes.add(`${prefix}${rest.slice(0, delimiterIndex + delimiter.length)}`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
files.push(createFile(this, name));
|
|
130
|
+
}
|
|
131
|
+
return [files, null, { prefixes: [...prefixes] }];
|
|
132
|
+
});
|
|
133
|
+
const deleteFiles = group.fn(async function (query) {
|
|
134
|
+
for (const name of namesInBucket(this.name, query?.prefix ?? "")) {
|
|
135
|
+
objects.delete(objectKey(this.name, name));
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
const bucket = group.fn((name) => ({ deleteFiles, file, getFiles, name }));
|
|
139
|
+
const storage = { bucket };
|
|
140
|
+
const Storage = group.fn((_options) => storage);
|
|
141
|
+
const reset = () => {
|
|
142
|
+
group.reset();
|
|
143
|
+
objects.clear();
|
|
144
|
+
};
|
|
145
|
+
bun_test_1.mock.module("@google-cloud/storage", () => ({ default: { Storage }, Storage }));
|
|
146
|
+
return {
|
|
147
|
+
bucket,
|
|
148
|
+
deleteFiles,
|
|
149
|
+
file,
|
|
150
|
+
fileMocks,
|
|
151
|
+
getFiles,
|
|
152
|
+
getObject: ({ bucket: bucketName, name }) => objects.get(objectKey(bucketName, name)),
|
|
153
|
+
listObjects: () => [...objects.keys()].sort(),
|
|
154
|
+
putObject: ({ bucket: bucketName, contentType, contents, name }) => {
|
|
155
|
+
store({ bucket: bucketName, contents: toBuffer(contents), name, options: { contentType } });
|
|
156
|
+
},
|
|
157
|
+
reset,
|
|
158
|
+
Storage,
|
|
159
|
+
storage,
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
exports.registerGcsMock = registerGcsMock;
|