file.routes.integration.test.ts 17 KB

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