// 测试环境准备:每个 suite 运行前初始化干净的测试数据库 import { DatabaseSync } from 'node:sqlite' import { mkdirSync } from 'node:fs' import { join, dirname } from 'node:path' import { fileURLToPath } from 'node:url' import { randomUUID } from 'crypto' const __dirname = dirname(fileURLToPath(import.meta.url)) const root = join(__dirname, '../..') const testDataDir = join(root, 'data', 'test-' + randomUUID().slice(0, 8)) mkdirSync(testDataDir, { recursive: true }) const TEST_DB_PATH = join(testDataDir, 'test.db') process.env.API_PORT = '0' // 让系统分配空闲端口 export { TEST_DB_PATH } // ── 初始化 schema ──────────────────────────────────────────────────────────── const db = new DatabaseSync(TEST_DB_PATH) db.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;`) // 复用已有的 migration SQL 来初始化 schema const migrationFiles = [ '001_create_initial_schema.sql', '002_create_audit_logs.sql', '003_create_people.sql', '004_create_stations.sql', '005_create_notices.sql', '006_optimize_indexes.sql', ] for (const file of migrationFiles) { const path = join(root, 'migrations', file) try { const { readFileSync } = await import('node:fs') const sql = readFileSync(path, 'utf-8') db.exec(sql) } catch { // 忽略文件不存在错误 } } // ── 公共 seed 数据 ─────────────────────────────────────────────────────────── const now = new Date().toISOString().slice(0, 10) db.exec(` INSERT INTO stations (code, name, region, address, leader, phone, established_at, status) VALUES ('STAT_BJ', '北京记者站', '华北', '北京市朝阳区', '苏明远', '010-12345678', '${now}', 'active'), ('STAT_SH', '上海记者站', '华东', '上海市浦东新区', '王海涛', '021-87654321', '${now}', 'active'), ('STAT_GZ', '广州记者站', '华南', '广州市天河区', '李娜', '020-11112222', '${now}', 'inactive'); INSERT INTO people (code, name, station, title, phone, joined_at, status) VALUES ('P_BJ_01', '林致远', '北京记者站', '总编辑', '13800000001', '${now}', 'active'), ('P_BJ_02', '苏明远', '北京记者站', '站长', '13800000002', '${now}', 'active'), ('P_BJ_03', '林晓', '北京记者站', '记者', '13800000003', '${now}', 'active'), ('P_SH_01', '王海涛', '上海记者站', '站长', '13900000001', '${now}', 'active'), ('P_SH_02', '张文', '上海记者站', '记者', '13900000002', '${now}', 'active'); INSERT INTO work_records (id, title, type, reporter, station, occurred_date, platform, status, score, description) VALUES ('WK-20260801-0001', '采访人工智能大会', 'interview', '林晓', '北京记者站', '${now}', '新华社客户端', 'archived', 85, '报道 AI 前沿技术'), ('WK-20260801-0002', '深度调研报告', 'report', '林晓', '北京记者站', '${now}', '自主平台', 'archived', 90, '产业调研'), ('WK-20260801-0003', '突发新闻采集', 'news', '林晓', '北京记者站', '${now}', '微博', 'station_review', null, '地震新闻'), ('WK-20260801-0004', '市场分析', 'report', '张文', '上海记者站', '${now}', '财经网站', 'headquarters_review', 78, '金融市场'); `) export default db