Study/tests/helpers.ts
Elijah eae109c166 Add HTTP routes, app wiring, V1 migration, backups, templates and API tests
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 08:22:47 -07:00

121 lines
4.6 KiB
TypeScript

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { Hono } from 'hono';
import { createApp } from '../server/app.ts';
import { initAuth, resetRateLimits } from '../server/auth.ts';
import { loadConfig } from '../server/config.ts';
import { openDatabase } from '../server/db.ts';
import type { AppContext } from '../server/http.ts';
import { getSetting } from '../server/settings.ts';
import { seedTemplates } from '../server/services/templates.ts';
export interface TestApp {
ctx: AppContext;
hono: Hono;
dir: string;
cookie: string;
/** JSON request with the session cookie and CSRF header attached. */
api: <T = any>(method: string, url: string, body?: unknown, opts?: { cookie?: string | null; headers?: Record<string, string> }) => Promise<{ status: number; body: T; headers: Headers }>;
raw: (method: string, url: string, init?: RequestInit & { cookie?: string | null }) => Promise<Response>;
close: () => void;
}
export const PASSWORD = 'correct horse battery';
export async function createTestApp(opts: { login?: boolean; dir?: string; env?: Record<string, string> } = {}): Promise<TestApp> {
const dir = opts.dir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'studydesk-test-'));
resetRateLimits();
const config = loadConfig({ env: 'test', dataDir: dir, webDir: null }, { NODE_ENV: 'test', TZ: 'America/Phoenix', ...opts.env });
const { db } = openDatabase(config.dbPath, config.backupsDir);
const logs: string[] = [];
const ctx: AppContext = { db, config, log: (level, message, extra) => logs.push(`${level} ${message} ${extra instanceof Error ? extra.stack : extra ? JSON.stringify(extra) : ''}`) };
await initAuth(ctx);
seedTemplates(db);
const hono = createApp(ctx);
const t: TestApp = {
ctx,
hono,
dir,
cookie: '',
raw: (method, url, init = {}) => {
const headers = new Headers(init.headers);
const cookie = init.cookie === undefined ? t.cookie : init.cookie;
if (cookie) headers.set('cookie', cookie);
if (!headers.has('x-requested-with')) headers.set('x-requested-with', 'studydesk');
return Promise.resolve(hono.request(url, { ...init, method, headers }));
},
api: async (method, url, body, o = {}) => {
const res = await t.raw(method, url, {
cookie: o.cookie,
headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...o.headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let parsed: any = text;
try {
parsed = JSON.parse(text);
} catch {
/* non-JSON response */
}
return { status: res.status, body: parsed, headers: res.headers };
},
close: () => {
try {
db.close();
} catch {
/* ignore */
}
if (!opts.dir) fs.rmSync(dir, { recursive: true, force: true });
},
};
if (opts.login !== false) {
const code = getSetting<string | null>(db, 'auth.setup_code', null);
const res = code
? await t.raw('POST', '/api/auth/setup', { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, password: PASSWORD }), cookie: null })
: await t.raw('POST', '/api/auth/login', { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ password: PASSWORD }), cookie: null });
if (res.status !== 200) throw new Error(`test login failed: ${res.status} ${await res.text()}`);
t.cookie = (res.headers.get('set-cookie') ?? '').split(';')[0];
}
return t;
}
export const sampleQuestions = [
{
type: 'single',
stem: 'Which electrolyte imbalance causes peaked T waves?',
options: [
{ text: 'Hypokalemia', correct: false },
{ text: 'Hyperkalemia', correct: true },
{ text: 'Hyponatremia', correct: false },
{ text: 'Hypercalcemia', correct: false },
],
rationale: 'High potassium produces tall, peaked T waves.',
topic: 'Electrolytes',
},
{
type: 'multi',
stem: 'Which are signs of digoxin toxicity? Select all that apply.',
options: [
{ text: 'Visual halos', correct: true },
{ text: 'Nausea', correct: true },
{ text: 'Hypertension', correct: false },
{ text: 'Bradycardia', correct: true },
],
rationale: 'GI and visual changes come first.',
topic: 'Pharmacology',
},
{
type: 'single',
stem: 'Normal adult serum potassium is:',
options: [
{ text: '3.5 to 5.0 mEq/L', correct: true },
{ text: '1.5 to 2.5 mEq/L', correct: false },
{ text: '135 to 145 mEq/L', correct: false },
],
rationale: '',
topic: 'Electrolytes',
},
];