File size: 2,540 Bytes
3f49e8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { vi, afterAll } from "vitest";
import dotenv from "dotenv";
import { resolve } from "path";
import fs from "fs";
import { MongoMemoryServer } from "mongodb-memory-server";
import { MODELS_FIXTURE, TEST_OPENAI_BASE_URL } from "../../src/lib/server/__fixtures__/models";

let mongoServer: MongoMemoryServer;
// Load the .env file
const envPath = resolve(__dirname, "../../.env");
dotenv.config({ path: envPath });

// Read the .env file content
const envContent = fs.readFileSync(envPath, "utf-8");

// Parse the .env content
const envVars = dotenv.parse(envContent);

// Separate public and private variables
const publicEnv = {};
const privateEnv = {};

for (const [key, value] of Object.entries(envVars)) {
	if (key.startsWith("PUBLIC_")) {
		publicEnv[key] = value;
	} else {
		privateEnv[key] = value;
	}
}

/*
 * Serve the model registry from a fixture instead of the network.
 *
 * `src/lib/server/models.ts` runs `await buildModels()` at module scope, guarded only by
 * `building` — which is false under Vitest. Any spec that transitively imports it therefore
 * used to hit the live upstream. This intercept keeps the real `buildModels()` code path
 * intact (fetch -> zod parse -> capability derivation -> override merge) while removing the
 * third-party dependency. Everything else falls through to the real `fetch`, so specs that
 * genuinely exercise the network (e.g. the SSRF/DNS suites) are unaffected.
 *
 * This must be installed before any module-scope `fetch` runs, which is why it lives in the
 * setup file body rather than in a `beforeAll`.
 */
const realFetch = globalThis.fetch;
const MODELS_URL = `${TEST_OPENAI_BASE_URL}/models`;

globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
	const url = input instanceof Request ? input.url : String(input);

	if (url === MODELS_URL) {
		return new Response(JSON.stringify(MODELS_FIXTURE), {
			status: 200,
			headers: { "content-type": "application/json" },
		});
	}

	return realFetch(input, init);
}) as typeof fetch;

vi.mock("$env/dynamic/public", () => ({
	env: publicEnv,
}));

vi.mock("$env/dynamic/private", async () => {
	mongoServer = await MongoMemoryServer.create();

	return {
		env: {
			...privateEnv,
			MONGODB_URL: mongoServer.getUri(),
			// Pin the model registry at the intercepted fixture host. Must stay in sync with
			// the intercept above.
			OPENAI_BASE_URL: TEST_OPENAI_BASE_URL,
		},
	};
});

afterAll(async () => {
	globalThis.fetch = realFetch;

	if (mongoServer) {
		await mongoServer.stop();
	}
});