@terreno/test 0.22.1
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/bunfig.toml +3 -0
- package/dist/cache/mongoTestCache.d.ts +16 -0
- package/dist/cache/mongoTestCache.js +541 -0
- package/dist/env/setTerrenoTestEnv.d.ts +13 -0
- package/dist/env/setTerrenoTestEnv.js +89 -0
- package/dist/http/authAsUser.d.ts +17 -0
- package/dist/http/authAsUser.js +165 -0
- package/dist/http/authAsUser.test.d.ts +1 -0
- package/dist/http/authAsUser.test.js +93 -0
- package/dist/http/getBaseServer.d.ts +9 -0
- package/dist/http/getBaseServer.js +33 -0
- package/dist/http/getBaseServer.test.d.ts +1 -0
- package/dist/http/getBaseServer.test.js +76 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +46 -0
- package/dist/logging/setupEnvironment.d.ts +2 -0
- package/dist/logging/setupEnvironment.js +19 -0
- package/dist/logging/silenceLogs.d.ts +20 -0
- package/dist/logging/silenceLogs.js +168 -0
- package/dist/logging/testLogger.d.ts +7 -0
- package/dist/logging/testLogger.js +22 -0
- package/dist/mocks/sentryBun.d.ts +2 -0
- package/dist/mocks/sentryBun.js +136 -0
- package/dist/mongo/connection.d.ts +16 -0
- package/dist/mongo/connection.js +134 -0
- package/dist/mongo/connection.test.d.ts +1 -0
- package/dist/mongo/connection.test.js +28 -0
- package/dist/mongo/ensureMongoBinary.d.ts +6 -0
- package/dist/mongo/ensureMongoBinary.js +104 -0
- package/dist/mongo/mongoServer.d.ts +26 -0
- package/dist/mongo/mongoServer.js +424 -0
- package/dist/preload/defaultBackendPreload.d.ts +1 -0
- package/dist/preload/defaultBackendPreload.js +8 -0
- package/dist/preload/memoryMongo.d.ts +0 -0
- package/dist/preload/memoryMongo.js +2 -0
- package/dist/preload/registerBackendPreload.d.ts +33 -0
- package/dist/preload/registerBackendPreload.js +302 -0
- package/dist/transaction/testTransaction.d.ts +91 -0
- package/dist/transaction/testTransaction.js +719 -0
- package/dist/utils/ensureAllIndexes.d.ts +2 -0
- package/dist/utils/ensureAllIndexes.js +84 -0
- package/dist/utils/timeout.d.ts +1 -0
- package/dist/utils/timeout.js +45 -0
- package/dist/utils/waitForDocuments.d.ts +13 -0
- package/dist/utils/waitForDocuments.js +127 -0
- package/package.json +65 -0
- package/src/cache/mongoTestCache.ts +311 -0
- package/src/env/setTerrenoTestEnv.ts +50 -0
- package/src/http/authAsUser.test.ts +40 -0
- package/src/http/authAsUser.ts +59 -0
- package/src/http/getBaseServer.test.ts +30 -0
- package/src/http/getBaseServer.ts +34 -0
- package/src/index.ts +53 -0
- package/src/logging/setupEnvironment.ts +15 -0
- package/src/logging/silenceLogs.ts +134 -0
- package/src/logging/testLogger.ts +19 -0
- package/src/mocks/sentryBun.ts +140 -0
- package/src/mongo/connection.test.ts +30 -0
- package/src/mongo/connection.ts +65 -0
- package/src/mongo/ensureMongoBinary.ts +25 -0
- package/src/mongo/mongoServer.ts +214 -0
- package/src/preload/defaultBackendPreload.ts +7 -0
- package/src/preload/memoryMongo.ts +1 -0
- package/src/preload/registerBackendPreload.ts +174 -0
- package/src/transaction/testTransaction.ts +524 -0
- package/src/utils/ensureAllIndexes.ts +11 -0
- package/src/utils/timeout.ts +3 -0
- package/src/utils/waitForDocuments.ts +50 -0
- package/tsconfig.json +31 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {setupTestEnvironment} from "../logging/setupEnvironment";
|
|
2
|
+
|
|
3
|
+
export interface TerrenoTestEnvOptions {
|
|
4
|
+
tokenIssuer?: string;
|
|
5
|
+
tokenSecret?: string;
|
|
6
|
+
sessionSecret?: string;
|
|
7
|
+
refreshTokenSecret?: string;
|
|
8
|
+
timezone?: string;
|
|
9
|
+
extra?: Record<string, string | undefined>;
|
|
10
|
+
deleteKeys?: string[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const DEFAULT_AUTH_ENV = {
|
|
14
|
+
REFRESH_TOKEN_SECRET: "refreshTokenSecret",
|
|
15
|
+
SESSION_SECRET: "sessionSecret",
|
|
16
|
+
TOKEN_ISSUER: "terreno.test",
|
|
17
|
+
TOKEN_SECRET: "secret",
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Applies the canonical Terreno backend test `process.env` surface for auth secrets.
|
|
22
|
+
*/
|
|
23
|
+
export const setTerrenoTestEnv = (options: TerrenoTestEnvOptions = {}): void => {
|
|
24
|
+
process.env.NODE_ENV = "test";
|
|
25
|
+
process.env.TZ = options.timezone ?? "UTC";
|
|
26
|
+
|
|
27
|
+
process.env.TOKEN_SECRET = options.tokenSecret ?? DEFAULT_AUTH_ENV.TOKEN_SECRET;
|
|
28
|
+
process.env.TOKEN_ISSUER = options.tokenIssuer ?? DEFAULT_AUTH_ENV.TOKEN_ISSUER;
|
|
29
|
+
process.env.SESSION_SECRET = options.sessionSecret ?? DEFAULT_AUTH_ENV.SESSION_SECRET;
|
|
30
|
+
process.env.REFRESH_TOKEN_SECRET =
|
|
31
|
+
options.refreshTokenSecret ?? DEFAULT_AUTH_ENV.REFRESH_TOKEN_SECRET;
|
|
32
|
+
|
|
33
|
+
if (options.extra) {
|
|
34
|
+
for (const [key, value] of Object.entries(options.extra)) {
|
|
35
|
+
if (value === undefined) {
|
|
36
|
+
Reflect.deleteProperty(process.env, key);
|
|
37
|
+
} else {
|
|
38
|
+
process.env[key] = value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (options.deleteKeys) {
|
|
44
|
+
for (const key of options.deleteKeys) {
|
|
45
|
+
Reflect.deleteProperty(process.env, key);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
setupTestEnvironment();
|
|
50
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import express from "express";
|
|
3
|
+
|
|
4
|
+
import {authAsUser} from "./authAsUser";
|
|
5
|
+
import {getBaseServer} from "./getBaseServer";
|
|
6
|
+
|
|
7
|
+
describe("authAsUser", () => {
|
|
8
|
+
it("returns an agent with Bearer authorization after login", async () => {
|
|
9
|
+
const app = getBaseServer();
|
|
10
|
+
app.use(express.json());
|
|
11
|
+
app.post("/auth/login", (req, res) => {
|
|
12
|
+
const {email, password} = req.body as {email?: string; password?: string};
|
|
13
|
+
if (email === "user@test.com" && password === "secret") {
|
|
14
|
+
res.json({data: {token: "test-token-123"}});
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
res.status(401).json({error: "Invalid credentials"});
|
|
18
|
+
});
|
|
19
|
+
app.get("/protected", (req, res) => {
|
|
20
|
+
res.json({authorization: req.headers.authorization});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const agent = await authAsUser(app, {email: "user@test.com", password: "secret"});
|
|
24
|
+
const response = await agent.get("/protected").expect(200);
|
|
25
|
+
|
|
26
|
+
expect(response.body.authorization).toBe("Bearer test-token-123");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("throws when the login response does not include a token", async () => {
|
|
30
|
+
const app = getBaseServer();
|
|
31
|
+
app.use(express.json());
|
|
32
|
+
app.post("/auth/login", (_req, res) => {
|
|
33
|
+
res.json({data: {}});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
await expect(
|
|
37
|
+
authAsUser(app, {email: "user@test.com", password: "secret"})
|
|
38
|
+
).rejects.toThrow('authAsUser: expected string token at response path "data.token"');
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
import supertest from "supertest";
|
|
3
|
+
import type TestAgent from "supertest/lib/agent";
|
|
4
|
+
|
|
5
|
+
export interface AuthUserCredentials {
|
|
6
|
+
email: string;
|
|
7
|
+
password: string;
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface AuthAsUserOptions {
|
|
12
|
+
loginPath?: string;
|
|
13
|
+
tokenPath?: string;
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
headers?: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Logs in via POST /auth/login (by default) and returns a supertest agent with Bearer auth.
|
|
20
|
+
*/
|
|
21
|
+
export const authAsUser = async (
|
|
22
|
+
app: express.Application,
|
|
23
|
+
credentials: AuthUserCredentials,
|
|
24
|
+
options: AuthAsUserOptions = {}
|
|
25
|
+
): Promise<TestAgent> => {
|
|
26
|
+
const loginPath = options.loginPath ?? "/auth/login";
|
|
27
|
+
const tokenPath = options.tokenPath ?? "data.token";
|
|
28
|
+
const timeoutMs = options.timeoutMs ?? 5000;
|
|
29
|
+
|
|
30
|
+
const agent = supertest.agent(app);
|
|
31
|
+
const request = agent.post(loginPath).send({
|
|
32
|
+
email: credentials.email,
|
|
33
|
+
password: credentials.password,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
if (timeoutMs > 0) {
|
|
37
|
+
request.timeout(timeoutMs);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const res = await request.expect(200);
|
|
41
|
+
const token = tokenPath.split(".").reduce<unknown>((value, key) => {
|
|
42
|
+
if (value && typeof value === "object" && key in (value as Record<string, unknown>)) {
|
|
43
|
+
return (value as Record<string, unknown>)[key];
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}, res.body);
|
|
47
|
+
|
|
48
|
+
if (typeof token !== "string" || !token) {
|
|
49
|
+
throw new Error(`authAsUser: expected string token at response path "${tokenPath}"`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const headers = {...options.headers, ...credentials.headers};
|
|
53
|
+
await agent.set("authorization", `Bearer ${token}`);
|
|
54
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
55
|
+
await agent.set(key, value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return agent;
|
|
59
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
|
|
3
|
+
import {getBaseServer} from "./getBaseServer";
|
|
4
|
+
|
|
5
|
+
describe("getBaseServer", () => {
|
|
6
|
+
it("creates an express app with json parsing enabled", async () => {
|
|
7
|
+
const app = getBaseServer();
|
|
8
|
+
app.get("/ping", (_req, res) => {
|
|
9
|
+
res.json({ok: true});
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
const server = app.listen(0);
|
|
13
|
+
const address = server.address();
|
|
14
|
+
const port = typeof address === "object" && address ? address.port : 0;
|
|
15
|
+
|
|
16
|
+
const response = await fetch(`http://127.0.0.1:${port}/ping`);
|
|
17
|
+
expect(response.status).toBe(200);
|
|
18
|
+
await response.json();
|
|
19
|
+
|
|
20
|
+
await new Promise<void>((resolve, reject) => {
|
|
21
|
+
server.close((error) => {
|
|
22
|
+
if (error) {
|
|
23
|
+
reject(error);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
resolve();
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import express, {type Express} from "express";
|
|
2
|
+
import qs from "qs";
|
|
3
|
+
|
|
4
|
+
export interface GetBaseServerOptions {
|
|
5
|
+
enableCors?: boolean;
|
|
6
|
+
patchOpenApiCompat?: (app: express.Application) => void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Minimal Express app for supertest with qs query parsing (Express 5 compatible).
|
|
11
|
+
*/
|
|
12
|
+
export const getBaseServer = (options: GetBaseServerOptions = {}): Express => {
|
|
13
|
+
const app = express();
|
|
14
|
+
app.set("query parser", (str: string) => qs.parse(str, {arrayLimit: 200}));
|
|
15
|
+
|
|
16
|
+
if (options.patchOpenApiCompat) {
|
|
17
|
+
options.patchOpenApiCompat(app);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (options.enableCors !== false) {
|
|
21
|
+
app.use((req, res, next) => {
|
|
22
|
+
res.header("Access-Control-Allow-Origin", "*");
|
|
23
|
+
res.header("Access-Control-Allow-Headers", "*");
|
|
24
|
+
if (req.method === "OPTIONS") {
|
|
25
|
+
res.send(200);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
next();
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
app.use(express.json());
|
|
33
|
+
return app;
|
|
34
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export {
|
|
2
|
+
ensureMongoBinary,
|
|
3
|
+
} from "./mongo/ensureMongoBinary";
|
|
4
|
+
|
|
5
|
+
export {setTerrenoTestEnv, type TerrenoTestEnvOptions} from "./env/setTerrenoTestEnv";
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
DEFAULT_LOCAL_MONGO_URI,
|
|
9
|
+
buildDatabaseUri,
|
|
10
|
+
ensureTestMongooseConnected,
|
|
11
|
+
splitMongoUri,
|
|
12
|
+
type EnsureTestMongooseConnectedOptions,
|
|
13
|
+
type SplitMongoUriResult,
|
|
14
|
+
} from "./mongo/connection";
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
getMongoServerUri,
|
|
18
|
+
initializeModels,
|
|
19
|
+
restartMongoServer,
|
|
20
|
+
startMongoServer,
|
|
21
|
+
stopMongoServer,
|
|
22
|
+
waitForDatabaseReady,
|
|
23
|
+
type MemoryMongoHandle,
|
|
24
|
+
type MongoServerOptions,
|
|
25
|
+
} from "./mongo/mongoServer";
|
|
26
|
+
|
|
27
|
+
export {createMongoTestCache, type MongoTestCacheController, type MongoTestCacheOptions} from "./cache/mongoTestCache";
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
abortTestTransaction,
|
|
31
|
+
getTestSession,
|
|
32
|
+
installTransactionPatches,
|
|
33
|
+
resetTestSessionAfterReconnect,
|
|
34
|
+
startTestTransaction,
|
|
35
|
+
} from "./transaction/testTransaction";
|
|
36
|
+
|
|
37
|
+
export {createLogSilencer, registerLogSilencing, type SilenceLogsController, type SilenceLogsOptions} from "./logging/silenceLogs";
|
|
38
|
+
|
|
39
|
+
export {registerSentryBunMock} from "./mocks/sentryBun";
|
|
40
|
+
|
|
41
|
+
export {authAsUser, type AuthAsUserOptions, type AuthUserCredentials} from "./http/authAsUser";
|
|
42
|
+
export {getBaseServer, type GetBaseServerOptions} from "./http/getBaseServer";
|
|
43
|
+
|
|
44
|
+
export {ensureAllIndexes} from "./utils/ensureAllIndexes";
|
|
45
|
+
export {timeout} from "./utils/timeout";
|
|
46
|
+
export {waitForDocument, waitForDocuments, type WaitForDocumentsOptions} from "./utils/waitForDocuments";
|
|
47
|
+
|
|
48
|
+
export {
|
|
49
|
+
registerBackendPreload,
|
|
50
|
+
registerSimpleMongoPreload,
|
|
51
|
+
type BackendPreloadOptions,
|
|
52
|
+
type SimpleMongoPreloadOptions,
|
|
53
|
+
} from "./preload/registerBackendPreload";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Minimal auth env validation for backend tests (mirrors @terreno/api setupEnvironment). */
|
|
2
|
+
export const setupTestEnvironment = (): void => {
|
|
3
|
+
if (!process.env.TOKEN_ISSUER) {
|
|
4
|
+
throw new Error("TOKEN_ISSUER must be set in env.");
|
|
5
|
+
}
|
|
6
|
+
if (!process.env.TOKEN_SECRET) {
|
|
7
|
+
throw new Error("TOKEN_SECRET must be set.");
|
|
8
|
+
}
|
|
9
|
+
if (!process.env.REFRESH_TOKEN_SECRET) {
|
|
10
|
+
throw new Error("REFRESH_TOKEN_SECRET must be set.");
|
|
11
|
+
}
|
|
12
|
+
if (!process.env.SESSION_SECRET) {
|
|
13
|
+
throw new Error("SESSION_SECRET must be set.");
|
|
14
|
+
}
|
|
15
|
+
};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
|
+
import {afterEach, beforeEach} from "bun:test";
|
|
3
|
+
import {Writable} from "node:stream";
|
|
4
|
+
import winston from "winston";
|
|
5
|
+
|
|
6
|
+
export interface SilenceLogsOptions {
|
|
7
|
+
showAllLogs?: boolean;
|
|
8
|
+
/** Extra winston loggers to silence (e.g. @terreno/api winstonLogger). */
|
|
9
|
+
additionalWinstonLoggers?: winston.Logger[];
|
|
10
|
+
onBeforeEach?: () => void;
|
|
11
|
+
onAfterEach?: () => void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SilenceLogsController {
|
|
15
|
+
getLogs: () => string[];
|
|
16
|
+
clearLogs: () => void;
|
|
17
|
+
restore: () => void;
|
|
18
|
+
reapply: () => void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const getApiWinstonLogger = (): winston.Logger | undefined => {
|
|
22
|
+
try {
|
|
23
|
+
// Runtime-only so @terreno/test compiles without @terreno/api.
|
|
24
|
+
// biome-ignore lint/suspicious/noExplicitAny: optional peer resolved at preload time
|
|
25
|
+
const api = require("@terreno/api") as any;
|
|
26
|
+
return api.winstonLogger as winston.Logger | undefined;
|
|
27
|
+
} catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const createLogStream = (logs: string[], showAllLogs: boolean): Writable => {
|
|
33
|
+
return new Writable({
|
|
34
|
+
write(chunk: unknown, _encoding: unknown, callback: () => void) {
|
|
35
|
+
const text = String(chunk);
|
|
36
|
+
logs.push(text);
|
|
37
|
+
if (showAllLogs) {
|
|
38
|
+
process.stdout.write(text);
|
|
39
|
+
}
|
|
40
|
+
callback();
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Silences winston and console output during tests while capturing log lines in memory.
|
|
47
|
+
*/
|
|
48
|
+
export const createLogSilencer = (options: SilenceLogsOptions = {}): SilenceLogsController => {
|
|
49
|
+
const showAllLogs = options.showAllLogs ?? process.env.SHOW_ALL_TEST_LOGS === "true";
|
|
50
|
+
let logs: string[] = [];
|
|
51
|
+
|
|
52
|
+
const originalConsole = {
|
|
53
|
+
debug: console.debug,
|
|
54
|
+
error: console.error,
|
|
55
|
+
info: console.info,
|
|
56
|
+
// biome-ignore lint/suspicious/noConsole: preserve original reference
|
|
57
|
+
log: console.log,
|
|
58
|
+
warn: console.warn,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const logStream = createLogStream(logs, showAllLogs);
|
|
62
|
+
const silentTransport = new winston.transports.Stream({
|
|
63
|
+
format: winston.format.simple(),
|
|
64
|
+
stream: logStream,
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const captureConsoleMethod = (method: keyof typeof originalConsole): void => {
|
|
68
|
+
(console as any)[method] = (...args: any[]) => {
|
|
69
|
+
const logMessage = `[console.${method}] ${args
|
|
70
|
+
.map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : String(arg)))
|
|
71
|
+
.join(" ")}`;
|
|
72
|
+
logs.push(logMessage);
|
|
73
|
+
if (showAllLogs) {
|
|
74
|
+
originalConsole[method](...args);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const applySilencing = (): void => {
|
|
80
|
+
winston.clear();
|
|
81
|
+
winston.add(silentTransport);
|
|
82
|
+
|
|
83
|
+
const extraLoggers = [
|
|
84
|
+
...(options.additionalWinstonLoggers ?? []),
|
|
85
|
+
getApiWinstonLogger(),
|
|
86
|
+
].filter(Boolean) as winston.Logger[];
|
|
87
|
+
|
|
88
|
+
for (const extraLogger of extraLoggers) {
|
|
89
|
+
extraLogger.clear();
|
|
90
|
+
extraLogger.add(silentTransport);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
captureConsoleMethod("log");
|
|
94
|
+
captureConsoleMethod("info");
|
|
95
|
+
captureConsoleMethod("warn");
|
|
96
|
+
captureConsoleMethod("error");
|
|
97
|
+
captureConsoleMethod("debug");
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
applySilencing();
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
clearLogs: (): void => {
|
|
104
|
+
logs = [];
|
|
105
|
+
},
|
|
106
|
+
getLogs: (): string[] => logs,
|
|
107
|
+
reapply: applySilencing,
|
|
108
|
+
restore: (): void => {
|
|
109
|
+
console.debug = originalConsole.debug;
|
|
110
|
+
console.error = originalConsole.error;
|
|
111
|
+
console.info = originalConsole.info;
|
|
112
|
+
console.log = originalConsole.log;
|
|
113
|
+
console.warn = originalConsole.warn;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** Registers beforeEach/afterEach hooks that silence logs and clear the capture buffer. */
|
|
119
|
+
export const registerLogSilencing = (options: SilenceLogsOptions = {}): SilenceLogsController => {
|
|
120
|
+
const silencer = createLogSilencer(options);
|
|
121
|
+
|
|
122
|
+
beforeEach(() => {
|
|
123
|
+
options.onBeforeEach?.();
|
|
124
|
+
silencer.reapply();
|
|
125
|
+
silencer.clearLogs();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
afterEach(() => {
|
|
129
|
+
silencer.clearLogs();
|
|
130
|
+
options.onAfterEach?.();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
return silencer;
|
|
134
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Lightweight logger for @terreno/test internals (avoids importing @terreno/api). */
|
|
2
|
+
export const testLogger = {
|
|
3
|
+
catch: (error: unknown): void => {
|
|
4
|
+
if (process.env.DEBUG_MONGO_PRELOAD === "true" || process.env.SHOW_ALL_TEST_LOGS === "true") {
|
|
5
|
+
console.error(error);
|
|
6
|
+
}
|
|
7
|
+
},
|
|
8
|
+
debug: (message: string): void => {
|
|
9
|
+
if (process.env.DEBUG_MONGO_PRELOAD === "true") {
|
|
10
|
+
console.debug(message);
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
info: (message: string): void => {
|
|
14
|
+
console.info(message);
|
|
15
|
+
},
|
|
16
|
+
warn: (message: string): void => {
|
|
17
|
+
console.warn(message);
|
|
18
|
+
},
|
|
19
|
+
};
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
|
+
import {mock} from "bun:test";
|
|
3
|
+
|
|
4
|
+
/** Registers a global `mock.module("@sentry/bun", ...)` for backend tests. */
|
|
5
|
+
export const registerSentryBunMock = (): void => {
|
|
6
|
+
mock.module("@sentry/bun", () => {
|
|
7
|
+
const mockFn = (): ReturnType<typeof mock> => mock(() => {});
|
|
8
|
+
|
|
9
|
+
const mockScope = {
|
|
10
|
+
addBreadcrumb: mockFn(),
|
|
11
|
+
clear: mockFn(),
|
|
12
|
+
getSpan: mockFn(),
|
|
13
|
+
setContext: mockFn(),
|
|
14
|
+
setFingerprint: mockFn(),
|
|
15
|
+
setLevel: mockFn(),
|
|
16
|
+
setSpan: mockFn(),
|
|
17
|
+
setTag: mockFn(),
|
|
18
|
+
setTags: mockFn(),
|
|
19
|
+
setTransactionName: mockFn(),
|
|
20
|
+
setUser: mockFn(),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const mockClient = {
|
|
24
|
+
captureException: mockFn(),
|
|
25
|
+
captureMessage: mockFn(),
|
|
26
|
+
close: mock(() => Promise.resolve(true)),
|
|
27
|
+
flush: mock(() => Promise.resolve(true)),
|
|
28
|
+
getOptions: mock(() => ({})),
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const mockHub = {
|
|
32
|
+
addBreadcrumb: mockFn(),
|
|
33
|
+
captureException: mockFn(),
|
|
34
|
+
captureMessage: mockFn(),
|
|
35
|
+
configureScope: mockFn(),
|
|
36
|
+
getClient: mock(() => mockClient),
|
|
37
|
+
getScope: mock(() => mockScope),
|
|
38
|
+
popScope: mockFn(),
|
|
39
|
+
pushScope: mockFn(),
|
|
40
|
+
setContext: mockFn(),
|
|
41
|
+
setTag: mockFn(),
|
|
42
|
+
setTags: mockFn(),
|
|
43
|
+
setUser: mockFn(),
|
|
44
|
+
withScope: mockFn(),
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const mockSpan: any = {
|
|
48
|
+
finish: mockFn(),
|
|
49
|
+
setData: mockFn(),
|
|
50
|
+
setStatus: mockFn(),
|
|
51
|
+
setTag: mockFn(),
|
|
52
|
+
startChild: mockFn(),
|
|
53
|
+
toTraceparent: mock(() => "mock-trace-parent"),
|
|
54
|
+
};
|
|
55
|
+
mockSpan.startChild = mock(() => mockSpan);
|
|
56
|
+
|
|
57
|
+
const mockTransaction = {
|
|
58
|
+
finish: mockFn(),
|
|
59
|
+
setData: mockFn(),
|
|
60
|
+
setName: mockFn(),
|
|
61
|
+
setStatus: mockFn(),
|
|
62
|
+
setTag: mockFn(),
|
|
63
|
+
startChild: mock(() => mockSpan),
|
|
64
|
+
toTraceparent: mock(() => "mock-trace-parent"),
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const handlers = {
|
|
68
|
+
errorHandler: mock(() => (err: any, _req: any, _res: any, next: any) => next(err)),
|
|
69
|
+
requestHandler: mock(() => (_req: any, _res: any, next: any) => next()),
|
|
70
|
+
tracingHandler: mock(() => (_req: any, _res: any, next: any) => next()),
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
addBreadcrumb: mockFn(),
|
|
75
|
+
captureException: mockFn(),
|
|
76
|
+
captureMessage: mockFn(),
|
|
77
|
+
clearScope: mockFn(),
|
|
78
|
+
close: mock(() => Promise.resolve(true)),
|
|
79
|
+
configureScope: mockFn(),
|
|
80
|
+
default: {
|
|
81
|
+
addBreadcrumb: mockFn(),
|
|
82
|
+
captureException: mockFn(),
|
|
83
|
+
captureMessage: mockFn(),
|
|
84
|
+
clearScope: mockFn(),
|
|
85
|
+
close: mock(() => Promise.resolve(true)),
|
|
86
|
+
configureScope: mockFn(),
|
|
87
|
+
flush: mock(() => Promise.resolve(true)),
|
|
88
|
+
getClient: mock(() => mockClient),
|
|
89
|
+
getCurrentHub: mock(() => mockHub),
|
|
90
|
+
getCurrentScope: mock(() => mockScope),
|
|
91
|
+
Handlers: handlers,
|
|
92
|
+
init: mockFn(),
|
|
93
|
+
isInitialized: mock(() => true),
|
|
94
|
+
popScope: mockFn(),
|
|
95
|
+
pushScope: mockFn(),
|
|
96
|
+
Severity: {
|
|
97
|
+
Debug: "debug",
|
|
98
|
+
Error: "error",
|
|
99
|
+
Fatal: "fatal",
|
|
100
|
+
Info: "info",
|
|
101
|
+
Warning: "warning",
|
|
102
|
+
} as const,
|
|
103
|
+
setContext: mockFn(),
|
|
104
|
+
setFingerprint: mockFn(),
|
|
105
|
+
setLevel: mockFn(),
|
|
106
|
+
setTag: mockFn(),
|
|
107
|
+
setTags: mockFn(),
|
|
108
|
+
setUser: mockFn(),
|
|
109
|
+
setupExpressErrorHandler: mockFn(),
|
|
110
|
+
startTransaction: mock(() => mockTransaction),
|
|
111
|
+
withScope: mock((callback: any) => callback(mockScope)),
|
|
112
|
+
},
|
|
113
|
+
flush: mock(() => Promise.resolve(true)),
|
|
114
|
+
getClient: mock(() => mockClient),
|
|
115
|
+
getCurrentHub: mock(() => mockHub),
|
|
116
|
+
getCurrentScope: mock(() => mockScope),
|
|
117
|
+
Handlers: handlers,
|
|
118
|
+
init: mockFn(),
|
|
119
|
+
isInitialized: mock(() => true),
|
|
120
|
+
popScope: mockFn(),
|
|
121
|
+
pushScope: mockFn(),
|
|
122
|
+
Severity: {
|
|
123
|
+
Debug: "debug",
|
|
124
|
+
Error: "error",
|
|
125
|
+
Fatal: "fatal",
|
|
126
|
+
Info: "info",
|
|
127
|
+
Warning: "warning",
|
|
128
|
+
} as const,
|
|
129
|
+
setContext: mockFn(),
|
|
130
|
+
setFingerprint: mockFn(),
|
|
131
|
+
setLevel: mockFn(),
|
|
132
|
+
setTag: mockFn(),
|
|
133
|
+
setTags: mockFn(),
|
|
134
|
+
setUser: mockFn(),
|
|
135
|
+
setupExpressErrorHandler: mockFn(),
|
|
136
|
+
startTransaction: mock(() => mockTransaction),
|
|
137
|
+
withScope: mock((callback: any) => callback(mockScope)),
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
|
|
3
|
+
import {buildDatabaseUri, splitMongoUri} from "./connection";
|
|
4
|
+
import {setTerrenoTestEnv} from "../env/setTerrenoTestEnv";
|
|
5
|
+
|
|
6
|
+
describe("mongo connection helpers", () => {
|
|
7
|
+
it("splitMongoUri separates base URI and query options", () => {
|
|
8
|
+
const result = splitMongoUri("mongodb://127.0.0.1/mydb?retryWrites=true");
|
|
9
|
+
expect(result.baseUri).toBe("mongodb://127.0.0.1");
|
|
10
|
+
expect(result.uriOptions).toBe("?retryWrites=true");
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it("buildDatabaseUri appends database name and preserves query params", () => {
|
|
14
|
+
const uri = buildDatabaseUri({
|
|
15
|
+
databaseName: "terrenoTest_base",
|
|
16
|
+
uri: "mongodb://127.0.0.1/?retryWrites=true",
|
|
17
|
+
});
|
|
18
|
+
expect(uri).toBe("mongodb://127.0.0.1/terrenoTest_base?retryWrites=true");
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe("setTerrenoTestEnv", () => {
|
|
23
|
+
it("sets canonical auth env keys", () => {
|
|
24
|
+
setTerrenoTestEnv({tokenIssuer: "unit.test"});
|
|
25
|
+
expect(process.env.TOKEN_SECRET).toBe("secret");
|
|
26
|
+
expect(process.env.TOKEN_ISSUER).toBe("unit.test");
|
|
27
|
+
expect(process.env.SESSION_SECRET).toBe("sessionSecret");
|
|
28
|
+
expect(process.env.REFRESH_TOKEN_SECRET).toBe("refreshTokenSecret");
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import mongoose from "mongoose";
|
|
2
|
+
|
|
3
|
+
import {testLogger} from "../logging/testLogger";
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_LOCAL_MONGO_URI = "mongodb://127.0.0.1/terreno?&connectTimeoutMS=360000";
|
|
6
|
+
|
|
7
|
+
export interface SplitMongoUriResult {
|
|
8
|
+
baseUri: string;
|
|
9
|
+
uriOptions: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const splitMongoUri = (uri: string): SplitMongoUriResult => {
|
|
13
|
+
const [uriWithoutQuery, query] = uri.split("?");
|
|
14
|
+
const lastSlashIndex = uriWithoutQuery.lastIndexOf("/");
|
|
15
|
+
const baseUri =
|
|
16
|
+
lastSlashIndex > "mongodb://".length
|
|
17
|
+
? uriWithoutQuery.slice(0, lastSlashIndex)
|
|
18
|
+
: uriWithoutQuery;
|
|
19
|
+
const uriOptions = query ? `?${query}` : "";
|
|
20
|
+
return {baseUri, uriOptions};
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const buildDatabaseUri = ({
|
|
24
|
+
uri,
|
|
25
|
+
databaseName,
|
|
26
|
+
}: {
|
|
27
|
+
uri: string;
|
|
28
|
+
databaseName: string;
|
|
29
|
+
}): string => {
|
|
30
|
+
const [uriWithoutQuery, queryParams] = uri.split("?");
|
|
31
|
+
const normalizedUri = uriWithoutQuery.endsWith("/") ? uriWithoutQuery : `${uriWithoutQuery}/`;
|
|
32
|
+
if (queryParams) {
|
|
33
|
+
return `${normalizedUri}${databaseName}?${queryParams}`;
|
|
34
|
+
}
|
|
35
|
+
return `${normalizedUri}${databaseName}`;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export interface EnsureTestMongooseConnectedOptions {
|
|
39
|
+
defaultUri?: string;
|
|
40
|
+
onConnectError?: (error: unknown) => void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Ensures Mongoose is connected without replacing an existing test connection. */
|
|
44
|
+
export const ensureTestMongooseConnected = async (
|
|
45
|
+
options: EnsureTestMongooseConnectedOptions = {}
|
|
46
|
+
): Promise<void> => {
|
|
47
|
+
if (mongoose.connection.readyState === 1) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (mongoose.connection.readyState === 2) {
|
|
51
|
+
await mongoose.connection.asPromise();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const uri = process.env.TERRENO_TEST_MONGODB_URI?.trim() || options.defaultUri || DEFAULT_LOCAL_MONGO_URI;
|
|
56
|
+
try {
|
|
57
|
+
await mongoose.connect(uri);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (options.onConnectError) {
|
|
60
|
+
options.onConnectError(error);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
testLogger.catch(error);
|
|
64
|
+
}
|
|
65
|
+
};
|