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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { beforeEach, expect, it } from "vitest";
|
||||
import { collectFieldData } from "@/lib/field-values";
|
||||
import { MAX_VERSIONS, recordVersion } from "@/lib/history";
|
||||
import type { FieldDef } from "@/lib/templates";
|
||||
import { describeDb, makeBook, makeEntity, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
describeDb("historik", () => {
|
||||
let userId: string;
|
||||
let bookId: string;
|
||||
let entityId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
userId = (await makeUser()).id;
|
||||
bookId = (await makeBook(userId)).id;
|
||||
entityId = (await makeEntity(bookId, "CHARACTER", "Anna")).id;
|
||||
});
|
||||
|
||||
it("sparar versionen med den som ändrade", async () => {
|
||||
await prisma.$transaction((tx) => recordVersion(tx, bookId, entityId, userId, { name: "Gammal", summary: null, tags: [], data: {} }));
|
||||
const [version] = await prisma.entityVersion.findMany({ where: { entityId } });
|
||||
expect(version).toMatchObject({ bookId, entityId, userId });
|
||||
expect(version.snapshot).toMatchObject({ name: "Gammal" });
|
||||
});
|
||||
|
||||
it(`behåller bara de ${MAX_VERSIONS} senaste versionerna`, async () => {
|
||||
for (let i = 1; i <= MAX_VERSIONS + 5; i++) {
|
||||
await prisma.$transaction((tx) => recordVersion(tx, bookId, entityId, userId, { name: `v${i}`, summary: null, tags: [], data: {} }));
|
||||
}
|
||||
const versions = await prisma.entityVersion.findMany({ where: { entityId }, orderBy: { createdAt: "asc" } });
|
||||
expect(versions).toHaveLength(MAX_VERSIONS);
|
||||
const names = versions.map((v) => (v.snapshot as { name: string }).name);
|
||||
expect(names[0]).toBe("v6"); // de fem äldsta är borta
|
||||
expect(names.at(-1)).toBe(`v${MAX_VERSIONS + 5}`);
|
||||
});
|
||||
|
||||
it("rensar bara den aktuella postens versioner", async () => {
|
||||
const other = await makeEntity(bookId, "CHARACTER", "Bo");
|
||||
for (let i = 0; i < MAX_VERSIONS + 2; i++) {
|
||||
await prisma.$transaction((tx) => recordVersion(tx, bookId, entityId, userId, { name: `a${i}`, summary: null, tags: [], data: {} }));
|
||||
}
|
||||
await prisma.$transaction((tx) => recordVersion(tx, bookId, other.id, userId, { name: "b", summary: null, tags: [], data: {} }));
|
||||
expect(await prisma.entityVersion.count({ where: { entityId: other.id } })).toBe(1);
|
||||
});
|
||||
|
||||
it("följer med när boken tas bort", async () => {
|
||||
await prisma.$transaction((tx) => recordVersion(tx, bookId, entityId, userId, { name: "x", summary: null, tags: [], data: {} }));
|
||||
await prisma.book.delete({ where: { id: bookId } });
|
||||
expect(await prisma.entityVersion.count()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describeDb("fältvärden från formulär", () => {
|
||||
let bookId: string;
|
||||
let premisesId: string;
|
||||
let characterId: string;
|
||||
let foreignPremisesId: string;
|
||||
|
||||
const fields: FieldDef[] = [
|
||||
{ key: "name", label: "Text", type: "text" },
|
||||
{ key: "age", label: "Ålder", type: "number" },
|
||||
{ key: "alive", label: "Vid liv", type: "checkbox" },
|
||||
{ key: "premises", label: "Lokal", type: "reference", refKind: "PREMISES" },
|
||||
{ key: "anything", label: "Vad som helst", type: "reference" },
|
||||
];
|
||||
const form = (values: Record<string, string>) => {
|
||||
const data = new FormData();
|
||||
for (const [key, value] of Object.entries(values)) data.set(`f_${key}`, value);
|
||||
return data;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
const user = await makeUser();
|
||||
bookId = (await makeBook(user.id)).id;
|
||||
premisesId = (await makeEntity(bookId, "PREMISES", "Lokal")).id;
|
||||
characterId = (await makeEntity(bookId, "CHARACTER", "Anna")).id;
|
||||
foreignPremisesId = (await makeEntity((await makeBook(user.id, "Annan")).id, "PREMISES", "Främmande")).id;
|
||||
});
|
||||
|
||||
it("läser text, tal och kryssrutor", async () => {
|
||||
const data = await collectFieldData(bookId, fields, form({ name: " Anna ", age: "1,5", alive: "on" }), null);
|
||||
expect(data).toMatchObject({ name: "Anna", age: 1.5, alive: true });
|
||||
});
|
||||
|
||||
it("en ibockad kryssruta som saknas i formuläret blir falsk", async () => {
|
||||
const data = await collectFieldData(bookId, fields, form({ name: "x" }), { alive: true });
|
||||
expect(data.alive).toBe(false);
|
||||
});
|
||||
|
||||
it("tomma fält tas bort och ogiltiga tal ignoreras", async () => {
|
||||
const data = await collectFieldData(bookId, fields, form({ name: "", age: "abc" }), { name: "gammal", age: 5 });
|
||||
expect(data.name).toBeUndefined();
|
||||
expect(data.age).toBe(5); // behåller det tidigare värdet när det nya inte är ett tal
|
||||
});
|
||||
|
||||
it("låter data för fält som inte finns i mallen vara orörd", async () => {
|
||||
const data = await collectFieldData(bookId, fields, form({ name: "x" }), { gammalt: "kvar" });
|
||||
expect(data.gammalt).toBe("kvar");
|
||||
});
|
||||
|
||||
it("godkänner en koppling till rätt typ av post i boken", async () => {
|
||||
const data = await collectFieldData(bookId, fields, form({ premises: premisesId, anything: characterId }), null);
|
||||
expect(data.premises).toBe(premisesId);
|
||||
expect(data.anything).toBe(characterId);
|
||||
});
|
||||
|
||||
it("tar bort kopplingar till fel typ, andra böcker och poster som inte finns", async () => {
|
||||
for (const value of [characterId, foreignPremisesId, "finns-inte"]) {
|
||||
const data = await collectFieldData(bookId, fields, form({ premises: value }), null);
|
||||
expect(data.premises).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { beforeEach, expect, it } from "vitest";
|
||||
import { nextEntityCode, nextMapCode, nextMarkerCode, nextRelationCode, nextScheduleCode } from "@/lib/ids";
|
||||
import { describeDb, makeBook, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
describeDb("löpande ID", () => {
|
||||
let bookId: string;
|
||||
let otherBookId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
const user = await makeUser();
|
||||
bookId = (await makeBook(user.id, "A")).id;
|
||||
otherBookId = (await makeBook(user.id, "B")).id;
|
||||
});
|
||||
|
||||
it("räknar upp per typ i varje bok", async () => {
|
||||
expect(await nextEntityCode(bookId, "CHARACTER")).toBe("KI-0001");
|
||||
expect(await nextEntityCode(bookId, "CHARACTER")).toBe("KI-0002");
|
||||
expect(await nextEntityCode(bookId, "PET")).toBe("DI-0001");
|
||||
expect(await nextEntityCode(bookId, "CHARACTER")).toBe("KI-0003");
|
||||
});
|
||||
|
||||
it("börjar om i en ny bok", async () => {
|
||||
await nextEntityCode(bookId, "CHARACTER");
|
||||
await nextEntityCode(bookId, "CHARACTER");
|
||||
expect(await nextEntityCode(otherBookId, "CHARACTER")).toBe("KI-0001");
|
||||
});
|
||||
|
||||
it("ger inget ID åt typer utan ID", async () => {
|
||||
expect(await nextEntityCode(bookId, "APP")).toBeNull();
|
||||
expect(await nextEntityCode(bookId, "WEBSITE")).toBeNull();
|
||||
expect(await prisma.idCounter.count({ where: { bookId } })).toBe(0);
|
||||
});
|
||||
|
||||
it("använder egna räknare för relationer, placeringar, scheman och kartor", async () => {
|
||||
expect(await nextRelationCode(bookId)).toBe("REI-0001");
|
||||
expect(await nextMarkerCode(bookId)).toBe("PI-0001");
|
||||
expect(await nextScheduleCode(bookId)).toBe("SCI-0001");
|
||||
expect(await nextMapCode(bookId, "GEO")).toBe("KD-R_0001");
|
||||
expect(await nextMapCode(bookId, "IMAGE")).toBe("KD-E_0001");
|
||||
expect(await nextMapCode(bookId, "GEO")).toBe("KD-R_0002");
|
||||
});
|
||||
|
||||
it("ger unika nummer även när många skapas samtidigt", async () => {
|
||||
const codes = await Promise.all(Array.from({ length: 25 }, () => nextEntityCode(bookId, "CHARACTER")));
|
||||
expect(new Set(codes).size).toBe(25);
|
||||
expect(codes.sort()[0]).toBe("KI-0001");
|
||||
expect(codes.sort()[24]).toBe("KI-0025");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { isAdminUser } from "@/lib/admin";
|
||||
import { saveImageBytes } from "@/lib/files";
|
||||
import { trashEntity } from "@/lib/trash";
|
||||
import { userImageNames, userStorageBytes } from "@/lib/storage";
|
||||
import { makeImage } from "../helpers/fixtures";
|
||||
import { describeDb, makeBook, makeEntity, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
// Sökvägen använder inloggningen. Här byter vi ut den mot en användare som testet väljer.
|
||||
const current = vi.hoisted(() => ({ userId: "" as string | null }));
|
||||
vi.mock("@/lib/session", () => ({ getCurrentUser: async () => (current.userId ? { id: current.userId } : null) }));
|
||||
|
||||
describeDb("lagringskvot", () => {
|
||||
beforeEach(resetAll);
|
||||
|
||||
it("räknar bilder på poster, kartor och i papperskorgen, men bara användarens egna", async () => {
|
||||
const me = await makeUser("Jag");
|
||||
const other = await makeUser("Annan");
|
||||
const mine = await makeBook(me.id);
|
||||
const theirs = await makeBook(other.id);
|
||||
|
||||
const a = await saveImageBytes(await makeImage(100, 100, "png"));
|
||||
const b = await saveImageBytes(await makeImage(120, 120, "png"), "map");
|
||||
const c = await saveImageBytes(await makeImage(80, 80, "png"));
|
||||
const foreign = await saveImageBytes(await makeImage(90, 90, "png"));
|
||||
|
||||
await makeEntity(mine.id, "CHARACTER", "Med bild", { imageFile: a });
|
||||
await prisma.bookMap.create({ data: { bookId: mine.id, name: "K", kind: "IMAGE", imageFile: b } });
|
||||
const inTrash = await makeEntity(mine.id, "CHARACTER", "Borttagen", { imageFile: c });
|
||||
await trashEntity(me.id, mine.id, inTrash.id);
|
||||
await makeEntity(theirs.id, "CHARACTER", "Någon annans", { imageFile: foreign });
|
||||
|
||||
expect((await userImageNames(me.id)).sort()).toEqual([a!, b!, c!].sort());
|
||||
expect(await userStorageBytes(me.id)).toBeGreaterThan(0);
|
||||
expect(await userStorageBytes(other.id)).toBeLessThan(await userStorageBytes(me.id));
|
||||
});
|
||||
|
||||
it("räknar noll utan bilder", async () => {
|
||||
const user = await makeUser();
|
||||
expect(await userStorageBytes(user.id)).toBe(0);
|
||||
});
|
||||
|
||||
it("withinQuota följer USER_QUOTA_MB", async () => {
|
||||
vi.stubEnv("USER_QUOTA_MB", "0.0001"); // cirka 100 byte
|
||||
vi.resetModules();
|
||||
const { withinQuota, USER_QUOTA_BYTES } = await import("@/lib/storage");
|
||||
expect(USER_QUOTA_BYTES).toBeLessThan(200);
|
||||
|
||||
const user = await makeUser();
|
||||
const book = await makeBook(user.id);
|
||||
expect(await withinQuota(user.id, 50)).toBe(true);
|
||||
expect(await withinQuota(user.id, 5000)).toBe(false);
|
||||
|
||||
const { saveImageBytes: save } = await import("@/lib/files");
|
||||
const image = await save(await makeImage(300, 300, "png"));
|
||||
await prisma.entity.create({ data: { bookId: book.id, kind: "CHARACTER", name: "X", imageFile: image } });
|
||||
expect(await withinQuota(user.id, 1)).toBe(false); // bilden ensam överskrider redan kvoten
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
});
|
||||
});
|
||||
|
||||
describeDb("administratör", () => {
|
||||
beforeEach(resetAll);
|
||||
|
||||
it("den äldsta användaren är administratör när ADMIN_EMAILS saknas", async () => {
|
||||
const first = await makeUser("Först");
|
||||
const second = await makeUser("Sist");
|
||||
expect(await isAdminUser(first.id, first.email)).toBe(true);
|
||||
expect(await isAdminUser(second.id, second.email)).toBe(false);
|
||||
});
|
||||
|
||||
it("ADMIN_EMAILS styr när den är satt, oberoende av stora bokstäver och mellanslag", async () => {
|
||||
const first = await makeUser("Först", "forst@example.com");
|
||||
const second = await makeUser("Sist", "Sist@Example.com");
|
||||
vi.stubEnv("ADMIN_EMAILS", " sist@example.com , annan@example.com ");
|
||||
expect(await isAdminUser(second.id, second.email)).toBe(true);
|
||||
expect(await isAdminUser(first.id, first.email)).toBe(false); // äldst, men inte i listan
|
||||
expect(await isAdminUser(first.id, null)).toBe(false);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
|
||||
describeDb("sök", () => {
|
||||
let bookId: string;
|
||||
let userId: string;
|
||||
const search = async (q: string, book = bookId) => {
|
||||
const { GET } = await import("@/app/api/books/[bookId]/search/route");
|
||||
return GET(new Request(`http://localhost/api/books/${book}/search?q=${encodeURIComponent(q)}`, { headers: { "x-forwarded-for": `10.0.0.${Math.floor(Math.random() * 250)}` } }), {
|
||||
params: Promise.resolve({ bookId: book }),
|
||||
});
|
||||
};
|
||||
const names = async (q: string) => ((await (await search(q)).json()) as { results: { name: string }[] }).results.map((r) => r.name);
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
userId = (await makeUser()).id;
|
||||
current.userId = userId;
|
||||
bookId = (await makeBook(userId)).id;
|
||||
await makeEntity(bookId, "CHARACTER", "Anna Lindqvist", { tags: ["huvudperson"], summary: "En bagare i Lund", data: { occupation: "Bagare", nickname: "Annie" } });
|
||||
await makeEntity(bookId, "CHARACTER", "Erik Berg", { data: { occupation: "Barista" } });
|
||||
await makeEntity(bookId, "PLACE", "100% Kaffe");
|
||||
});
|
||||
|
||||
it("hittar på namn, ID, sammanfattning, taggar och värden i mallfält", async () => {
|
||||
expect(await names("lindqvist")).toEqual(["Anna Lindqvist"]);
|
||||
expect(await names("KI-0002")).toEqual(["Erik Berg"]);
|
||||
expect(await names("bagare i lund")).toEqual(["Anna Lindqvist"]);
|
||||
expect(await names("huvudperson")).toEqual(["Anna Lindqvist"]);
|
||||
expect(await names("barista")).toEqual(["Erik Berg"]);
|
||||
expect(await names("annie")).toEqual(["Anna Lindqvist"]);
|
||||
});
|
||||
|
||||
it("söker i fältens värden men inte i deras nycklar", async () => {
|
||||
expect(await names("occupation")).toEqual([]);
|
||||
expect(await names("nickname")).toEqual([]);
|
||||
});
|
||||
|
||||
it("behandlar procenttecken och understreck som vanliga tecken", async () => {
|
||||
expect(await names("100%")).toEqual(["100% Kaffe"]);
|
||||
expect(await names("%%")).toEqual([]);
|
||||
expect(await names("A_n")).toEqual([]); // _ är inte jokertecken
|
||||
});
|
||||
|
||||
it("sorterar träffar som börjar med söktexten först", async () => {
|
||||
await makeEntity(bookId, "CHARACTER", "Maria Anna");
|
||||
expect((await names("anna"))[0]).toBe("Anna Lindqvist");
|
||||
});
|
||||
|
||||
it("kräver minst två tecken", async () => {
|
||||
expect(await names("a")).toEqual([]);
|
||||
});
|
||||
|
||||
it("nekar andra användare och utloggade", async () => {
|
||||
const intruder = await makeUser("Inkräktare");
|
||||
current.userId = intruder.id;
|
||||
expect((await search("anna")).status).toBe(404);
|
||||
current.userId = null;
|
||||
expect((await search("anna")).status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hjälpare", () => {
|
||||
it("testfilerna körs i en egen tillfällig mapp, inte i projektets data", () => {
|
||||
expect(process.env.UPLOAD_DIR).toContain("bookmanager-test-data");
|
||||
expect(process.env.BACKUP_DIR).toContain("bookmanager-test-data");
|
||||
expect(process.env.TRASH_DIR).toContain("bookmanager-test-data");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { strToU8, zipSync, type Zippable } from "fflate";
|
||||
import { beforeEach, expect, it } from "vitest";
|
||||
import { buildExport, importBook, readImportFile } from "@/lib/book-transfer";
|
||||
import { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
||||
import { nextMapCode, nextMarkerCode, nextScheduleCode } from "@/lib/ids";
|
||||
import { entityRow, makeImage, validExport } from "../helpers/fixtures";
|
||||
import { describeDb, filesIn, makeBook, makeEntity, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
/** Skickar exporten genom samma zip-format som exportknappen och läser tillbaka den. */
|
||||
function viaZip(exported: Awaited<ReturnType<typeof buildExport>>) {
|
||||
const entries: Zippable = { "book.json": strToU8(JSON.stringify(exported.data)) };
|
||||
for (const [name, bytes] of exported.files) entries[`files/${name}`] = [bytes, { level: 0 }];
|
||||
return readImportFile(zipSync(entries));
|
||||
}
|
||||
|
||||
describeDb("export och import", () => {
|
||||
let ownerId: string;
|
||||
let bookId: string;
|
||||
const ids = {} as Record<"anna" | "erik" | "cafe" | "firma" | "relation" | "map", string>;
|
||||
|
||||
/** En bok med allt: bilder, relation med deltagare, kopplingsfält, scheman, kartor och mall. */
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
ownerId = (await makeUser("Ägare")).id;
|
||||
bookId = (await makeBook(ownerId, "Testbok")).id;
|
||||
|
||||
const portrait = await saveImageBytes(await makeImage(120, 80, "png"));
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna", { imageFile: portrait, tags: ["huvud"], summary: "Huvudperson", data: { age: 30 } });
|
||||
const erik = await makeEntity(bookId, "CHARACTER", "Erik");
|
||||
const cafe = await makeEntity(bookId, "PREMISES", "Café Lund");
|
||||
const firma = await makeEntity(bookId, "COMPANY", "Lunds Kaffe", { data: { industry: "Kaffe", premises: cafe.id } });
|
||||
const relation = await makeRelation(bookId, anna.id, erik.id, "Vänner", [cafe.id]);
|
||||
|
||||
const scheduleCode = await nextScheduleCode(bookId);
|
||||
await prisma.shift.createMany({
|
||||
data: [0, 1].map((weekday) => ({ bookId, personId: erik.id, workplaceId: cafe.id, weekday, startTime: "08:00", endTime: "16:00", scheduleCode })),
|
||||
});
|
||||
|
||||
const mapImage = await saveImageBytes(await makeImage(200, 100, "png"), "map");
|
||||
const geo = await prisma.bookMap.create({ data: { bookId, name: "Lund", kind: "GEO", code: await nextMapCode(bookId, "GEO"), centerLat: 55.7, centerLng: 13.19, zoom: 14 } });
|
||||
await prisma.bookMap.create({ data: { bookId, name: "Egen", kind: "IMAGE", code: await nextMapCode(bookId, "IMAGE"), imageFile: mapImage } });
|
||||
await prisma.marker.create({ data: { mapId: geo.id, entityId: cafe.id, label: "Café", code: await nextMarkerCode(bookId), lat: 55.7047, lng: 13.191, color: "orange", note: "Hörnet" } });
|
||||
await prisma.template.create({ data: { bookId, kind: "CHARACTER", fields: [{ key: "mood", label: "Läge", type: "text" }] } });
|
||||
|
||||
Object.assign(ids, { anna: anna.id, erik: erik.id, cafe: cafe.id, firma: firma.id, relation: relation.id, map: geo.id });
|
||||
});
|
||||
|
||||
it("en export som importeras igen blir en likadan bok med nya id", async () => {
|
||||
const exported = await buildExport(bookId, true);
|
||||
const { data, files } = viaZip(exported);
|
||||
const result = await importBook(ownerId, data, files);
|
||||
|
||||
expect(result).toMatchObject({ entities: 4, relations: 1, maps: 2, markers: 1, shifts: 2, skippedImages: 0, skippedLinks: 0 });
|
||||
expect(result.bookId).not.toBe(bookId);
|
||||
|
||||
const copy = await prisma.book.findUniqueOrThrow({
|
||||
where: { id: result.bookId },
|
||||
include: { entities: true, relations: { include: { members: true } }, shifts: true, maps: { include: { markers: true } }, templates: true, counters: true },
|
||||
});
|
||||
// Samma titel får ett tillägg så att böckerna går att skilja åt
|
||||
expect(copy.title).toBe("Testbok (import)");
|
||||
|
||||
// Poster: nya id, men samma namn, ID-nummer, taggar och mallfält
|
||||
const byName = Object.fromEntries(copy.entities.map((e) => [e.name, e]));
|
||||
expect(Object.keys(byName).sort()).toEqual(["Anna", "Café Lund", "Erik", "Lunds Kaffe"]);
|
||||
expect(byName.Anna).toMatchObject({ code: "KI-0001", tags: ["huvud"], summary: "Huvudperson", data: { age: 30 } });
|
||||
expect(byName["Café Lund"].code).toBe("LI-0001");
|
||||
for (const old of Object.values(ids)) expect(copy.entities.map((e) => e.id)).not.toContain(old);
|
||||
|
||||
// Kopplingsfältet pekar på den nya lokalen, inte den gamla
|
||||
expect((byName["Lunds Kaffe"].data as { premises: string }).premises).toBe(byName["Café Lund"].id);
|
||||
|
||||
// Relationen och dess extra deltagare pekar på de nya posterna
|
||||
const [relation] = copy.relations;
|
||||
expect(relation).toMatchObject({ code: "REI-0001", type: "Vänner", fromId: byName.Anna.id, toId: byName.Erik.id });
|
||||
expect(relation.members.map((m) => m.entityId)).toEqual([byName["Café Lund"].id]);
|
||||
|
||||
// Scheman delar schema-ID och pekar på nya poster
|
||||
expect(copy.shifts).toHaveLength(2);
|
||||
expect(new Set(copy.shifts.map((s) => s.scheduleCode))).toEqual(new Set(["SCI-0001"]));
|
||||
expect(copy.shifts.every((s) => s.personId === byName.Erik.id && s.workplaceId === byName["Café Lund"].id)).toBe(true);
|
||||
|
||||
// Kartor och markeringar
|
||||
const geo = copy.maps.find((m) => m.kind === "GEO")!;
|
||||
expect(geo).toMatchObject({ code: "KD-R_0001", zoom: 14, centerLat: 55.7 });
|
||||
expect(geo.markers[0]).toMatchObject({ code: "PI-0001", label: "Café", color: "orange", note: "Hörnet", entityId: byName["Café Lund"].id });
|
||||
expect(copy.maps.find((m) => m.kind === "IMAGE")?.code).toBe("KD-E_0001");
|
||||
|
||||
// Mall och räknare
|
||||
expect(copy.templates).toHaveLength(1);
|
||||
const counter = Object.fromEntries(copy.counters.map((c) => [c.key, c.next]));
|
||||
expect(counter).toMatchObject({ KI: 2, LI: 1, FI: 1, REI: 1, SCI: 1, PI: 1, "KD-R": 1, "KD-E": 1 });
|
||||
});
|
||||
|
||||
it("bilderna kopieras till nya filer", async () => {
|
||||
const before = await filesIn(UPLOAD_DIR);
|
||||
expect(before).toHaveLength(2);
|
||||
const { data, files } = viaZip(await buildExport(bookId, true));
|
||||
const result = await importBook(ownerId, data, files);
|
||||
|
||||
const after = await filesIn(UPLOAD_DIR);
|
||||
expect(after).toHaveLength(4);
|
||||
const copy = await prisma.entity.findFirstOrThrow({ where: { bookId: result.bookId, name: "Anna" } });
|
||||
expect(copy.imageFile).toBeTruthy();
|
||||
expect(before).not.toContain(copy.imageFile);
|
||||
expect((await readFile(path.join(UPLOAD_DIR, copy.imageFile!))).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("nya poster fortsätter numreringen efter importen", async () => {
|
||||
const { data, files } = viaZip(await buildExport(bookId, true));
|
||||
const { bookId: copyId } = await importBook(ownerId, data, files);
|
||||
const next = await makeEntity(copyId, "CHARACTER", "Ny");
|
||||
expect(next.code).toBe("KI-0003");
|
||||
});
|
||||
|
||||
it("JSON utan bilder går att importera", async () => {
|
||||
const { data } = await buildExport(bookId, false);
|
||||
const result = await importBook(ownerId, data, new Map());
|
||||
expect(result.entities).toBe(4);
|
||||
expect(result.skippedImages).toBe(0);
|
||||
expect((await prisma.entity.findFirstOrThrow({ where: { bookId: result.bookId, name: "Anna" } })).imageFile).toBeNull();
|
||||
});
|
||||
|
||||
it("kan importeras till en annan användare utan tillägg i titeln", async () => {
|
||||
const other = await makeUser("Annan");
|
||||
const { data, files } = viaZip(await buildExport(bookId, true));
|
||||
const result = await importBook(other.id, data, files);
|
||||
const copy = await prisma.book.findUniqueOrThrow({ where: { id: result.bookId } });
|
||||
expect(copy.ownerId).toBe(other.id);
|
||||
expect(copy.title).toBe("Testbok");
|
||||
});
|
||||
|
||||
it("saknade bilder och trasiga kopplingar hoppas över och räknas", async () => {
|
||||
const data = validExport({
|
||||
entities: [entityRow("a", "CHARACTER", "Anna", { image: "saknas.png" }), entityRow("b", "CHARACTER", "Bo", { image: "skräp.png" })],
|
||||
relations: [
|
||||
{ id: "r1", code: null, fromId: "a", toId: "b", type: "Vänner", description: null, data: {}, members: ["finns-inte"] },
|
||||
{ id: "r2", code: null, fromId: "a", toId: "okänd", type: "Fiende", description: null, data: {}, members: [] },
|
||||
{ id: "r3", code: null, fromId: "a", toId: "a", type: "Självrelation", description: null, data: {}, members: [] },
|
||||
],
|
||||
shifts: [{ personId: "okänd", workplaceId: null, weekday: 0, startTime: "08:00", endTime: "16:00", weeks: "ALL", label: null, scheduleCode: null }],
|
||||
});
|
||||
const files = new Map([["skräp.png", new TextEncoder().encode("det här är ingen bild")]]);
|
||||
const result = await importBook(ownerId, data, files);
|
||||
|
||||
expect(result).toMatchObject({ entities: 2, relations: 1, shifts: 0, skippedImages: 2, skippedLinks: 3 });
|
||||
const relations = await prisma.relation.findMany({ where: { bookId: result.bookId }, include: { members: true } });
|
||||
expect(relations).toHaveLength(1);
|
||||
expect(relations[0].members).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("behåller giltiga ID men ger nya åt dubbletter och felaktiga", async () => {
|
||||
const data = validExport({
|
||||
entities: [
|
||||
entityRow("a", "CHARACTER", "Anna", { code: "KI-0007" }),
|
||||
entityRow("b", "CHARACTER", "Bo", { code: "KI-0007" }), // dubblett
|
||||
entityRow("c", "CHARACTER", "Cia", { code: "FEL-1" }), // fel format
|
||||
entityRow("d", "CHARACTER", "Dan", { code: "FI-0002" }), // fel prefix för en karaktär
|
||||
entityRow("e", "CHARACTER", "Eva", { code: null }),
|
||||
entityRow("f", "APP", "En app", { code: "KI-0001" }), // appar har inget ID
|
||||
],
|
||||
});
|
||||
const result = await importBook(ownerId, data, new Map());
|
||||
const rows = await prisma.entity.findMany({ where: { bookId: result.bookId }, orderBy: { name: "asc" } });
|
||||
const code = (name: string) => rows.find((e) => e.name === name)!.code;
|
||||
|
||||
expect(code("Anna")).toBe("KI-0007");
|
||||
expect(code("En app")).toBeNull();
|
||||
const assigned = ["Bo", "Cia", "Dan", "Eva"].map(code);
|
||||
expect(new Set([...assigned, "KI-0007"]).size).toBe(5); // alla unika
|
||||
expect(assigned.every((c) => /^KI-\d{4}$/.test(c!))).toBe(true);
|
||||
// Nya nummer fortsätter efter det högsta som användes
|
||||
expect(assigned.sort()).toEqual(["KI-0008", "KI-0009", "KI-0010", "KI-0011"]);
|
||||
});
|
||||
|
||||
it("tar bort de sparade bilderna igen om importen misslyckas", async () => {
|
||||
const image = await makeImage(40, 40, "png");
|
||||
const before = await filesIn(UPLOAD_DIR);
|
||||
// Samma id två gånger gör att databasen avvisar raderna (unik nyckel) efter att bilderna sparats
|
||||
const data = validExport({
|
||||
entities: [entityRow("dubbel", "CHARACTER", "A", { image: "a.png" }), entityRow("dubbel", "CHARACTER", "B", { image: "b.png" })],
|
||||
});
|
||||
await expect(importBook(ownerId, data, new Map([["a.png", image], ["b.png", image]]))).rejects.toThrow();
|
||||
expect(await filesIn(UPLOAD_DIR)).toEqual(before);
|
||||
expect(await prisma.book.count({ where: { title: "Testbok (import)" } })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
||||
import { nextMapCode, nextMarkerCode, nextScheduleCode } from "@/lib/ids";
|
||||
import { TRASH_DIR, TRASH_DAYS, emptyBookTrash, purgeExpiredTrash, purgeTrashItem, restoreBook, restoreEntity, trashBook, trashEntity } from "@/lib/trash";
|
||||
import { makeImage } from "../helpers/fixtures";
|
||||
import { describeDb, filesIn, makeBook, makeEntity, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
describeDb("papperskorg", () => {
|
||||
let ownerId: string;
|
||||
let bookId: string;
|
||||
let anna: { id: string; code: string | null };
|
||||
let erik: { id: string };
|
||||
let cafe: { id: string };
|
||||
let relationId: string;
|
||||
let markerId: string;
|
||||
let hostedShiftId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
ownerId = (await makeUser()).id;
|
||||
bookId = (await makeBook(ownerId)).id;
|
||||
const image = await saveImageBytes(await makeImage(80, 60, "png"));
|
||||
anna = await makeEntity(bookId, "CHARACTER", "Anna", { imageFile: image, data: { age: 30 } });
|
||||
erik = await makeEntity(bookId, "CHARACTER", "Erik");
|
||||
cafe = await makeEntity(bookId, "PREMISES", "Café");
|
||||
const company = await makeEntity(bookId, "COMPANY", "Firma");
|
||||
|
||||
// Anna är med i en relation som parti, i en annan som extra deltagare, har egna pass och är arbetsplats åt ett pass
|
||||
relationId = (await makeRelation(bookId, anna.id, erik.id, "Vänner", [cafe.id])).id;
|
||||
await makeRelation(bookId, erik.id, company.id, "Jobbar på", [anna.id]);
|
||||
const code = await nextScheduleCode(bookId);
|
||||
await prisma.shift.create({ data: { bookId, personId: anna.id, workplaceId: cafe.id, weekday: 0, startTime: "08:00", endTime: "16:00", scheduleCode: code } });
|
||||
hostedShiftId = (await prisma.shift.create({ data: { bookId, personId: erik.id, workplaceId: anna.id, weekday: 1, startTime: "09:00", endTime: "17:00", scheduleCode: code } })).id;
|
||||
const map = await prisma.bookMap.create({ data: { bookId, name: "Karta", kind: "GEO", code: await nextMapCode(bookId, "GEO") } });
|
||||
markerId = (await prisma.marker.create({ data: { mapId: map.id, entityId: anna.id, label: "Annas hus", code: await nextMarkerCode(bookId), lat: 1, lng: 2 } })).id;
|
||||
});
|
||||
|
||||
describe("poster", () => {
|
||||
it("flyttar posten till papperskorgen och tar bort den ur boken", async () => {
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
expect(await prisma.entity.findUnique({ where: { id: anna.id } })).toBeNull();
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
expect(item).toMatchObject({ kind: "entity", label: "Anna", detail: "CHARACTER", ownerId, bookId });
|
||||
// Annas relationer och egna pass följer med bort
|
||||
expect(await prisma.relation.count({ where: { id: relationId } })).toBe(0);
|
||||
expect(await prisma.shift.count({ where: { personId: anna.id } })).toBe(0);
|
||||
// Det som bara pekade på henne blir kvar utan koppling
|
||||
expect((await prisma.shift.findUniqueOrThrow({ where: { id: hostedShiftId } })).workplaceId).toBeNull();
|
||||
expect((await prisma.marker.findUniqueOrThrow({ where: { id: markerId } })).entityId).toBeNull();
|
||||
});
|
||||
|
||||
it("behåller bilden medan posten ligger i papperskorgen", async () => {
|
||||
const image = (await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } })).imageFile!;
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
expect(await filesIn(UPLOAD_DIR)).toContain(image);
|
||||
});
|
||||
|
||||
it("återställer allt: samma id och ID-nummer, relationer, deltagande, pass, arbetsplats och markering", async () => {
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
const restored = await restoreEntity(ownerId, item.id);
|
||||
expect(restored).toEqual({ bookId, entityId: anna.id });
|
||||
|
||||
const back = await prisma.entity.findUniqueOrThrow({ where: { id: anna.id }, include: { outgoing: { include: { members: true } }, memberOf: true, shifts: true } });
|
||||
expect(back).toMatchObject({ name: "Anna", code: anna.code, data: { age: 30 } });
|
||||
expect(back.imageFile).toBeTruthy();
|
||||
expect(back.outgoing).toHaveLength(1);
|
||||
expect(back.outgoing[0].id).toBe(relationId);
|
||||
expect(back.outgoing[0].members.map((m) => m.entityId)).toEqual([cafe.id]);
|
||||
expect(back.memberOf).toHaveLength(1);
|
||||
expect(back.shifts).toHaveLength(1);
|
||||
expect(back.shifts[0].scheduleCode).toBe("SCI-0001");
|
||||
expect((await prisma.shift.findUniqueOrThrow({ where: { id: hostedShiftId } })).workplaceId).toBe(anna.id);
|
||||
expect((await prisma.marker.findUniqueOrThrow({ where: { id: markerId } })).entityId).toBe(anna.id);
|
||||
expect(await prisma.trashItem.count()).toBe(0);
|
||||
});
|
||||
|
||||
it("hoppar över relationer vars andra part tagits bort under tiden", async () => {
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
await prisma.entity.delete({ where: { id: erik.id } });
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
await restoreEntity(ownerId, item.id);
|
||||
expect(await prisma.entity.findUnique({ where: { id: anna.id } })).not.toBeNull();
|
||||
expect(await prisma.relation.count({ where: { id: relationId } })).toBe(0);
|
||||
});
|
||||
|
||||
it("ger en ny kod om den gamla hunnit tas av en annan post", async () => {
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
await prisma.entity.update({ where: { id: erik.id }, data: { code: anna.code } });
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
await restoreEntity(ownerId, item.id);
|
||||
const back = await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } });
|
||||
expect(back.code).toMatch(/^KI-\d{4}$/);
|
||||
expect(back.code).not.toBe(anna.code);
|
||||
});
|
||||
|
||||
it("kan inte återställas av någon annan, eller när boken är borta", async () => {
|
||||
const intruder = await makeUser("Inkräktare");
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
expect(await restoreEntity(intruder.id, item.id)).toBeNull();
|
||||
expect(await prisma.entity.count({ where: { id: anna.id } })).toBe(0);
|
||||
|
||||
await prisma.book.delete({ where: { id: bookId } });
|
||||
expect(await restoreEntity(ownerId, item.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("rensar för gott: tar bort bilden och historiken", async () => {
|
||||
const image = (await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } })).imageFile!;
|
||||
await prisma.entityVersion.create({ data: { bookId, entityId: anna.id, snapshot: { name: "Gammal" } } });
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
|
||||
await purgeTrashItem(ownerId, item.id);
|
||||
expect(await prisma.trashItem.count()).toBe(0);
|
||||
expect(await filesIn(UPLOAD_DIR)).not.toContain(image);
|
||||
expect(await prisma.entityVersion.count({ where: { entityId: anna.id } })).toBe(0);
|
||||
});
|
||||
|
||||
it("kan inte rensa någon annans papperskorg", async () => {
|
||||
const intruder = await makeUser("Inkräktare");
|
||||
await trashEntity(ownerId, bookId, anna.id);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
await purgeTrashItem(intruder.id, item.id);
|
||||
expect(await prisma.trashItem.count()).toBe(1);
|
||||
});
|
||||
|
||||
it("tömmer bokens papperskorg men rör inga andra böcker", async () => {
|
||||
const otherBook = await makeBook(ownerId, "Annan");
|
||||
const stray = await makeEntity(otherBook.id, "CHARACTER", "Kvar");
|
||||
await trashEntity(ownerId, bookId, erik.id);
|
||||
await trashEntity(ownerId, otherBook.id, stray.id);
|
||||
await emptyBookTrash(ownerId, bookId);
|
||||
const left = await prisma.trashItem.findMany();
|
||||
expect(left.map((i) => i.label)).toEqual(["Kvar"]);
|
||||
});
|
||||
|
||||
it("rensar bara det som legat längre än gränsen", async () => {
|
||||
await trashEntity(ownerId, bookId, erik.id);
|
||||
await trashEntity(ownerId, bookId, cafe.id);
|
||||
const old = await prisma.trashItem.findFirstOrThrow({ where: { label: "Erik" } });
|
||||
await prisma.trashItem.update({ where: { id: old.id }, data: { deletedAt: new Date(Date.now() - (TRASH_DAYS + 1) * 86_400_000) } });
|
||||
|
||||
expect(await purgeExpiredTrash()).toBe(1);
|
||||
expect((await prisma.trashItem.findMany()).map((i) => i.label)).toEqual(["Café"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("böcker", () => {
|
||||
it("sparar boken som zip med bilderna och tar bort den", async () => {
|
||||
expect(await filesIn(UPLOAD_DIR)).toHaveLength(1);
|
||||
await trashBook(ownerId, bookId);
|
||||
|
||||
expect(await prisma.book.count()).toBe(0);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
expect(item).toMatchObject({ kind: "book", label: "Testbok", ownerId });
|
||||
expect(await readdir(TRASH_DIR)).toEqual([item.file]);
|
||||
// Bilden ligger nu i zip-filen och inte längre bland de uppladdade
|
||||
expect(await filesIn(UPLOAD_DIR)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("återställer boken som en ny bok med allt innehåll och bilderna", async () => {
|
||||
await trashBook(ownerId, bookId);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
const newId = await restoreBook(ownerId, item.id);
|
||||
|
||||
expect(newId).toBeTruthy();
|
||||
const book = await prisma.book.findUniqueOrThrow({ where: { id: newId! }, include: { entities: true, relations: true, shifts: true, maps: { include: { markers: true } } } });
|
||||
expect(book.title).toBe("Testbok");
|
||||
expect(book.entities).toHaveLength(4);
|
||||
expect(book.relations).toHaveLength(2);
|
||||
expect(book.shifts).toHaveLength(2);
|
||||
expect(book.maps[0].markers).toHaveLength(1);
|
||||
expect(book.entities.find((e) => e.name === "Anna")?.code).toBe(anna.code);
|
||||
expect(await filesIn(UPLOAD_DIR)).toHaveLength(1);
|
||||
|
||||
// Papperskorgen och zip-filen är borta
|
||||
expect(await prisma.trashItem.count()).toBe(0);
|
||||
expect(await readdir(TRASH_DIR)).toEqual([]);
|
||||
});
|
||||
|
||||
it("kan inte återställas av någon annan", async () => {
|
||||
const intruder = await makeUser("Inkräktare");
|
||||
await trashBook(ownerId, bookId);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
expect(await restoreBook(intruder.id, item.id)).toBeNull();
|
||||
expect(await prisma.book.count()).toBe(0);
|
||||
});
|
||||
|
||||
it("rensar zip-filen när den tas bort för gott", async () => {
|
||||
await trashBook(ownerId, bookId);
|
||||
const [item] = await prisma.trashItem.findMany();
|
||||
await purgeTrashItem(ownerId, item.id);
|
||||
expect(await readdir(TRASH_DIR)).toEqual([]);
|
||||
expect(await prisma.trashItem.count()).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user