Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
45
packages/khb_common/src/testing/index.ts
Normal file
45
packages/khb_common/src/testing/index.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import pg from "pg";
|
||||
import { createPool, migrate, type Pool } from "../db/index.js";
|
||||
import { readSettingsFile } from "../settings/index.js";
|
||||
|
||||
export interface TestDb {
|
||||
pool: Pool;
|
||||
name: string;
|
||||
drop(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Адрес серверной БД из settings.json5 (или KHB_TEST_DATABASE_URL); null - БД недоступна, интеграционные тесты пропускаются. */
|
||||
export function testDatabaseUrl(): string | null {
|
||||
if (process.env.KHB_TEST_DATABASE_URL) return process.env.KHB_TEST_DATABASE_URL;
|
||||
try {
|
||||
const url = (readSettingsFile().common as { database?: { url?: string } } | undefined)?.database?.url;
|
||||
return url || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Создаёт временную базу llmtest_<random>, применяет миграции, возвращает пул и drop(). */
|
||||
export async function createTestDb(baseUrl: string): Promise<TestDb> {
|
||||
const name = `llmtest_${randomBytes(4).toString("hex")}`;
|
||||
const admin = new pg.Client({ connectionString: baseUrl });
|
||||
await admin.connect();
|
||||
await admin.query(`create database ${name}`);
|
||||
await admin.end();
|
||||
const u = new URL(baseUrl);
|
||||
u.pathname = `/${name}`;
|
||||
const pool = createPool(u.toString(), 4);
|
||||
await migrate(pool);
|
||||
return {
|
||||
pool,
|
||||
name,
|
||||
async drop() {
|
||||
await pool.end();
|
||||
const a = new pg.Client({ connectionString: baseUrl });
|
||||
await a.connect();
|
||||
await a.query(`drop database if exists ${name} with (force)`);
|
||||
await a.end();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user