passengers.integration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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: { page: 1, pageSize: 10 }
  121. },
  122. {
  123. headers: {
  124. 'Authorization': `Bearer ${testToken}`
  125. }
  126. });
  127. if (response.status !== 200) {
  128. const errorData = await response.json() as any;
  129. console.debug('获取乘客列表失败:', errorData);
  130. if (errorData.errors) {
  131. console.debug('详细验证错误:', errorData.errors.map((err: any) => ({
  132. path: err.path,
  133. message: err.message,
  134. expected: err.expected
  135. })));
  136. }
  137. }
  138. expect(response.status).toBe(200);
  139. if (response.status === 200) {
  140. const responseData = await response.json();
  141. expect(Array.isArray(responseData.data)).toBe(true);
  142. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  143. }
  144. });
  145. it('应该成功获取单个乘客详情', async () => {
  146. const dataSource = await IntegrationTestDatabase.getDataSource();
  147. if (!dataSource) throw new Error('Database not initialized');
  148. const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
  149. name: '测试乘客详情'
  150. });
  151. const response = await client.passengers[':id'].$get({
  152. param: { id: testPassenger.id }
  153. },
  154. {
  155. headers: {
  156. 'Authorization': `Bearer ${testToken}`
  157. }
  158. });
  159. expect(response.status).toBe(200);
  160. if (response.status === 200) {
  161. const responseData = await response.json();
  162. expect(responseData.id).toBe(testPassenger.id);
  163. expect(responseData.name).toBe(testPassenger.name);
  164. expect(responseData.idType).toBe(testPassenger.idType);
  165. expect(responseData.idNumber).toBe(testPassenger.idNumber);
  166. expect(responseData.phone).toBe(testPassenger.phone);
  167. }
  168. });
  169. it('应该返回404当乘客不存在时', async () => {
  170. const response = await client.passengers[':id'].$get({
  171. param: { id: 999999 }
  172. },
  173. {
  174. headers: {
  175. 'Authorization': `Bearer ${testToken}`
  176. }
  177. });
  178. expect(response.status).toBe(404);
  179. if (response.status === 404) {
  180. const responseData = await response.json();
  181. expect(responseData.message).toContain('资源不存在');
  182. }
  183. });
  184. });
  185. describe('乘客更新测试', () => {
  186. it('应该成功更新乘客信息', async () => {
  187. const dataSource = await IntegrationTestDatabase.getDataSource();
  188. if (!dataSource) throw new Error('Database not initialized');
  189. const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
  190. name: '测试乘客更新'
  191. });
  192. const updateData = {
  193. name: '更新后的乘客名称',
  194. phone: '13987654321',
  195. isDefault: true
  196. };
  197. const response = await client.passengers[':id'].$put({
  198. param: { id: testPassenger.id },
  199. json: updateData
  200. },
  201. {
  202. headers: {
  203. 'Authorization': `Bearer ${testToken}`
  204. }
  205. });
  206. expect(response.status).toBe(200);
  207. if (response.status === 200) {
  208. const responseData = await response.json();
  209. expect(responseData.name).toBe(updateData.name);
  210. expect(responseData.phone).toBe(updateData.phone);
  211. expect(responseData.isDefault).toBe(updateData.isDefault);
  212. }
  213. // 验证数据库中的更新
  214. const getResponse = await client.passengers[':id'].$get({
  215. param: { id: testPassenger.id }
  216. },
  217. {
  218. headers: {
  219. 'Authorization': `Bearer ${testToken}`
  220. }
  221. });
  222. if (getResponse.status === 200) {
  223. expect(getResponse.status).toBe(200);
  224. const getResponseData = await getResponse.json();
  225. expect(getResponseData.name).toBe(updateData.name);
  226. expect(getResponseData.phone).toBe(updateData.phone);
  227. }
  228. });
  229. it('应该返回404当更新不存在的乘客时', async () => {
  230. const updateData = {
  231. name: '更新后的名称'
  232. };
  233. const response = await client.passengers[':id'].$put({
  234. param: { id: 999999 },
  235. json: updateData
  236. },
  237. {
  238. headers: {
  239. 'Authorization': `Bearer ${testToken}`
  240. }
  241. });
  242. expect(response.status).toBe(404);
  243. if (response.status === 404) {
  244. const responseData = await response.json();
  245. expect(responseData.message).toContain('资源不存在');
  246. }
  247. });
  248. });
  249. describe('乘客删除测试', () => {
  250. it('应该成功删除乘客', async () => {
  251. const dataSource = await IntegrationTestDatabase.getDataSource();
  252. if (!dataSource) throw new Error('Database not initialized');
  253. const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
  254. name: '测试乘客删除'
  255. });
  256. const response = await client.passengers[':id'].$delete({
  257. param: { id: testPassenger.id }
  258. },
  259. {
  260. headers: {
  261. 'Authorization': `Bearer ${testToken}`
  262. }
  263. });
  264. IntegrationTestAssertions.expectStatus(response, 204);
  265. // 验证乘客已从数据库中删除
  266. await IntegrationTestAssertions.expectPassengerNotToExist(testPassenger.id);
  267. // 验证再次获取乘客返回404
  268. const getResponse = await client.passengers[':id'].$get({
  269. param: { id: testPassenger.id }
  270. },
  271. {
  272. headers: {
  273. 'Authorization': `Bearer ${testToken}`
  274. }
  275. });
  276. IntegrationTestAssertions.expectStatus(getResponse, 404);
  277. });
  278. it('应该返回404当删除不存在的乘客时', async () => {
  279. const response = await client.passengers[':id'].$delete({
  280. param: { id: 999999 }
  281. },
  282. {
  283. headers: {
  284. 'Authorization': `Bearer ${testToken}`
  285. }
  286. });
  287. IntegrationTestAssertions.expectStatus(response, 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. await TestDataFactory.createTestPassenger(dataSource, { name: '搜索乘客1', phone: '13811111111' });
  299. await TestDataFactory.createTestPassenger(dataSource, { name: '搜索乘客2', phone: '13822222222' });
  300. await TestDataFactory.createTestPassenger(dataSource, { name: '其他乘客', phone: '13833333333' });
  301. const response = await client.passengers.$get({
  302. query: { keyword: '搜索乘客', page: 1, pageSize: 10 }
  303. },
  304. {
  305. headers: {
  306. 'Authorization': `Bearer ${testToken}`
  307. }
  308. });
  309. IntegrationTestAssertions.expectStatus(response, 200);
  310. if (response.status === 200) {
  311. const responseData = await response.json();
  312. expect(Array.isArray(responseData.data)).toBe(true);
  313. expect(responseData.data.length).toBe(2);
  314. // 验证搜索结果包含正确的乘客
  315. const names = responseData.data.map((passenger) => passenger.name);
  316. expect(names).toContain('搜索乘客1');
  317. expect(names).toContain('搜索乘客2');
  318. expect(names).not.toContain('其他乘客');
  319. }
  320. });
  321. it('应该能够按手机号搜索乘客', async () => {
  322. const dataSource = await IntegrationTestDatabase.getDataSource();
  323. if (!dataSource) throw new Error('Database not initialized');
  324. await TestDataFactory.createTestPassenger(dataSource, { name: '乘客1', phone: '13811112222' });
  325. await TestDataFactory.createTestPassenger(dataSource, { name: '乘客2', phone: '13811113333' });
  326. const response = await client.passengers.$get({
  327. query: { keyword: '1381111', page: 1, pageSize: 10 }
  328. },
  329. {
  330. headers: {
  331. 'Authorization': `Bearer ${testToken}`
  332. }
  333. });
  334. IntegrationTestAssertions.expectStatus(response, 200);
  335. if (response.status === 200) {
  336. const responseData = await response.json();
  337. expect(responseData.data.length).toBe(2);
  338. const phones = responseData.data.map((passenger) => passenger.phone);
  339. expect(phones).toContain('13811112222');
  340. expect(phones).toContain('13811113333');
  341. }
  342. });
  343. it('应该能够按证件号码搜索乘客', async () => {
  344. const dataSource = await IntegrationTestDatabase.getDataSource();
  345. if (!dataSource) throw new Error('Database not initialized');
  346. await TestDataFactory.createTestPassenger(dataSource, {
  347. name: '乘客1',
  348. idNumber: '110101199001011111'
  349. });
  350. await TestDataFactory.createTestPassenger(dataSource, {
  351. name: '乘客2',
  352. idNumber: '110101199001012222'
  353. });
  354. const response = await client.passengers.$get({
  355. query: { keyword: '11010119900101', page: 1, pageSize: 10 }
  356. },
  357. {
  358. headers: {
  359. 'Authorization': `Bearer ${testToken}`
  360. }
  361. });
  362. IntegrationTestAssertions.expectStatus(response, 200);
  363. if (response.status === 200) {
  364. const responseData = await response.json();
  365. expect(responseData.data.length).toBe(2);
  366. const idNumbers = responseData.data.map((passenger) => passenger.idNumber);
  367. expect(idNumbers).toContain('110101199001011111');
  368. expect(idNumbers).toContain('110101199001012222');
  369. }
  370. });
  371. it('应该能够按用户ID筛选乘客', async () => {
  372. const dataSource = await IntegrationTestDatabase.getDataSource();
  373. if (!dataSource) throw new Error('Database not initialized');
  374. const testUser1 = await TestDataFactory.createTestUser(dataSource);
  375. const testUser2 = await TestDataFactory.createTestUser(dataSource);
  376. await TestDataFactory.createTestPassenger(dataSource, {
  377. name: '用户1的乘客1',
  378. userId: testUser1.id
  379. });
  380. await TestDataFactory.createTestPassenger(dataSource, {
  381. name: '用户1的乘客2',
  382. userId: testUser1.id
  383. });
  384. await TestDataFactory.createTestPassenger(dataSource, {
  385. name: '用户2的乘客',
  386. userId: testUser2.id
  387. });
  388. const response = await client.passengers.$get({
  389. query: { filters: JSON.stringify({ userId: testUser1.id }), page: 1, pageSize: 10 }
  390. },
  391. {
  392. headers: {
  393. 'Authorization': `Bearer ${testToken}`
  394. }
  395. });
  396. IntegrationTestAssertions.expectStatus(response, 200);
  397. if (response.status === 200) {
  398. const responseData = await response.json();
  399. expect(responseData.data.length).toBe(2);
  400. const names = responseData.data.map((passenger) => passenger.name);
  401. expect(names).toContain('用户1的乘客1');
  402. expect(names).toContain('用户1的乘客2');
  403. expect(names).not.toContain('用户2的乘客');
  404. }
  405. });
  406. });
  407. describe('性能测试', () => {
  408. it('乘客列表查询响应时间应小于200ms', async () => {
  409. const dataSource = await IntegrationTestDatabase.getDataSource();
  410. if (!dataSource) throw new Error('Database not initialized');
  411. // 创建一些测试数据
  412. for (let i = 0; i < 10; i++) {
  413. await TestDataFactory.createTestPassenger(dataSource, {
  414. name: `性能测试乘客_${i}`,
  415. phone: `138${i.toString().padStart(8, '0')}`
  416. });
  417. }
  418. const startTime = Date.now();
  419. const response = await client.passengers.$get({
  420. query: { page: 1, pageSize: 10 }
  421. },
  422. {
  423. headers: {
  424. 'Authorization': `Bearer ${testToken}`
  425. }
  426. });
  427. const endTime = Date.now();
  428. const responseTime = endTime - startTime;
  429. IntegrationTestAssertions.expectStatus(response, 200);
  430. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  431. });
  432. });
  433. });