user-routes.integration.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. import { describe, it, expect, beforeEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
  4. import { JWTUtil } from '@d8d/shared-utils';
  5. import { UserEntity, Role } from '@d8d/user-module';
  6. import { File } from '@d8d/file-module';
  7. import { userSupplierRoutes } from '../../src/routes';
  8. import { Supplier } from '../../src/entities';
  9. // 设置集成测试钩子
  10. setupIntegrationDatabaseHooksWithEntities([UserEntity, Role, Supplier, File])
  11. describe('用户供应商管理API集成测试', () => {
  12. let client: ReturnType<typeof testClient<typeof userSupplierRoutes>>;
  13. let userToken: string;
  14. let otherUserToken: string;
  15. let testUser: UserEntity;
  16. let otherUser: UserEntity;
  17. beforeEach(async () => {
  18. // 创建测试客户端
  19. client = testClient(userSupplierRoutes);
  20. // 获取数据源
  21. const dataSource = await IntegrationTestDatabase.getDataSource();
  22. // 创建测试用户
  23. const userRepository = dataSource.getRepository(UserEntity);
  24. testUser = userRepository.create({
  25. username: `test_user_${Math.floor(Math.random() * 100000)}`,
  26. password: 'test_password',
  27. nickname: '测试用户',
  28. registrationSource: 'web'
  29. });
  30. await userRepository.save(testUser);
  31. // 创建其他用户
  32. otherUser = userRepository.create({
  33. username: `other_user_${Math.floor(Math.random() * 100000)}`,
  34. password: 'other_password',
  35. nickname: '其他用户',
  36. registrationSource: 'web'
  37. });
  38. await userRepository.save(otherUser);
  39. // 生成测试用户的token
  40. userToken = JWTUtil.generateToken({
  41. id: testUser.id,
  42. username: testUser.username,
  43. roles: [{name:'user'}]
  44. });
  45. // 生成其他用户的token
  46. otherUserToken = JWTUtil.generateToken({
  47. id: otherUser.id,
  48. username: otherUser.username,
  49. roles: [{name:'user'}]
  50. });
  51. });
  52. describe('GET /suppliers', () => {
  53. it('应该返回当前用户的供应商列表', async () => {
  54. // 为测试用户创建一些供应商
  55. const dataSource = await IntegrationTestDatabase.getDataSource();
  56. const supplierRepository = dataSource.getRepository(Supplier);
  57. const userSupplier1 = supplierRepository.create({
  58. name: '用户供应商1',
  59. username: `user_supplier1_${Math.floor(Math.random() * 100000)}`,
  60. password: 'password123',
  61. phone: '13800138001',
  62. realname: '用户供应商1',
  63. loginNum: 0,
  64. loginTime: 0,
  65. loginIp: null,
  66. lastLoginTime: 0,
  67. lastLoginIp: null,
  68. state: 1,
  69. createdBy: testUser.id
  70. });
  71. await supplierRepository.save(userSupplier1);
  72. const userSupplier2 = supplierRepository.create({
  73. name: '用户供应商2',
  74. username: `user_supplier2_${Math.floor(Math.random() * 100000)}`,
  75. password: 'password123',
  76. phone: '13800138002',
  77. realname: '用户供应商2',
  78. loginNum: 0,
  79. loginTime: 0,
  80. loginIp: null,
  81. lastLoginTime: 0,
  82. lastLoginIp: null,
  83. state: 1,
  84. createdBy: testUser.id
  85. });
  86. await supplierRepository.save(userSupplier2);
  87. // 为其他用户创建一个供应商,确保不会返回
  88. const otherUserSupplier = supplierRepository.create({
  89. name: '其他用户供应商',
  90. username: `other_supplier_${Math.floor(Math.random() * 100000)}`,
  91. password: 'password123',
  92. phone: '13800138003',
  93. realname: '其他用户供应商',
  94. loginNum: 0,
  95. loginTime: 0,
  96. loginIp: null,
  97. lastLoginTime: 0,
  98. lastLoginIp: null,
  99. state: 1,
  100. createdBy: otherUser.id
  101. });
  102. await supplierRepository.save(otherUserSupplier);
  103. const response = await client.index.$get({
  104. query: {}
  105. }, {
  106. headers: {
  107. 'Authorization': `Bearer ${userToken}`
  108. }
  109. });
  110. console.debug('用户供应商列表响应状态:', response.status);
  111. expect(response.status).toBe(200);
  112. if (response.status === 200) {
  113. const data = await response.json();
  114. if (data && 'data' in data) {
  115. expect(Array.isArray(data.data)).toBe(true);
  116. // 应该只返回当前用户的供应商
  117. data.data.forEach((supplier: any) => {
  118. expect(supplier.createdBy).toBe(testUser.id);
  119. });
  120. }
  121. }
  122. });
  123. it('应该拒绝未认证用户的访问', async () => {
  124. const response = await client.index.$get({
  125. query: {}
  126. });
  127. expect(response.status).toBe(401);
  128. });
  129. });
  130. describe('POST /suppliers', () => {
  131. it('应该成功创建供应商并自动使用当前用户ID', async () => {
  132. const createData = {
  133. name: '测试供应商',
  134. username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
  135. password: 'password123',
  136. phone: '13800138000',
  137. realname: '测试供应商',
  138. state: 1
  139. };
  140. const response = await client.index.$post({
  141. json: createData
  142. }, {
  143. headers: {
  144. 'Authorization': `Bearer ${userToken}`
  145. }
  146. });
  147. console.debug('用户创建供应商响应状态:', response.status);
  148. expect(response.status).toBe(201);
  149. if (response.status === 201) {
  150. const data = await response.json();
  151. console.debug('用户创建供应商响应数据:', JSON.stringify(data, null, 2));
  152. expect(data).toHaveProperty('id');
  153. expect(data.createdBy).toBe(testUser.id); // 自动使用当前用户ID
  154. expect(data.name).toBe(createData.name);
  155. expect(data.username).toBe(createData.username);
  156. expect(data.phone).toBe(createData.phone);
  157. expect(data.realname).toBe(createData.realname);
  158. }
  159. });
  160. it('应该验证创建供应商的必填字段', async () => {
  161. const invalidData = {
  162. // 缺少必填字段
  163. name: '',
  164. username: '',
  165. password: '',
  166. phone: '',
  167. realname: ''
  168. };
  169. const response = await client.index.$post({
  170. json: invalidData
  171. }, {
  172. headers: {
  173. 'Authorization': `Bearer ${userToken}`
  174. }
  175. });
  176. expect(response.status).toBe(400);
  177. });
  178. });
  179. describe('GET /suppliers/:id', () => {
  180. it('应该返回当前用户的供应商详情', async () => {
  181. // 先为当前用户创建一个供应商
  182. const dataSource = await IntegrationTestDatabase.getDataSource();
  183. const supplierRepository = dataSource.getRepository(Supplier);
  184. const testSupplier = supplierRepository.create({
  185. name: '测试供应商详情',
  186. username: `test_supplier_detail_${Math.floor(Math.random() * 100000)}`,
  187. password: 'password123',
  188. phone: '13600136000',
  189. realname: '测试供应商详情',
  190. loginNum: 5,
  191. loginTime: new Date('2024-01-01T12:00:00Z'),
  192. loginIp: '192.168.1.1',
  193. lastLoginTime: new Date('2024-01-01T12:00:00Z'),
  194. lastLoginIp: '192.168.1.1',
  195. state: 1,
  196. createdBy: testUser.id
  197. });
  198. await supplierRepository.save(testSupplier);
  199. const response = await client[':id'].$get({
  200. param: { id: testSupplier.id }
  201. }, {
  202. headers: {
  203. 'Authorization': `Bearer ${userToken}`
  204. }
  205. });
  206. console.debug('用户供应商详情响应状态:', response.status);
  207. expect(response.status).toBe(200);
  208. if (response.status === 200) {
  209. const data = await response.json();
  210. expect(data.id).toBe(testSupplier.id);
  211. expect(data.createdBy).toBe(testUser.id);
  212. expect(data.name).toBe(testSupplier.name);
  213. expect(data.username).toBe(testSupplier.username);
  214. expect(data.phone).toBe(testSupplier.phone);
  215. expect(data.realname).toBe(testSupplier.realname);
  216. }
  217. });
  218. it('应该拒绝访问其他用户的供应商', async () => {
  219. // 为其他用户创建一个供应商
  220. const dataSource = await IntegrationTestDatabase.getDataSource();
  221. const supplierRepository = dataSource.getRepository(Supplier);
  222. const otherUserSupplier = supplierRepository.create({
  223. name: '其他用户供应商',
  224. username: `other_supplier_detail_${Math.floor(Math.random() * 100000)}`,
  225. password: 'password123',
  226. phone: '13600136001',
  227. realname: '其他用户供应商',
  228. loginNum: 0,
  229. loginTime: 0,
  230. loginIp: null,
  231. lastLoginTime: 0,
  232. lastLoginIp: null,
  233. state: 1,
  234. createdBy: otherUser.id
  235. });
  236. await supplierRepository.save(otherUserSupplier);
  237. // 当前用户尝试访问其他用户的供应商
  238. const response = await client[':id'].$get({
  239. param: { id: otherUserSupplier.id }
  240. }, {
  241. headers: {
  242. 'Authorization': `Bearer ${userToken}`
  243. }
  244. });
  245. console.debug('用户访问其他用户供应商响应状态:', response.status);
  246. expect(response.status).toBe(404); // 应该返回404,而不是403
  247. });
  248. it('应该处理不存在的供应商', async () => {
  249. const response = await client[':id'].$get({
  250. param: { id: 999999 }
  251. }, {
  252. headers: {
  253. 'Authorization': `Bearer ${userToken}`
  254. }
  255. });
  256. expect(response.status).toBe(404);
  257. });
  258. });
  259. describe('PUT /suppliers/:id', () => {
  260. it('应该成功更新当前用户的供应商', async () => {
  261. // 先为当前用户创建一个供应商
  262. const dataSource = await IntegrationTestDatabase.getDataSource();
  263. const supplierRepository = dataSource.getRepository(Supplier);
  264. const testSupplier = supplierRepository.create({
  265. name: '原始供应商',
  266. username: `original_supplier_${Math.floor(Math.random() * 100000)}`,
  267. password: 'password123',
  268. phone: '13500135000',
  269. realname: '原始供应商',
  270. loginNum: 0,
  271. loginTime: 0,
  272. loginIp: null,
  273. lastLoginTime: 0,
  274. lastLoginIp: null,
  275. state: 1,
  276. createdBy: testUser.id
  277. });
  278. await supplierRepository.save(testSupplier);
  279. const updateData = {
  280. name: '更新后的供应商',
  281. phone: '13700137000',
  282. realname: '更新后的供应商',
  283. state: 2
  284. };
  285. const response = await client[':id'].$put({
  286. param: { id: testSupplier.id },
  287. json: updateData
  288. }, {
  289. headers: {
  290. 'Authorization': `Bearer ${userToken}`
  291. }
  292. });
  293. console.debug('用户更新供应商响应状态:', response.status);
  294. expect(response.status).toBe(200);
  295. if (response.status === 200) {
  296. const data = await response.json();
  297. expect(data.name).toBe(updateData.name);
  298. expect(data.phone).toBe(updateData.phone);
  299. expect(data.realname).toBe(updateData.realname);
  300. expect(data.state).toBe(updateData.state);
  301. }
  302. });
  303. it('应该拒绝更新其他用户的供应商', async () => {
  304. // 为其他用户创建一个供应商
  305. const dataSource = await IntegrationTestDatabase.getDataSource();
  306. const supplierRepository = dataSource.getRepository(Supplier);
  307. const otherUserSupplier = supplierRepository.create({
  308. name: '其他用户供应商',
  309. username: `other_supplier_update_${Math.floor(Math.random() * 100000)}`,
  310. password: 'password123',
  311. phone: '13500135001',
  312. realname: '其他用户供应商',
  313. loginNum: 0,
  314. loginTime: 0,
  315. loginIp: null,
  316. lastLoginTime: 0,
  317. lastLoginIp: null,
  318. state: 1,
  319. createdBy: otherUser.id
  320. });
  321. await supplierRepository.save(otherUserSupplier);
  322. const updateData = {
  323. name: '尝试更新的供应商',
  324. phone: '13700137001',
  325. realname: '尝试更新的供应商'
  326. };
  327. // 当前用户尝试更新其他用户的供应商
  328. const response = await client[':id'].$put({
  329. param: { id: otherUserSupplier.id },
  330. json: updateData
  331. }, {
  332. headers: {
  333. 'Authorization': `Bearer ${userToken}`
  334. }
  335. });
  336. console.debug('用户更新其他用户供应商响应状态:', response.status);
  337. expect(response.status).toBe(403); // 数据权限控制返回403
  338. });
  339. });
  340. describe('DELETE /suppliers/:id', () => {
  341. it('应该成功删除当前用户的供应商', async () => {
  342. // 先为当前用户创建一个供应商
  343. const dataSource = await IntegrationTestDatabase.getDataSource();
  344. const supplierRepository = dataSource.getRepository(Supplier);
  345. const testSupplier = supplierRepository.create({
  346. name: '待删除供应商',
  347. username: `delete_supplier_${Math.floor(Math.random() * 100000)}`,
  348. password: 'password123',
  349. phone: '13400134000',
  350. realname: '待删除供应商',
  351. loginNum: 0,
  352. loginTime: 0,
  353. loginIp: null,
  354. lastLoginTime: 0,
  355. lastLoginIp: null,
  356. state: 1,
  357. createdBy: testUser.id
  358. });
  359. await supplierRepository.save(testSupplier);
  360. const response = await client[':id'].$delete({
  361. param: { id: testSupplier.id }
  362. }, {
  363. headers: {
  364. 'Authorization': `Bearer ${userToken}`
  365. }
  366. });
  367. console.debug('用户删除供应商响应状态:', response.status);
  368. expect(response.status).toBe(204);
  369. // 验证供应商确实被删除
  370. const deletedSupplier = await supplierRepository.findOne({
  371. where: { id: testSupplier.id }
  372. });
  373. expect(deletedSupplier).toBeNull();
  374. });
  375. it('应该拒绝删除其他用户的供应商', async () => {
  376. // 为其他用户创建一个供应商
  377. const dataSource = await IntegrationTestDatabase.getDataSource();
  378. const supplierRepository = dataSource.getRepository(Supplier);
  379. const otherUserSupplier = supplierRepository.create({
  380. name: '其他用户供应商',
  381. username: `other_supplier_delete_${Math.floor(Math.random() * 100000)}`,
  382. password: 'password123',
  383. phone: '13400134001',
  384. realname: '其他用户供应商',
  385. loginNum: 0,
  386. loginTime: 0,
  387. loginIp: null,
  388. lastLoginTime: 0,
  389. lastLoginIp: null,
  390. state: 1,
  391. createdBy: otherUser.id
  392. });
  393. await supplierRepository.save(otherUserSupplier);
  394. // 当前用户尝试删除其他用户的供应商
  395. const response = await client[':id'].$delete({
  396. param: { id: otherUserSupplier.id }
  397. }, {
  398. headers: {
  399. 'Authorization': `Bearer ${userToken}`
  400. }
  401. });
  402. console.debug('用户删除其他用户供应商响应状态:', response.status);
  403. expect(response.status).toBe(403); // 数据权限控制返回403
  404. });
  405. });
  406. describe('数据权限验证', () => {
  407. it('用户应该只能访问和操作自己的数据', async () => {
  408. // 为两个用户都创建供应商
  409. const dataSource = await IntegrationTestDatabase.getDataSource();
  410. const supplierRepository = dataSource.getRepository(Supplier);
  411. const userSupplier = supplierRepository.create({
  412. name: '用户供应商',
  413. username: `user_supplier_perm_${Math.floor(Math.random() * 100000)}`,
  414. password: 'password123',
  415. phone: '13800138004',
  416. realname: '用户供应商',
  417. loginNum: 0,
  418. loginTime: 0,
  419. loginIp: null,
  420. lastLoginTime: 0,
  421. lastLoginIp: null,
  422. state: 1,
  423. createdBy: testUser.id
  424. });
  425. await supplierRepository.save(userSupplier);
  426. const otherUserSupplier = supplierRepository.create({
  427. name: '其他用户供应商',
  428. username: `other_supplier_perm_${Math.floor(Math.random() * 100000)}`,
  429. password: 'password123',
  430. phone: '13800138005',
  431. realname: '其他用户供应商',
  432. loginNum: 0,
  433. loginTime: 0,
  434. loginIp: null,
  435. lastLoginTime: 0,
  436. lastLoginIp: null,
  437. state: 1,
  438. createdBy: otherUser.id
  439. });
  440. await supplierRepository.save(otherUserSupplier);
  441. // 当前用户应该只能看到自己的供应商
  442. const listResponse = await client.index.$get({
  443. query: {}
  444. }, {
  445. headers: {
  446. 'Authorization': `Bearer ${userToken}`
  447. }
  448. });
  449. expect(listResponse.status).toBe(200);
  450. const listData = await listResponse.json();
  451. if (listData && 'data' in listData) {
  452. expect(Array.isArray(listData.data)).toBe(true);
  453. // 应该只包含当前用户的供应商
  454. listData.data.forEach((supplier: any) => {
  455. expect(supplier.createdBy).toBe(testUser.id);
  456. });
  457. }
  458. // 当前用户应该无法访问其他用户的供应商详情
  459. const getResponse = await client[':id'].$get({
  460. param: { id: otherUserSupplier.id }
  461. }, {
  462. headers: {
  463. 'Authorization': `Bearer ${userToken}`
  464. }
  465. });
  466. expect(getResponse.status).toBe(404);
  467. // 当前用户应该无法更新其他用户的供应商
  468. const updateResponse = await client[':id'].$put({
  469. param: { id: otherUserSupplier.id },
  470. json: { name: '尝试更新' }
  471. }, {
  472. headers: {
  473. 'Authorization': `Bearer ${userToken}`
  474. }
  475. });
  476. expect(updateResponse.status).toBe(403);
  477. // 当前用户应该无法删除其他用户的供应商
  478. const deleteResponse = await client[':id'].$delete({
  479. param: { id: otherUserSupplier.id }
  480. }, {
  481. headers: {
  482. 'Authorization': `Bearer ${userToken}`
  483. }
  484. });
  485. expect(deleteResponse.status).toBe(403);
  486. });
  487. });
  488. describe('供应商状态管理', () => {
  489. it('应该支持供应商状态管理', async () => {
  490. // 创建启用状态的供应商
  491. const createData = {
  492. name: '状态测试供应商',
  493. username: `status_test_supplier_${Math.floor(Math.random() * 100000)}`,
  494. password: 'password123',
  495. phone: '13800138006',
  496. realname: '状态测试供应商',
  497. state: 1 // 启用状态
  498. };
  499. const createResponse = await client.index.$post({
  500. json: createData
  501. }, {
  502. headers: {
  503. 'Authorization': `Bearer ${userToken}`
  504. }
  505. });
  506. expect(createResponse.status).toBe(201);
  507. const createdData = await createResponse.json();
  508. // 更新为禁用状态
  509. if (typeof createdData === 'object' && createdData !== null && 'id' in createdData) {
  510. const updateResponse = await client[':id'].$put({
  511. param: { id: createdData.id },
  512. json: { state: 2 } // 禁用状态
  513. }, {
  514. headers: {
  515. 'Authorization': `Bearer ${userToken}`
  516. }
  517. });
  518. expect(updateResponse.status).toBe(200);
  519. const updatedData = await updateResponse.json();
  520. if (typeof updatedData === 'object' && updatedData !== null && 'state' in updatedData) {
  521. expect(updatedData.state).toBe(2);
  522. }
  523. }
  524. });
  525. });
  526. describe('供应商登录统计', () => {
  527. it('应该支持供应商登录统计功能', async () => {
  528. // 创建供应商
  529. const createData = {
  530. name: '登录统计供应商',
  531. username: `login_stat_supplier_${Math.floor(Math.random() * 100000)}`,
  532. password: 'password123',
  533. phone: '13800138007',
  534. realname: '登录统计供应商',
  535. state: 1
  536. };
  537. const createResponse = await client.index.$post({
  538. json: createData
  539. }, {
  540. headers: {
  541. 'Authorization': `Bearer ${userToken}`
  542. }
  543. });
  544. expect(createResponse.status).toBe(201);
  545. const createdData = await createResponse.json();
  546. // 验证初始登录统计
  547. if (typeof createdData === 'object' && createdData !== null) {
  548. if ('loginNum' in createdData) expect(createdData.loginNum).toBe(0);
  549. if ('loginTime' in createdData) expect(createdData.loginTime).toBe(0);
  550. if ('lastLoginTime' in createdData) expect(createdData.lastLoginTime).toBe(0);
  551. if ('loginIp' in createdData) expect(createdData.loginIp).toBeNull();
  552. if ('lastLoginIp' in createdData) expect(createdData.lastLoginIp).toBeNull();
  553. }
  554. // 获取供应商详情验证字段存在
  555. if (typeof createdData === 'object' && createdData !== null && 'id' in createdData) {
  556. const getResponse = await client[':id'].$get({
  557. param: { id: createdData.id }
  558. }, {
  559. headers: {
  560. 'Authorization': `Bearer ${userToken}`
  561. }
  562. });
  563. expect(getResponse.status).toBe(200);
  564. const supplierData = await getResponse.json();
  565. if (typeof supplierData === 'object' && supplierData !== null) {
  566. expect(supplierData).toHaveProperty('loginNum');
  567. expect(supplierData).toHaveProperty('loginTime');
  568. expect(supplierData).toHaveProperty('lastLoginTime');
  569. expect(supplierData).toHaveProperty('loginIp');
  570. expect(supplierData).toHaveProperty('lastLoginIp');
  571. }
  572. }
  573. });
  574. });
  575. });