file.routes.integration.test.ts 17 KB

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