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,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { formatBytes, formatDuration } from "@/lib/format";
|
||||
|
||||
describe("formatBytes", () => {
|
||||
it("visar storlekar med svenskt decimaltecken", () => {
|
||||
expect(formatBytes(0)).toBe("0 B");
|
||||
expect(formatBytes(1023)).toBe("1023 B");
|
||||
expect(formatBytes(1536)).toBe("1,5 KB");
|
||||
expect(formatBytes(1024 * 1024)).toBe("1,0 MB");
|
||||
expect(formatBytes(150 * 1024 * 1024)).toBe("150 MB");
|
||||
expect(formatBytes(3 * 1024 ** 3)).toBe("3,0 GB");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatDuration", () => {
|
||||
it("visar dagar, timmar och minuter", () => {
|
||||
expect(formatDuration(59)).toBe("0 min");
|
||||
expect(formatDuration(3600)).toBe("1 h 0 min");
|
||||
expect(formatDuration(93784)).toBe("1 d 2 h 3 min");
|
||||
expect(formatDuration(86400)).toBe("1 d 0 h 0 min");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { diffSnapshots, sameSnapshot, snapshotOf, type Snapshot } from "@/lib/history";
|
||||
import type { FieldDef } from "@/lib/templates";
|
||||
|
||||
const labels = { name: "Namn", summary: "Sammanfattning", tags: "Taggar" };
|
||||
const fields: FieldDef[] = [
|
||||
{ key: "age", label: "Ålder", type: "number" },
|
||||
{ key: "alive", label: "Vid liv", type: "checkbox" },
|
||||
];
|
||||
const base: Snapshot = { name: "Anna", summary: null, tags: ["a"], data: { age: 30, alive: true } };
|
||||
|
||||
describe("snapshotOf", () => {
|
||||
it("normaliserar saknad sammanfattning och ogiltig data", () => {
|
||||
expect(snapshotOf({ name: "A", summary: null, tags: [], data: null })).toEqual({ name: "A", summary: null, tags: [], data: {} });
|
||||
expect(snapshotOf({ name: "A", summary: "x", tags: ["t"], data: [1, 2] }).data).toEqual({});
|
||||
expect(snapshotOf({ name: "A", summary: "x", tags: [], data: { k: 1 } }).data).toEqual({ k: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("sameSnapshot", () => {
|
||||
it("är oberoende av nyckelordningen i data", () => {
|
||||
const a = { ...base, data: { age: 30, alive: true } };
|
||||
const b = { ...base, data: { alive: true, age: 30 } };
|
||||
expect(sameSnapshot(a, b)).toBe(true);
|
||||
});
|
||||
|
||||
it("upptäcker ändringar i namn, taggar och data", () => {
|
||||
expect(sameSnapshot(base, { ...base, name: "Bo" })).toBe(false);
|
||||
expect(sameSnapshot(base, { ...base, tags: ["a", "b"] })).toBe(false);
|
||||
expect(sameSnapshot(base, { ...base, data: { age: 31, alive: true } })).toBe(false);
|
||||
expect(sameSnapshot(base, { ...base })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("diffSnapshots", () => {
|
||||
it("ger inga skillnader när inget ändrats", () => {
|
||||
expect(diffSnapshots(base, { ...base }, fields, labels)).toEqual([]);
|
||||
});
|
||||
|
||||
it("namnger fälten med mallens rubriker", () => {
|
||||
const changes = diffSnapshots(base, { ...base, name: "Anna L", data: { age: 31, alive: true } }, fields, labels);
|
||||
expect(changes).toEqual([
|
||||
{ label: "Namn", before: "Anna", after: "Anna L" },
|
||||
{ label: "Ålder", before: "30", after: "31" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("visar taggar som lista, kryssrutor som bock och tomt som tomt", () => {
|
||||
const changes = diffSnapshots(base, { ...base, tags: ["a", "b"], summary: "ny", data: { age: 30, alive: false } }, fields, labels);
|
||||
expect(changes).toContainEqual({ label: "Taggar", before: "a", after: "a, b" });
|
||||
expect(changes).toContainEqual({ label: "Sammanfattning", before: "", after: "ny" });
|
||||
expect(changes).toContainEqual({ label: "Vid liv", before: "✓", after: "" });
|
||||
});
|
||||
|
||||
it("tar med värden för fält som inte längre finns i mallen", () => {
|
||||
const changes = diffSnapshots({ ...base, data: { ...base.data, gammal: "x" } }, base, fields, labels);
|
||||
expect(changes).toEqual([{ label: "gammal", before: "x", after: "" }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ENTITY_PREFIX, mapLetter, pad } from "@/lib/ids";
|
||||
import { KINDS } from "@/lib/kinds";
|
||||
|
||||
describe("ID-prefix", () => {
|
||||
it("varje posttyp med ID har ett eget prefix", () => {
|
||||
const prefixes = Object.values(ENTITY_PREFIX);
|
||||
expect(new Set(prefixes).size).toBe(prefixes.length);
|
||||
});
|
||||
|
||||
it("alla typer utom appar och hemsidor får ID", () => {
|
||||
const without = KINDS.filter((k) => !ENTITY_PREFIX[k.kind]).map((k) => k.kind);
|
||||
expect(without.sort()).toEqual(["APP", "WEBSITE"]);
|
||||
});
|
||||
|
||||
it("följer ID-översikten", () => {
|
||||
expect(ENTITY_PREFIX.CHARACTER).toBe("KI");
|
||||
expect(ENTITY_PREFIX.COMPANY).toBe("FI");
|
||||
expect(ENTITY_PREFIX.HOME).toBe("BI");
|
||||
expect(ENTITY_PREFIX.PET).toBe("DI");
|
||||
expect(ENTITY_PREFIX.PREMISES).toBe("LI");
|
||||
expect(ENTITY_PREFIX.EDUCATION).toBe("UI");
|
||||
expect(ENTITY_PREFIX.VEHICLE).toBe("FD");
|
||||
expect(ENTITY_PREFIX.RESEARCH).toBe("RI");
|
||||
expect(ENTITY_PREFIX.REFERENCE).toBe("RD");
|
||||
expect(ENTITY_PREFIX.SKETCH).toBe("SI");
|
||||
});
|
||||
|
||||
it("kartans bokstav följer typen", () => {
|
||||
expect(mapLetter("GEO")).toBe("R");
|
||||
expect(mapLetter("IMAGE")).toBe("E");
|
||||
});
|
||||
|
||||
it("siffrorna fylls ut till fyra och växer vid behov", () => {
|
||||
expect(pad(1)).toBe("0001");
|
||||
expect(pad(42)).toBe("0042");
|
||||
expect(pad(9999)).toBe("9999");
|
||||
expect(pad(12345)).toBe("12345");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import sharp from "sharp";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { detectImageExt, makeThumbnail, optimizeImage } from "@/lib/images";
|
||||
import { makeImage } from "../helpers/fixtures";
|
||||
|
||||
describe("detectImageExt", () => {
|
||||
it("känner igen bildtyper på de första byten, inte på namnet", async () => {
|
||||
expect(detectImageExt(await makeImage(4, 4, "png"))).toBe("png");
|
||||
expect(detectImageExt(await makeImage(4, 4, "jpeg"))).toBe("jpg");
|
||||
expect(detectImageExt(await makeImage(4, 4, "webp"))).toBe("webp");
|
||||
expect(detectImageExt(new TextEncoder().encode("GIF89a......"))).toBe("gif");
|
||||
});
|
||||
|
||||
it("avvisar annat än bilder", () => {
|
||||
expect(detectImageExt(new TextEncoder().encode("<svg xmlns='http://www.w3.org/2000/svg'></svg>"))).toBeNull();
|
||||
expect(detectImageExt(new TextEncoder().encode("#!/bin/sh\necho hej"))).toBeNull();
|
||||
expect(detectImageExt(new Uint8Array([]))).toBeNull();
|
||||
expect(detectImageExt(new Uint8Array([0x89, 0x50]))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("optimizeImage", () => {
|
||||
it("skalar ned stora bilder till högst 2400 px på längsta sidan", async () => {
|
||||
const result = await optimizeImage(await makeImage(3600, 1800, "jpeg"), "entity");
|
||||
const meta = await sharp(result!.bytes).metadata();
|
||||
expect(result!.ext).toBe("jpg");
|
||||
expect(meta.width).toBe(2400);
|
||||
expect(meta.height).toBe(1200);
|
||||
});
|
||||
|
||||
it("lämnar små bilder i storlek", async () => {
|
||||
const result = await optimizeImage(await makeImage(300, 200, "png"), "entity");
|
||||
const meta = await sharp(result!.bytes).metadata();
|
||||
expect([meta.width, meta.height]).toEqual([300, 200]);
|
||||
expect(result!.ext).toBe("png");
|
||||
});
|
||||
|
||||
it("roterar efter EXIF och tar bort metadata", async () => {
|
||||
const input = await makeImage(300, 200, "jpeg", { orientation: 6 });
|
||||
expect((await sharp(input).metadata()).orientation).toBe(6);
|
||||
|
||||
const result = await optimizeImage(input, "entity");
|
||||
const meta = await sharp(result!.bytes).metadata();
|
||||
// 300x200 med rotation 90 grader blir 200x300, och orienteringsflaggan är borta
|
||||
expect([meta.width, meta.height]).toEqual([200, 300]);
|
||||
expect(meta.orientation).toBeUndefined();
|
||||
expect(meta.exif).toBeUndefined();
|
||||
});
|
||||
|
||||
it("kartbilder får behålla mer upplösning än porträtt", async () => {
|
||||
const map = await optimizeImage(await makeImage(3000, 2000, "png"), "map");
|
||||
expect((await sharp(map!.bytes).metadata()).width).toBe(3000);
|
||||
const portrait = await optimizeImage(await makeImage(3000, 2000, "png"), "entity");
|
||||
expect((await sharp(portrait!.bytes).metadata()).width).toBe(2400);
|
||||
});
|
||||
|
||||
it("lämnar GIF orörd", async () => {
|
||||
const gif = new TextEncoder().encode("GIF89a\x01\x00\x01\x00\x00\x00\x00;");
|
||||
const result = await optimizeImage(gif, "entity");
|
||||
expect(result?.ext).toBe("gif");
|
||||
expect(Array.from(result!.bytes)).toEqual(Array.from(gif));
|
||||
});
|
||||
|
||||
it("avvisar filer som inte är bilder eller är skadade", async () => {
|
||||
expect(await optimizeImage(new TextEncoder().encode("hej"), "entity")).toBeNull();
|
||||
const png = await makeImage(50, 50, "png");
|
||||
expect(await optimizeImage(png.slice(0, 40), "entity")).toBeNull(); // avklippt bild
|
||||
});
|
||||
});
|
||||
|
||||
describe("makeThumbnail", () => {
|
||||
it("ger en liten WebP-bild med högst 480 px", async () => {
|
||||
const thumb = await makeThumbnail(await makeImage(2000, 1000, "jpeg"));
|
||||
const meta = await sharp(thumb).metadata();
|
||||
expect(meta.format).toBe("webp");
|
||||
expect(meta.width).toBe(480);
|
||||
expect(meta.height).toBe(240);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ImportError, parseExport, readImportFile, type ImportErrorCode } from "@/lib/book-transfer";
|
||||
import { entityRow, validExport } from "../helpers/fixtures";
|
||||
|
||||
function codeOf(fn: () => unknown): ImportErrorCode | "no-error" {
|
||||
try {
|
||||
fn();
|
||||
return "no-error";
|
||||
} catch (error) {
|
||||
if (error instanceof ImportError) return error.code;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const json = (data: unknown) => new TextEncoder().encode(JSON.stringify(data));
|
||||
const zip = (entries: Record<string, Uint8Array>) => zipSync(entries);
|
||||
|
||||
describe("parseExport", () => {
|
||||
it("godkänner en minimal exportfil", () => {
|
||||
const parsed = parseExport(validExport());
|
||||
expect(parsed.book.title).toBe("Testbok");
|
||||
expect(parsed.entities).toEqual([]);
|
||||
});
|
||||
|
||||
it("avvisar annat än en exportfil", () => {
|
||||
expect(codeOf(() => parseExport(null))).toBe("not-export");
|
||||
expect(codeOf(() => parseExport([]))).toBe("not-export");
|
||||
expect(codeOf(() => parseExport({ a: 1 }))).toBe("not-export");
|
||||
expect(codeOf(() => parseExport({ ...validExport(), format: "annat" }))).toBe("not-export");
|
||||
});
|
||||
|
||||
it("avvisar okänd version", () => {
|
||||
expect(codeOf(() => parseExport({ ...validExport(), version: 2 }))).toBe("version");
|
||||
});
|
||||
|
||||
it("kräver en boktitel", () => {
|
||||
expect(codeOf(() => parseExport({ ...validExport(), book: { title: " " } }))).toBe("invalid");
|
||||
expect(codeOf(() => parseExport({ ...validExport(), book: undefined }))).toBe("invalid");
|
||||
});
|
||||
|
||||
it("avvisar poster med okänd typ, saknat id eller saknat namn", () => {
|
||||
expect(codeOf(() => parseExport({ ...validExport(), entities: [{ id: "a", kind: "DRAGON", name: "X" }] }))).toBe("invalid");
|
||||
expect(codeOf(() => parseExport({ ...validExport(), entities: [{ kind: "CHARACTER", name: "X" }] }))).toBe("invalid");
|
||||
expect(codeOf(() => parseExport({ ...validExport(), entities: [{ id: "a", kind: "CHARACTER", name: "" }] }))).toBe("invalid");
|
||||
expect(codeOf(() => parseExport({ ...validExport(), entities: ["x"] }))).toBe("invalid");
|
||||
});
|
||||
|
||||
it("rensar och begränsar fält", () => {
|
||||
const parsed = parseExport({
|
||||
...validExport(),
|
||||
entities: [{ id: "a", kind: "CHARACTER", name: ` ${"x".repeat(300)} `, tags: ["ok", "", 5, "y".repeat(100)], data: "inte ett objekt" }],
|
||||
});
|
||||
expect(parsed.entities[0].name).toHaveLength(200);
|
||||
expect(parsed.entities[0].tags).toEqual(["ok", "y".repeat(40)]);
|
||||
expect(parsed.entities[0].data).toEqual({});
|
||||
});
|
||||
|
||||
it("avvisar för många poster", () => {
|
||||
expect(codeOf(() => parseExport({ ...validExport(), entities: new Array(20001).fill(0) }))).toBe("too-large");
|
||||
});
|
||||
|
||||
it("kontrollerar pass: veckodag och tider", () => {
|
||||
const shift = { personId: "a", workplaceId: null, weekday: 0, startTime: "08:00", endTime: "16:00", weeks: "ALL", label: null, scheduleCode: null };
|
||||
expect(parseExport({ ...validExport(), shifts: [shift] }).shifts).toHaveLength(1);
|
||||
expect(codeOf(() => parseExport({ ...validExport(), shifts: [{ ...shift, weekday: 7 }] }))).toBe("invalid");
|
||||
expect(codeOf(() => parseExport({ ...validExport(), shifts: [{ ...shift, startTime: "25:00" }] }))).toBe("invalid");
|
||||
expect(parseExport({ ...validExport(), shifts: [{ ...shift, weeks: "knas" }] }).shifts[0].weeks).toBe("ALL");
|
||||
});
|
||||
|
||||
it("kontrollerar kartor och markeringar", () => {
|
||||
const marker = { code: null, entityId: null, label: "M", note: null, color: "neon", lat: 1, lng: 2 };
|
||||
const map = { id: "m", code: null, name: "Karta", kind: "GEO", image: null, centerLat: null, centerLng: null, zoom: 3.7, markers: [marker] };
|
||||
const parsed = parseExport({ ...validExport(), maps: [map] });
|
||||
expect(parsed.maps[0].markers[0].color).toBe("blue"); // okänd färg blir standardfärg
|
||||
expect(parsed.maps[0].zoom).toBe(4);
|
||||
expect(codeOf(() => parseExport({ ...validExport(), maps: [{ ...map, markers: [{ ...marker, lat: "x" }] }] }))).toBe("invalid");
|
||||
expect(parseExport({ ...validExport(), maps: [{ ...map, kind: "vad som helst" }] }).maps[0].kind).toBe("GEO");
|
||||
});
|
||||
|
||||
it("hoppar över trasiga mallar utan att avvisa filen", () => {
|
||||
const parsed = parseExport({
|
||||
...validExport(),
|
||||
templates: [
|
||||
{ kind: "CHARACTER", fields: [{ key: "ok", label: "Ok", type: "text" }] },
|
||||
{ kind: "HOME", fields: "trasig" },
|
||||
{ kind: "NOPE", fields: [] },
|
||||
"skräp",
|
||||
],
|
||||
});
|
||||
expect(parsed.templates).toHaveLength(1);
|
||||
expect(parsed.templates[0].kind).toBe("CHARACTER");
|
||||
});
|
||||
});
|
||||
|
||||
describe("readImportFile", () => {
|
||||
const valid = validExport({ entities: [entityRow("e1", "CHARACTER", "Anna")] });
|
||||
|
||||
it("läser ren JSON, även med BOM", () => {
|
||||
expect(readImportFile(json(valid)).data.entities).toHaveLength(1);
|
||||
const withBom = new Uint8Array([0xef, 0xbb, 0xbf, ...json(valid)]);
|
||||
expect(readImportFile(withBom).data.book.title).toBe("Testbok");
|
||||
});
|
||||
|
||||
it("läser en zip med book.json och bilder", () => {
|
||||
const image = new Uint8Array([1, 2, 3]);
|
||||
const { data, files } = readImportFile(zip({ "book.json": json(valid), "files/a.png": image }));
|
||||
expect(data.entities[0].name).toBe("Anna");
|
||||
expect(Array.from(files.keys())).toEqual(["a.png"]);
|
||||
});
|
||||
|
||||
it("ignorerar allt i zip-filen utom book.json och files/", () => {
|
||||
const { files } = readImportFile(
|
||||
zip({
|
||||
"book.json": json(valid),
|
||||
"files/ok.png": new Uint8Array([1]),
|
||||
"files/undermapp/inne.png": new Uint8Array([2]),
|
||||
"annat/fil.png": new Uint8Array([3]),
|
||||
"hemlig.txt": new Uint8Array([4]),
|
||||
}),
|
||||
);
|
||||
expect(Array.from(files.keys())).toEqual(["ok.png"]);
|
||||
});
|
||||
|
||||
it("hoppar över bilder som är större än gränsen", () => {
|
||||
const big = new Uint8Array(17 * 1024 * 1024); // komprimeras till nästan inget men packas inte upp
|
||||
const { files } = readImportFile(zip({ "book.json": json(valid), "files/stor.png": big, "files/liten.png": new Uint8Array([1]) }));
|
||||
expect(Array.from(files.keys())).toEqual(["liten.png"]);
|
||||
});
|
||||
|
||||
it("ger tydliga fel", () => {
|
||||
expect(codeOf(() => readImportFile(new Uint8Array([])))).toBe("empty");
|
||||
expect(codeOf(() => readImportFile(new TextEncoder().encode("det här är inte JSON")))).toBe("invalid");
|
||||
expect(codeOf(() => readImportFile(new Uint8Array([0x50, 0x4b, 3, 4, 1, 2, 3])))).toBe("invalid"); // trasig zip
|
||||
expect(codeOf(() => readImportFile(zip({ "annat.txt": strToU8("hej") })))).toBe("not-export");
|
||||
expect(codeOf(() => readImportFile(json({ a: 1 })))).toBe("not-export");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeName } from "@/lib/name-stats";
|
||||
import { BUILT_IN_POOLS, FEMALE_NAMES, MALE_NAMES, SURNAMES, generateName, generateNames, type NamePools } from "@/lib/names";
|
||||
|
||||
/** Förutsägbar slumpföljd: ger värdena i tur och ordning, om och om igen. */
|
||||
const sequence = (...values: number[]) => {
|
||||
let i = 0;
|
||||
return () => values[i++ % values.length];
|
||||
};
|
||||
|
||||
describe("inbyggda namnlistor", () => {
|
||||
it("har inga dubbletter och inget namn finns i båda könen", () => {
|
||||
for (const list of [FEMALE_NAMES, MALE_NAMES, SURNAMES]) expect(new Set(list).size).toBe(list.length);
|
||||
expect(FEMALE_NAMES.filter((n) => MALE_NAMES.includes(n))).toEqual([]);
|
||||
});
|
||||
|
||||
it("är tillräckligt stora", () => {
|
||||
expect(FEMALE_NAMES.length).toBeGreaterThan(100);
|
||||
expect(MALE_NAMES.length).toBeGreaterThan(100);
|
||||
expect(SURNAMES.length).toBeGreaterThan(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateName", () => {
|
||||
const options = { gender: "female", middleName: false, surname: "all" } as const;
|
||||
|
||||
it("väljer förnamn efter kön", () => {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
expect(FEMALE_NAMES).toContain(generateName({ ...options, gender: "female" }).split(" ")[0]);
|
||||
expect(MALE_NAMES).toContain(generateName({ ...options, gender: "male" }).split(" ")[0]);
|
||||
}
|
||||
});
|
||||
|
||||
it("slumpar kön när det är valfritt", () => {
|
||||
const female = generateName({ ...options, gender: "any" }, BUILT_IN_POOLS, sequence(0.1, 0, 0));
|
||||
const male = generateName({ ...options, gender: "any" }, BUILT_IN_POOLS, sequence(0.9, 0, 0));
|
||||
expect(FEMALE_NAMES).toContain(female.split(" ")[0]);
|
||||
expect(MALE_NAMES).toContain(male.split(" ")[0]);
|
||||
});
|
||||
|
||||
it("filtrerar efternamn på -son", () => {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
expect(generateName({ ...options, surname: "son" }).endsWith("son")).toBe(true);
|
||||
expect(generateName({ ...options, surname: "other" }).endsWith("son")).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("lägger till ett mellannamn när det önskas", () => {
|
||||
const name = generateName({ ...options, middleName: true }, BUILT_IN_POOLS, sequence(0, 0.5, 0.9));
|
||||
expect(name.split(" ")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("hoppar över mellannamnet om det blev samma som förnamnet", () => {
|
||||
const name = generateName({ ...options, middleName: true }, BUILT_IN_POOLS, sequence(0, 0, 0));
|
||||
expect(name.split(" ")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("viktar efter hur vanligt namnet är", () => {
|
||||
const pools: NamePools = { female: [["Vanlig", 1000], ["Ovanlig", 1]], male: [["X", 1]], surnames: [["Andersson", 1]] };
|
||||
expect(generateName(options, pools, () => 0.5)).toBe("Vanlig Andersson");
|
||||
expect(generateName(options, pools, () => 0.9999)).toBe("Ovanlig Andersson");
|
||||
});
|
||||
|
||||
it("faller tillbaka på alla efternamn om filtret inte ger något", () => {
|
||||
const pools: NamePools = { female: [["Anna", 1]], male: [["Erik", 1]], surnames: [["Lindqvist", 1]] };
|
||||
expect(generateName({ ...options, surname: "son" }, pools)).toBe("Anna Lindqvist");
|
||||
});
|
||||
|
||||
it("generateNames ger unika namn och högst begärt antal", () => {
|
||||
const names = generateNames({ gender: "any", middleName: false, surname: "all" }, 20);
|
||||
expect(names).toHaveLength(20);
|
||||
expect(new Set(names).size).toBe(20);
|
||||
const few = generateNames(options, 5, { female: [["Anna", 1]], male: [["Erik", 1]], surnames: [["A", 1]] });
|
||||
expect(few).toEqual(["Anna A"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeName (statistik från SCB)", () => {
|
||||
it("gör versaler till vanlig skrivning", () => {
|
||||
expect(normalizeName("JACOB")).toBe("Jacob");
|
||||
expect(normalizeName("ÅSA")).toBe("Åsa");
|
||||
expect(normalizeName("ANN-MARIE")).toBe("Ann-Marie");
|
||||
});
|
||||
|
||||
it("låter vanlig skrivning vara", () => {
|
||||
expect(normalizeName("Anna")).toBe("Anna");
|
||||
expect(normalizeName("Ann-Marie")).toBe("Ann-Marie");
|
||||
expect(normalizeName(" Erik ")).toBe("Erik");
|
||||
expect(normalizeName("O'Neil")).toBe("O'Neil");
|
||||
});
|
||||
|
||||
it("avvisar namn med mellanslag, siffror eller konstiga tecken", () => {
|
||||
for (const bad of ["", " ", "Mc Donald", "1Adam", "Anna2", "A".repeat(31), "Anna@", "<b>"]) {
|
||||
expect(normalizeName(bad)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { clientIp, limitRequest, rateLimit, rateLimitStats } from "@/lib/rate-limit";
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("rateLimit", () => {
|
||||
it("släpper igenom upp till gränsen och stoppar sedan", () => {
|
||||
const key = "test-limit";
|
||||
expect(rateLimit(key, 3, 1000).ok).toBe(true);
|
||||
expect(rateLimit(key, 3, 1000).ok).toBe(true);
|
||||
expect(rateLimit(key, 3, 1000).ok).toBe(true);
|
||||
const blocked = rateLimit(key, 3, 1000);
|
||||
expect(blocked.ok).toBe(false);
|
||||
expect(blocked.retryAfter).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("släpper igenom igen när tidsfönstret gått ut", () => {
|
||||
const key = "test-window";
|
||||
for (let i = 0; i < 2; i++) rateLimit(key, 2, 1000);
|
||||
expect(rateLimit(key, 2, 1000).ok).toBe(false);
|
||||
vi.advanceTimersByTime(1001);
|
||||
expect(rateLimit(key, 2, 1000).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("räknar varje nyckel för sig", () => {
|
||||
rateLimit("a", 1, 1000);
|
||||
expect(rateLimit("a", 1, 1000).ok).toBe(false);
|
||||
expect(rateLimit("b", 1, 1000).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("räknar stoppade anrop", () => {
|
||||
const before = rateLimitStats.blocked;
|
||||
rateLimit("count", 1, 1000);
|
||||
rateLimit("count", 1, 1000);
|
||||
rateLimit("count", 1, 1000);
|
||||
expect(rateLimitStats.blocked).toBe(before + 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clientIp och limitRequest", () => {
|
||||
const request = (headers: Record<string, string>) => new Request("http://localhost/x", { headers });
|
||||
|
||||
it("läser första adressen i x-forwarded-for", () => {
|
||||
expect(clientIp(request({ "x-forwarded-for": "1.2.3.4, 10.0.0.1" }))).toBe("1.2.3.4");
|
||||
expect(clientIp(request({ "x-real-ip": "5.6.7.8" }))).toBe("5.6.7.8");
|
||||
expect(clientIp(request({}))).toBe("unknown");
|
||||
});
|
||||
|
||||
it("svarar 429 med Retry-After när gränsen är nådd", () => {
|
||||
const req = request({ "x-forwarded-for": "9.9.9.9" });
|
||||
expect(limitRequest(req, "route", 1, 60_000)).toBeNull();
|
||||
const response = limitRequest(req, "route", 1, 60_000);
|
||||
expect(response?.status).toBe(429);
|
||||
expect(Number(response?.headers.get("Retry-After"))).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("begränsar per IP-adress", () => {
|
||||
expect(limitRequest(request({ "x-forwarded-for": "1.1.1.1" }), "ip-route", 1, 60_000)).toBeNull();
|
||||
expect(limitRequest(request({ "x-forwarded-for": "2.2.2.2" }), "ip-route", 1, 60_000)).toBeNull();
|
||||
expect(limitRequest(request({ "x-forwarded-for": "1.1.1.1" }), "ip-route", 1, 60_000)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { contentSecurityPolicy, runtimeSecurityHeaders } from "@/lib/security";
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
const directive = (csp: string, name: string) => csp.split("; ").find((d) => d.startsWith(`${name} `)) ?? "";
|
||||
|
||||
describe("Content-Security-Policy", () => {
|
||||
it("släpper igenom OpenStreetMap som standard", () => {
|
||||
vi.stubEnv("MAP_TILE_URL", "");
|
||||
vi.stubEnv("MAP_GEOCODER_URL", "");
|
||||
// Tomma värden (t.ex. "MAP_TILE_URL=" i .env) ska ge standard
|
||||
const csp = contentSecurityPolicy();
|
||||
expect(directive(csp, "img-src")).toContain("https://tile.openstreetmap.org");
|
||||
expect(directive(csp, "connect-src")).toContain("https://nominatim.openstreetmap.org");
|
||||
expect(csp).toContain("frame-ancestors 'none'");
|
||||
expect(csp).toContain("object-src 'none'");
|
||||
expect(csp).toContain("base-uri 'self'");
|
||||
});
|
||||
|
||||
it("använder adresserna från MAP_TILE_URL och MAP_GEOCODER_URL", () => {
|
||||
vi.stubEnv("MAP_TILE_URL", "https://tiles.example.com/{z}/{x}/{y}.png");
|
||||
vi.stubEnv("MAP_GEOCODER_URL", "https://geo.example.com/search");
|
||||
const csp = contentSecurityPolicy();
|
||||
expect(csp).toMatch(/img-src [^;]*https:\/\/tiles\.example\.com/);
|
||||
expect(csp).toMatch(/connect-src [^;]*https:\/\/geo\.example\.com/);
|
||||
expect(csp).not.toContain("openstreetmap.org");
|
||||
});
|
||||
|
||||
it("tillåter underdomäner när tilladressen har {s}", () => {
|
||||
vi.stubEnv("MAP_TILE_URL", "https://{s}.tiles.example.com/{z}/{x}/{y}.png");
|
||||
expect(contentSecurityPolicy()).toContain("https://*.tiles.example.com");
|
||||
});
|
||||
|
||||
it("tillåter inte eval i produktion men gör det vid utveckling", () => {
|
||||
vi.stubEnv("NODE_ENV", "production");
|
||||
expect(contentSecurityPolicy()).not.toContain("unsafe-eval");
|
||||
vi.stubEnv("NODE_ENV", "development");
|
||||
expect(contentSecurityPolicy()).toContain("unsafe-eval");
|
||||
});
|
||||
|
||||
it("ignorerar en trasig adress i stället för att krascha", () => {
|
||||
vi.stubEnv("MAP_TILE_URL", "inte en adress");
|
||||
expect(() => contentSecurityPolicy()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("runtimeSecurityHeaders", () => {
|
||||
it("sätter HSTS bara när AUTH_URL är https", () => {
|
||||
vi.stubEnv("AUTH_URL", "https://bocker.example.com");
|
||||
expect(runtimeSecurityHeaders()["Strict-Transport-Security"]).toContain("max-age=");
|
||||
vi.stubEnv("AUTH_URL", "http://localhost:3000");
|
||||
expect(runtimeSecurityHeaders()["Strict-Transport-Security"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("innehåller alltid en policy", () => {
|
||||
expect(runtimeSecurityHeaders()["Content-Security-Policy"]).toContain("default-src 'self'");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { KINDS } from "@/lib/kinds";
|
||||
import { FIELD_TYPES, formatFieldValue, getDefaultTemplate, getPresets, validateFields } from "@/lib/templates";
|
||||
|
||||
const ALL_KINDS = [...KINDS.map((k) => k.kind), "RELATION" as const];
|
||||
|
||||
describe("standardmallar", () => {
|
||||
for (const locale of ["sv", "en"] as const) {
|
||||
for (const kind of ALL_KINDS) {
|
||||
it(`${kind} (${locale}) har giltiga fält med unika nycklar`, () => {
|
||||
const fields = getDefaultTemplate(kind, locale);
|
||||
expect(fields.length).toBeGreaterThan(0);
|
||||
// Mallen ska klara samma kontroll som en sparad mall
|
||||
expect(validateFields(fields)).toEqual(fields);
|
||||
expect(new Set(fields.map((f) => f.key)).size).toBe(fields.length);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
it("val-fält har alternativ och kopplingsfält pekar på en känd typ", () => {
|
||||
for (const kind of ALL_KINDS) {
|
||||
for (const field of getDefaultTemplate(kind, "sv")) {
|
||||
if (field.type === "select") expect(field.options?.length).toBeGreaterThan(0);
|
||||
if (field.refKind) expect(KINDS.map((k) => k.kind)).toContain(field.refKind);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("svenska och engelska mallar har samma nycklar i samma ordning", () => {
|
||||
for (const kind of ALL_KINDS) {
|
||||
expect(getDefaultTemplate(kind, "en").map((f) => f.key)).toEqual(getDefaultTemplate(kind, "sv").map((f) => f.key));
|
||||
}
|
||||
});
|
||||
|
||||
it("kopplingar i standardmallarna är fältet Lokal i företag och utbildning", () => {
|
||||
const company = getDefaultTemplate("COMPANY", "sv").find((f) => f.key === "premises");
|
||||
expect(company).toMatchObject({ type: "reference", refKind: "PREMISES" });
|
||||
expect(getDefaultTemplate("EDUCATION", "sv").find((f) => f.key === "premises")).toMatchObject({ type: "reference", refKind: "PREMISES" });
|
||||
});
|
||||
|
||||
it("den korta karaktärsmallen är en delmängd av den fulla", () => {
|
||||
const full = getDefaultTemplate("CHARACTER", "sv").map((f) => f.key);
|
||||
const [preset] = getPresets("CHARACTER", "sv");
|
||||
expect(preset.id).toBe("short");
|
||||
expect(preset.fields.length).toBeLessThan(full.length);
|
||||
for (const field of preset.fields) expect(full).toContain(field.key);
|
||||
expect(getPresets("HOME", "sv")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateFields", () => {
|
||||
const ok = { key: "age", label: "Ålder", type: "number" };
|
||||
|
||||
it("godkänner en giltig mall och rensar mellanslag", () => {
|
||||
expect(validateFields([{ key: " age ", label: " Ålder ", type: "number", section: " Basics " }])).toEqual([
|
||||
{ key: "age", label: "Ålder", type: "number", section: "Basics" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("kräver en lista", () => {
|
||||
expect(() => validateFields({})).toThrow();
|
||||
expect(() => validateFields("x")).toThrow();
|
||||
});
|
||||
|
||||
it("avvisar ogiltiga nycklar", () => {
|
||||
for (const key of ["", "1abc", "a-b", "a b", "å", "x".repeat(50)]) {
|
||||
expect(() => validateFields([{ ...ok, key }])).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("avvisar dubbletter av nyckel", () => {
|
||||
expect(() => validateFields([ok, { ...ok, label: "Annat" }])).toThrow(/duplicate/);
|
||||
});
|
||||
|
||||
it("avvisar saknad rubrik och okänd typ", () => {
|
||||
expect(() => validateFields([{ ...ok, label: " " }])).toThrow();
|
||||
expect(() => validateFields([{ ...ok, type: "magic" }])).toThrow();
|
||||
});
|
||||
|
||||
it("godkänner alla fälttyper", () => {
|
||||
for (const type of FIELD_TYPES) expect(() => validateFields([{ key: "f", label: "F", type }])).not.toThrow();
|
||||
});
|
||||
|
||||
it("val-fält får rensade alternativ och andra typer får inga", () => {
|
||||
const [select] = validateFields([{ key: "s", label: "S", type: "select", options: [" A ", "", "B"] }]);
|
||||
expect(select.options).toEqual(["A", "B"]);
|
||||
const [text] = validateFields([{ key: "t", label: "T", type: "text", options: ["A"] }]);
|
||||
expect(text.options).toBeUndefined();
|
||||
});
|
||||
|
||||
it("kopplingsfält godkänner känd typ och avvisar okänd", () => {
|
||||
expect(validateFields([{ key: "p", label: "P", type: "reference", refKind: "PREMISES" }])[0].refKind).toBe("PREMISES");
|
||||
expect(validateFields([{ key: "p", label: "P", type: "reference" }])[0].refKind).toBeUndefined();
|
||||
expect(() => validateFields([{ key: "p", label: "P", type: "reference", refKind: "NOPE" }])).toThrow();
|
||||
});
|
||||
|
||||
it("begränsar antal fält och rubrikens längd", () => {
|
||||
const many = Array.from({ length: 101 }, (_, i) => ({ key: `f${i}`, label: "F", type: "text" }));
|
||||
expect(() => validateFields(many)).toThrow();
|
||||
expect(validateFields([{ key: "f", label: "x".repeat(500), type: "text" }])[0].label.length).toBe(160);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatFieldValue", () => {
|
||||
it("visar värden som text", () => {
|
||||
const text = { key: "t", label: "T", type: "text" as const };
|
||||
expect(formatFieldValue(text, "hej")).toBe("hej");
|
||||
expect(formatFieldValue({ ...text, type: "number" }, 0)).toBe("0");
|
||||
expect(formatFieldValue(text, null)).toBe("");
|
||||
expect(formatFieldValue(text, undefined)).toBe("");
|
||||
expect(formatFieldValue(text, "")).toBe("");
|
||||
});
|
||||
|
||||
it("visar kryssrutor som bock eller tomt, och kopplingar som tomt", () => {
|
||||
expect(formatFieldValue({ key: "c", label: "C", type: "checkbox" }, true)).toBe("✓");
|
||||
expect(formatFieldValue({ key: "c", label: "C", type: "checkbox" }, false)).toBe("");
|
||||
expect(formatFieldValue({ key: "r", label: "R", type: "reference" }, "abc")).toBe("");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user