79 lines
2.6 KiB
TypeScript
79 lines
2.6 KiB
TypeScript
import type Database from "bun:sqlite";
|
|
|
|
import { describe, expect, test } from "bun:test";
|
|
|
|
import { getSettings, updateSettings } from "../../../src/server/db/settings";
|
|
import { createNoopLogger } from "../../../src/server/logger";
|
|
import { createMigratedTestDatabase } from "../../helpers";
|
|
|
|
function withSettingsDb(callback: (db: Database) => void): void {
|
|
const handle = createMigratedTestDatabase("settings-test");
|
|
try {
|
|
callback(handle.db);
|
|
handle.close();
|
|
} finally {
|
|
handle.cleanup();
|
|
}
|
|
}
|
|
|
|
describe("设置数据访问层", () => {
|
|
test("getSettings 无数据时返回默认值", () => {
|
|
withSettingsDb((db) => {
|
|
const result = getSettings(db);
|
|
expect(result).toEqual({ theme: "system" });
|
|
});
|
|
});
|
|
|
|
test("updateSettings 写入并读取", () => {
|
|
withSettingsDb((db) => {
|
|
const updated = updateSettings(db, { theme: "dark" }, createNoopLogger());
|
|
expect(updated).toEqual({ theme: "dark" });
|
|
|
|
const read = getSettings(db);
|
|
expect(read).toEqual({ theme: "dark" });
|
|
});
|
|
});
|
|
|
|
test("updateSettings 部分更新合并", () => {
|
|
withSettingsDb((db) => {
|
|
updateSettings(db, { theme: "dark" }, createNoopLogger());
|
|
const result = updateSettings(db, { theme: "light" }, createNoopLogger());
|
|
expect(result).toEqual({ theme: "light" });
|
|
});
|
|
});
|
|
|
|
test("getSettings 解析非法 JSON 返回默认值", () => {
|
|
withSettingsDb((db) => {
|
|
db.run(
|
|
"INSERT INTO settings (id, created_at, updated_at, data) VALUES ('default', '2024-01-01T00:00:00.000Z', '2024-01-01T00:00:00.000Z', 'not-json')",
|
|
);
|
|
const result = getSettings(db);
|
|
expect(result).toEqual({ theme: "system" });
|
|
});
|
|
});
|
|
|
|
test("getSettings 未知 theme 值返回默认值", () => {
|
|
withSettingsDb((db) => {
|
|
db.run(
|
|
"INSERT INTO settings (id, created_at, updated_at, data) VALUES ('default', '2024-01-01T00:00:00.000Z', '2024-01-01T00:00:00.000Z', '{\"theme\":\"unknown\"}')",
|
|
);
|
|
const result = getSettings(db);
|
|
expect(result).toEqual({ theme: "system" });
|
|
});
|
|
});
|
|
|
|
test("updateSettings 幂等覆盖", () => {
|
|
withSettingsDb((db) => {
|
|
const a = updateSettings(db, { theme: "dark" }, createNoopLogger());
|
|
const b = updateSettings(db, { theme: "dark" }, createNoopLogger());
|
|
expect(a).toEqual({ theme: "dark" });
|
|
expect(b).toEqual({ theme: "dark" });
|
|
|
|
const row = db
|
|
.query("SELECT COUNT(*) as cnt FROM settings WHERE id = 'default' AND deleted_at IS NULL")
|
|
.get() as { cnt: number };
|
|
expect(row.cnt).toBe(1);
|
|
});
|
|
});
|
|
});
|