Files
booksorter/src/server/app.test.ts
T
swaitsandClaude Fable 5.2 e23b6ee6c4 Add rotation calibration and millimetre rulers on the calibration sheet
A new rotation setting turns the whole print about the sheet centre, in
steps of 0.01 degree, on card sheets and the calibration sheet. The
calibration sheet now has millimetre rulers at every card edge; the four
lettered ones (A to D) are typed into Settings, which converts them into
corrected offsets and rotation. A simulation test checks the conversion
against modelled printer errors.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 17:14:22 -07:00

315 lines
17 KiB
TypeScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { openDb } from './db.ts';
import { createJobs } from './jobs.ts';
import { createApp, createEventBus } from './app.ts';
import type { CardData, Resolution, Settings } from '../shared/types.ts';
const found: Resolution = {
meta: { title: 'Rust', authors: ['Klabnik, Steve'], subjects: [] },
callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null,
};
function setupRecording(fresh: (boolean | undefined)[]) {
return setup(async (_i?: unknown, o?: { fresh?: boolean }) => { fresh.push(o?.fresh ?? false); return found; });
}
function setup(resolve: (i?: any, o?: any) => Promise<Resolution> = async () => found, port?: number) {
const db = openDb(':memory:');
const events = createEventBus();
const resolver = { resolve, tail: async () => [], search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} });
const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
const app = createApp({
db, jobs, resolver, events, port,
renderCardsPdf: async (cards, opts) => { pdfCalls.push({ cards, opts }); return new TextEncoder().encode('%PDF-stub'); },
renderCalibrationPdf: async () => new TextEncoder().encode('%PDF-cal'),
classNames: (l) => ({ className: 'Class ' + l[0], subclassName: 'Sub ' + l }),
});
const req = (method: string, path: string, json?: unknown, extra: Record<string, string> = {}) =>
app.request(path, { method, headers: { ...(json === undefined ? {} : { 'content-type': 'application/json' }), ...extra }, ...(json === undefined ? {} : { body: JSON.stringify(json) }) });
return { db, jobs, app, req, pdfCalls, events };
}
test('scan: valid, invalid, duplicate', async () => {
const { req, jobs, db } = setup();
const bad = await req('POST', '/api/scan', { isbn: '123' });
assert.equal(bad.status, 400);
assert.deepEqual(await bad.json(), { error: 'Not a valid ISBN' });
const ok = await req('POST', '/api/scan', { isbn: '978-1-59327-828-1' });
const j = await ok.json() as any;
assert.equal(j.duplicate, false);
assert.equal(j.book.isbn13, '9781593278281');
assert.equal(j.book.inQueue, true);
assert.equal(j.book.title, '9781593278281');
await jobs.idle();
assert.equal(db.getBook(j.book.id)!.status, 'resolved');
const dup = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
assert.equal(dup.duplicate, true);
assert.equal(dup.book.id, j.book.id);
assert.equal(dup.book.status, 'resolved');
});
test('two simultaneous scans of one ISBN yield one row', async () => {
const { req, db } = setup();
const rs = await Promise.all([1, 2, 3].map(() => req('POST', '/api/scan', { isbn: '9781593278281' })));
const js = await Promise.all(rs.map((r) => r.json() as Promise<any>));
assert.equal(db.listBooks().length, 1);
assert.equal(js.filter((j) => !j.duplicate).length, 1);
});
test('PATCH call number that parses, and one that does not', async () => {
const { req, db } = setup();
const { book } = db.insertPending({ isbn13: '9781593278281', title: 't' });
const a = await (await req('PATCH', `/api/books/${book.id}`, { callNumber: 'QA76.73.R87 K53 2018' })).json() as any;
assert.equal(a.book.callNumber, 'QA76.73.R87 K53 2018');
assert.equal(a.book.status, 'resolved');
assert.equal(a.book.manualOverride, true);
assert.equal(a.book.confidence, 'manual');
const b = await (await req('PATCH', `/api/books/${book.id}`, { callNumber: 'shelf by the window' })).json() as any;
assert.equal(b.book.callNumber, 'shelf by the window');
assert.equal(b.book.status, 'needs_attention');
assert.equal(b.book.attentionReason, 'Call number not recognised');
assert.equal(b.book.manualOverride, true);
assert.equal((await req('PATCH', '/api/books/999', { title: 'x' })).status, 404);
});
test('list order follows sort key with unparseable last; filters', async () => {
const { req } = setup();
const mk = async (title: string, callNumber: string) =>
req('POST', '/api/books/manual', { title, authors: ['A'], callNumber });
await mk('Window', 'shelf by the window');
await mk('Second', 'QA76.73.R87 K53 2018');
await mk('First', 'PS3558.E63 D8 2005');
const all = await (await req('GET', '/api/books')).json() as any[];
assert.deepEqual(all.map((b) => b.title), ['First', 'Second', 'Window']);
assert.equal(((await (await req('GET', '/api/books?filter=attention')).json()) as any[]).length, 1);
assert.equal(((await (await req('GET', '/api/books?q=second')).json()) as any[]).length, 1);
});
test('manual without call number enqueues a lookup; retry refused for override', async () => {
const { req, jobs, db } = setup();
const m = await (await req('POST', '/api/books/manual', { title: 'Foo', authors: ['Bar'] })).json() as any;
assert.equal(m.book.status, 'pending');
await jobs.idle();
assert.equal(db.getBook(m.book.id)!.status, 'resolved');
const r = await req('POST', `/api/books/${m.book.id}/retry`);
assert.equal(r.status, 200);
await jobs.idle();
await req('PATCH', `/api/books/${m.book.id}`, { callNumber: 'QA76' });
assert.equal((await req('POST', `/api/books/${m.book.id}/retry`)).status, 400);
});
test('lccn, from-search, search, delete, queue', async () => {
const { req, jobs, db } = setup();
const l = await (await req('POST', '/api/books/lccn', { lccn: '88005934' })).json() as any;
assert.equal(l.book.lccn, '88005934');
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], year: 1999, lccn: '1', lcc: [] } })).json() as any;
assert.equal(f.book.year, 1999);
assert.equal(((await (await req('GET', '/api/search?title=a&author=b')).json()) as any[])[0].title, 'Hit');
await jobs.idle();
db.updateBook(l.book.id, { inQueue: false });
assert.equal(((await (await req('POST', `/api/books/${l.book.id}/queue`)).json()) as any).book.inQueue, true);
assert.equal((await req('DELETE', `/api/books/${l.book.id}`)).status, 200);
assert.equal(db.getBook(l.book.id), null);
});
test('print with empty queue -> 400', async () => {
const { req } = setup();
const r = await req('GET', '/api/print.pdf');
assert.equal(r.status, 400);
assert.deepEqual(await r.json(), { error: 'Nothing to print' });
});
test('print passes cards in shelf order and honours start; confirm clears queue', async () => {
const { req, pdfCalls, db } = setup();
await req('POST', '/api/books/manual', { title: 'Second', callNumber: 'QA76.73.R87 K53 2018' });
await req('POST', '/api/books/manual', { title: 'First', callNumber: 'PS3558.E63 D8 2005' });
await req('POST', '/api/books/manual', { title: 'Odd', callNumber: 'shelf by the window' });
const approx = db.insertPending({ title: 'Approx', callNumber: 'B1 .A1 2000', sortKey: 'B 1', status: 'resolved', confidence: 'approximate', inQueue: true }).book;
const r = await req('GET', '/api/print.pdf?start=2');
assert.equal(r.status, 200);
assert.equal(r.headers.get('content-type'), 'application/pdf');
assert.equal(await r.text(), '%PDF-stub');
const call = pdfCalls[0]!;
assert.deepEqual(call.cards.map((c) => c.title), ['Approx', 'First', 'Second']);
assert.equal(call.opts.startPosition, 2);
assert.deepEqual(call.cards[1]!.hierarchy, { outline: ['Class P', 'Sub PS'], tail: [] });
assert.equal(call.cards[0]!.approximate, true);
assert.equal(call.cards[1]!.approximate, false);
const ids = r.headers.get('x-book-ids')!.split(',').map(Number);
assert.equal(ids.length, 3);
assert.equal(ids[0], approx.id);
await req('POST', '/api/print/confirm', { ids });
assert.equal((await req('GET', '/api/print.pdf')).status, 400);
assert.ok(db.getBook(ids[0]!)!.printedAt);
assert.equal(((await (await req('GET', '/api/books?filter=queue')).json()) as any[]).length, 1);
});
test('settings clamp and calibration pdf', async () => {
const { req } = setup();
assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 });
const s = await (await req('PUT', '/api/settings', { offsetXmm: 50, offsetYmm: -50, rotationDeg: 9 })).json();
assert.deepEqual(s, { offsetXmm: 10, offsetYmm: -10, rotationDeg: 3 });
assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 10, offsetYmm: -10, rotationDeg: 3 });
assert.deepEqual(await (await req('PUT', '/api/settings', { offsetXmm: 0.05, offsetYmm: 0, rotationDeg: -0.01 })).json(),
{ offsetXmm: 0.05, offsetYmm: 0, rotationDeg: -0.01 });
assert.equal((await (await req('PUT', '/api/settings', { offsetXmm: 1, offsetYmm: 2, rotationDeg: -7 })).json() as any).rotationDeg, -3);
// a body without rotationDeg leaves the stored rotation alone
assert.deepEqual(await (await req('PUT', '/api/settings', { offsetXmm: 1, offsetYmm: 2 })).json(), { offsetXmm: 1, offsetYmm: 2, rotationDeg: -3 });
assert.equal((await req('PUT', '/api/settings', { offsetXmm: 1, offsetYmm: 1, rotationDeg: 'x' })).status, 400);
assert.equal((await req('PUT', '/api/settings', { offsetXmm: 'a', offsetYmm: 1 })).status, 400);
assert.equal(await (await req('GET', '/api/calibration.pdf')).text(), '%PDF-cal');
});
test('events stream delivers changes and cleans up on disconnect', async () => {
const { app, req, events, db } = setup();
const ac = new AbortController();
const res = await app.request('/api/events', { signal: ac.signal });
assert.equal(res.headers.get('content-type'), 'text/event-stream');
assert.equal(events.listenerCount(), 1);
const reader = res.body!.getReader();
const dec = new TextDecoder();
await reader.read(); // initial comment
const { book } = db.insertPending({ title: 'x' });
await req('PATCH', `/api/books/${book.id}`, { title: 'y' });
const chunk = dec.decode((await reader.read()).value);
assert.match(chunk, /^event: book\ndata: .*"title":"y"/);
await req('DELETE', `/api/books/${book.id}`);
assert.match(dec.decode((await reader.read()).value), /^event: deleted\ndata: \{"id":\d+\}/);
ac.abort();
assert.equal(events.listenerCount(), 0);
const res2 = await app.request('/api/events');
assert.equal(events.listenerCount(), 1);
await res2.body!.cancel();
assert.equal(events.listenerCount(), 0);
});
test('state-changing requests from another origin are refused', async () => {
const { req, db } = setup(undefined, 4321);
const ok = ['http://localhost:4321', 'http://127.0.0.1:4321'];
const bad = ['http://evil.example', 'http://localhost:9999', 'http://localhost:4321.evil.com', 'null', 'https://localhost:4321'];
for (const origin of ok) assert.equal((await req('POST', '/api/books/manual', { title: 'T' }, { origin })).status, 200, origin);
for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
for (const origin of bad) {
const r = await req(method, '/api/books/1', method === 'DELETE' ? undefined : { title: 'x' }, { origin });
assert.equal(r.status, 403, `${method} ${origin}`);
}
}
assert.equal(db.listBooks().length, 2);
assert.equal((await req('GET', '/api/books', undefined, { origin: 'http://evil.example' })).status, 200);
assert.equal((await req('POST', '/api/books/manual', { title: 'No origin header' })).status, 200);
});
test('PATCH year must be an integer or null', async () => {
const { req, db, jobs } = setup();
const m = await (await req('POST', '/api/books/manual', { title: 'Foo', year: 2000 })).json() as any;
await jobs.idle();
for (const year of ['abc', 1999.5, true, {}, -4]) {
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year })).status, 400, JSON.stringify(year));
}
assert.equal(db.getBook(m.book.id)!.year, 2000);
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: 2011 })).status, 200);
assert.equal(db.getBook(m.book.id)!.year, 2011);
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: null })).status, 200);
assert.equal(db.getBook(m.book.id)!.year, null);
});
test('retry forgets the book\'s cached source responses', async () => {
const { req, db, jobs } = setup();
const s = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
await jobs.idle();
db.updateBook(s.book.id, { lccn: '2018012345', title: 'Rust Book' });
for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345',
'loc-title:Rust Book|Steve Klabnik', 'ol-data:9780201835953', 'loc-title:Other|X']) db.cache.set(k, 'body');
assert.equal((await req('POST', `/api/books/${s.book.id}/retry`)).status, 200);
await jobs.idle();
for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345', 'loc-title:Rust Book|Steve Klabnik']) {
assert.equal(db.cache.get(k), null, k);
}
assert.equal(db.cache.get('ol-data:9780201835953'), 'body');
assert.equal(db.cache.get('loc-title:Other|X'), 'body');
});
test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', async () => {
const { mkdtempSync, readdirSync, rmSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
const dir = mkdtempSync(join(tmpdir(), 'captures-'));
try {
const db = openDb(':memory:');
const resolver = { resolve: async () => found, tail: async () => [], search: async () => [] };
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} });
const app = createApp({
db, jobs, resolver, capturesDir: join(dir, 'captures'),
renderCardsPdf: async () => new Uint8Array(), renderCalibrationPdf: async () => new Uint8Array(),
classNames: () => ({ className: '', subclassName: '' }),
});
const png: Uint8Array<ArrayBuffer> = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);
const post = (b: Uint8Array<ArrayBuffer>) => app.request('/api/debug/capture', { method: 'POST', body: b });
const r = await post(png);
assert.equal(r.status, 200);
const j = await r.json() as { saved: string };
assert.match(j.saved, /^capture-.*\.png$/);
assert.equal((await post(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]))).status, 400);
assert.equal((await post(new Uint8Array(8 * 1024 * 1024 + 1))).status, 413);
for (let i = 0; i < 35; i++) await post(png);
assert.equal(readdirSync(join(dir, 'captures')).length, 30);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('retry asks the lookup to ignore its caches', async () => {
const fresh: (boolean | undefined)[] = [];
const { req, jobs } = setupRecording(fresh);
const s = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
await jobs.idle();
assert.equal((await req('POST', `/api/books/${s.book.id}/retry`)).status, 200);
await jobs.idle();
assert.deepEqual(fresh, [false, true]);
});
test('print order and the book list break identical sort keys by author surname, then title', async () => {
const { req, db, pdfCalls } = setup();
const add = (title: string, authors: string[]) => db.insertPending({
title, authors, callNumber: 'GV199.42 2020', sortKey: 'GV 0199.42 2020', confidence: 'approximate', source: 'ol-edition',
status: 'resolved', manualOverride: false, inQueue: true,
}).book;
add('Zebra trails', ['Pat Young']); add('Sierra South', ['Kathy Morey']); add('Alpine', ['Pat Young']); add('Day hikes', ['Marlise Kast-Myers']);
assert.deepEqual(db.listBooks().map((b) => b.title), ['Day hikes', 'Sierra South', 'Alpine', 'Zebra trails']);
assert.equal((await req('GET', '/api/print.pdf')).status, 200);
assert.deepEqual(pdfCalls[0]!.cards.map((c) => c.title), ['Day hikes', 'Sierra South', 'Alpine', 'Zebra trails']);
});
test('cards print stored author names in natural order', async () => {
const { req, db, pdfCalls } = setup();
db.insertPending({
title: 'Canyoneering 2', authors: ['Allen, Steve', 'Wilderness Press, Inc.'], callNumber: 'GV199.42 2020', sortKey: 'GV 0199.42 2020',
confidence: 'approximate', source: 'ol-edition', status: 'resolved', manualOverride: false, inQueue: true,
});
assert.equal((await req('GET', '/api/print.pdf')).status, 200);
assert.deepEqual(pdfCalls[0]!.cards[0]!.authors, ['Steve Allen', 'Wilderness Press, Inc.']);
});
test('a search result\'s LCCN (work-level) is not saved onto the book', async () => {
const { req } = setup();
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], lccn: '96067014', lcc: [] } })).json() as any;
assert.equal(f.book.lccn, null);
});
test('GET /api/books/:id/hierarchy answers with the outline and the stored tail', async () => {
const { req, db } = setup();
const b = db.insertPending({ title: 'H', callNumber: 'PS3558.E63 D8 2005', status: 'resolved', hierarchyTail: ['Utah'] }).book;
const r = await req('GET', `/api/books/${b.id}/hierarchy`);
assert.equal(r.status, 200);
assert.deepEqual(await r.json(), { outline: ['Class P', 'Sub PS'], tail: [] }); // the default builds from class names only
assert.equal((await req('GET', '/api/books/999/hierarchy')).status, 404);
});
test('a cross-origin request that changes state is refused', async () => {
const { req, db } = setup(undefined, 4321);
assert.equal((await req('POST', '/api/books/manual', { title: 'X' }, { origin: 'http://evil.example' })).status, 403);
assert.equal((await req('POST', '/api/books/manual', { title: 'X' }, { origin: 'http://localhost:4321' })).status, 200);
assert.equal(db.listBooks().length, 1);
});