import { OpenAPIHono } from '@hono/zod-openapi'; import { Hono } from 'hono'; import { DataSource } from 'typeorm'; export interface TestServerOptions { setupAuth?: boolean; setupDatabase?: boolean; setupMiddlewares?: boolean; } /** * 创建测试服务器实例 */ export function createTestServer( app: OpenAPIHono | Hono, options: TestServerOptions = {} ) { const server = app as any; // 设置默认选项 const { setupAuth = true } = options; return { get: (path: string, headers?: Record) => makeRequest('GET', path, undefined, headers), post: (path: string, body?: any, headers?: Record) => makeRequest('POST', path, body, headers), put: (path: string, body?: any, headers?: Record) => makeRequest('PUT', path, body, headers), delete: (path: string, headers?: Record) => makeRequest('DELETE', path, undefined, headers), patch: (path: string, body?: any, headers?: Record) => makeRequest('PATCH', path, body, headers) }; async function makeRequest( method: string, path: string, body?: any, customHeaders?: Record ) { const url = new URL(path, 'http://localhost:3000'); const headers: Record = { 'Content-Type': 'application/json', ...(setupAuth && { 'Authorization': 'Bearer test-token-123' }), ...customHeaders }; const request = new Request(url.toString(), { method, headers, body: body ? JSON.stringify(body) : undefined, }); try { const response = await server.fetch(request); const responseHeaders: Record = {}; response.headers.forEach((value: string, key: string) => { responseHeaders[key] = value; }); let responseData: any; const contentType = response.headers.get('content-type'); if (contentType?.includes('application/json')) { responseData = await response.json(); } else { responseData = await response.text(); } return { status: response.status, headers: responseHeaders, data: responseData, json: async () => responseData, text: async () => responseData }; } catch (error) { throw new Error(`Request failed: ${error}`); } } } /** * 创建完整的测试应用实例 */ export async function createTestApp(routes: any[]) { const app = new OpenAPIHono(); // 注册所有路由 routes.forEach(route => { if (typeof route === 'function') { route(app); } }); return app; } /** * 创建测试数据库连接 */ export async function createTestDataSource(): Promise { // 使用内存数据库或测试数据库 const dataSource = new DataSource({ type: 'better-sqlite3', database: ':memory:', synchronize: true, logging: false, entities: [], // 需要根据实际实体配置 }); await dataSource.initialize(); return dataSource; }