@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.
Files changed (115) hide show
  1. package/CHANGELOG.md +1681 -0
  2. package/README.md +6 -0
  3. package/dist/assertions/expectAPIError.d.ts +18 -0
  4. package/dist/assertions/expectAPIError.js +33 -0
  5. package/dist/assertions/strictResponseProperties.d.ts +14 -0
  6. package/dist/assertions/strictResponseProperties.js +37 -0
  7. package/dist/cache/mongoTestCache.js +2 -2
  8. package/dist/cli/collectFiles.d.ts +38 -0
  9. package/dist/cli/collectFiles.js +73 -0
  10. package/dist/cli/testHygiene.d.ts +134 -0
  11. package/dist/cli/testHygiene.js +357 -0
  12. package/dist/cli/testHygieneCli.d.ts +2 -0
  13. package/dist/cli/testHygieneCli.js +5 -0
  14. package/dist/cli/testHygieneRules.d.ts +58 -0
  15. package/dist/cli/testHygieneRules.js +517 -0
  16. package/dist/cli/testShard.d.ts +155 -0
  17. package/dist/cli/testShard.js +377 -0
  18. package/dist/cli/testShardCli.d.ts +2 -0
  19. package/dist/cli/testShardCli.js +5 -0
  20. package/dist/expo/authTokenStorage.d.ts +76 -0
  21. package/dist/expo/authTokenStorage.js +160 -0
  22. package/dist/expo/expoModuleMocks.d.ts +24 -0
  23. package/dist/expo/expoModuleMocks.js +456 -0
  24. package/dist/expo/libraryModuleMocks.d.ts +17 -0
  25. package/dist/expo/libraryModuleMocks.js +347 -0
  26. package/dist/expo/mockHelpers.d.ts +39 -0
  27. package/dist/expo/mockHelpers.js +45 -0
  28. package/dist/expo/mockModuleAliases.d.ts +50 -0
  29. package/dist/expo/mockModuleAliases.js +174 -0
  30. package/dist/expo/reactNativeMock.d.ts +39 -0
  31. package/dist/expo/reactNativeMock.js +421 -0
  32. package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
  33. package/dist/expo/registerExpoTestEnvironment.js +163 -0
  34. package/dist/expo/renderWithTerreno.d.ts +47 -0
  35. package/dist/expo/renderWithTerreno.js +47 -0
  36. package/dist/http/authWithToken.d.ts +20 -0
  37. package/dist/http/authWithToken.js +30 -0
  38. package/dist/index.d.ts +14 -1
  39. package/dist/index.js +33 -1
  40. package/dist/logging/silenceLogs.js +0 -2
  41. package/dist/mocks/aiSdk.d.ts +77 -0
  42. package/dist/mocks/aiSdk.js +102 -0
  43. package/dist/mocks/cloudTasks.d.ts +91 -0
  44. package/dist/mocks/cloudTasks.js +197 -0
  45. package/dist/mocks/expoPush.d.ts +53 -0
  46. package/dist/mocks/expoPush.js +57 -0
  47. package/dist/mocks/gcs.d.ts +101 -0
  48. package/dist/mocks/gcs.js +162 -0
  49. package/dist/mocks/googleAuth.d.ts +69 -0
  50. package/dist/mocks/googleAuth.js +55 -0
  51. package/dist/mocks/mockGroup.d.ts +11 -0
  52. package/dist/mocks/mockGroup.js +21 -0
  53. package/dist/mocks/notifiers.d.ts +21 -0
  54. package/dist/mocks/notifiers.js +26 -0
  55. package/dist/mocks/sendgrid.d.ts +22 -0
  56. package/dist/mocks/sendgrid.js +32 -0
  57. package/dist/mocks/twilio.d.ts +72 -0
  58. package/dist/mocks/twilio.js +64 -0
  59. package/dist/preload/registerBackendPreload.js +4 -1
  60. package/dist/time/freezeTime.d.ts +16 -0
  61. package/dist/time/freezeTime.js +49 -0
  62. package/dist/transaction/testTransaction.d.ts +43 -6
  63. package/dist/transaction/testTransaction.js +371 -92
  64. package/dist/utils/waitUntil.d.ts +22 -0
  65. package/dist/utils/waitUntil.js +34 -0
  66. package/package.json +53 -8
  67. package/src/assertions/expectAPIError.ts +51 -0
  68. package/src/assertions/strictResponseProperties.ts +42 -0
  69. package/src/cache/mongoTestCache.ts +2 -2
  70. package/src/cli/collectFiles.ts +115 -0
  71. package/src/cli/testHygiene.ts +539 -0
  72. package/src/cli/testHygieneCli.ts +4 -0
  73. package/src/cli/testHygieneRules.ts +719 -0
  74. package/src/cli/testShard.ts +532 -0
  75. package/src/cli/testShardCli.ts +4 -0
  76. package/src/expo/authTokenStorage.ts +198 -0
  77. package/src/expo/expoModuleMocks.ts +503 -0
  78. package/src/expo/libraryModuleMocks.ts +411 -0
  79. package/src/expo/mockHelpers.ts +73 -0
  80. package/src/expo/mockModuleAliases.ts +252 -0
  81. package/src/expo/reactNativeMock.ts +534 -0
  82. package/src/expo/registerExpoTestEnvironment.ts +260 -0
  83. package/src/expo/renderWithTerreno.ts +79 -0
  84. package/src/http/authWithToken.ts +38 -0
  85. package/src/index.ts +82 -1
  86. package/src/logging/silenceLogs.ts +0 -2
  87. package/src/mocks/aiSdk.ts +199 -0
  88. package/src/mocks/cloudTasks.ts +323 -0
  89. package/src/mocks/expoPush.ts +134 -0
  90. package/src/mocks/gcs.ts +305 -0
  91. package/src/mocks/googleAuth.ts +136 -0
  92. package/src/mocks/mockGroup.ts +32 -0
  93. package/src/mocks/notifiers.ts +36 -0
  94. package/src/mocks/sendgrid.ts +57 -0
  95. package/src/mocks/twilio.ts +143 -0
  96. package/src/preload/registerBackendPreload.ts +4 -1
  97. package/src/time/freezeTime.ts +61 -0
  98. package/src/transaction/testTransaction.ts +456 -124
  99. package/src/utils/waitUntil.ts +47 -0
  100. package/biome.jsonc +0 -20
  101. package/bunfig.toml +0 -16
  102. package/src/cache/mongoTestCache.test.ts +0 -103
  103. package/src/env/setTerrenoTestEnv.test.ts +0 -26
  104. package/src/http/authAsUser.test.ts +0 -40
  105. package/src/http/getBaseServer.test.ts +0 -45
  106. package/src/logging/setupEnvironment.test.ts +0 -24
  107. package/src/logging/silenceLogs.test.ts +0 -52
  108. package/src/logging/testLogger.test.ts +0 -58
  109. package/src/mocks/sentryBun.test.ts +0 -230
  110. package/src/mongo/connection.test.ts +0 -43
  111. package/src/mongo/mongoServer.test.ts +0 -99
  112. package/src/preload/registerBackendPreload.test.ts +0 -10
  113. package/src/transaction/testTransaction.test.ts +0 -64
  114. package/src/utils/helpers.test.ts +0 -46
  115. package/tsconfig.json +0 -18
@@ -0,0 +1,199 @@
1
+ import type {Mock} from "bun:test";
2
+
3
+ import {createMockGroup} from "./mockGroup";
4
+
5
+ export type MockLanguageModelFinishReason =
6
+ | "stop"
7
+ | "length"
8
+ | "content-filter"
9
+ | "tool-calls"
10
+ | "error"
11
+ | "other"
12
+ | "unknown";
13
+
14
+ export interface MockLanguageModelUsage {
15
+ inputTokens: number;
16
+ outputTokens: number;
17
+ totalTokens: number;
18
+ }
19
+
20
+ export interface MockLanguageModelToolCall {
21
+ /** Tool input; serialized to the JSON string the provider spec expects. */
22
+ input: unknown;
23
+ /** Default `call_<n>` (1-based across the response's calls). */
24
+ toolCallId?: string;
25
+ toolName: string;
26
+ }
27
+
28
+ /** One scripted model turn. Each `doGenerate`/`doStream` call consumes the next one. */
29
+ export interface MockLanguageModelResponse {
30
+ /** Stream deltas. Default `[text]`. `doGenerate` returns `text`, or the joined chunks. */
31
+ chunks?: string[];
32
+ /** Makes the call fail: `doGenerate` rejects, `doStream` errors after the text deltas. */
33
+ error?: string;
34
+ /** Default `"tool-calls"` when `toolCalls` is set, otherwise `"stop"`. */
35
+ finishReason?: MockLanguageModelFinishReason;
36
+ text?: string;
37
+ toolCalls?: MockLanguageModelToolCall[];
38
+ usage?: MockLanguageModelUsage;
39
+ }
40
+
41
+ export interface MockLanguageModelStreamPart {
42
+ type: string;
43
+ [key: string]: unknown;
44
+ }
45
+
46
+ export interface MockLanguageModelGenerateResult {
47
+ content: Array<
48
+ | {text: string; type: "text"}
49
+ | {input: string; toolCallId: string; toolName: string; type: "tool-call"}
50
+ >;
51
+ finishReason: MockLanguageModelFinishReason;
52
+ usage: MockLanguageModelUsage;
53
+ warnings: never[];
54
+ }
55
+
56
+ export interface CreateMockLanguageModelOptions {
57
+ modelId?: string;
58
+ provider?: string;
59
+ /** Scripted turns, in order. The last one repeats once the script runs out. */
60
+ responses?: MockLanguageModelResponse[];
61
+ /** Shorthand for `responses: [{text}]`. Default `"Mock response"`. */
62
+ text?: string;
63
+ }
64
+
65
+ /**
66
+ * A Vercel AI SDK `LanguageModelV2` (spec `"v2"`, which AI SDK 5 and 6 accept) for passing
67
+ * straight to `AIService`, `streamText`, or `generateText`. Assert on `doGenerate.mock.calls` /
68
+ * `doStream.mock.calls` to see the prompt and tools the SDK sent.
69
+ */
70
+ export interface MockLanguageModel {
71
+ doGenerate: Mock<(options: unknown) => Promise<MockLanguageModelGenerateResult>>;
72
+ doStream: Mock<
73
+ (options: unknown) => Promise<{stream: ReadableStream<MockLanguageModelStreamPart>}>
74
+ >;
75
+ readonly modelId: string;
76
+ readonly provider: string;
77
+ /** Clears calls and overrides and restarts the script at the first response. */
78
+ reset: () => void;
79
+ readonly specificationVersion: "v2";
80
+ readonly supportedUrls: Record<string, RegExp[]>;
81
+ }
82
+
83
+ const DEFAULT_USAGE: MockLanguageModelUsage = {inputTokens: 1, outputTokens: 1, totalTokens: 2};
84
+
85
+ const toolCallParts = (
86
+ toolCalls: MockLanguageModelToolCall[] | undefined
87
+ ): Array<{input: string; toolCallId: string; toolName: string; type: "tool-call"}> =>
88
+ (toolCalls ?? []).map((call, index) => ({
89
+ input: JSON.stringify(call.input ?? {}),
90
+ toolCallId: call.toolCallId ?? `call_${index + 1}`,
91
+ toolName: call.toolName,
92
+ type: "tool-call",
93
+ }));
94
+
95
+ const finishReasonFor = (response: MockLanguageModelResponse): MockLanguageModelFinishReason =>
96
+ response.finishReason ?? (response.toolCalls?.length ? "tool-calls" : "stop");
97
+
98
+ /** Builds the `LanguageModelV2` stream parts a response produces. */
99
+ export const mockLanguageModelStreamParts = (
100
+ response: MockLanguageModelResponse
101
+ ): MockLanguageModelStreamPart[] => {
102
+ const chunks = response.chunks ?? (response.text ? [response.text] : []);
103
+ const textParts: MockLanguageModelStreamPart[] =
104
+ chunks.length === 0
105
+ ? []
106
+ : [
107
+ {id: "text-1", type: "text-start"},
108
+ ...chunks.map((delta) => ({delta, id: "text-1", type: "text-delta"})),
109
+ {id: "text-1", type: "text-end"},
110
+ ];
111
+ return [
112
+ {type: "stream-start", warnings: []},
113
+ ...textParts,
114
+ ...toolCallParts(response.toolCalls),
115
+ {
116
+ finishReason: finishReasonFor(response),
117
+ type: "finish",
118
+ usage: response.usage ?? DEFAULT_USAGE,
119
+ },
120
+ ];
121
+ };
122
+
123
+ /**
124
+ * Creates a scripted mock language model. Prefer this to `mock.module("ai", ...)`: the real AI SDK
125
+ * runs, so tool loops, structured output, and streaming behave as in production. Needs no `ai`
126
+ * install. For full-spec V3 fidelity, `MockLanguageModelV3` from `ai/test` is the SDK's own.
127
+ */
128
+ export const createMockLanguageModel = (
129
+ options: CreateMockLanguageModelOptions = {}
130
+ ): MockLanguageModel => {
131
+ const responses = options.responses?.length
132
+ ? options.responses
133
+ : [{text: options.text ?? "Mock response"}];
134
+ const group = createMockGroup();
135
+ let callCount = 0;
136
+
137
+ const nextResponse = (): MockLanguageModelResponse => {
138
+ const response = responses[Math.min(callCount, responses.length - 1)];
139
+ callCount += 1;
140
+ return response as MockLanguageModelResponse;
141
+ };
142
+
143
+ const doGenerate = group.fn(
144
+ async (_options: unknown): Promise<MockLanguageModelGenerateResult> => {
145
+ const response = nextResponse();
146
+ if (response.error) {
147
+ throw new Error(response.error);
148
+ }
149
+ const text = response.text ?? response.chunks?.join("");
150
+ return {
151
+ content: [
152
+ ...(text ? [{text, type: "text" as const}] : []),
153
+ ...toolCallParts(response.toolCalls),
154
+ ],
155
+ finishReason: finishReasonFor(response),
156
+ usage: response.usage ?? DEFAULT_USAGE,
157
+ warnings: [],
158
+ };
159
+ }
160
+ );
161
+
162
+ const doStream = group.fn(
163
+ async (_options: unknown): Promise<{stream: ReadableStream<MockLanguageModelStreamPart>}> => {
164
+ const response = nextResponse();
165
+ const parts = mockLanguageModelStreamParts(response);
166
+ let index = 0;
167
+ // Pull one part at a time so parts before a scripted error still reach the reader.
168
+ const stream = new ReadableStream<MockLanguageModelStreamPart>({
169
+ pull: (controller): void => {
170
+ const part = parts[index];
171
+ index += 1;
172
+ if (!part) {
173
+ controller.close();
174
+ return;
175
+ }
176
+ if (response.error && part.type !== "stream-start" && !part.type.startsWith("text")) {
177
+ controller.error(new Error(response.error));
178
+ return;
179
+ }
180
+ controller.enqueue(part);
181
+ },
182
+ });
183
+ return {stream};
184
+ }
185
+ );
186
+
187
+ return {
188
+ doGenerate,
189
+ doStream,
190
+ modelId: options.modelId ?? "mock-model",
191
+ provider: options.provider ?? "mock-provider",
192
+ reset: (): void => {
193
+ group.reset();
194
+ callCount = 0;
195
+ },
196
+ specificationVersion: "v2",
197
+ supportedUrls: {},
198
+ };
199
+ };
@@ -0,0 +1,323 @@
1
+ import {type Mock, mock} from "bun:test";
2
+ import type express from "express";
3
+ import supertest from "supertest";
4
+
5
+ import {createMockGroup} from "./mockGroup";
6
+
7
+ /** protobuf Timestamp / Duration as `@google-cloud/tasks` accepts them. */
8
+ export interface CloudTasksTime {
9
+ nanos?: number | null;
10
+ seconds?: number | string | null;
11
+ }
12
+
13
+ export interface CloudTasksHttpRequest {
14
+ /** Base64 string (what the REST surface sends) or raw bytes. */
15
+ body?: string | Uint8Array | null;
16
+ headers?: Record<string, string> | null;
17
+ /** `"POST"` or the numeric `protos.google.cloud.tasks.v2.HttpMethod` value. */
18
+ httpMethod?: string | number | null;
19
+ oidcToken?: {audience?: string | null; serviceAccountEmail?: string | null} | null;
20
+ url?: string | null;
21
+ }
22
+
23
+ export interface CloudTasksTask {
24
+ dispatchDeadline?: CloudTasksTime | null;
25
+ httpRequest?: CloudTasksHttpRequest | null;
26
+ name?: string | null;
27
+ scheduleTime?: CloudTasksTime | null;
28
+ }
29
+
30
+ export interface CloudTasksCreateTaskRequest {
31
+ parent?: string | null;
32
+ task?: CloudTasksTask | null;
33
+ }
34
+
35
+ /** A task the mock accepted, with its body decoded. */
36
+ export interface EnqueuedCloudTask {
37
+ /** Body parsed as JSON; the decoded string when it is not JSON; undefined when absent. */
38
+ body: unknown;
39
+ headers: Record<string, string>;
40
+ httpMethod: string;
41
+ name: string;
42
+ parent: string;
43
+ /** The decoded body text before JSON parsing. */
44
+ rawBody?: string;
45
+ request: CloudTasksCreateTaskRequest;
46
+ url?: string;
47
+ }
48
+
49
+ export interface DrainCloudTasksOptions {
50
+ app: express.Application;
51
+ /** Exact status every dispatch must return, `"2xx"` (default), or `"any"` to skip the check. */
52
+ expectStatus?: number | "2xx" | "any";
53
+ /** Only dispatch matching tasks; the rest stay enqueued. */
54
+ filter?: (task: EnqueuedCloudTask) => boolean;
55
+ /** Extra request headers (e.g. an auth header your execute route checks). */
56
+ headers?: Record<string, string> | ((task: EnqueuedCloudTask) => Record<string, string>);
57
+ /** Rounds to drain tasks enqueued by dispatched tasks. Default 10; throws if work remains. */
58
+ maxRounds?: number;
59
+ /** Request path. Default: the path and query of the task's `httpRequest.url`. */
60
+ path?: string | ((task: EnqueuedCloudTask) => string);
61
+ }
62
+
63
+ export interface DrainedCloudTask {
64
+ response: supertest.Response;
65
+ task: EnqueuedCloudTask;
66
+ }
67
+
68
+ export interface CloudTasksMockClient {
69
+ createTask: Mock<
70
+ (request: CloudTasksCreateTaskRequest) => Promise<[CloudTasksTask & {name: string}]>
71
+ >;
72
+ deleteTask: Mock<(request: {name?: string | null}) => Promise<[Record<string, never>]>>;
73
+ queuePath: Mock<(project: string, location: string, queue: string) => string>;
74
+ }
75
+
76
+ export interface CloudTasksMock extends CloudTasksMockClient {
77
+ /** Constructor registered as `CloudTasksClient`; every instance is `client`. */
78
+ CloudTasksClient: Mock<() => CloudTasksMockClient>;
79
+ client: CloudTasksMockClient;
80
+ /** Dispatches enqueued tasks to `app` with supertest, in enqueue order. */
81
+ drainTasks: (options: DrainCloudTasksOptions) => Promise<DrainedCloudTask[]>;
82
+ /** Tasks created and not yet drained or deleted. */
83
+ getEnqueuedTasks: () => EnqueuedCloudTask[];
84
+ /** Clears calls, drained state, and overrides. */
85
+ reset: () => void;
86
+ }
87
+
88
+ const HTTP_METHODS_BY_NUMBER: Record<number, string> = {
89
+ 1: "POST",
90
+ 2: "GET",
91
+ 3: "HEAD",
92
+ 4: "PUT",
93
+ 5: "DELETE",
94
+ 6: "PATCH",
95
+ 7: "OPTIONS",
96
+ };
97
+
98
+ type SupertestMethod = "delete" | "get" | "head" | "options" | "patch" | "post" | "put";
99
+
100
+ const SUPPORTED_METHODS = new Set<string>([
101
+ "delete",
102
+ "get",
103
+ "head",
104
+ "options",
105
+ "patch",
106
+ "post",
107
+ "put",
108
+ ]);
109
+
110
+ const CLOUD_TASKS_PROTOS = {
111
+ google: {
112
+ cloud: {
113
+ tasks: {
114
+ v2: {
115
+ HttpMethod: {
116
+ DELETE: 5,
117
+ GET: 2,
118
+ HEAD: 3,
119
+ HTTP_METHOD_UNSPECIFIED: 0,
120
+ OPTIONS: 7,
121
+ PATCH: 6,
122
+ POST: 1,
123
+ PUT: 4,
124
+ },
125
+ },
126
+ },
127
+ },
128
+ },
129
+ } as const;
130
+
131
+ /** Decodes a Cloud Tasks HTTP body (base64 string or bytes) and parses it as JSON when it can. */
132
+ export const decodeCloudTaskBody = (
133
+ body: string | Uint8Array | null | undefined
134
+ ): {body: unknown; rawBody?: string} => {
135
+ if (body === null || body === undefined) {
136
+ return {body: undefined};
137
+ }
138
+ const rawBody =
139
+ typeof body === "string"
140
+ ? Buffer.from(body, "base64").toString("utf8")
141
+ : Buffer.from(body).toString("utf8");
142
+ try {
143
+ return {body: JSON.parse(rawBody), rawBody};
144
+ } catch {
145
+ return {body: rawBody, rawBody};
146
+ }
147
+ };
148
+
149
+ const resolveHttpMethod = (httpMethod: string | number | null | undefined): string => {
150
+ if (typeof httpMethod === "number") {
151
+ return HTTP_METHODS_BY_NUMBER[httpMethod] ?? "POST";
152
+ }
153
+ return httpMethod ? httpMethod.toUpperCase() : "POST";
154
+ };
155
+
156
+ const defaultTaskName = (parent: string, index: number): string =>
157
+ `${parent}/tasks/mock-task-${index + 1}`;
158
+
159
+ const toEnqueuedTask = (request: CloudTasksCreateTaskRequest, index: number): EnqueuedCloudTask => {
160
+ const parent = request.parent ?? "";
161
+ const httpRequest = request.task?.httpRequest ?? undefined;
162
+ return {
163
+ ...decodeCloudTaskBody(httpRequest?.body),
164
+ headers: {...(httpRequest?.headers ?? {})},
165
+ httpMethod: resolveHttpMethod(httpRequest?.httpMethod),
166
+ name: request.task?.name ?? defaultTaskName(parent, index),
167
+ parent,
168
+ request,
169
+ url: httpRequest?.url ?? undefined,
170
+ };
171
+ };
172
+
173
+ const resolveTaskPath = (task: EnqueuedCloudTask, path: DrainCloudTasksOptions["path"]): string => {
174
+ if (typeof path === "function") {
175
+ return path(task);
176
+ }
177
+ if (path) {
178
+ return path;
179
+ }
180
+ if (!task.url) {
181
+ throw new Error(`Cloud task ${task.name} has no httpRequest.url; pass drainTasks({path})`);
182
+ }
183
+ const url = new URL(task.url, "http://localhost");
184
+ return `${url.pathname}${url.search}`;
185
+ };
186
+
187
+ const assertStatus = (
188
+ task: EnqueuedCloudTask,
189
+ response: supertest.Response,
190
+ expectStatus: NonNullable<DrainCloudTasksOptions["expectStatus"]>
191
+ ): void => {
192
+ if (expectStatus === "any") {
193
+ return;
194
+ }
195
+ const isExpected =
196
+ expectStatus === "2xx"
197
+ ? response.status >= 200 && response.status < 300
198
+ : response.status === expectStatus;
199
+ if (!isExpected) {
200
+ throw new Error(
201
+ `Cloud task ${task.name} returned ${response.status} (expected ${expectStatus}): ${JSON.stringify(response.body)}`
202
+ );
203
+ }
204
+ };
205
+
206
+ const dispatchTask = async ({
207
+ options,
208
+ task,
209
+ }: {
210
+ options: DrainCloudTasksOptions;
211
+ task: EnqueuedCloudTask;
212
+ }): Promise<supertest.Response> => {
213
+ const path = resolveTaskPath(task, options.path);
214
+ const extraHeaders =
215
+ typeof options.headers === "function" ? options.headers(task) : (options.headers ?? {});
216
+ const method = task.httpMethod.toLowerCase();
217
+ if (!SUPPORTED_METHODS.has(method)) {
218
+ throw new Error(`Cloud task ${task.name} uses unsupported method ${task.httpMethod}`);
219
+ }
220
+ const agent = supertest(options.app);
221
+ const start = agent[method as SupertestMethod].bind(agent);
222
+ const headers = {...task.headers, ...extraHeaders};
223
+ const hasContentType = Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
224
+ if (!hasContentType && task.rawBody !== undefined && task.body !== task.rawBody) {
225
+ headers["Content-Type"] = "application/json";
226
+ }
227
+ const request = start(path).set(headers);
228
+ if (task.rawBody === undefined) {
229
+ return request;
230
+ }
231
+ return request.send(task.rawBody);
232
+ };
233
+
234
+ /**
235
+ * Registers `mock.module("@google-cloud/tasks", ...)`. Call once (e.g. in a preload), call
236
+ * `reset()` in `beforeEach`, and inject nothing: code that does `new CloudTasksClient()` gets
237
+ * the shared `client`. `@google-cloud/tasks` does not need to be installed.
238
+ */
239
+ export const registerCloudTasksMock = (): CloudTasksMock => {
240
+ const group = createMockGroup();
241
+ const consumed = new Set<number>();
242
+
243
+ const createTask = group.fn(
244
+ async (request: CloudTasksCreateTaskRequest): Promise<[CloudTasksTask & {name: string}]> => {
245
+ const index = createTask.mock.calls.length - 1;
246
+ const name = request.task?.name ?? defaultTaskName(request.parent ?? "", index);
247
+ return [{...(request.task ?? {}), name}];
248
+ }
249
+ );
250
+
251
+ const getEnqueuedEntries = (): Array<{index: number; task: EnqueuedCloudTask}> =>
252
+ createTask.mock.calls
253
+ .map(([request], index) => ({index, task: toEnqueuedTask(request, index)}))
254
+ .filter(({index}) => !consumed.has(index));
255
+
256
+ const deleteTask = group.fn(
257
+ async (request: {name?: string | null}): Promise<[Record<string, never>]> => {
258
+ for (const entry of getEnqueuedEntries()) {
259
+ if (entry.task.name === request.name) {
260
+ consumed.add(entry.index);
261
+ }
262
+ }
263
+ return [{}];
264
+ }
265
+ );
266
+
267
+ const queuePath = group.fn(
268
+ (project: string, location: string, queue: string): string =>
269
+ `projects/${project}/locations/${location}/queues/${queue}`
270
+ );
271
+
272
+ const client: CloudTasksMockClient = {createTask, deleteTask, queuePath};
273
+ const CloudTasksClient = group.fn((): CloudTasksMockClient => client);
274
+
275
+ const drainTasks = async (options: DrainCloudTasksOptions): Promise<DrainedCloudTask[]> => {
276
+ const maxRounds = options.maxRounds ?? 10;
277
+ const expectStatus = options.expectStatus ?? "2xx";
278
+ const matches = (): Array<{index: number; task: EnqueuedCloudTask}> =>
279
+ getEnqueuedEntries().filter(({task}) => (options.filter ? options.filter(task) : true));
280
+ const drained: DrainedCloudTask[] = [];
281
+
282
+ for (let round = 0; ; round += 1) {
283
+ const batch = matches();
284
+ if (batch.length === 0) {
285
+ return drained;
286
+ }
287
+ if (round >= maxRounds) {
288
+ throw new Error(
289
+ `drainTasks stopped after ${maxRounds} rounds with ${batch.length} task(s) still enqueued`
290
+ );
291
+ }
292
+ for (const {index, task} of batch) {
293
+ consumed.add(index);
294
+ const response = await dispatchTask({options, task});
295
+ assertStatus(task, response, expectStatus);
296
+ drained.push({response, task});
297
+ }
298
+ }
299
+ };
300
+
301
+ const reset = (): void => {
302
+ group.reset();
303
+ consumed.clear();
304
+ };
305
+
306
+ const moduleExports = {
307
+ CloudTasksClient,
308
+ protos: CLOUD_TASKS_PROTOS,
309
+ v2: {CloudTasksClient},
310
+ };
311
+ mock.module("@google-cloud/tasks", () => ({...moduleExports, default: moduleExports}));
312
+
313
+ return {
314
+ CloudTasksClient,
315
+ client,
316
+ createTask,
317
+ deleteTask,
318
+ drainTasks,
319
+ getEnqueuedTasks: (): EnqueuedCloudTask[] => getEnqueuedEntries().map(({task}) => task),
320
+ queuePath,
321
+ reset,
322
+ };
323
+ };
@@ -0,0 +1,134 @@
1
+ import {type Mock, mock} from "bun:test";
2
+
3
+ import {createMockGroup} from "./mockGroup";
4
+
5
+ export interface ExpoMockPushMessage {
6
+ body?: string;
7
+ data?: Record<string, unknown>;
8
+ title?: string;
9
+ to: string | string[];
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ export interface ExpoMockPushTicket {
14
+ details?: Record<string, unknown>;
15
+ id?: string;
16
+ message?: string;
17
+ status: "ok" | "error";
18
+ }
19
+
20
+ export interface ExpoMockPushReceipt {
21
+ details?: Record<string, unknown>;
22
+ message?: string;
23
+ status: "ok" | "error";
24
+ }
25
+
26
+ export interface ExpoMockClient {
27
+ chunkPushNotificationReceiptIds: ExpoPushMock["chunkPushNotificationReceiptIds"];
28
+ chunkPushNotifications: ExpoPushMock["chunkPushNotifications"];
29
+ getPushNotificationReceiptsAsync: ExpoPushMock["getPushNotificationReceiptsAsync"];
30
+ sendPushNotificationsAsync: ExpoPushMock["sendPushNotificationsAsync"];
31
+ }
32
+
33
+ export interface ExpoPushMock {
34
+ /** `new Expo(options)` — every instance is the shared `client`. Has static `isExpoPushToken`. */
35
+ Expo: Mock<(options?: {accessToken?: string}) => ExpoMockClient> & {
36
+ isExpoPushToken: ExpoPushMock["isExpoPushToken"];
37
+ };
38
+ client: ExpoMockClient;
39
+ /** Accepts `ExponentPushToken[...]`, `ExpoPushToken[...]`, and bare UUID device ids. */
40
+ isExpoPushToken: Mock<(token: unknown) => boolean>;
41
+ /** Splits into chunks of 100 messages, Expo's per-request limit. */
42
+ chunkPushNotifications: Mock<(messages: ExpoMockPushMessage[]) => ExpoMockPushMessage[][]>;
43
+ /** Splits into chunks of 300 ids, Expo's per-request limit. */
44
+ chunkPushNotificationReceiptIds: Mock<(receiptIds: string[]) => string[][]>;
45
+ /** Resolves one `{status: "ok", id}` ticket per recipient. */
46
+ sendPushNotificationsAsync: Mock<
47
+ (messages: ExpoMockPushMessage[]) => Promise<ExpoMockPushTicket[]>
48
+ >;
49
+ /** Resolves `{status: "ok"}` for every requested receipt id. */
50
+ getPushNotificationReceiptsAsync: Mock<
51
+ (receiptIds: string[]) => Promise<Record<string, ExpoMockPushReceipt>>
52
+ >;
53
+ /** Every message passed to `sendPushNotificationsAsync`, in order. */
54
+ getSentMessages: () => ExpoMockPushMessage[];
55
+ /** Clears calls, overrides, and the ticket counter. */
56
+ reset: () => void;
57
+ }
58
+
59
+ const EXPO_TOKEN_PATTERN = /^Expo(nent)?PushToken\[.+\]$/;
60
+ const UUID_PATTERN = /^[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}$/i;
61
+
62
+ const chunk = <T>(items: T[], size: number): T[][] => {
63
+ const chunks: T[][] = [];
64
+ for (let start = 0; start < items.length; start += size) {
65
+ chunks.push(items.slice(start, start + size));
66
+ }
67
+ return chunks;
68
+ };
69
+
70
+ /**
71
+ * Registers `mock.module("expo-server-sdk", ...)` exporting `Expo` (named and default).
72
+ * `expo-server-sdk` does not need to be installed.
73
+ */
74
+ export const registerExpoPushMock = (): ExpoPushMock => {
75
+ const group = createMockGroup();
76
+ let ticketCount = 0;
77
+
78
+ const isExpoPushToken = group.fn(
79
+ (token: unknown): boolean =>
80
+ typeof token === "string" && (EXPO_TOKEN_PATTERN.test(token) || UUID_PATTERN.test(token))
81
+ );
82
+ const chunkPushNotifications = group.fn(
83
+ (messages: ExpoMockPushMessage[]): ExpoMockPushMessage[][] => chunk(messages, 100)
84
+ );
85
+ const chunkPushNotificationReceiptIds = group.fn((receiptIds: string[]): string[][] =>
86
+ chunk(receiptIds, 300)
87
+ );
88
+ const sendPushNotificationsAsync = group.fn(
89
+ async (messages: ExpoMockPushMessage[]): Promise<ExpoMockPushTicket[]> =>
90
+ messages
91
+ .flatMap((message) => (Array.isArray(message.to) ? message.to : [message.to]))
92
+ .map((): ExpoMockPushTicket => {
93
+ ticketCount += 1;
94
+ return {id: `mock-ticket-${ticketCount}`, status: "ok"};
95
+ })
96
+ );
97
+ const getPushNotificationReceiptsAsync = group.fn(
98
+ async (receiptIds: string[]): Promise<Record<string, ExpoMockPushReceipt>> =>
99
+ Object.fromEntries(receiptIds.map((id) => [id, {status: "ok" as const}]))
100
+ );
101
+
102
+ const client: ExpoMockClient = {
103
+ chunkPushNotificationReceiptIds,
104
+ chunkPushNotifications,
105
+ getPushNotificationReceiptsAsync,
106
+ sendPushNotificationsAsync,
107
+ };
108
+ const Expo = Object.assign(
109
+ group.fn((_options?: {accessToken?: string}): ExpoMockClient => client),
110
+ {isExpoPushToken}
111
+ );
112
+
113
+ const getSentMessages = (): ExpoMockPushMessage[] =>
114
+ sendPushNotificationsAsync.mock.calls.flatMap(([messages]) => messages);
115
+
116
+ const reset = (): void => {
117
+ group.reset();
118
+ ticketCount = 0;
119
+ };
120
+
121
+ mock.module("expo-server-sdk", () => ({default: Expo, Expo}));
122
+
123
+ return {
124
+ chunkPushNotificationReceiptIds,
125
+ chunkPushNotifications,
126
+ client,
127
+ Expo,
128
+ getPushNotificationReceiptsAsync,
129
+ getSentMessages,
130
+ isExpoPushToken,
131
+ reset,
132
+ sendPushNotificationsAsync,
133
+ };
134
+ };