routes.integration.test.ts 17 KB

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