file.routes.integration.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. import { describe, it, expect, beforeEach, vi } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooksWithEntities
  6. } from '@d8d/shared-test-util';
  7. import {
  8. IntegrationTestAssertions
  9. } from '../utils/integration-test-utils';
  10. import fileRoutes from '../../src/routes';
  11. import { File } from '../../src/entities';
  12. import { UserEntity, Role } from '@d8d/user-module';
  13. import { TestDataFactory } from '../utils/integration-test-db';
  14. import { AuthService } from '@d8d/auth-module';
  15. import { UserService } from '@d8d/user-module';
  16. import { MinioService } from '../../src/services/minio.service';
  17. // Mock MinIO service to avoid real connections in tests
  18. vi.mock('../../src/services/minio.service', () => {
  19. const MockMinioService = vi.fn(() => ({
  20. bucketName: 'test-bucket',
  21. ensureBucketExists: vi.fn().mockResolvedValue(true),
  22. objectExists: vi.fn().mockResolvedValue(false), // Assume files don't exist in MinIO for tests
  23. deleteObject: vi.fn().mockResolvedValue(undefined),
  24. generateUploadPolicy: vi.fn().mockResolvedValue({
  25. 'x-amz-algorithm': 'AWS4-HMAC-SHA256',
  26. 'x-amz-credential': 'test-credential',
  27. 'x-amz-date': '20230101T000000Z',
  28. policy: 'test-policy',
  29. 'x-amz-signature': 'test-signature',
  30. host: 'http://localhost:9000',
  31. key: 'test-key',
  32. bucket: 'test-bucket'
  33. }),
  34. getPresignedFileUrl: vi.fn().mockResolvedValue('http://localhost:9000/test-bucket/test-file'),
  35. getPresignedFileDownloadUrl: vi.fn().mockResolvedValue('http://localhost:9000/test-bucket/test-file?download=true'),
  36. createMultipartUpload: vi.fn().mockResolvedValue('test-upload-id'),
  37. generateMultipartUploadUrls: vi.fn().mockResolvedValue(['http://localhost:9000/part1', 'http://localhost:9000/part2']),
  38. completeMultipartUpload: vi.fn().mockResolvedValue({ size: 1024 }),
  39. createObject: vi.fn().mockResolvedValue('http://localhost:9000/test-bucket/test-file'),
  40. getFileUrl: vi.fn().mockReturnValue('http://localhost:9000/test-bucket/test-file')
  41. }));
  42. return { MinioService: MockMinioService };
  43. });
  44. // 设置集成测试钩子
  45. setupIntegrationDatabaseHooksWithEntities([File, UserEntity, Role])
  46. describe('文件路由API集成测试 (使用hono/testing)', () => {
  47. let client: ReturnType<typeof testClient<typeof fileRoutes>>;
  48. let authService: AuthService;
  49. let userService: UserService;
  50. let testToken: string;
  51. let testUser: any;
  52. beforeEach(async () => {
  53. // 创建测试客户端
  54. client = testClient(fileRoutes);
  55. // 获取数据源
  56. const dataSource = await IntegrationTestDatabase.getDataSource();
  57. if (!dataSource) throw new Error('Database not initialized');
  58. // 初始化服务
  59. userService = new UserService(dataSource);
  60. authService = new AuthService(userService);
  61. // 创建测试用户并生成token
  62. testUser = await TestDataFactory.createTestUser(dataSource, {
  63. username: 'testuser_file',
  64. password: 'TestPassword123!',
  65. email: 'testuser_file@example.com'
  66. });
  67. // 生成测试用户的token
  68. testToken = authService.generateToken(testUser);
  69. });
  70. describe('文件创建路由测试', () => {
  71. it('应该拒绝无认证令牌的文件创建请求', async () => {
  72. const fileData = {
  73. name: 'test.txt',
  74. type: 'text/plain',
  75. size: 1024,
  76. path: '/uploads/test.txt',
  77. description: 'Test file'
  78. };
  79. const response = await client['upload-policy'].$post({
  80. json: fileData
  81. });
  82. // 应该返回401状态码,因为缺少认证
  83. expect(response.status).toBe(401);
  84. if (response.status === 401) {
  85. const responseData = await response.json();
  86. expect(responseData.message).toContain('Authorization header missing');
  87. }
  88. });
  89. it('应该拒绝无效认证令牌的文件创建请求', async () => {
  90. const fileData = {
  91. name: 'test.txt',
  92. type: 'text/plain',
  93. size: 1024,
  94. path: '/uploads/test.txt',
  95. description: 'Test file'
  96. };
  97. const response = await client['upload-policy'].$post({
  98. json: fileData
  99. }, {
  100. headers: {
  101. 'Authorization': 'Bearer invalid.token.here'
  102. }
  103. });
  104. // 应该返回401状态码,因为令牌无效
  105. expect(response.status).toBe(401);
  106. if (response.status === 401) {
  107. const responseData = await response.json();
  108. expect(responseData.message).toContain('Invalid token');
  109. }
  110. });
  111. it('应该成功创建文件上传策略(使用有效认证令牌)', async () => {
  112. const fileData = {
  113. name: 'test.txt',
  114. type: 'text/plain',
  115. size: 1024,
  116. path: '/uploads/test.txt',
  117. description: 'Test file'
  118. };
  119. const response = await client['upload-policy'].$post({
  120. json: fileData
  121. }, {
  122. headers: {
  123. 'Authorization': `Bearer ${testToken}`
  124. }
  125. });
  126. // 断言响应
  127. if (response.status !== 200) {
  128. const errorData = await response.json();
  129. console.debug('File creation error:', JSON.stringify(errorData, null, 2));
  130. }
  131. expect(response.status).toBe(200);
  132. if (response.status === 200) {
  133. const responseData = await response.json();
  134. expect(responseData).toHaveProperty('file');
  135. expect(responseData).toHaveProperty('uploadPolicy');
  136. expect(responseData.file.name).toBe(fileData.name);
  137. expect(responseData.file.type).toBe(fileData.type);
  138. expect(responseData.file.size).toBe(fileData.size);
  139. expect(responseData.file.uploadUserId).toBe(testUser.id);
  140. // 断言数据库中存在文件记录
  141. const dataSource = await IntegrationTestDatabase.getDataSource();
  142. if (!dataSource) throw new Error('Database not initialized');
  143. const fileRepository = dataSource.getRepository(File);
  144. const savedFile = await fileRepository.findOne({
  145. where: { name: fileData.name }
  146. });
  147. expect(savedFile).toBeTruthy();
  148. expect(savedFile?.uploadUserId).toBe(testUser.id);
  149. }
  150. });
  151. it('应该拒绝创建无效文件数据的请求', async () => {
  152. const invalidFileData = {
  153. name: '', // 空文件名
  154. type: 'text/plain',
  155. path: 'test/path.txt'
  156. };
  157. const response = await client['upload-policy'].$post({
  158. json: invalidFileData
  159. }, {
  160. headers: {
  161. 'Authorization': `Bearer ${testToken}`
  162. }
  163. });
  164. // 应该返回验证错误
  165. expect([400, 500]).toContain(response.status);
  166. });
  167. });
  168. describe('文件读取路由测试', () => {
  169. it('应该成功获取文件列表', async () => {
  170. const dataSource = await IntegrationTestDatabase.getDataSource();
  171. if (!dataSource) throw new Error('Database not initialized');
  172. // 创建几个测试文件
  173. await TestDataFactory.createTestFile(dataSource, {
  174. name: 'file1.txt',
  175. uploadUserId: testUser.id
  176. });
  177. await TestDataFactory.createTestFile(dataSource, {
  178. name: 'file2.txt',
  179. uploadUserId: testUser.id
  180. });
  181. const response = await client.index.$get({
  182. query: {}
  183. }, {
  184. headers: {
  185. 'Authorization': `Bearer ${testToken}`
  186. }
  187. });
  188. expect(response.status).toBe(200);
  189. if (response.status === 200) {
  190. const responseData = await response.json();
  191. expect(Array.isArray(responseData.data)).toBe(true);
  192. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  193. }
  194. });
  195. it('应该成功获取单个文件详情', async () => {
  196. const dataSource = await IntegrationTestDatabase.getDataSource();
  197. if (!dataSource) throw new Error('Database not initialized');
  198. const testFile = await TestDataFactory.createTestFile(dataSource, {
  199. name: 'testfile_detail',
  200. uploadUserId: testUser.id
  201. });
  202. const response = await client[':id'].$get({
  203. param: { id: testFile.id }
  204. }, {
  205. headers: {
  206. 'Authorization': `Bearer ${testToken}`
  207. }
  208. });
  209. expect(response.status).toBe(200);
  210. if (response.status === 200) {
  211. const responseData = await response.json();
  212. expect(responseData.id).toBe(testFile.id);
  213. expect(responseData.name).toBe(testFile.name);
  214. expect(responseData.type).toBe(testFile.type);
  215. }
  216. });
  217. it('应该返回404当文件不存在时', async () => {
  218. const response = await client[':id'].$get({
  219. param: { id: 999999 }
  220. }, {
  221. headers: {
  222. 'Authorization': `Bearer ${testToken}`
  223. }
  224. });
  225. expect(response.status).toBe(404);
  226. if (response.status === 404) {
  227. const responseData = await response.json();
  228. expect(responseData.message).toContain('资源不存在');
  229. }
  230. });
  231. });
  232. describe('文件URL生成路由测试', () => {
  233. it('应该成功生成文件访问URL', async () => {
  234. const dataSource = await IntegrationTestDatabase.getDataSource();
  235. if (!dataSource) throw new Error('Database not initialized');
  236. const testFile = await TestDataFactory.createTestFile(dataSource, {
  237. name: 'testfile_url',
  238. uploadUserId: testUser.id
  239. });
  240. const response = await client[':id']['url'].$get({
  241. param: { id: testFile.id }
  242. }, {
  243. headers: {
  244. 'Authorization': `Bearer ${testToken}`
  245. }
  246. });
  247. expect(response.status).toBe(200);
  248. if (response.status === 200) {
  249. const responseData = await response.json();
  250. expect(responseData).toHaveProperty('url');
  251. expect(typeof responseData.url).toBe('string');
  252. expect(responseData.url.length).toBeGreaterThan(0);
  253. }
  254. });
  255. it('应该返回404当为不存在的文件生成URL时', async () => {
  256. const response = await client[':id']['url'].$get({
  257. param: { id: 999999 }
  258. }, {
  259. headers: {
  260. 'Authorization': `Bearer ${testToken}`
  261. }
  262. });
  263. expect(response.status).toBe(404);
  264. if (response.status === 404) {
  265. const responseData = await response.json();
  266. expect(responseData.message).toContain('文件不存在');
  267. }
  268. });
  269. });
  270. describe('文件下载路由测试', () => {
  271. it('应该成功生成文件下载URL', async () => {
  272. const dataSource = await IntegrationTestDatabase.getDataSource();
  273. if (!dataSource) throw new Error('Database not initialized');
  274. const testFile = await TestDataFactory.createTestFile(dataSource, {
  275. name: 'testfile_download.txt',
  276. uploadUserId: testUser.id
  277. });
  278. const response = await client[':id']['download'].$get({
  279. param: { id: testFile.id }
  280. }, {
  281. headers: {
  282. 'Authorization': `Bearer ${testToken}`
  283. }
  284. });
  285. expect(response.status).toBe(200);
  286. if (response.status === 200) {
  287. const responseData = await response.json();
  288. expect(responseData).toHaveProperty('url');
  289. expect(responseData).toHaveProperty('filename');
  290. expect(typeof responseData.url).toBe('string');
  291. expect(responseData.filename).toBe(testFile.name);
  292. }
  293. });
  294. it('应该返回404当为不存在的文件生成下载URL时', async () => {
  295. const response = await client[':id']['download'].$get({
  296. param: { id: 999999 }
  297. }, {
  298. headers: {
  299. 'Authorization': `Bearer ${testToken}`
  300. }
  301. });
  302. expect(response.status).toBe(404);
  303. if (response.status === 404) {
  304. const responseData = await response.json();
  305. expect(responseData.message).toContain('文件不存在');
  306. }
  307. });
  308. });
  309. describe('文件删除路由测试', () => {
  310. it('应该拒绝无认证令牌的文件删除请求', async () => {
  311. const dataSource = await IntegrationTestDatabase.getDataSource();
  312. if (!dataSource) throw new Error('Database not initialized');
  313. const testFile = await TestDataFactory.createTestFile(dataSource, {
  314. name: 'testfile_delete_no_auth',
  315. uploadUserId: testUser.id
  316. });
  317. const response = await client[':id'].$delete({
  318. param: { id: testFile.id }
  319. });
  320. // 应该返回401状态码,因为缺少认证
  321. expect(response.status).toBe(401);
  322. if (response.status === 401) {
  323. const responseData = await response.json();
  324. expect(responseData.message).toContain('Authorization header missing');
  325. }
  326. });
  327. it('应该成功删除文件(使用有效认证令牌)', async () => {
  328. const dataSource = await IntegrationTestDatabase.getDataSource();
  329. if (!dataSource) throw new Error('Database not initialized');
  330. const testFile = await TestDataFactory.createTestFile(dataSource, {
  331. name: 'testfile_delete',
  332. uploadUserId: testUser.id
  333. });
  334. const response = await client[':id'].$delete({
  335. param: { id: testFile.id }
  336. }, {
  337. headers: {
  338. 'Authorization': `Bearer ${testToken}`
  339. }
  340. });
  341. IntegrationTestAssertions.expectStatus(response, 200);
  342. // 验证文件已从数据库中删除
  343. const fileRepository = dataSource.getRepository(File);
  344. const deletedFile = await fileRepository.findOne({
  345. where: { id: testFile.id }
  346. });
  347. expect(deletedFile).toBeNull();
  348. // 验证再次获取文件返回404
  349. const getResponse = await client[':id'].$get({
  350. param: { id: testFile.id }
  351. }, {
  352. headers: {
  353. 'Authorization': `Bearer ${testToken}`
  354. }
  355. });
  356. IntegrationTestAssertions.expectStatus(getResponse, 404);
  357. });
  358. it('应该返回404当删除不存在的文件时', async () => {
  359. const response = await client[':id'].$delete({
  360. param: { id: 999999 }
  361. }, {
  362. headers: {
  363. 'Authorization': `Bearer ${testToken}`
  364. }
  365. });
  366. IntegrationTestAssertions.expectStatus(response, 404);
  367. if (response.status === 404) {
  368. const responseData = await response.json();
  369. expect(responseData.message).toContain('文件不存在');
  370. }
  371. });
  372. });
  373. describe('文件搜索路由测试', () => {
  374. it('应该能够按文件名搜索文件', async () => {
  375. const dataSource = await IntegrationTestDatabase.getDataSource();
  376. if (!dataSource) throw new Error('Database not initialized');
  377. await TestDataFactory.createTestFile(dataSource, {
  378. name: 'search_file_1.txt',
  379. uploadUserId: testUser.id
  380. });
  381. await TestDataFactory.createTestFile(dataSource, {
  382. name: 'search_file_2.txt',
  383. uploadUserId: testUser.id
  384. });
  385. await TestDataFactory.createTestFile(dataSource, {
  386. name: 'other_file.txt',
  387. uploadUserId: testUser.id
  388. });
  389. const response = await client.index.$get({
  390. query: { keyword: 'search_file' }
  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(Array.isArray(responseData.data)).toBe(true);
  400. expect(responseData.data.length).toBe(2);
  401. // 验证搜索结果包含正确的文件
  402. const filenames = responseData.data.map((file: any) => file.name);
  403. expect(filenames).toContain('search_file_1.txt');
  404. expect(filenames).toContain('search_file_2.txt');
  405. expect(filenames).not.toContain('other_file.txt');
  406. }
  407. });
  408. it('应该能够按文件类型搜索文件', async () => {
  409. const dataSource = await IntegrationTestDatabase.getDataSource();
  410. if (!dataSource) throw new Error('Database not initialized');
  411. await TestDataFactory.createTestFile(dataSource, {
  412. name: 'image1.jpg',
  413. type: 'image/jpeg',
  414. uploadUserId: testUser.id
  415. });
  416. await TestDataFactory.createTestFile(dataSource, {
  417. name: 'image2.png',
  418. type: 'image/png',
  419. uploadUserId: testUser.id
  420. });
  421. const response = await client.index.$get({
  422. query: { keyword: 'image' }
  423. }, {
  424. headers: {
  425. 'Authorization': `Bearer ${testToken}`
  426. }
  427. });
  428. IntegrationTestAssertions.expectStatus(response, 200);
  429. if (response.status === 200) {
  430. const responseData = await response.json();
  431. expect(responseData.data.length).toBe(2);
  432. const types = responseData.data.map((file: any) => file.type);
  433. expect(types).toContain('image/jpeg');
  434. expect(types).toContain('image/png');
  435. }
  436. });
  437. });
  438. describe('性能测试', () => {
  439. it('文件列表查询响应时间应小于200ms', async () => {
  440. const dataSource = await IntegrationTestDatabase.getDataSource();
  441. if (!dataSource) throw new Error('Database not initialized');
  442. // 创建一些测试数据
  443. for (let i = 0; i < 10; i++) {
  444. await TestDataFactory.createTestFile(dataSource, {
  445. name: `perf_file_${i}.txt`,
  446. uploadUserId: testUser.id
  447. });
  448. }
  449. const startTime = Date.now();
  450. const response = await client.index.$get({
  451. query: {}
  452. }, {
  453. headers: {
  454. 'Authorization': `Bearer ${testToken}`
  455. }
  456. });
  457. const endTime = Date.now();
  458. const responseTime = endTime - startTime;
  459. IntegrationTestAssertions.expectStatus(response, 200);
  460. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  461. });
  462. });
  463. describe('认证令牌测试', () => {
  464. it('应该拒绝过期令牌的文件请求', async () => {
  465. // 创建立即过期的令牌
  466. const expiredToken = authService.generateToken(testUser, '1ms');
  467. // 等待令牌过期
  468. await new Promise(resolve => setTimeout(resolve, 10));
  469. const response = await client['upload-policy'].$post({
  470. json: {
  471. name: 'test_expired_token.txt',
  472. type: 'text/plain',
  473. size: 1024,
  474. path: 'test/expired_token.txt'
  475. }
  476. }, {
  477. headers: {
  478. 'Authorization': `Bearer ${expiredToken}`
  479. }
  480. });
  481. // 应该返回401状态码,因为令牌过期
  482. expect(response.status).toBe(401);
  483. if (response.status === 401) {
  484. const responseData = await response.json();
  485. expect(responseData.message).toContain('Invalid token');
  486. }
  487. });
  488. it('应该拒绝格式错误的认证头', async () => {
  489. const response = await client['upload-policy'].$post({
  490. json: {
  491. name: 'test_bad_auth_header.txt',
  492. type: 'text/plain',
  493. size: 1024,
  494. path: 'test/bad_auth_header.txt'
  495. }
  496. }, {
  497. headers: {
  498. 'Authorization': 'Basic invalid_format'
  499. }
  500. });
  501. // 应该返回401状态码,因为认证头格式错误
  502. expect(response.status).toBe(401);
  503. if (response.status === 401) {
  504. const responseData = await response.json();
  505. expect(responseData.message).toContain('Authorization header missing');
  506. }
  507. });
  508. });
  509. });