passengers.integration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 { adminPassengersRoutesExport } from '@/server/api';
  10. import { AuthService } from '@/server/modules/auth/auth.service';
  11. import { UserService } from '@/server/modules/users/user.service';
  12. import { IdType } from '@/server/modules/passengers/passenger.entity';
  13. // 设置集成测试钩子
  14. setupIntegrationDatabaseHooks()
  15. describe('乘客管理API集成测试', () => {
  16. let client: ReturnType<typeof testClient<typeof adminPassengersRoutesExport>>['api']['v1']['admin'];
  17. let testToken: string;
  18. beforeEach(async () => {
  19. // 创建测试客户端
  20. client = testClient(adminPassengersRoutesExport).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. const testUser = await TestDataFactory.createTestUser(dataSource);
  34. const passengerData = {
  35. userId: testUser.id,
  36. name: '测试乘客',
  37. idType: IdType.ID_CARD,
  38. idNumber: '110101199001011234',
  39. phone: '13812345678',
  40. isDefault: false
  41. };
  42. const response = await client.passengers.$post({
  43. json: passengerData,
  44. },
  45. {
  46. headers: {
  47. 'Authorization': `Bearer ${testToken}`
  48. }
  49. });
  50. // 断言响应
  51. expect(response.status).toBe(201);
  52. if (response.status === 201) {
  53. const responseData = await response.json();
  54. expect(responseData).toHaveProperty('id');
  55. expect(responseData.name).toBe(passengerData.name);
  56. expect(responseData.idType).toBe(passengerData.idType);
  57. expect(responseData.idNumber).toBe(passengerData.idNumber);
  58. expect(responseData.phone).toBe(passengerData.phone);
  59. expect(responseData.isDefault).toBe(passengerData.isDefault);
  60. // 断言数据库中存在乘客
  61. await IntegrationTestAssertions.expectPassengerToExist(responseData.id);
  62. }
  63. });
  64. it('应该成功创建默认乘客', async () => {
  65. const dataSource = await IntegrationTestDatabase.getDataSource();
  66. const testUser = await TestDataFactory.createTestUser(dataSource);
  67. const passengerData = {
  68. userId: testUser.id,
  69. name: '默认乘客',
  70. idType: IdType.PASSPORT,
  71. idNumber: 'E12345678',
  72. phone: '13987654321',
  73. isDefault: true
  74. };
  75. const response = await client.passengers.$post({
  76. json: passengerData,
  77. },
  78. {
  79. headers: {
  80. 'Authorization': `Bearer ${testToken}`
  81. }
  82. });
  83. expect(response.status).toBe(201);
  84. if (response.status === 201) {
  85. const responseData = await response.json();
  86. expect(responseData.isDefault).toBe(true);
  87. }
  88. });
  89. it('应该拒绝创建无效证件类型的乘客', async () => {
  90. const dataSource = await IntegrationTestDatabase.getDataSource();
  91. const testUser = await TestDataFactory.createTestUser(dataSource);
  92. const passengerData = {
  93. userId: testUser.id,
  94. name: '测试乘客',
  95. idType: 'invalid_type' as any, // 无效类型
  96. idNumber: '110101199001011234',
  97. phone: '13812345678',
  98. isDefault: false
  99. };
  100. const response = await client.passengers.$post({
  101. json: passengerData,
  102. },
  103. {
  104. headers: {
  105. 'Authorization': `Bearer ${testToken}`
  106. }
  107. });
  108. // 应该返回验证错误
  109. expect([400, 500]).toContain(response.status);
  110. });
  111. });
  112. describe('乘客读取测试', () => {
  113. it('应该成功获取乘客列表', async () => {
  114. const dataSource = await IntegrationTestDatabase.getDataSource();
  115. if (!dataSource) throw new Error('Database not initialized');
  116. // 创建几个测试乘客
  117. await TestDataFactory.createTestPassenger(dataSource, { name: '乘客1' });
  118. await TestDataFactory.createTestPassenger(dataSource, { name: '乘客2' });
  119. const response = await client.passengers.$get({
  120. query: {}
  121. },
  122. {
  123. headers: {
  124. 'Authorization': `Bearer ${testToken}`
  125. }
  126. });
  127. if (response.status !== 200) {
  128. const errorData = await response.json();
  129. console.debug('获取乘客列表失败:', errorData);
  130. }
  131. expect(response.status).toBe(200);
  132. if (response.status === 200) {
  133. const responseData = await response.json();
  134. expect(Array.isArray(responseData.data)).toBe(true);
  135. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  136. }
  137. });
  138. it('应该成功获取单个乘客详情', async () => {
  139. const dataSource = await IntegrationTestDatabase.getDataSource();
  140. if (!dataSource) throw new Error('Database not initialized');
  141. const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
  142. name: '测试乘客详情'
  143. });
  144. const response = await client.passengers[':id'].$get({
  145. param: { id: testPassenger.id }
  146. },
  147. {
  148. headers: {
  149. 'Authorization': `Bearer ${testToken}`
  150. }
  151. });
  152. expect(response.status).toBe(200);
  153. if (response.status === 200) {
  154. const responseData = await response.json();
  155. expect(responseData.id).toBe(testPassenger.id);
  156. expect(responseData.name).toBe(testPassenger.name);
  157. expect(responseData.idType).toBe(testPassenger.idType);
  158. expect(responseData.idNumber).toBe(testPassenger.idNumber);
  159. expect(responseData.phone).toBe(testPassenger.phone);
  160. }
  161. });
  162. it('应该返回404当乘客不存在时', async () => {
  163. const response = await client.passengers[':id'].$get({
  164. param: { id: 999999 }
  165. },
  166. {
  167. headers: {
  168. 'Authorization': `Bearer ${testToken}`
  169. }
  170. });
  171. expect(response.status).toBe(404);
  172. if (response.status === 404) {
  173. const responseData = await response.json();
  174. expect(responseData.message).toContain('资源不存在');
  175. }
  176. });
  177. });
  178. describe('乘客更新测试', () => {
  179. it('应该成功更新乘客信息', async () => {
  180. const dataSource = await IntegrationTestDatabase.getDataSource();
  181. if (!dataSource) throw new Error('Database not initialized');
  182. const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
  183. name: '测试乘客更新'
  184. });
  185. const updateData = {
  186. name: '更新后的乘客名称',
  187. phone: '13987654321',
  188. isDefault: true
  189. };
  190. const response = await client.passengers[':id'].$put({
  191. param: { id: testPassenger.id },
  192. json: updateData
  193. },
  194. {
  195. headers: {
  196. 'Authorization': `Bearer ${testToken}`
  197. }
  198. });
  199. expect(response.status).toBe(200);
  200. if (response.status === 200) {
  201. const responseData = await response.json();
  202. expect(responseData.name).toBe(updateData.name);
  203. expect(responseData.phone).toBe(updateData.phone);
  204. expect(responseData.isDefault).toBe(updateData.isDefault);
  205. }
  206. // 验证数据库中的更新
  207. const getResponse = await client.passengers[':id'].$get({
  208. param: { id: testPassenger.id }
  209. },
  210. {
  211. headers: {
  212. 'Authorization': `Bearer ${testToken}`
  213. }
  214. });
  215. if (getResponse.status === 200) {
  216. expect(getResponse.status).toBe(200);
  217. const getResponseData = await getResponse.json();
  218. expect(getResponseData.name).toBe(updateData.name);
  219. expect(getResponseData.phone).toBe(updateData.phone);
  220. }
  221. });
  222. it('应该返回404当更新不存在的乘客时', async () => {
  223. const updateData = {
  224. name: '更新后的名称'
  225. };
  226. const response = await client.passengers[':id'].$put({
  227. param: { id: 999999 },
  228. json: updateData
  229. },
  230. {
  231. headers: {
  232. 'Authorization': `Bearer ${testToken}`
  233. }
  234. });
  235. expect(response.status).toBe(404);
  236. if (response.status === 404) {
  237. const responseData = await response.json();
  238. expect(responseData.message).toContain('资源不存在');
  239. }
  240. });
  241. });
  242. describe('乘客删除测试', () => {
  243. it('应该成功删除乘客', async () => {
  244. const dataSource = await IntegrationTestDatabase.getDataSource();
  245. if (!dataSource) throw new Error('Database not initialized');
  246. const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
  247. name: '测试乘客删除'
  248. });
  249. const response = await client.passengers[':id'].$delete({
  250. param: { id: testPassenger.id }
  251. },
  252. {
  253. headers: {
  254. 'Authorization': `Bearer ${testToken}`
  255. }
  256. });
  257. IntegrationTestAssertions.expectStatus(response, 204);
  258. // 验证乘客已从数据库中删除
  259. await IntegrationTestAssertions.expectPassengerNotToExist(testPassenger.id);
  260. // 验证再次获取乘客返回404
  261. const getResponse = await client.passengers[':id'].$get({
  262. param: { id: testPassenger.id }
  263. },
  264. {
  265. headers: {
  266. 'Authorization': `Bearer ${testToken}`
  267. }
  268. });
  269. IntegrationTestAssertions.expectStatus(getResponse, 404);
  270. });
  271. it('应该返回404当删除不存在的乘客时', async () => {
  272. const response = await client.passengers[':id'].$delete({
  273. param: { id: 999999 }
  274. },
  275. {
  276. headers: {
  277. 'Authorization': `Bearer ${testToken}`
  278. }
  279. });
  280. IntegrationTestAssertions.expectStatus(response, 404);
  281. if (response.status === 404) {
  282. const responseData = await response.json();
  283. expect(responseData.message).toContain('资源不存在');
  284. }
  285. });
  286. });
  287. describe('乘客搜索测试', () => {
  288. it('应该能够按乘客姓名搜索乘客', async () => {
  289. const dataSource = await IntegrationTestDatabase.getDataSource();
  290. if (!dataSource) throw new Error('Database not initialized');
  291. await TestDataFactory.createTestPassenger(dataSource, { name: '搜索乘客1', phone: '13811111111' });
  292. await TestDataFactory.createTestPassenger(dataSource, { name: '搜索乘客2', phone: '13822222222' });
  293. await TestDataFactory.createTestPassenger(dataSource, { name: '其他乘客', phone: '13833333333' });
  294. const response = await client.passengers.$get({
  295. query: { keyword: '搜索乘客' }
  296. },
  297. {
  298. headers: {
  299. 'Authorization': `Bearer ${testToken}`
  300. }
  301. });
  302. IntegrationTestAssertions.expectStatus(response, 200);
  303. if (response.status === 200) {
  304. const responseData = await response.json();
  305. expect(Array.isArray(responseData.data)).toBe(true);
  306. expect(responseData.data.length).toBe(2);
  307. // 验证搜索结果包含正确的乘客
  308. const names = responseData.data.map((passenger) => passenger.name);
  309. expect(names).toContain('搜索乘客1');
  310. expect(names).toContain('搜索乘客2');
  311. expect(names).not.toContain('其他乘客');
  312. }
  313. });
  314. it('应该能够按手机号搜索乘客', async () => {
  315. const dataSource = await IntegrationTestDatabase.getDataSource();
  316. if (!dataSource) throw new Error('Database not initialized');
  317. await TestDataFactory.createTestPassenger(dataSource, { name: '乘客1', phone: '13811112222' });
  318. await TestDataFactory.createTestPassenger(dataSource, { name: '乘客2', phone: '13811113333' });
  319. const response = await client.passengers.$get({
  320. query: { keyword: '1381111' }
  321. },
  322. {
  323. headers: {
  324. 'Authorization': `Bearer ${testToken}`
  325. }
  326. });
  327. IntegrationTestAssertions.expectStatus(response, 200);
  328. if (response.status === 200) {
  329. const responseData = await response.json();
  330. expect(responseData.data.length).toBe(2);
  331. const phones = responseData.data.map((passenger) => passenger.phone);
  332. expect(phones).toContain('13811112222');
  333. expect(phones).toContain('13811113333');
  334. }
  335. });
  336. it('应该能够按证件号码搜索乘客', async () => {
  337. const dataSource = await IntegrationTestDatabase.getDataSource();
  338. if (!dataSource) throw new Error('Database not initialized');
  339. await TestDataFactory.createTestPassenger(dataSource, {
  340. name: '乘客1',
  341. idNumber: '110101199001011111'
  342. });
  343. await TestDataFactory.createTestPassenger(dataSource, {
  344. name: '乘客2',
  345. idNumber: '110101199001012222'
  346. });
  347. const response = await client.passengers.$get({
  348. query: { keyword: '11010119900101' }
  349. },
  350. {
  351. headers: {
  352. 'Authorization': `Bearer ${testToken}`
  353. }
  354. });
  355. IntegrationTestAssertions.expectStatus(response, 200);
  356. if (response.status === 200) {
  357. const responseData = await response.json();
  358. expect(responseData.data.length).toBe(2);
  359. const idNumbers = responseData.data.map((passenger) => passenger.idNumber);
  360. expect(idNumbers).toContain('110101199001011111');
  361. expect(idNumbers).toContain('110101199001012222');
  362. }
  363. });
  364. it('应该能够按用户ID筛选乘客', async () => {
  365. const dataSource = await IntegrationTestDatabase.getDataSource();
  366. if (!dataSource) throw new Error('Database not initialized');
  367. const testUser1 = await TestDataFactory.createTestUser(dataSource);
  368. const testUser2 = await TestDataFactory.createTestUser(dataSource);
  369. await TestDataFactory.createTestPassenger(dataSource, {
  370. name: '用户1的乘客1',
  371. userId: testUser1.id
  372. });
  373. await TestDataFactory.createTestPassenger(dataSource, {
  374. name: '用户1的乘客2',
  375. userId: testUser1.id
  376. });
  377. await TestDataFactory.createTestPassenger(dataSource, {
  378. name: '用户2的乘客',
  379. userId: testUser2.id
  380. });
  381. const response = await client.passengers.$get({
  382. query: { filters: JSON.stringify({ userId: testUser1.id }) }
  383. },
  384. {
  385. headers: {
  386. 'Authorization': `Bearer ${testToken}`
  387. }
  388. });
  389. IntegrationTestAssertions.expectStatus(response, 200);
  390. if (response.status === 200) {
  391. const responseData = await response.json();
  392. expect(responseData.data.length).toBe(2);
  393. const names = responseData.data.map((passenger) => passenger.name);
  394. expect(names).toContain('用户1的乘客1');
  395. expect(names).toContain('用户1的乘客2');
  396. expect(names).not.toContain('用户2的乘客');
  397. }
  398. });
  399. });
  400. describe('性能测试', () => {
  401. it('乘客列表查询响应时间应小于200ms', async () => {
  402. const dataSource = await IntegrationTestDatabase.getDataSource();
  403. if (!dataSource) throw new Error('Database not initialized');
  404. // 创建一些测试数据
  405. for (let i = 0; i < 10; i++) {
  406. await TestDataFactory.createTestPassenger(dataSource, {
  407. name: `性能测试乘客_${i}`,
  408. phone: `138${i.toString().padStart(8, '0')}`
  409. });
  410. }
  411. const startTime = Date.now();
  412. const response = await client.passengers.$get({
  413. query: {}
  414. },
  415. {
  416. headers: {
  417. 'Authorization': `Bearer ${testToken}`
  418. }
  419. });
  420. const endTime = Date.now();
  421. const responseTime = endTime - startTime;
  422. IntegrationTestAssertions.expectStatus(response, 200);
  423. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  424. });
  425. });
  426. });