MEGAINFRA-WEBAPP/src/lib/dn-pipeline/split.test.ts

48 lines
1.7 KiB
TypeScript

import { describe, it, expect, beforeAll } from "vitest";
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { extractPageRange, pageCount, splitPages } from "./split";
const FIXTURE = "src/lib/dn-pipeline/__fixtures__/four-note-scan.pdf";
const PDF = "application/pdf";
describe.skipIf(!existsSync(FIXTURE))("split (requires poppler + the fixture)", () => {
let buf: Buffer;
beforeAll(async () => {
buf = await readFile(FIXTURE);
});
it("counts the pages", async () => {
expect(await pageCount(buf, PDF)).toBe(4);
});
it("renders one PNG per page, in order", async () => {
const pages = await splitPages(buf, PDF);
expect(pages.map((p) => p.page)).toEqual([1, 2, 3, 4]);
for (const p of pages) {
// PNG magic number.
expect(p.png.subarray(0, 4)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47]));
expect(p.png.length).toBeGreaterThan(1000);
}
});
it("extracts a page range into its own PDF", async () => {
const out = await extractPageRange(buf, PDF, 2, 3);
expect(await pageCount(out, PDF)).toBe(2);
});
it("extracts a page range from a PDF despite an incorrect declared MIME", async () => {
const out = await extractPageRange(buf, "image/jpeg", 2, 3);
expect(await pageCount(out, PDF)).toBe(2);
});
it("rejects a range outside the document", async () => {
await expect(extractPageRange(buf, PDF, 3, 9)).rejects.toThrow("out of range");
});
it("normalises an image as a single PNG page", async () => {
const fake = Buffer.from([0xff, 0xd8, 0xff]);
expect(await pageCount(fake, "image/jpeg")).toBe(1);
await expect(splitPages(fake, "image/jpeg")).rejects.toThrow("unsupported_image_codec");
});
});