test_unified_architecture.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #!/usr/bin/env node
  2. /**
  3. * 🧪 统一架构测试脚本
  4. * 验证新旧架构的完全统一和生产环境兼容性
  5. */
  6. import { SystemOrchestrator } from './src/modules/SystemOrchestrator.js'
  7. import { UnifiedTradingSystem } from './src/main-production.js'
  8. import { DevelopmentTradingSystem } from './src/core/app.js'
  9. import { logger } from './src/utils/logger.js'
  10. import * as dotenv from 'dotenv'
  11. // 加载环境变量
  12. dotenv.config()
  13. interface TestResult {
  14. name: string
  15. status: 'PASS' | 'FAIL' | 'SKIP'
  16. duration: number
  17. details?: string
  18. error?: string
  19. }
  20. class UnifiedArchitectureTestSuite {
  21. private results: TestResult[] = []
  22. /**
  23. * 运行完整的统一架构测试套件
  24. */
  25. async runAllTests(): Promise<void> {
  26. console.log('🧪 开始统一架构测试套件')
  27. console.log('=' + '='.repeat(60))
  28. await this.testSystemOrchestratorIntegration()
  29. await this.testProductionSystemCompatibility()
  30. await this.testDevelopmentSystemCompatibility()
  31. await this.testDeltaNeutralControllerIntegration()
  32. await this.testRiskMonitoringServiceIntegration()
  33. await this.testServiceLifecycleManagement()
  34. await this.testBackwardCompatibility()
  35. this.printTestResults()
  36. }
  37. /**
  38. * 测试SystemOrchestrator集成
  39. */
  40. private async testSystemOrchestratorIntegration(): Promise<void> {
  41. const testName = 'SystemOrchestrator 集成测试'
  42. const startTime = Date.now()
  43. try {
  44. logger.info('🧪 测试 SystemOrchestrator 集成...')
  45. const orchestrator = new SystemOrchestrator()
  46. // 初始化系统服务
  47. await orchestrator.initialize({
  48. accounts: [],
  49. enableTrading: false,
  50. enableDashboard: false,
  51. enableControlPlane: false
  52. })
  53. // 验证服务注册
  54. const services = await orchestrator.getSystemStatus()
  55. if (!services || typeof services !== 'object') {
  56. throw new Error('SystemOrchestrator 状态获取失败')
  57. }
  58. // 验证核心服务存在
  59. const requiredServices = [
  60. 'AccountManager',
  61. 'RiskManager',
  62. 'TradingEngine',
  63. 'DashboardService'
  64. ]
  65. for (const serviceName of requiredServices) {
  66. if (!services.services || !services.services[serviceName]) {
  67. throw new Error(`必需服务未注册: ${serviceName}`)
  68. }
  69. }
  70. this.results.push({
  71. name: testName,
  72. status: 'PASS',
  73. duration: Date.now() - startTime,
  74. details: `验证了 ${Object.keys(services.services).length} 个服务`
  75. })
  76. } catch (error) {
  77. this.results.push({
  78. name: testName,
  79. status: 'FAIL',
  80. duration: Date.now() - startTime,
  81. error: error instanceof Error ? error.message : String(error)
  82. })
  83. }
  84. }
  85. /**
  86. * 测试生产环境系统兼容性
  87. */
  88. private async testProductionSystemCompatibility(): Promise<void> {
  89. const testName = '生产环境系统兼容性'
  90. const startTime = Date.now()
  91. try {
  92. logger.info('🧪 测试生产环境系统兼容性...')
  93. // 测试生产环境配置验证
  94. const originalEnv = process.env.NODE_ENV
  95. process.env.NODE_ENV = 'production'
  96. // 验证生产环境类可以实例化
  97. const productionSystem = new UnifiedTradingSystem()
  98. if (!productionSystem) {
  99. throw new Error('生产环境系统实例化失败')
  100. }
  101. // 恢复环境变量
  102. process.env.NODE_ENV = originalEnv
  103. this.results.push({
  104. name: testName,
  105. status: 'PASS',
  106. duration: Date.now() - startTime,
  107. details: '生产环境系统类实例化成功'
  108. })
  109. } catch (error) {
  110. this.results.push({
  111. name: testName,
  112. status: 'FAIL',
  113. duration: Date.now() - startTime,
  114. error: error instanceof Error ? error.message : String(error)
  115. })
  116. }
  117. }
  118. /**
  119. * 测试开发环境系统兼容性
  120. */
  121. private async testDevelopmentSystemCompatibility(): Promise<void> {
  122. const testName = '开发环境系统兼容性'
  123. const startTime = Date.now()
  124. try {
  125. logger.info('🧪 测试开发环境系统兼容性...')
  126. // 验证开发环境类可以实例化
  127. const developmentSystem = new DevelopmentTradingSystem()
  128. if (!developmentSystem) {
  129. throw new Error('开发环境系统实例化失败')
  130. }
  131. // 测试开发环境状态获取
  132. const status = await developmentSystem.getStatus()
  133. if (!status || !status.environment || status.environment !== 'development') {
  134. throw new Error('开发环境状态获取失败')
  135. }
  136. this.results.push({
  137. name: testName,
  138. status: 'PASS',
  139. duration: Date.now() - startTime,
  140. details: `开发环境状态: ${status.status}`
  141. })
  142. } catch (error) {
  143. this.results.push({
  144. name: testName,
  145. status: 'FAIL',
  146. duration: Date.now() - startTime,
  147. error: error instanceof Error ? error.message : String(error)
  148. })
  149. }
  150. }
  151. /**
  152. * 测试DeltaNeutralController集成
  153. */
  154. private async testDeltaNeutralControllerIntegration(): Promise<void> {
  155. const testName = 'DeltaNeutralController 集成'
  156. const startTime = Date.now()
  157. try {
  158. logger.info('🧪 测试 DeltaNeutralController 集成...')
  159. // 验证DeltaNeutralController文件存在
  160. const { DeltaNeutralController } = await import('./src/controllers/DeltaNeutralController.js')
  161. if (!DeltaNeutralController) {
  162. throw new Error('DeltaNeutralController 导入失败')
  163. }
  164. this.results.push({
  165. name: testName,
  166. status: 'PASS',
  167. duration: Date.now() - startTime,
  168. details: 'DeltaNeutralController 成功集成'
  169. })
  170. } catch (error) {
  171. this.results.push({
  172. name: testName,
  173. status: 'FAIL',
  174. duration: Date.now() - startTime,
  175. error: error instanceof Error ? error.message : String(error)
  176. })
  177. }
  178. }
  179. /**
  180. * 测试RiskMonitoringService集成
  181. */
  182. private async testRiskMonitoringServiceIntegration(): Promise<void> {
  183. const testName = 'RiskMonitoringService 集成'
  184. const startTime = Date.now()
  185. try {
  186. logger.info('🧪 测试 RiskMonitoringService 集成...')
  187. // 验证RiskMonitoringService文件存在
  188. const { RiskMonitoringService } = await import('./src/services/RiskMonitoringService.js')
  189. if (!RiskMonitoringService) {
  190. throw new Error('RiskMonitoringService 导入失败')
  191. }
  192. this.results.push({
  193. name: testName,
  194. status: 'PASS',
  195. duration: Date.now() - startTime,
  196. details: 'RiskMonitoringService 成功集成'
  197. })
  198. } catch (error) {
  199. this.results.push({
  200. name: testName,
  201. status: 'FAIL',
  202. duration: Date.now() - startTime,
  203. error: error instanceof Error ? error.message : String(error)
  204. })
  205. }
  206. }
  207. /**
  208. * 测试服务生命周期管理
  209. */
  210. private async testServiceLifecycleManagement(): Promise<void> {
  211. const testName = '服务生命周期管理'
  212. const startTime = Date.now()
  213. try {
  214. logger.info('🧪 测试服务生命周期管理...')
  215. const orchestrator = new SystemOrchestrator()
  216. // 测试系统状态获取(不启动实际服务)
  217. const initialStatus = await orchestrator.getSystemStatus()
  218. if (!initialStatus || (initialStatus.status !== 'stopped' && initialStatus.status !== 'initialized')) {
  219. throw new Error(`初始状态应为 stopped 或 initialized,当前为: ${initialStatus.status}`)
  220. }
  221. this.results.push({
  222. name: testName,
  223. status: 'PASS',
  224. duration: Date.now() - startTime,
  225. details: `初始状态: ${initialStatus.status}`
  226. })
  227. } catch (error) {
  228. this.results.push({
  229. name: testName,
  230. status: 'FAIL',
  231. duration: Date.now() - startTime,
  232. error: error instanceof Error ? error.message : String(error)
  233. })
  234. }
  235. }
  236. /**
  237. * 测试向后兼容性
  238. */
  239. private async testBackwardCompatibility(): Promise<void> {
  240. const testName = '向后兼容性'
  241. const startTime = Date.now()
  242. try {
  243. logger.info('🧪 测试向后兼容性...')
  244. // 验证main.ts导出的向后兼容函数
  245. const mainModule = await import('./src/main.js')
  246. // 检查向后兼容导出
  247. if (typeof mainModule.greeter !== 'function') {
  248. throw new Error('向后兼容函数 greeter 不存在')
  249. }
  250. // 测试向后兼容函数
  251. const greeting = await mainModule.greeter('统一架构')
  252. if (!greeting || !greeting.includes('统一架构')) {
  253. throw new Error('向后兼容函数返回值不正确')
  254. }
  255. this.results.push({
  256. name: testName,
  257. status: 'PASS',
  258. duration: Date.now() - startTime,
  259. details: `兼容性测试: ${greeting}`
  260. })
  261. } catch (error) {
  262. this.results.push({
  263. name: testName,
  264. status: 'FAIL',
  265. duration: Date.now() - startTime,
  266. error: error instanceof Error ? error.message : String(error)
  267. })
  268. }
  269. }
  270. /**
  271. * 打印测试结果
  272. */
  273. private printTestResults(): void {
  274. console.log('\n' + '🧪 统一架构测试结果')
  275. console.log('=' + '='.repeat(60))
  276. let passCount = 0
  277. let failCount = 0
  278. let totalDuration = 0
  279. this.results.forEach(result => {
  280. const statusIcon = result.status === 'PASS' ? '✅' : result.status === 'FAIL' ? '❌' : '⏭️'
  281. console.log(`${statusIcon} ${result.name} (${result.duration}ms)`)
  282. if (result.details) {
  283. console.log(` 📋 ${result.details}`)
  284. }
  285. if (result.error) {
  286. console.log(` ❌ ${result.error}`)
  287. }
  288. if (result.status === 'PASS') passCount++
  289. if (result.status === 'FAIL') failCount++
  290. totalDuration += result.duration
  291. })
  292. console.log('\n' + '📊 测试统计')
  293. console.log('=' + '='.repeat(60))
  294. console.log(`✅ 通过: ${passCount}`)
  295. console.log(`❌ 失败: ${failCount}`)
  296. console.log(`⏭️ 跳过: ${this.results.length - passCount - failCount}`)
  297. console.log(`⏱️ 总时间: ${totalDuration}ms`)
  298. console.log(`📈 成功率: ${((passCount / this.results.length) * 100).toFixed(1)}%`)
  299. if (failCount === 0) {
  300. console.log('\n🎉 所有测试通过!统一架构验证成功!')
  301. } else {
  302. console.log('\n⚠️ 有测试失败,需要修复后再进行生产环境部署')
  303. }
  304. }
  305. }
  306. /**
  307. * 主测试函数
  308. */
  309. async function main(): Promise<void> {
  310. try {
  311. const testSuite = new UnifiedArchitectureTestSuite()
  312. await testSuite.runAllTests()
  313. } catch (error) {
  314. console.error('💥 测试套件执行失败:', error)
  315. process.exit(1)
  316. }
  317. }
  318. // 如果直接运行此文件,启动测试
  319. if (import.meta.url === `file://${process.argv[1]}`) {
  320. main().catch(error => {
  321. console.error('💥 测试失败:', error)
  322. process.exit(1)
  323. })
  324. }