user-goods-routes.integration.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 { Supplier } from '@d8d/supplier-module';
  8. import { Merchant } from '@d8d/merchant-module';
  9. import { userGoodsRoutes } from '../../src/routes';
  10. import { Goods, GoodsCategory } from '../../src/entities';
  11. // 设置集成测试钩子
  12. setupIntegrationDatabaseHooksWithEntities([
  13. UserEntity, Role, Goods, GoodsCategory, File, Supplier, Merchant
  14. ])
  15. describe('用户商品管理API集成测试', () => {
  16. let client: ReturnType<typeof testClient<typeof userGoodsRoutes>>;
  17. let userToken: string;
  18. let otherUserToken: string;
  19. let testUser: UserEntity;
  20. let otherUser: UserEntity;
  21. let testCategory: GoodsCategory;
  22. let testSupplier: Supplier;
  23. let testMerchant: Merchant;
  24. let testFile: File;
  25. beforeEach(async () => {
  26. // 创建测试客户端
  27. client = testClient(userGoodsRoutes);
  28. // 获取数据源
  29. const dataSource = await IntegrationTestDatabase.getDataSource();
  30. // 创建测试用户
  31. const userRepository = dataSource.getRepository(UserEntity);
  32. testUser = userRepository.create({
  33. username: `test_user_${Math.floor(Math.random() * 100000)}`,
  34. password: 'test_password',
  35. nickname: '测试用户',
  36. registrationSource: 'web'
  37. });
  38. await userRepository.save(testUser);
  39. // 创建其他用户
  40. otherUser = userRepository.create({
  41. username: `other_user_${Math.floor(Math.random() * 100000)}`,
  42. password: 'other_password',
  43. nickname: '其他用户',
  44. registrationSource: 'web'
  45. });
  46. await userRepository.save(otherUser);
  47. // 生成测试用户的token
  48. userToken = JWTUtil.generateToken({
  49. id: testUser.id,
  50. username: testUser.username,
  51. roles: [{name:'user'}]
  52. });
  53. // 生成其他用户的token
  54. otherUserToken = JWTUtil.generateToken({
  55. id: otherUser.id,
  56. username: otherUser.username,
  57. roles: [{name:'user'}]
  58. });
  59. // 创建测试商品分类
  60. const categoryRepository = dataSource.getRepository(GoodsCategory);
  61. testCategory = categoryRepository.create({
  62. name: '测试分类',
  63. parentId: 0,
  64. level: 1,
  65. state: 1,
  66. createdBy: testUser.id
  67. });
  68. await categoryRepository.save(testCategory);
  69. // 创建测试供应商
  70. const supplierRepository = dataSource.getRepository(Supplier);
  71. testSupplier = supplierRepository.create({
  72. name: '测试供应商',
  73. username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
  74. password: 'password123',
  75. phone: '13800138000',
  76. realname: '测试供应商',
  77. state: 1,
  78. createdBy: testUser.id
  79. });
  80. await supplierRepository.save(testSupplier);
  81. // 创建测试商户
  82. const merchantRepository = dataSource.getRepository(Merchant);
  83. testMerchant = merchantRepository.create({
  84. name: '测试商户',
  85. username: `test_merchant_${Math.floor(Math.random() * 100000)}`,
  86. password: 'password123',
  87. phone: '13800138001',
  88. realname: '测试商户',
  89. state: 1,
  90. createdBy: testUser.id
  91. });
  92. await merchantRepository.save(testMerchant);
  93. // 创建测试文件
  94. const fileRepository = dataSource.getRepository(File);
  95. testFile = fileRepository.create({
  96. name: 'test_image.jpg',
  97. type: 'image/jpeg',
  98. size: 102400,
  99. path: 'images/test_image.jpg',
  100. uploadUserId: testUser.id,
  101. uploadTime: new Date(),
  102. createdAt: new Date(),
  103. updatedAt: new Date()
  104. });
  105. await fileRepository.save(testFile);
  106. });
  107. describe('GET /goods', () => {
  108. it('应该返回当前用户的商品列表', async () => {
  109. // 为测试用户创建一些商品
  110. const dataSource = await IntegrationTestDatabase.getDataSource();
  111. const goodsRepository = dataSource.getRepository(Goods);
  112. const userGoods1 = goodsRepository.create({
  113. name: '用户商品1',
  114. price: 100.00,
  115. costPrice: 80.00,
  116. categoryId1: testCategory.id,
  117. categoryId2: 0,
  118. categoryId3: 0,
  119. goodsType: 1,
  120. supplierId: testSupplier.id,
  121. merchantId: testMerchant.id,
  122. imageFileId: testFile.id,
  123. state: 1,
  124. stock: 100,
  125. lowestBuy: 1,
  126. createdBy: testUser.id
  127. });
  128. await goodsRepository.save(userGoods1);
  129. const userGoods2 = goodsRepository.create({
  130. name: '用户商品2',
  131. price: 200.00,
  132. costPrice: 160.00,
  133. categoryId1: testCategory.id,
  134. categoryId2: 0,
  135. categoryId3: 0,
  136. goodsType: 1,
  137. supplierId: testSupplier.id,
  138. merchantId: testMerchant.id,
  139. imageFileId: testFile.id,
  140. state: 1,
  141. stock: 50,
  142. lowestBuy: 1,
  143. createdBy: testUser.id
  144. });
  145. await goodsRepository.save(userGoods2);
  146. // 为其他用户创建一个商品,确保不会返回
  147. const otherUserGoods = goodsRepository.create({
  148. name: '其他用户商品',
  149. price: 300.00,
  150. costPrice: 240.00,
  151. categoryId1: testCategory.id,
  152. categoryId2: 0,
  153. categoryId3: 0,
  154. goodsType: 1,
  155. supplierId: testSupplier.id,
  156. merchantId: testMerchant.id,
  157. imageFileId: testFile.id,
  158. state: 1,
  159. stock: 30,
  160. lowestBuy: 1,
  161. createdBy: otherUser.id
  162. });
  163. await goodsRepository.save(otherUserGoods);
  164. const response = await client.index.$get({
  165. query: {}
  166. }, {
  167. headers: {
  168. 'Authorization': `Bearer ${userToken}`
  169. }
  170. });
  171. console.debug('用户商品列表响应状态:', response.status);
  172. expect(response.status).toBe(200);
  173. if (response.status === 200) {
  174. const data = await response.json();
  175. expect(data).toHaveProperty('data');
  176. expect(Array.isArray(data.data)).toBe(true);
  177. // 验证只返回当前用户的商品
  178. data.data.forEach((goods: any) => {
  179. expect(goods.createdBy).toBe(testUser.id);
  180. });
  181. // 验证不包含其他用户的商品
  182. const otherUserGoodsInResponse = data.data.find((goods: any) => goods.createdBy === otherUser.id);
  183. expect(otherUserGoodsInResponse).toBeUndefined();
  184. }
  185. });
  186. it('应该拒绝未认证用户的访问', async () => {
  187. const response = await client.index.$get({
  188. query: {}
  189. });
  190. expect(response.status).toBe(401);
  191. });
  192. });
  193. describe('POST /goods', () => {
  194. it('应该成功创建商品并自动设置当前用户权限', async () => {
  195. const createData = {
  196. name: '用户创建商品',
  197. price: 150.00,
  198. costPrice: 120.00,
  199. categoryId1: testCategory.id,
  200. categoryId2: 0,
  201. categoryId3: 0,
  202. goodsType: 1,
  203. supplierId: testSupplier.id,
  204. merchantId: testMerchant.id,
  205. state: 1,
  206. stock: 80,
  207. lowestBuy: 1
  208. };
  209. const response = await client.index.$post({
  210. json: createData
  211. }, {
  212. headers: {
  213. 'Authorization': `Bearer ${userToken}`
  214. }
  215. });
  216. console.debug('用户创建商品响应状态:', response.status);
  217. if (response.status !== 201) {
  218. const errorData = await response.json();
  219. console.debug('用户创建商品错误响应:', errorData);
  220. }
  221. expect(response.status).toBe(201);
  222. if (response.status === 201) {
  223. const data = await response.json();
  224. expect(data).toHaveProperty('id');
  225. expect(data.name).toBe(createData.name);
  226. expect(data.price).toBe(createData.price);
  227. expect(data.createdBy).toBe(testUser.id); // 验证自动设置当前用户权限
  228. }
  229. });
  230. it('应该验证创建商品的必填字段', async () => {
  231. const invalidData = {
  232. // 缺少必填字段
  233. name: '',
  234. price: -1,
  235. categoryId1: -1
  236. };
  237. const response = await client.index.$post({
  238. json: invalidData
  239. }, {
  240. headers: {
  241. 'Authorization': `Bearer ${userToken}`
  242. }
  243. });
  244. expect(response.status).toBe(400);
  245. });
  246. });
  247. describe('GET /goods/:id', () => {
  248. it('应该返回当前用户的商品详情', async () => {
  249. // 先为测试用户创建一个商品
  250. const dataSource = await IntegrationTestDatabase.getDataSource();
  251. const goodsRepository = dataSource.getRepository(Goods);
  252. const testGoods = goodsRepository.create({
  253. name: '测试用户商品详情',
  254. price: 100.00,
  255. costPrice: 80.00,
  256. categoryId1: testCategory.id,
  257. categoryId2: 0,
  258. categoryId3: 0,
  259. goodsType: 1,
  260. supplierId: testSupplier.id,
  261. merchantId: testMerchant.id,
  262. state: 1,
  263. stock: 100,
  264. lowestBuy: 1,
  265. createdBy: testUser.id
  266. });
  267. await goodsRepository.save(testGoods);
  268. const response = await client[':id'].$get({
  269. param: { id: testGoods.id }
  270. }, {
  271. headers: {
  272. 'Authorization': `Bearer ${userToken}`
  273. }
  274. });
  275. console.debug('用户商品详情响应状态:', response.status);
  276. expect(response.status).toBe(200);
  277. if (response.status === 200) {
  278. const data = await response.json();
  279. expect(data.id).toBe(testGoods.id);
  280. expect(data.name).toBe(testGoods.name);
  281. expect(data.createdBy).toBe(testUser.id);
  282. }
  283. });
  284. it('应该拒绝访问其他用户的商品', async () => {
  285. // 为其他用户创建一个商品
  286. const dataSource = await IntegrationTestDatabase.getDataSource();
  287. const goodsRepository = dataSource.getRepository(Goods);
  288. const otherUserGoods = goodsRepository.create({
  289. name: '其他用户商品',
  290. price: 100.00,
  291. costPrice: 80.00,
  292. categoryId1: testCategory.id,
  293. categoryId2: 0,
  294. categoryId3: 0,
  295. goodsType: 1,
  296. supplierId: testSupplier.id,
  297. merchantId: testMerchant.id,
  298. state: 1,
  299. stock: 100,
  300. lowestBuy: 1,
  301. createdBy: otherUser.id
  302. });
  303. await goodsRepository.save(otherUserGoods);
  304. const response = await client[':id'].$get({
  305. param: { id: otherUserGoods.id }
  306. }, {
  307. headers: {
  308. 'Authorization': `Bearer ${userToken}`
  309. }
  310. });
  311. expect(response.status).toBe(404); // 数据权限控制应该返回404而不是403
  312. });
  313. it('应该处理不存在的商品', async () => {
  314. const response = await client[':id'].$get({
  315. param: { id: 999999 }
  316. }, {
  317. headers: {
  318. 'Authorization': `Bearer ${userToken}`
  319. }
  320. });
  321. expect(response.status).toBe(404);
  322. });
  323. });
  324. describe('PUT /goods/:id', () => {
  325. it('应该成功更新当前用户的商品', async () => {
  326. // 先为测试用户创建一个商品
  327. const dataSource = await IntegrationTestDatabase.getDataSource();
  328. const goodsRepository = dataSource.getRepository(Goods);
  329. const testGoods = goodsRepository.create({
  330. name: '测试更新商品',
  331. price: 100.00,
  332. costPrice: 80.00,
  333. categoryId1: testCategory.id,
  334. categoryId2: 0,
  335. categoryId3: 0,
  336. goodsType: 1,
  337. supplierId: testSupplier.id,
  338. merchantId: testMerchant.id,
  339. state: 1,
  340. stock: 100,
  341. lowestBuy: 1,
  342. createdBy: testUser.id
  343. });
  344. await goodsRepository.save(testGoods);
  345. const updateData = {
  346. name: '更新后的商品名称',
  347. price: 120.00,
  348. state: 2
  349. };
  350. const response = await client[':id'].$put({
  351. param: { id: testGoods.id },
  352. json: updateData
  353. }, {
  354. headers: {
  355. 'Authorization': `Bearer ${userToken}`
  356. }
  357. });
  358. console.debug('用户更新商品响应状态:', response.status);
  359. expect(response.status).toBe(200);
  360. if (response.status === 200) {
  361. const data = await response.json();
  362. expect(data.name).toBe(updateData.name);
  363. expect(data.price).toBe(updateData.price);
  364. expect(data.state).toBe(updateData.state);
  365. expect(data.updatedBy).toBe(testUser.id); // 验证自动设置更新用户
  366. }
  367. });
  368. it('应该拒绝更新其他用户的商品', async () => {
  369. // 为其他用户创建一个商品
  370. const dataSource = await IntegrationTestDatabase.getDataSource();
  371. const goodsRepository = dataSource.getRepository(Goods);
  372. const otherUserGoods = goodsRepository.create({
  373. name: '其他用户商品',
  374. price: 100.00,
  375. costPrice: 80.00,
  376. categoryId1: testCategory.id,
  377. categoryId2: 0,
  378. categoryId3: 0,
  379. goodsType: 1,
  380. supplierId: testSupplier.id,
  381. merchantId: testMerchant.id,
  382. state: 1,
  383. stock: 100,
  384. lowestBuy: 1,
  385. createdBy: otherUser.id
  386. });
  387. await goodsRepository.save(otherUserGoods);
  388. const updateData = {
  389. name: '尝试更新其他用户商品'
  390. };
  391. const response = await client[':id'].$put({
  392. param: { id: otherUserGoods.id },
  393. json: updateData
  394. }, {
  395. headers: {
  396. 'Authorization': `Bearer ${userToken}`
  397. }
  398. });
  399. expect(response.status).toBe(404); // 数据权限控制应该返回404而不是403
  400. });
  401. });
  402. describe('DELETE /goods/:id', () => {
  403. it('应该成功删除当前用户的商品', async () => {
  404. // 先为测试用户创建一个商品
  405. const dataSource = await IntegrationTestDatabase.getDataSource();
  406. const goodsRepository = dataSource.getRepository(Goods);
  407. const testGoods = goodsRepository.create({
  408. name: '测试删除商品',
  409. price: 100.00,
  410. costPrice: 80.00,
  411. categoryId1: testCategory.id,
  412. categoryId2: 0,
  413. categoryId3: 0,
  414. goodsType: 1,
  415. supplierId: testSupplier.id,
  416. merchantId: testMerchant.id,
  417. state: 1,
  418. stock: 100,
  419. lowestBuy: 1,
  420. createdBy: testUser.id
  421. });
  422. await goodsRepository.save(testGoods);
  423. const response = await client[':id'].$delete({
  424. param: { id: testGoods.id }
  425. }, {
  426. headers: {
  427. 'Authorization': `Bearer ${userToken}`
  428. }
  429. });
  430. console.debug('用户删除商品响应状态:', response.status);
  431. expect(response.status).toBe(204);
  432. });
  433. it('应该拒绝删除其他用户的商品', async () => {
  434. // 为其他用户创建一个商品
  435. const dataSource = await IntegrationTestDatabase.getDataSource();
  436. const goodsRepository = dataSource.getRepository(Goods);
  437. const otherUserGoods = goodsRepository.create({
  438. name: '其他用户商品',
  439. price: 100.00,
  440. costPrice: 80.00,
  441. categoryId1: testCategory.id,
  442. categoryId2: 0,
  443. categoryId3: 0,
  444. goodsType: 1,
  445. supplierId: testSupplier.id,
  446. merchantId: testMerchant.id,
  447. state: 1,
  448. stock: 100,
  449. lowestBuy: 1,
  450. createdBy: otherUser.id
  451. });
  452. await goodsRepository.save(otherUserGoods);
  453. const response = await client[':id'].$delete({
  454. param: { id: otherUserGoods.id }
  455. }, {
  456. headers: {
  457. 'Authorization': `Bearer ${userToken}`
  458. }
  459. });
  460. expect(response.status).toBe(404); // 数据权限控制应该返回404而不是403
  461. });
  462. });
  463. describe('数据权限配置测试', () => {
  464. it('应该验证dataPermission配置正确工作', async () => {
  465. // 这个测试验证数据权限配置是否正常工作
  466. // 用户只能访问自己创建的商品
  467. const dataSource = await IntegrationTestDatabase.getDataSource();
  468. const goodsRepository = dataSource.getRepository(Goods);
  469. // 创建测试用户和其他用户的商品
  470. const userGoods = goodsRepository.create({
  471. name: '用户商品',
  472. price: 100.00,
  473. costPrice: 80.00,
  474. categoryId1: testCategory.id,
  475. categoryId2: 0,
  476. categoryId3: 0,
  477. goodsType: 1,
  478. supplierId: testSupplier.id,
  479. merchantId: testMerchant.id,
  480. state: 1,
  481. stock: 100,
  482. lowestBuy: 1,
  483. createdBy: testUser.id
  484. });
  485. await goodsRepository.save(userGoods);
  486. const otherUserGoods = goodsRepository.create({
  487. name: '其他用户商品',
  488. price: 200.00,
  489. costPrice: 160.00,
  490. categoryId1: testCategory.id,
  491. categoryId2: 0,
  492. categoryId3: 0,
  493. goodsType: 1,
  494. supplierId: testSupplier.id,
  495. merchantId: testMerchant.id,
  496. state: 1,
  497. stock: 50,
  498. lowestBuy: 1,
  499. createdBy: otherUser.id
  500. });
  501. await goodsRepository.save(otherUserGoods);
  502. // 使用测试用户token获取列表
  503. const response = await client.index.$get({
  504. query: {}
  505. }, {
  506. headers: {
  507. 'Authorization': `Bearer ${userToken}`
  508. }
  509. });
  510. expect(response.status).toBe(200);
  511. const data = await response.json();
  512. // 类型检查确保data属性存在
  513. if ('data' in data && Array.isArray(data.data)) {
  514. // 验证只返回测试用户的商品
  515. const userGoodsInResponse = data.data.filter((goods: any) => goods.createdBy === testUser.id);
  516. const otherUserGoodsInResponse = data.data.filter((goods: any) => goods.createdBy === otherUser.id);
  517. expect(userGoodsInResponse.length).toBeGreaterThan(0);
  518. expect(otherUserGoodsInResponse.length).toBe(0);
  519. } else {
  520. // 如果响应是错误格式,应该失败
  521. expect(data).toHaveProperty('data');
  522. }
  523. });
  524. });
  525. });