import routeCache from '../utils/cache/RouteCache.js' import performanceMonitor from '../middlewares/RoutePerformance/index.js' import { logger } from '@/logger.js' /** * 路由缓存测试工具 * 用于验证缓存功能和性能监控 */ class RouteCacheTest { constructor() { this.testResults = [] } /** * 运行所有测试 */ async runAllTests() { logger.info('[缓存测试] 开始运行路由缓存测试套件') // 清除之前的测试数据 this.testResults = [] routeCache.clearAll() try { await this.testBasicCaching() await this.testControllerCaching() await this.testPerformanceMonitoring() await this.testCacheConfiguration() this.printTestResults() } catch (error) { logger.error('[缓存测试] 测试过程中发生错误:', error) } } /** * 测试基本路由缓存功能 */ async testBasicCaching() { logger.info('[缓存测试] 测试基本路由缓存功能') try { // 测试缓存miss const route1 = routeCache.getRouteMatch('GET', '/api/test') this.assert(route1 === null, '初始状态应该缓存miss') // 测试缓存set const mockRoute = { path: '/api/test', params: {}, handler: () => {}, meta: {} } routeCache.setRouteMatch('GET', '/api/test', mockRoute) // 测试缓存hit const route2 = routeCache.getRouteMatch('GET', '/api/test') this.assert(route2 !== null, '设置缓存后应该命中') this.assert(route2.path === '/api/test', '缓存内容应该正确') this.addTestResult('基本路由缓存', true, '缓存设置和获取功能正常') } catch (error) { this.addTestResult('基本路由缓存', false, error.message) } } /** * 测试控制器缓存功能 */ async testControllerCaching() { logger.info('[缓存测试] 测试控制器缓存功能') try { // 测试控制器缓存miss const controller1 = routeCache.getController('TestController') this.assert(controller1 === null, '初始状态控制器缓存应该miss') // 测试控制器缓存set const mockController = { name: 'TestController', methods: ['test'] } routeCache.setController('TestController', mockController) // 测试控制器缓存hit const controller2 = routeCache.getController('TestController') this.assert(controller2 !== null, '设置控制器缓存后应该命中') this.assert(controller2.name === 'TestController', '控制器缓存内容应该正确') this.addTestResult('控制器缓存', true, '控制器缓存功能正常') } catch (error) { this.addTestResult('控制器缓存', false, error.message) } } /** * 测试性能监控功能 */ async testPerformanceMonitoring() { logger.info('[缓存测试] 测试性能监控功能') try { // 启用性能监控 performanceMonitor.enable() // 模拟记录一些性能数据 performanceMonitor.recordPerformance('GET', '/api/test', 150, false) performanceMonitor.recordPerformance('GET', '/api/test', 120, true) performanceMonitor.recordPerformance('GET', '/api/test', 180, false) // 获取性能报告 const report = performanceMonitor.getPerformanceReport() this.assert(report.enabled === true, '性能监控应该启用') this.assert(report.routes.length > 0, '应该有性能数据') const testRoute = report.routes.find(r => r.path === '/api/test') this.assert(testRoute !== undefined, '应该找到测试路由的性能数据') this.assert(testRoute.requestCount === 3, '请求计数应该正确') this.addTestResult('性能监控', true, '性能监控功能正常') } catch (error) { this.addTestResult('性能监控', false, error.message) } } /** * 测试缓存配置功能 */ async testCacheConfiguration() { logger.info('[缓存测试] 测试缓存配置功能') try { // 获取初始统计 const initialStats = routeCache.getStats() this.assert(typeof initialStats.hitRate === 'string', '命中率应该是字符串格式') this.assert(initialStats.caches !== undefined, '应该有缓存统计信息') // 测试禁用缓存 routeCache.disable() this.assert(routeCache.config.enabled === false, '缓存应该被禁用') // 测试启用缓存 routeCache.enable() this.assert(routeCache.config.enabled === true, '缓存应该被启用') // 测试配置更新 const newConfig = { maxMatchCacheSize: 2000 } routeCache.updateConfig(newConfig) this.assert(routeCache.config.maxMatchCacheSize === 2000, '配置应该被更新') this.addTestResult('缓存配置', true, '缓存配置功能正常') } catch (error) { this.addTestResult('缓存配置', false, error.message) } } /** * 断言辅助函数 */ assert(condition, message) { if (!condition) { throw new Error(`断言失败: ${message}`) } } /** * 添加测试结果 */ addTestResult(testName, passed, message) { this.testResults.push({ name: testName, passed, message, timestamp: new Date().toISOString() }) const status = passed ? '✅ 通过' : '❌ 失败' logger.info(`[缓存测试] ${testName}: ${status} - ${message}`) } /** * 打印测试结果摘要 */ printTestResults() { const totalTests = this.testResults.length const passedTests = this.testResults.filter(r => r.passed).length const failedTests = totalTests - passedTests logger.info('[缓存测试] =================== 测试结果摘要 ===================') logger.info(`[缓存测试] 总计测试: ${totalTests}`) logger.info(`[缓存测试] 通过: ${passedTests}`) logger.info(`[缓存测试] 失败: ${failedTests}`) logger.info(`[缓存测试] 成功率: ${((passedTests / totalTests) * 100).toFixed(2)}%`) if (failedTests > 0) { logger.warn('[缓存测试] 失败的测试:') this.testResults.filter(r => !r.passed).forEach(result => { logger.warn(`[缓存测试] - ${result.name}: ${result.message}`) }) } // 输出缓存统计 const stats = routeCache.getStats() logger.info('[缓存测试] 最终缓存统计:', stats) logger.info('[缓存测试] ================================================') } /** * 获取测试结果 */ getTestResults() { return { summary: { total: this.testResults.length, passed: this.testResults.filter(r => r.passed).length, failed: this.testResults.filter(r => !r.passed).length, successRate: this.testResults.length > 0 ? ((this.testResults.filter(r => r.passed).length / this.testResults.length) * 100).toFixed(2) + '%' : '0%' }, details: this.testResults, cacheStats: routeCache.getStats(), performanceReport: performanceMonitor.getPerformanceReport() } } } // 导出测试类 export default RouteCacheTest export { RouteCacheTest }