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:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 23:19:30 +01:00
1 parent 4e8d79ee10
commit dcb5d43429
30 files changed
+2872 -13

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
import { randomUUID } from "node:crypto";
import { mkdir, readdir, rm } from "node:fs/promises";
import type { EntityKind, Prisma } from "@prisma/client";
import { describe } from "vitest";
import { prisma } from "@/lib/db";
import { UPLOAD_DIR } from "@/lib/files";
import { nextEntityCode, nextRelationCode } from "@/lib/ids";
import { BACKUP_DIR } from "@/lib/backup";
import { TRASH_DIR } from "@/lib/trash";
export { prisma };
/** Databastester körs bara när en testdatabas är konfigurerad (se vitest.config.ts). */
export const hasDb = Boolean(process.env.DATABASE_URL);
export const describeDb = hasDb ? describe : describe.skip;
/** Tömmer alla tabeller och filmapparna. Kräver att databasens namn slutar på _test. */
export async function resetAll() {
const [{ current_database: name }] = await prisma.$queryRaw<{ current_database: string }[]>`SELECT current_database()`;
if (!name.endsWith("_test")) throw new Error(`Vägrar tömma databasen "${name}": namnet slutar inte på _test`);
const tables = await prisma.$queryRaw<{ tablename: string }[]>`SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename <> '_prisma_migrations'`;
if (tables.length > 0) {
await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${tables.map((t) => `"${t.tablename}"`).join(", ")} RESTART IDENTITY CASCADE`);
}
for (const dir of [UPLOAD_DIR, BACKUP_DIR, TRASH_DIR]) {
await rm(dir, { recursive: true, force: true });
await mkdir(dir, { recursive: true });
}
}
export async function filesIn(dir: string): Promise<string[]> {
try {
return (await readdir(dir)).filter((f) => f !== "thumbs").sort();
} catch {
return [];
}
}
export async function makeUser(name = "Tester", email: string | null = `${name.toLowerCase()}@example.com`) {
return prisma.user.create({ data: { externalId: `test:${randomUUID()}`, name, email } });
}
export async function makeBook(ownerId: string, title = "Testbok") {
return prisma.book.create({ data: { ownerId, title } });
}
export async function makeEntity(
bookId: string,
kind: EntityKind,
name: string,
extra: { data?: Prisma.InputJsonObject; imageFile?: string | null; tags?: string[]; summary?: string } = {},
) {
return prisma.entity.create({
data: { bookId, kind, name, code: await nextEntityCode(bookId, kind), tags: extra.tags ?? [], data: extra.data ?? {}, imageFile: extra.imageFile ?? null, summary: extra.summary ?? null },
});
}
export async function makeRelation(bookId: string, fromId: string, toId: string, type = "Vänner", memberIds: string[] = []) {
return prisma.relation.create({
data: { bookId, fromId, toId, type, code: await nextRelationCode(bookId), members: { create: memberIds.map((entityId) => ({ entityId })) } },
});
}
+38
View File
@@ -0,0 +1,38 @@
import sharp from "sharp";
import type { ExportData } from "@/lib/book-transfer";
/** En giltig minimal exportfil. Åsidosätt delar för att testa enskilda fall. */
export function validExport(overrides: Partial<ExportData> = {}): ExportData {
return {
format: "bookmanager-export",
version: 1,
exportedAt: "2026-01-01T00:00:00.000Z",
includesImages: false,
book: { title: "Testbok", subtitle: null, genre: null, description: null },
entities: [],
relations: [],
shifts: [],
maps: [],
templates: [],
...overrides,
};
}
export function entityRow(id: string, kind: ExportData["entities"][number]["kind"], name: string, extra: Partial<ExportData["entities"][number]> = {}): ExportData["entities"][number] {
return { id, kind, name, code: null, summary: null, tags: [], data: {}, image: null, ...extra };
}
/** En riktig bild (PNG, JPEG eller WebP) av önskad storlek, för tester av bildbehandling och uppladdning. */
export async function makeImage(
width: number,
height: number,
format: "png" | "jpeg" | "webp" = "png",
options: { orientation?: number } = {},
): Promise<Uint8Array> {
let pipeline = sharp({ create: { width, height, channels: 3, background: { r: 200, g: 60, b: 60 } } });
if (format === "png") pipeline = pipeline.png();
else if (format === "jpeg") pipeline = pipeline.jpeg({ quality: 40 });
else pipeline = pipeline.webp({ quality: 40 });
if (options.orientation) pipeline = pipeline.withMetadata({ orientation: options.orientation });
return new Uint8Array(await pipeline.toBuffer());
}