files.integration.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import { DataSource } from 'typeorm';
  4. import { FileService } from '@/server/modules/files/file.service';
  5. import { authMiddleware } from '@/server/middleware/auth.middleware';
  6. import { fileApiRoutes } from '@/server/api';
  7. vi.mock('@/server/modules/files/file.service');
  8. vi.mock('@/server/middleware/auth.middleware');
  9. describe('File API Integration Tests', () => {
  10. let client: ReturnType<typeof testClient<typeof fileApiRoutes>>['api']['v1'];
  11. const user1 = {
  12. id: 1,
  13. username: 'testuser',
  14. password: 'password123',
  15. phone: null,
  16. email: null,
  17. nickname: null,
  18. name: null,
  19. avatarFileId: null,
  20. avatarFile: null,
  21. isDisabled: 0,
  22. isDeleted: 0,
  23. roles: [],
  24. createdAt: new Date(),
  25. updatedAt: new Date()
  26. };
  27. const user1Response = {
  28. ...user1,
  29. createdAt: (user1.createdAt).toISOString(),
  30. updatedAt: (user1.updatedAt).toISOString()
  31. }
  32. beforeEach(async () => {
  33. vi.clearAllMocks();
  34. // Mock auth middleware to bypass authentication
  35. vi.mocked(authMiddleware).mockImplementation(async (c, next) => {
  36. const authHeader = c.req.header('Authorization');
  37. if (!authHeader) {
  38. return c.json({ message: 'Authorization header missing' }, 401);
  39. }
  40. c.set('user', user1)
  41. await next();
  42. });
  43. client = testClient(fileApiRoutes).api.v1;
  44. });
  45. afterEach(() => {
  46. vi.clearAllMocks();
  47. });
  48. describe('POST /api/v1/files/upload-policy', () => {
  49. it('should generate upload policy successfully', async () => {
  50. const mockFileData = {
  51. name: 'test.txt',
  52. type: 'text/plain',
  53. size: 1024,
  54. path: '/uploads/test.txt',
  55. description: 'Test file',
  56. uploadUserId: 1
  57. };
  58. const mockResponse = {
  59. file: {
  60. id: 1,
  61. ...mockFileData,
  62. path: '1/test-uuid-123-test.txt',
  63. uploadTime: (new Date()).toISOString(),
  64. createdAt: (new Date()).toISOString(),
  65. updatedAt: (new Date()).toISOString(),
  66. fullUrl: 'https://minio.example.com/d8dai/1/test-uuid-123-test.txt',
  67. uploadUser: user1Response,
  68. lastUpdated: null
  69. },
  70. uploadPolicy: {
  71. 'x-amz-algorithm': 'AWS4-HMAC-SHA256',
  72. 'x-amz-credential': 'test-credential',
  73. 'x-amz-date': '20250101T120000Z',
  74. 'x-amz-security-token': 'test-token',
  75. policy: 'test-policy',
  76. 'x-amz-signature': 'test-signature',
  77. host: 'https://minio.example.com',
  78. key: '1/test-uuid-123-test.txt',
  79. bucket: 'd8dai'
  80. }
  81. };
  82. const mockCreateFile = vi.fn().mockResolvedValue(mockResponse);
  83. vi.mocked(FileService).mockImplementation(() => ({
  84. createFile: mockCreateFile
  85. } as unknown as FileService));
  86. const response = await client.files['upload-policy'].$post({
  87. json: mockFileData
  88. },
  89. {
  90. headers: {
  91. 'Authorization': 'Bearer test-token'
  92. }
  93. });
  94. if (response.status !== 200) {
  95. const error = await response.json();
  96. console.debug('Error response:', JSON.stringify(error, null, 2));
  97. console.debug('Response status:', response.status);
  98. }
  99. expect(response.status).toBe(200);
  100. const result = await response.json();
  101. expect(result).toEqual(mockResponse);
  102. expect(mockCreateFile).toHaveBeenCalledWith({
  103. ...mockFileData,
  104. uploadTime: expect.any(Date),
  105. uploadUserId: 1
  106. });
  107. });
  108. it('should return 400 for invalid request data', async () => {
  109. const invalidData = {
  110. name: '', // Empty name
  111. type: 'text/plain'
  112. };
  113. const response = await client.files['upload-policy'].$post({
  114. json: invalidData as any
  115. },
  116. {
  117. headers: {
  118. 'Authorization': 'Bearer test-token'
  119. }
  120. });
  121. expect(response.status).toBe(400);
  122. });
  123. // it('should handle service errors gracefully', async () => {
  124. // const mockFileData = {
  125. // name: 'test.txt',
  126. // type: 'text/plain',
  127. // uploadUserId: 1
  128. // };
  129. // mockFileService.createFile = vi.fn().mockRejectedValue(new Error('Service error'));
  130. // const response = await client.files['upload-policy'].$post({
  131. // json: mockFileData
  132. // },
  133. // {
  134. // headers: {
  135. // 'Authorization': 'Bearer test-token'
  136. // }
  137. // });
  138. // expect(response.status).toBe(500);
  139. // });
  140. });
  141. // describe('GET /api/v1/files/{id}/url', () => {
  142. // it('should generate file access URL successfully', async () => {
  143. // const mockUrl = 'https://minio.example.com/presigned-url';
  144. // vi.mocked(mockFileService.getFileUrl).mockResolvedValue(mockUrl);
  145. // const response = await client.files[':id']['url'].$get({
  146. // param: { id: 1 }
  147. // },
  148. // {
  149. // headers: {
  150. // 'Authorization': 'Bearer test-token'
  151. // }
  152. // });
  153. // expect(response.status).toBe(200);
  154. // const result = await response.json();
  155. // expect(result).toEqual({ url: mockUrl });
  156. // expect(mockFileService.getFileUrl).toHaveBeenCalledWith(1);
  157. // });
  158. // it('should return 404 when file not found', async () => {
  159. // vi.mocked(mockFileService.getFileUrl).mockRejectedValue(new Error('文件不存在'));
  160. // const response = await client.files[':id']['url'].$get({
  161. // param: { id: 999 }
  162. // },
  163. // {
  164. // headers: {
  165. // 'Authorization': 'Bearer test-token'
  166. // }
  167. // });
  168. // expect(response.status).toBe(404);
  169. // });
  170. // });
  171. // describe('GET /api/v1/files/{id}/download', () => {
  172. // it('should generate file download URL successfully', async () => {
  173. // const mockDownloadInfo = {
  174. // url: 'https://minio.example.com/download-url',
  175. // filename: 'test.txt'
  176. // };
  177. // vi.mocked(mockFileService.getFileDownloadUrl).mockResolvedValue(mockDownloadInfo);
  178. // const response = await client.files[':id']['download'].$get({
  179. // param: { id: 1 }
  180. // },
  181. // {
  182. // headers: {
  183. // 'Authorization': 'Bearer test-token'
  184. // }
  185. // });
  186. // expect(response.status).toBe(200);
  187. // const result = await response.json();
  188. // expect(result).toEqual(mockDownloadInfo);
  189. // expect(mockFileService.getFileDownloadUrl).toHaveBeenCalledWith(1);
  190. // });
  191. // it('should return 404 when file not found for download', async () => {
  192. // vi.mocked(mockFileService.getFileDownloadUrl).mockRejectedValue(new Error('文件不存在'));
  193. // const response = await client.files[':id']['download'].$get({
  194. // param: { id: 999 }
  195. // },
  196. // {
  197. // headers: {
  198. // 'Authorization': 'Bearer test-token'
  199. // }
  200. // });
  201. // expect(response.status).toBe(404);
  202. // });
  203. // });
  204. // describe('DELETE /api/v1/files/{id}', () => {
  205. // it('should delete file successfully', async () => {
  206. // vi.mocked(mockFileService.deleteFile).mockResolvedValue(true);
  207. // const response = await client.files[':id'].$delete({
  208. // param: { id: 1 }
  209. // },
  210. // {
  211. // headers: {
  212. // 'Authorization': 'Bearer test-token'
  213. // }
  214. // });
  215. // expect(response.status).toBe(200);
  216. // const result = await response.json();
  217. // expect(result).toEqual({ success: true });
  218. // expect(mockFileService.deleteFile).toHaveBeenCalledWith(1);
  219. // });
  220. // it('should return 404 when file not found for deletion', async () => {
  221. // vi.mocked(mockFileService.deleteFile).mockRejectedValue(new Error('文件不存在'));
  222. // const response = await client.files[':id'].$delete({
  223. // param: { id: 999 }
  224. // },
  225. // {
  226. // headers: {
  227. // 'Authorization': 'Bearer test-token'
  228. // }
  229. // });
  230. // expect(response.status).toBe(404);
  231. // });
  232. // it('should handle deletion errors', async () => {
  233. // vi.mocked(mockFileService.deleteFile).mockRejectedValue(new Error('删除失败'));
  234. // const response = await client.files[':id'].$delete({
  235. // param: { id: 1 }
  236. // },
  237. // {
  238. // headers: {
  239. // 'Authorization': 'Bearer test-token'
  240. // }
  241. // });
  242. // expect(response.status).toBe(500);
  243. // });
  244. // });
  245. // describe('POST /api/v1/files/multipart-policy', () => {
  246. // it('should generate multipart upload policy successfully', async () => {
  247. // const mockRequestData = {
  248. // fileKey: 'large-file.zip',
  249. // totalSize: 1024 * 1024 * 100, // 100MB
  250. // partSize: 1024 * 1024 * 20, // 20MB
  251. // name: 'large-file.zip',
  252. // type: 'application/zip',
  253. // uploadUserId: 1
  254. // };
  255. // const mockResponse = {
  256. // file: {
  257. // id: 1,
  258. // ...mockRequestData,
  259. // path: '1/test-uuid-123-large-file.zip',
  260. // description: null,
  261. // uploadUser: {} as any,
  262. // uploadTime: new Date(),
  263. // lastUpdated: null,
  264. // createdAt: new Date(),
  265. // updatedAt: new Date(),
  266. // fullUrl: Promise.resolve('https://minio.example.com/d8dai/1/test-uuid-123-large-file.zip')
  267. // },
  268. // uploadId: 'upload-123',
  269. // uploadUrls: ['url1', 'url2', 'url3', 'url4', 'url5'],
  270. // bucket: 'd8dai',
  271. // key: '1/test-uuid-123-large-file.zip'
  272. // };
  273. // vi.mocked(mockFileService.createMultipartUploadPolicy).mockResolvedValue(mockResponse);
  274. // const response = await client.files['multipart-policy'].$post({
  275. // json: mockRequestData
  276. // },
  277. // {
  278. // headers: {
  279. // 'Authorization': 'Bearer test-token'
  280. // }
  281. // });
  282. // expect(response.status).toBe(200);
  283. // const result = await response.json();
  284. // expect(result).toEqual(mockResponse);
  285. // expect(mockFileService.createMultipartUploadPolicy).toHaveBeenCalledWith(
  286. // {
  287. // name: 'large-file.zip',
  288. // type: 'application/zip',
  289. // size: 104857600,
  290. // uploadUserId: 1
  291. // },
  292. // 5
  293. // );
  294. // });
  295. // it('should validate multipart policy request data', async () => {
  296. // const invalidData = {
  297. // name: 'test.zip',
  298. // // Missing required fields: fileKey, totalSize, partSize
  299. // };
  300. // const response = await client.files['multipart-policy'].$post({
  301. // json: invalidData
  302. // },
  303. // {
  304. // headers: {
  305. // 'Authorization': 'Bearer test-token'
  306. // }
  307. // });
  308. // expect(response.status).toBe(400);
  309. // });
  310. // });
  311. // describe('POST /api/v1/files/multipart-complete', () => {
  312. // it('should complete multipart upload successfully', async () => {
  313. // const mockCompleteData = {
  314. // uploadId: 'upload-123',
  315. // bucket: 'd8dai',
  316. // key: '1/test-file.zip',
  317. // parts: [
  318. // { partNumber: 1, etag: 'etag1' },
  319. // { partNumber: 2, etag: 'etag2' }
  320. // ]
  321. // };
  322. // const mockResponse = {
  323. // fileId: 1,
  324. // url: 'https://minio.example.com/file.zip',
  325. // key: '1/test-file.zip',
  326. // size: 2048
  327. // };
  328. // vi.mocked(mockFileService.completeMultipartUpload).mockResolvedValue(mockResponse);
  329. // const response = await client.files['multipart-complete'].$post({
  330. // json: mockCompleteData
  331. // },
  332. // {
  333. // headers: {
  334. // 'Authorization': 'Bearer test-token'
  335. // }
  336. // });
  337. // expect(response.status).toBe(200);
  338. // const result = await response.json();
  339. // expect(result).toEqual(mockResponse);
  340. // expect(mockFileService.completeMultipartUpload).toHaveBeenCalledWith(mockCompleteData);
  341. // });
  342. // it('should validate complete multipart request data', async () => {
  343. // const invalidData = {
  344. // uploadId: 'upload-123',
  345. // // Missing required fields: bucket, key, parts
  346. // };
  347. // const response = await client.files['multipart-complete'].$post({
  348. // json: invalidData
  349. // },
  350. // {
  351. // headers: {
  352. // 'Authorization': 'Bearer test-token'
  353. // }
  354. // });
  355. // expect(response.status).toBe(400);
  356. // });
  357. // it('should handle completion errors', async () => {
  358. // const completeData = {
  359. // uploadId: 'upload-123',
  360. // bucket: 'd8dai',
  361. // key: '1/test-file.zip',
  362. // parts: [{ partNumber: 1, etag: 'etag1' }]
  363. // };
  364. // vi.mocked(mockFileService.completeMultipartUpload).mockRejectedValue(new Error('Completion failed'));
  365. // const response = await client.files['multipart-complete'].$post({
  366. // json: completeData
  367. // },
  368. // {
  369. // headers: {
  370. // 'Authorization': 'Bearer test-token'
  371. // }
  372. // });
  373. // expect(response.status).toBe(500);
  374. // });
  375. // });
  376. // describe('CRUD Operations', () => {
  377. // it('should list files successfully', async () => {
  378. // const mockFiles = [
  379. // {
  380. // id: 1,
  381. // name: 'file1.txt',
  382. // type: 'text/plain',
  383. // size: 1024,
  384. // uploadUserId: 1
  385. // },
  386. // {
  387. // id: 2,
  388. // name: 'file2.txt',
  389. // type: 'text/plain',
  390. // size: 2048,
  391. // uploadUserId: 1
  392. // }
  393. // ];
  394. // vi.spyOn(mockFileService, 'getList').mockResolvedValue([mockFiles as File[], mockFiles.length]);
  395. // const response = await client.files.$get({
  396. // query: {}
  397. // },
  398. // {
  399. // headers: {
  400. // 'Authorization': 'Bearer test-token'
  401. // }
  402. // });
  403. // expect(response.status).toBe(200);
  404. // const result = await response.json();
  405. // expect(result).toEqual(mockFiles);
  406. // });
  407. // it('should get file by ID successfully', async () => {
  408. // const mockFile = {
  409. // id: 1,
  410. // name: 'file.txt',
  411. // type: 'text/plain',
  412. // size: 1024,
  413. // uploadUserId: 1
  414. // };
  415. // vi.spyOn(mockFileService, 'getById').mockResolvedValue(mockFile as File);
  416. // const response = await client.files[':id'].$get({
  417. // param: { id: 1 }
  418. // },
  419. // {
  420. // headers: {
  421. // 'Authorization': 'Bearer test-token'
  422. // }
  423. // });
  424. // expect(response.status).toBe(200);
  425. // const result = await response.json();
  426. // expect(result).toEqual(mockFile);
  427. // });
  428. // it('should search files successfully', async () => {
  429. // const mockFiles = [
  430. // {
  431. // id: 1,
  432. // name: 'document.pdf',
  433. // type: 'application/pdf',
  434. // size: 1024,
  435. // uploadUserId: 1
  436. // }
  437. // ];
  438. // vi.spyOn(mockFileService, 'getList').mockResolvedValue([mockFiles as File[], mockFiles.length]);
  439. // const response = await client.files.$get({
  440. // query: { keyword: 'document' }
  441. // },
  442. // {
  443. // headers: {
  444. // 'Authorization': 'Bearer test-token'
  445. // }
  446. // });
  447. // expect(response.status).toBe(200);
  448. // const result = await response.json();
  449. // expect(result).toEqual(mockFiles);
  450. // expect(mockFileService.getList).toHaveBeenCalledWith(1, 10, 'document', ['name', 'type', 'description'], undefined, [], {}, undefined);
  451. // });
  452. // });
  453. });