routes.integration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import { describe, it, expect, beforeEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooks,
  6. TestDataFactory
  7. } from '~/utils/server/integration-test-db';
  8. import { IntegrationTestAssertions } from '~/utils/server/integration-test-utils';
  9. import { routesRoutes } from '@/server/api/admin/routes';
  10. import { AuthService } from '@/server/modules/auth/auth.service';
  11. import { UserService } from '@/server/modules/users/user.service';
  12. // 设置集成测试钩子
  13. setupIntegrationDatabaseHooks()
  14. describe('路线管理API集成测试', () => {
  15. let client: ReturnType<typeof testClient<typeof routesRoutes>>['api']['v1']['admin'];
  16. let testToken: string;
  17. beforeEach(async () => {
  18. // 创建测试客户端
  19. client = testClient(routesRoutes).api.v1.admin;
  20. // 创建测试用户并生成token
  21. const dataSource = await IntegrationTestDatabase.getDataSource();
  22. const userService = new UserService(dataSource);
  23. const authService = new AuthService(userService);
  24. // 确保admin用户存在
  25. const user = await authService.ensureAdminExists();
  26. // 生成admin用户的token
  27. testToken = authService.generateToken(user);
  28. });
  29. describe('路线创建测试', () => {
  30. it('应该成功创建路线', async () => {
  31. const dataSource = await IntegrationTestDatabase.getDataSource();
  32. if (!dataSource) throw new Error('Database not initialized');
  33. // 先创建一个活动
  34. const testActivity = await TestDataFactory.createTestActivity(dataSource);
  35. const routeData = {
  36. name: '测试路线',
  37. startPoint: '北京',
  38. endPoint: '上海',
  39. pickupPoint: '北京西站',
  40. dropoffPoint: '上海南站',
  41. departureTime: '2025-10-17T08:00:00.000Z',
  42. vehicleType: 'bus',
  43. price: 200,
  44. seatCount: 40,
  45. availableSeats: 40,
  46. activityId: testActivity.id
  47. };
  48. const response = await client.routes.$post({
  49. json: routeData,
  50. },
  51. {
  52. headers: {
  53. 'Authorization': `Bearer ${testToken}`
  54. }
  55. });
  56. // 断言响应
  57. expect(response.status).toBe(201);
  58. if (response.status === 201) {
  59. const responseData = await response.json();
  60. expect(responseData).toHaveProperty('id');
  61. expect(responseData.name).toBe(routeData.name);
  62. expect(responseData.startPoint).toBe(routeData.startPoint);
  63. expect(responseData.endPoint).toBe(routeData.endPoint);
  64. expect(responseData.pickupPoint).toBe(routeData.pickupPoint);
  65. expect(responseData.dropoffPoint).toBe(routeData.dropoffPoint);
  66. expect(responseData.vehicleType).toBe(routeData.vehicleType);
  67. expect(responseData.price).toBe(routeData.price);
  68. expect(responseData.seatCount).toBe(routeData.seatCount);
  69. expect(responseData.availableSeats).toBe(routeData.availableSeats);
  70. expect(responseData.isDisabled).toBe(0); // 默认启用
  71. // 断言数据库中存在路线
  72. await IntegrationTestAssertions.expectRouteToExist(responseData.id);
  73. }
  74. });
  75. it('应该拒绝创建无效车型的路线', async () => {
  76. const dataSource = await IntegrationTestDatabase.getDataSource();
  77. if (!dataSource) throw new Error('Database not initialized');
  78. const testActivity = await TestDataFactory.createTestActivity(dataSource);
  79. const routeData = {
  80. name: '测试路线',
  81. startPoint: '北京',
  82. endPoint: '上海',
  83. pickupPoint: '北京西站',
  84. dropoffPoint: '上海南站',
  85. departureTime: '2025-10-17T08:00:00.000Z',
  86. vehicleType: 'invalid_vehicle' as any, // 无效车型
  87. price: 200,
  88. seatCount: 40,
  89. availableSeats: 40,
  90. activityId: testActivity.id
  91. };
  92. const response = await client.routes.$post({
  93. json: routeData,
  94. },
  95. {
  96. headers: {
  97. 'Authorization': `Bearer ${testToken}`
  98. }
  99. });
  100. // 应该返回验证错误
  101. expect([400, 500]).toContain(response.status);
  102. });
  103. it('应该拒绝创建价格为负数的路线', async () => {
  104. const dataSource = await IntegrationTestDatabase.getDataSource();
  105. if (!dataSource) throw new Error('Database not initialized');
  106. const testActivity = await TestDataFactory.createTestActivity(dataSource);
  107. const routeData = {
  108. name: '测试路线',
  109. startPoint: '北京',
  110. endPoint: '上海',
  111. pickupPoint: '北京西站',
  112. dropoffPoint: '上海南站',
  113. departureTime: '2025-10-17T08:00:00.000Z',
  114. vehicleType: 'bus',
  115. price: -100, // 负数价格
  116. seatCount: 40,
  117. availableSeats: 40,
  118. activityId: testActivity.id
  119. };
  120. const response = await client.routes.$post({
  121. json: routeData,
  122. },
  123. {
  124. headers: {
  125. 'Authorization': `Bearer ${testToken}`
  126. }
  127. });
  128. // 应该返回验证错误
  129. expect([400, 500]).toContain(response.status);
  130. });
  131. });
  132. describe('路线读取测试', () => {
  133. it('应该成功获取路线列表', async () => {
  134. const dataSource = await IntegrationTestDatabase.getDataSource();
  135. if (!dataSource) throw new Error('Database not initialized');
  136. // 创建几个测试路线
  137. await TestDataFactory.createTestRoute(dataSource, { name: '路线1', vehicleType: 'bus' });
  138. await TestDataFactory.createTestRoute(dataSource, { name: '路线2', vehicleType: 'van' });
  139. const response = await client.routes.$get({
  140. query: {}
  141. },
  142. {
  143. headers: {
  144. 'Authorization': `Bearer ${testToken}`
  145. }
  146. });
  147. expect(response.status).toBe(200);
  148. if (response.status === 200) {
  149. const responseData = await response.json();
  150. expect(Array.isArray(responseData.data)).toBe(true);
  151. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  152. }
  153. });
  154. it('应该成功获取单个路线详情', async () => {
  155. const dataSource = await IntegrationTestDatabase.getDataSource();
  156. if (!dataSource) throw new Error('Database not initialized');
  157. const testRoute = await TestDataFactory.createTestRoute(dataSource, {
  158. name: '测试路线详情'
  159. });
  160. const response = await client.routes[':id'].$get({
  161. param: { id: testRoute.id }
  162. },
  163. {
  164. headers: {
  165. 'Authorization': `Bearer ${testToken}`
  166. }
  167. });
  168. expect(response.status).toBe(200);
  169. if (response.status === 200) {
  170. const responseData = await response.json();
  171. expect(responseData.id).toBe(testRoute.id);
  172. expect(responseData.name).toBe(testRoute.name);
  173. expect(responseData.vehicleType).toBe(testRoute.vehicleType);
  174. }
  175. });
  176. it('应该返回404当路线不存在时', async () => {
  177. const response = await client.routes[':id'].$get({
  178. param: { id: 999999 }
  179. },
  180. {
  181. headers: {
  182. 'Authorization': `Bearer ${testToken}`
  183. }
  184. });
  185. expect(response.status).toBe(404);
  186. if (response.status === 404) {
  187. const responseData = await response.json();
  188. expect(responseData.message).toContain('资源不存在');
  189. }
  190. });
  191. });
  192. describe('路线更新测试', () => {
  193. it('应该成功更新路线信息', async () => {
  194. const dataSource = await IntegrationTestDatabase.getDataSource();
  195. if (!dataSource) throw new Error('Database not initialized');
  196. const testRoute = await TestDataFactory.createTestRoute(dataSource, {
  197. name: '测试路线更新'
  198. });
  199. const updateData = {
  200. name: '更新后的路线名称',
  201. startPoint: '更新后的出发地',
  202. price: 300
  203. };
  204. const response = await client.routes[':id'].$put({
  205. param: { id: testRoute.id },
  206. json: updateData
  207. },
  208. {
  209. headers: {
  210. 'Authorization': `Bearer ${testToken}`
  211. }
  212. });
  213. expect(response.status).toBe(200);
  214. if (response.status === 200) {
  215. const responseData = await response.json();
  216. expect(responseData.name).toBe(updateData.name);
  217. expect(responseData.startPoint).toBe(updateData.startPoint);
  218. expect(responseData.price).toBe(updateData.price);
  219. }
  220. // 验证数据库中的更新
  221. const getResponse = await client.routes[':id'].$get({
  222. param: { id: testRoute.id }
  223. },
  224. {
  225. headers: {
  226. 'Authorization': `Bearer ${testToken}`
  227. }
  228. });
  229. if (getResponse.status === 200) {
  230. expect(getResponse.status).toBe(200);
  231. const getResponseData = await getResponse.json();
  232. expect(getResponseData.name).toBe(updateData.name);
  233. }
  234. });
  235. it('应该成功启用/禁用路线', async () => {
  236. const dataSource = await IntegrationTestDatabase.getDataSource();
  237. if (!dataSource) throw new Error('Database not initialized');
  238. const testRoute = await TestDataFactory.createTestRoute(dataSource, {
  239. name: '测试状态切换',
  240. isDisabled: 0 // 启用状态
  241. });
  242. // 禁用路线
  243. const disableResponse = await client.routes[':id'].$put({
  244. param: { id: testRoute.id },
  245. json: { isDisabled: 1 } // 禁用
  246. },
  247. {
  248. headers: {
  249. 'Authorization': `Bearer ${testToken}`
  250. }
  251. });
  252. expect(disableResponse.status).toBe(200);
  253. if (disableResponse.status === 200) {
  254. const disableData = await disableResponse.json();
  255. expect(disableData.isDisabled).toBe(1);
  256. }
  257. // 重新启用路线
  258. const enableResponse = await client.routes[':id'].$put({
  259. param: { id: testRoute.id },
  260. json: { isDisabled: 0 } // 启用
  261. },
  262. {
  263. headers: {
  264. 'Authorization': `Bearer ${testToken}`
  265. }
  266. });
  267. expect(enableResponse.status).toBe(200);
  268. if (enableResponse.status === 200) {
  269. const enableData = await enableResponse.json();
  270. expect(enableData.isDisabled).toBe(0);
  271. }
  272. });
  273. it('应该返回404当更新不存在的路线时', async () => {
  274. const updateData = {
  275. name: '更新后的名称'
  276. };
  277. const response = await client.routes[':id'].$put({
  278. param: { id: 999999 },
  279. json: updateData
  280. },
  281. {
  282. headers: {
  283. 'Authorization': `Bearer ${testToken}`
  284. }
  285. });
  286. expect(response.status).toBe(404);
  287. if (response.status === 404) {
  288. const responseData = await response.json();
  289. expect(responseData.message).toContain('资源不存在');
  290. }
  291. });
  292. });
  293. describe('路线删除测试', () => {
  294. it('应该成功删除路线', async () => {
  295. const dataSource = await IntegrationTestDatabase.getDataSource();
  296. if (!dataSource) throw new Error('Database not initialized');
  297. const testRoute = await TestDataFactory.createTestRoute(dataSource, {
  298. name: '测试路线删除'
  299. });
  300. const response = await client.routes[':id'].$delete({
  301. param: { id: testRoute.id }
  302. },
  303. {
  304. headers: {
  305. 'Authorization': `Bearer ${testToken}`
  306. }
  307. });
  308. IntegrationTestAssertions.expectStatus(response, 204);
  309. // 验证路线已从数据库中删除
  310. await IntegrationTestAssertions.expectRouteNotToExist(testRoute.id);
  311. // 验证再次获取路线返回404
  312. const getResponse = await client.routes[':id'].$get({
  313. param: { id: testRoute.id }
  314. },
  315. {
  316. headers: {
  317. 'Authorization': `Bearer ${testToken}`
  318. }
  319. });
  320. IntegrationTestAssertions.expectStatus(getResponse, 404);
  321. });
  322. it('应该返回404当删除不存在的路线时', async () => {
  323. const response = await client.routes[':id'].$delete({
  324. param: { id: 999999 }
  325. },
  326. {
  327. headers: {
  328. 'Authorization': `Bearer ${testToken}`
  329. }
  330. });
  331. IntegrationTestAssertions.expectStatus(response, 404);
  332. if (response.status === 404) {
  333. const responseData = await response.json();
  334. expect(responseData.message).toContain('资源不存在');
  335. }
  336. });
  337. });
  338. describe('路线搜索测试', () => {
  339. it('应该能够按路线名称搜索路线', async () => {
  340. const dataSource = await IntegrationTestDatabase.getDataSource();
  341. if (!dataSource) throw new Error('Database not initialized');
  342. await TestDataFactory.createTestRoute(dataSource, { name: '搜索路线1', startPoint: '北京' });
  343. await TestDataFactory.createTestRoute(dataSource, { name: '搜索路线2', startPoint: '上海' });
  344. await TestDataFactory.createTestRoute(dataSource, { name: '其他路线', startPoint: '广州' });
  345. const response = await client.routes.$get({
  346. query: { keyword: '搜索路线' }
  347. },
  348. {
  349. headers: {
  350. 'Authorization': `Bearer ${testToken}`
  351. }
  352. });
  353. IntegrationTestAssertions.expectStatus(response, 200);
  354. if (response.status === 200) {
  355. const responseData = await response.json();
  356. expect(Array.isArray(responseData.data)).toBe(true);
  357. expect(responseData.data.length).toBe(2);
  358. // 验证搜索结果包含正确的路线
  359. const names = responseData.data.map((route: any) => route.name);
  360. expect(names).toContain('搜索路线1');
  361. expect(names).toContain('搜索路线2');
  362. expect(names).not.toContain('其他路线');
  363. }
  364. });
  365. it('应该能够按出发地搜索路线', async () => {
  366. const dataSource = await IntegrationTestDatabase.getDataSource();
  367. if (!dataSource) throw new Error('Database not initialized');
  368. await TestDataFactory.createTestRoute(dataSource, { name: '路线1', startPoint: '北京出发' });
  369. await TestDataFactory.createTestRoute(dataSource, { name: '路线2', startPoint: '北京西站' });
  370. const response = await client.routes.$get({
  371. query: { keyword: '北京' }
  372. },
  373. {
  374. headers: {
  375. 'Authorization': `Bearer ${testToken}`
  376. }
  377. });
  378. IntegrationTestAssertions.expectStatus(response, 200);
  379. if (response.status === 200) {
  380. const responseData = await response.json();
  381. expect(responseData.data.length).toBe(2);
  382. const startPoints = responseData.data.map((route: any) => route.startPoint);
  383. expect(startPoints).toContain('北京出发');
  384. expect(startPoints).toContain('北京西站');
  385. }
  386. });
  387. it('应该能够按车型筛选路线', async () => {
  388. const dataSource = await IntegrationTestDatabase.getDataSource();
  389. if (!dataSource) throw new Error('Database not initialized');
  390. await TestDataFactory.createTestRoute(dataSource, { name: '大巴路线1', vehicleType: 'bus' });
  391. await TestDataFactory.createTestRoute(dataSource, { name: '大巴路线2', vehicleType: 'bus' });
  392. await TestDataFactory.createTestRoute(dataSource, { name: '中巴路线', vehicleType: 'van' });
  393. const response = await client.routes.$get({
  394. query: { filters: { vehicleType: 'bus' } }
  395. },
  396. {
  397. headers: {
  398. 'Authorization': `Bearer ${testToken}`
  399. }
  400. });
  401. IntegrationTestAssertions.expectStatus(response, 200);
  402. if (response.status === 200) {
  403. const responseData = await response.json();
  404. expect(responseData.data.length).toBe(2);
  405. const vehicleTypes = responseData.data.map((route: any) => route.vehicleType);
  406. expect(vehicleTypes.every((type: string) => type === 'bus')).toBe(true);
  407. }
  408. });
  409. });
  410. describe('性能测试', () => {
  411. it('路线列表查询响应时间应小于200ms', async () => {
  412. const dataSource = await IntegrationTestDatabase.getDataSource();
  413. if (!dataSource) throw new Error('Database not initialized');
  414. // 创建一些测试数据
  415. for (let i = 0; i < 10; i++) {
  416. await TestDataFactory.createTestRoute(dataSource, {
  417. name: `性能测试路线_${i}`,
  418. startPoint: `出发地_${i}`,
  419. endPoint: `目的地_${i}`
  420. });
  421. }
  422. const startTime = Date.now();
  423. const response = await client.routes.$get({
  424. query: {}
  425. },
  426. {
  427. headers: {
  428. 'Authorization': `Bearer ${testToken}`
  429. }
  430. });
  431. const endTime = Date.now();
  432. const responseTime = endTime - startTime;
  433. IntegrationTestAssertions.expectStatus(response, 200);
  434. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  435. });
  436. });
  437. });