stock-bot/test/integration/experiment-comparison-api.test.ts

128 lines
4.9 KiB
TypeScript

import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { z } from 'zod';
import { createHttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
const tokens = {
operator: 'validation-admin-fixture-not-a-real-secret-1234',
service: 'validation-service-fixture-not-a-real-secret-1234',
read: 'validation-read-fixture-not-a-real-secret-1234',
};
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
function fixture(
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => ({ rows: [] })
) {
const client = { query: mock(query) };
const database = {
query: mock(query),
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
};
const app = new Hono();
if (mode !== 'absent') {
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
hostname: '127.0.0.1',
disabled: mode === 'disabled',
}).mount(app);
}
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
return {
database,
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
return app.request('/api/v2/experiments' + path, {
method,
headers: {
'Content-Type': 'application/json',
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
...(key ? { 'Idempotency-Key': key } : {}),
},
...(body === undefined ? {} : { body }),
});
},
};
}
const leftId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
rightId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
query = `?leftId=${leftId}&rightId=${rightId}`;
describe('experiment comparison HTTP boundary', () => {
test('authorized read clients may compare without mutation credentials; unauthenticated reads are denied', async () => {
const f = fixture();
expect((await f.request('/compare' + query)).status).toBe(401);
for (const role of ['read', 'operator', 'service'] as const) {
const response = await f.request('/compare' + query, 'GET', undefined, role);
expect(response.status).toBe(404);
expect(response.headers.get('Cache-Control')).toBe('no-store');
}
expect(f.database.query.mock.calls).toHaveLength(0);
});
test('unknown/duplicate query keys, malformed IDs, same pair and reference keys fail before transactions', async () => {
for (const suffix of [
'',
`?leftId=${leftId}`,
query + '&unknown=1',
query + '&leftId=' + leftId,
query + '&%6CeftId=' + leftId,
query + '&referenceTrialKey=x',
`?leftId=${leftId}&rightId=${leftId}`,
`?leftId=${leftId}&rightId=${leftId.toUpperCase()}`,
query + '&referenceTrialKey=' + 'a'.repeat(64) + '&referenceTrialKey=' + 'a'.repeat(64),
]) {
const f = fixture();
expect((await f.request('/compare' + suffix, 'GET', undefined, 'read')).status).toBe(400);
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
});
test('valid UUID casing normalizes before querying retained experiment identities', async () => {
const identifiers: unknown[] = [];
const f = fixture('enabled', async (sql, values) => {
if (sql.includes('SELECT id,validation_phase')) {
identifiers.push(values?.[0]);
}
return { rows: [] };
});
expect(
(
await f.request(
`/compare?leftId=${leftId.toUpperCase()}&rightId=${rightId.toUpperCase()}`,
'GET',
undefined,
'read'
)
).status
).toBe(404);
expect(identifiers).toEqual([[leftId, rightId]]);
});
test('snapshot mode precedes role reads; unsupported phases409 and unexpected DB errors500 are sanitized', async () => {
const calls: string[] = [];
const f = fixture('enabled', async sql => {
calls.push(sql);
if (sql.includes('SELECT id,validation_phase')) {
return {
rows: [
{ id: leftId, validation_phase: 'train' },
{ id: rightId, validation_phase: null },
],
};
}
return { rows: [] };
});
expect((await f.request('/compare' + query, 'GET', undefined, 'read')).status).toBe(409);
expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
expect(calls).toHaveLength(2);
for (const error of [new Error('private storage error'), new z.ZodError([])]) {
const broken = fixture('enabled', async () => {
throw error;
});
const response = await broken.request('/compare' + query, 'GET', undefined, 'read');
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
}
});
});