file.routes.integration.test.ts 17 KB

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