import { mkdtemp, writeFile, cp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import type { FastifyInstance } from "fastify"; import { buildApp } from "../src/app.ts"; import { MIGRATIONS_DIR, runMigrations } from "../src/db/migrate.ts"; import { createTestDb } from "./helpers/db.ts"; let app: FastifyInstance | undefined; afterEach(async () => app?.close()); const names = async (db: Awaited>) => (await db.query<{ name: string }>("SELECT name FROM schema_migrations ORDER BY name")).rows.map((r) => r.name); describe("Requirement: Подключение к Postgres из окружения", () => { it("Scenario: БД не настроена", async () => { app = await buildApp(); const res = await app.inject({ method: "POST", url: "/api/auth/login", payload: {} }); expect(res.statusCode).toBe(404); expect(res.json()).toEqual({ error: "not_found" }); expect((await app.inject({ method: "GET", url: "/healthz" })).statusCode).toBe(200); }); it("Scenario: БД настроена", async () => { app = await buildApp({ db: await createTestDb() }); const res = await app.inject({ method: "GET", url: "/api/session" }); expect(res.statusCode).toBe(401); expect(res.json()).toEqual({ error: "unauthenticated" }); }); }); describe("Requirement: Миграции", () => { it("Scenario: Первое применение", async () => { const db = await createTestDb(); const tables = ( await db.query<{ table_name: string }>( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", ) ).rows.map((r) => r.table_name); expect(tables).toEqual(expect.arrayContaining(["organizations", "users", "sessions"])); expect(await names(db)).toContain("0001_accounts"); }); it("Scenario: Повторный запуск", async () => { const db = await createTestDb(); expect(await runMigrations(db)).toEqual([]); expect(await names(db)).toEqual(["0001_accounts"]); }); it("Scenario: Ошибка в миграции", async () => { const db = await createTestDb(); const dir = await mkdtemp(join(tmpdir(), "mig-")); await cp(MIGRATIONS_DIR, dir, { recursive: true }); await writeFile(join(dir, "0002_broken.sql"), "CREATE TABLE ok_table (id int); SELECT * FROM no_such_table;"); await expect(runMigrations(db, dir + "/")).rejects.toThrow(); expect(await names(db)).toEqual(["0001_accounts"]); const r = await db.query("SELECT 1 FROM information_schema.tables WHERE table_name = 'ok_table'"); expect(r.rows).toHaveLength(0); }); });