/** * HTTP test helper - utilities for testing API endpoints */ import { testConfig } from '../test.config.ts'; export interface ITestRequest { method: string; path: string; body?: unknown; headers?: Record; query?: Record; } export interface ITestResponse { status: number; body: unknown; headers: Headers; } /** * Make a test request to the registry API */ export async function testRequest(options: ITestRequest): Promise { const baseUrl = testConfig.registry.url; let url = `${baseUrl}${options.path}`; if (options.query) { const params = new URLSearchParams(options.query); url += `?${params.toString()}`; } const response = await fetch(url, { method: options.method, headers: { 'Content-Type': 'application/json', ...options.headers, }, body: options.body ? JSON.stringify(options.body) : undefined, }); let body: unknown; try { body = await response.json(); } catch { body = await response.text(); } return { status: response.status, body, headers: response.headers, }; } // Convenience methods export const get = (path: string, headers?: Record) => testRequest({ method: 'GET', path, headers }); export const post = (path: string, body?: unknown, headers?: Record) => testRequest({ method: 'POST', path, body, headers }); export const put = (path: string, body?: unknown, headers?: Record) => testRequest({ method: 'PUT', path, body, headers }); export const patch = (path: string, body?: unknown, headers?: Record) => testRequest({ method: 'PATCH', path, body, headers }); export const del = (path: string, headers?: Record) => testRequest({ method: 'DELETE', path, headers }); /** * Assert response status */ export function assertStatus(response: ITestResponse, expected: number): void { if (response.status !== expected) { throw new Error( `Expected status ${expected} but got ${response.status}: ${JSON.stringify(response.body)}` ); } } /** * Assert response body has specific keys */ export function assertBodyHas(response: ITestResponse, keys: string[]): void { const body = response.body as Record; for (const key of keys) { if (!(key in body)) { throw new Error(`Expected response to have key "${key}", body: ${JSON.stringify(body)}`); } } } /** * Assert response is successful (2xx) */ export function assertSuccess(response: ITestResponse): void { if (response.status < 200 || response.status >= 300) { throw new Error( `Expected successful response but got ${response.status}: ${JSON.stringify(response.body)}` ); } } /** * Assert response is an error (4xx or 5xx) */ export function assertError(response: ITestResponse, expectedStatus?: number): void { if (response.status < 400) { throw new Error(`Expected error response but got ${response.status}`); } if (expectedStatus !== undefined && response.status !== expectedStatus) { throw new Error(`Expected status ${expectedStatus} but got ${response.status}`); } }