Automatiska tester, och rättningar som testerna hittade
Vitest med enhetstester utan databas och databastester mot en egen testdatabas vars namn måste sluta på _test. Rättar tomma MAP_*-värden i .env och säkerhetskopior med å, ä och ö i filnamnet. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4e8d79ee10
commit
dcb5d43429
30 files changed
+2872
-13
No files matched your search
@@ -0,0 +1,135 @@
|
||||
import { mkdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { BACKUP_DIR, BACKUP_FILE_PATTERN, BACKUP_KEEP, backupDue, failStaleRuns, listBackups, runBackup, safeName } from "@/lib/backup";
|
||||
import { importBook, readImportFile } from "@/lib/book-transfer";
|
||||
import { saveImageBytes } from "@/lib/files";
|
||||
import { makeImage } from "../helpers/fixtures";
|
||||
import { describeDb, makeBook, makeEntity, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
describeDb("säkerhetskopiering", () => {
|
||||
let ownerId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
ownerId = (await makeUser()).id;
|
||||
});
|
||||
|
||||
it("sparar en zip per bok och en indexfil, och loggar körningen", async () => {
|
||||
const image = await saveImageBytes(await makeImage(60, 40, "png"));
|
||||
const a = await makeBook(ownerId, "Första boken");
|
||||
const b = await makeBook(ownerId, "Andra boken");
|
||||
await makeEntity(a.id, "CHARACTER", "Anna", { imageFile: image });
|
||||
await makeEntity(b.id, "CHARACTER", "Bo");
|
||||
|
||||
const runId = await runBackup("manual");
|
||||
const run = await prisma.backupRun.findUniqueOrThrow({ where: { id: runId } });
|
||||
expect(run).toMatchObject({ status: "ok", trigger: "manual", books: 2, error: null });
|
||||
expect(run.finishedAt).not.toBeNull();
|
||||
|
||||
const [folder] = await listBackups();
|
||||
expect(folder.folder).toBe(run.folder);
|
||||
// Filnamnen är ASCII (Första blir Forsta), annars kan de inte listas eller laddas ner
|
||||
expect(folder.files.map((f) => f.name).sort()).toEqual([`Andra-boken-${b.id.slice(-8)}.zip`, `Forsta-boken-${a.id.slice(-8)}.zip`, "index.json"].sort());
|
||||
|
||||
const index = JSON.parse(await readFile(path.join(BACKUP_DIR, folder.folder, "index.json"), "utf8")) as { books: { title: string; file: string }[] };
|
||||
expect(index.books.map((x) => x.title)).toEqual(["Första boken", "Andra boken"]);
|
||||
});
|
||||
|
||||
it("filnamn av boktitlar blir alltid giltiga för nedladdning", () => {
|
||||
expect(safeName("Skuggor över Lund")).toBe("Skuggor-over-Lund");
|
||||
expect(safeName("Åsa & Örjan: del 2")).toBe("Asa-Orjan-del-2");
|
||||
expect(safeName(" ")).toBe("bok");
|
||||
expect(safeName("日本語")).toBe("bok");
|
||||
expect(safeName("x".repeat(200))).toHaveLength(50);
|
||||
for (const title of ["Skuggor över Lund", "Åsa/Örjan", "../../etc/passwd", "a b.c"]) {
|
||||
expect(`${safeName(title)}-cmvabcde.zip`).toMatch(BACKUP_FILE_PATTERN);
|
||||
}
|
||||
});
|
||||
|
||||
it("zip-filerna går att importera igen, med bilder", async () => {
|
||||
const image = await saveImageBytes(await makeImage(60, 40, "png"));
|
||||
const book = await makeBook(ownerId, "Min bok");
|
||||
const anna = await makeEntity(book.id, "CHARACTER", "Anna", { imageFile: image });
|
||||
const erik = await makeEntity(book.id, "CHARACTER", "Erik");
|
||||
await makeRelation(book.id, anna.id, erik.id);
|
||||
|
||||
await runBackup("schedule");
|
||||
const [folder] = await listBackups();
|
||||
const zip = folder.files.find((f) => f.name.endsWith(".zip"))!;
|
||||
const { data, files } = readImportFile(new Uint8Array(await readFile(path.join(BACKUP_DIR, folder.folder, zip.name))));
|
||||
const result = await importBook(ownerId, data, files);
|
||||
|
||||
expect(result).toMatchObject({ entities: 2, relations: 1, skippedImages: 0 });
|
||||
expect((await prisma.entity.findFirstOrThrow({ where: { bookId: result.bookId, name: "Anna" } })).imageFile).toBeTruthy();
|
||||
});
|
||||
|
||||
it("fungerar även utan några böcker", async () => {
|
||||
const runId = await runBackup("schedule");
|
||||
expect(await prisma.backupRun.findUniqueOrThrow({ where: { id: runId } })).toMatchObject({ status: "ok", books: 0 });
|
||||
});
|
||||
|
||||
it(`behåller bara de ${BACKUP_KEEP} senaste körningarna`, async () => {
|
||||
await makeBook(ownerId, "Bok");
|
||||
// Äldre mappar med tidsstämpelnamn, äldre än dagens körning
|
||||
for (let day = 1; day <= BACKUP_KEEP + 1; day++) {
|
||||
await mkdir(path.join(BACKUP_DIR, `2020-01-${String(day).padStart(2, "0")}T03-00-00`), { recursive: true });
|
||||
}
|
||||
await runBackup("schedule");
|
||||
|
||||
const folders = (await listBackups()).map((f) => f.folder);
|
||||
expect(folders).toHaveLength(BACKUP_KEEP);
|
||||
expect(folders).not.toContain("2020-01-01T03-00-00"); // äldst är borttagen
|
||||
expect(folders).not.toContain("2020-01-02T03-00-00");
|
||||
expect(folders[0] > "2020").toBe(true); // nyaste först
|
||||
});
|
||||
|
||||
it("listBackups ignorerar mappar och filer som inte är säkerhetskopior", async () => {
|
||||
await mkdir(path.join(BACKUP_DIR, "vad-som-helst"), { recursive: true });
|
||||
await mkdir(path.join(BACKUP_DIR, "2021-05-05T03-00-00"), { recursive: true });
|
||||
const folders = await listBackups();
|
||||
expect(folders.map((f) => f.folder)).toEqual(["2021-05-05T03-00-00"]);
|
||||
});
|
||||
|
||||
describe("backupDue", () => {
|
||||
const at = (hour: number) => new Date(2026, 5, 15, hour, 0, 0);
|
||||
const runAt = (hour: number, status: string) => prisma.backupRun.create({ data: { trigger: "schedule", status, startedAt: at(hour) } });
|
||||
|
||||
it("är inte aktuell före inställd timme", async () => {
|
||||
expect(await backupDue(at(2))).toBe(false);
|
||||
});
|
||||
|
||||
it("är aktuell efter inställd timme när ingen körning gjorts i dag", async () => {
|
||||
expect(await backupDue(at(3))).toBe(true);
|
||||
expect(await backupDue(at(23))).toBe(true);
|
||||
});
|
||||
|
||||
it("är inte aktuell när en körning redan lyckats eller pågår i dag", async () => {
|
||||
await runAt(3, "ok");
|
||||
expect(await backupDue(at(10))).toBe(false);
|
||||
});
|
||||
|
||||
it("pågående körning hindrar en ny", async () => {
|
||||
await runAt(4, "running");
|
||||
expect(await backupDue(at(10))).toBe(false);
|
||||
});
|
||||
|
||||
it("försöker igen efter en misslyckad körning", async () => {
|
||||
await runAt(3, "error");
|
||||
expect(await backupDue(at(10))).toBe(true);
|
||||
});
|
||||
|
||||
it("en körning från igår räknas inte", async () => {
|
||||
await prisma.backupRun.create({ data: { trigger: "schedule", status: "ok", startedAt: new Date(2026, 5, 14, 3, 0, 0) } });
|
||||
expect(await backupDue(at(10))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("markerar körningar som fastnat som misslyckade", async () => {
|
||||
const stale = await prisma.backupRun.create({ data: { trigger: "schedule", status: "running", startedAt: new Date(Date.now() - 2 * 3600_000) } });
|
||||
const fresh = await prisma.backupRun.create({ data: { trigger: "manual", status: "running" } });
|
||||
await failStaleRuns();
|
||||
expect((await prisma.backupRun.findUniqueOrThrow({ where: { id: stale.id } })).status).toBe("error");
|
||||
expect((await prisma.backupRun.findUniqueOrThrow({ where: { id: fresh.id } })).status).toBe("running");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user