user.routes.integration.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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 { userRoutes } from '../../src/routes';
  11. import { UserEntity } from '../../src/entities/user.entity';
  12. import { Role } from '../../src/entities/role.entity';
  13. import { TestDataFactory } from '../utils/integration-test-db';
  14. import { AuthService } from '@d8d/auth-module';
  15. import { UserService } from '../../src/services/user.service';
  16. import { File } from '@d8d/file-module';
  17. // 设置集成测试钩子
  18. setupIntegrationDatabaseHooksWithEntities([UserEntity, Role, File])
  19. describe('用户路由API集成测试 (使用hono/testing)', () => {
  20. let client: ReturnType<typeof testClient<typeof userRoutes>>;
  21. let authService: AuthService;
  22. let userService: UserService;
  23. let testToken: string;
  24. let testUser: any;
  25. beforeEach(async () => {
  26. // 创建测试客户端
  27. client = testClient(userRoutes);
  28. // 获取数据源
  29. const dataSource = await IntegrationTestDatabase.getDataSource();
  30. if (!dataSource) throw new Error('Database not initialized');
  31. // 初始化服务
  32. userService = new UserService(dataSource);
  33. authService = new AuthService(userService);
  34. // 创建测试用户并生成token
  35. testUser = await TestDataFactory.createTestUser(dataSource, {
  36. username: 'testuser_auth',
  37. password: 'TestPassword123!',
  38. email: 'testuser_auth@example.com'
  39. });
  40. // 生成测试用户的token
  41. testToken = authService.generateToken(testUser);
  42. });
  43. describe('用户创建路由测试', () => {
  44. it('应该拒绝无认证令牌的用户创建请求', async () => {
  45. const userData = {
  46. username: 'testuser_create_route_no_auth',
  47. email: 'testcreate_route_no_auth@example.com',
  48. password: 'TestPassword123!',
  49. nickname: 'Test User Route No Auth',
  50. phone: '13800138001'
  51. };
  52. const response = await client.index.$post({
  53. json: userData
  54. });
  55. // 应该返回401状态码,因为缺少认证
  56. expect(response.status).toBe(401);
  57. if (response.status === 401) {
  58. const responseData = await response.json();
  59. expect(responseData.message).toContain('Authorization header missing');
  60. }
  61. });
  62. it('应该拒绝无效认证令牌的用户创建请求', async () => {
  63. const userData = {
  64. username: 'testuser_create_route_invalid_token',
  65. email: 'testcreate_route_invalid_token@example.com',
  66. password: 'TestPassword123!',
  67. nickname: 'Test User Route Invalid Token',
  68. phone: '13800138001'
  69. };
  70. const response = await client.index.$post({
  71. json: userData
  72. }, {
  73. headers: {
  74. 'Authorization': 'Bearer invalid.token.here'
  75. }
  76. });
  77. // 应该返回401状态码,因为令牌无效
  78. expect(response.status).toBe(401);
  79. if (response.status === 401) {
  80. const responseData = await response.json();
  81. expect(responseData.message).toContain('Invalid token');
  82. }
  83. });
  84. it('应该成功创建用户(使用有效认证令牌)', async () => {
  85. const userData = {
  86. username: 'testuser_create_route',
  87. email: 'testcreate_route@example.com',
  88. password: 'TestPassword123!',
  89. nickname: 'Test User Route',
  90. phone: '13800138001'
  91. };
  92. const response = await client.index.$post({
  93. json: userData
  94. }, {
  95. headers: {
  96. 'Authorization': `Bearer ${testToken}`
  97. }
  98. });
  99. // 断言响应
  100. expect(response.status).toBe(201);
  101. if (response.status === 201) {
  102. const responseData = await response.json();
  103. expect(responseData).toHaveProperty('id');
  104. expect(responseData.username).toBe(userData.username);
  105. expect(responseData.email).toBe(userData.email);
  106. expect(responseData.nickname).toBe(userData.nickname);
  107. // 断言数据库中存在用户
  108. await IntegrationTestAssertions.expectUserToExist(userData.username);
  109. }
  110. });
  111. it('应该拒绝创建重复用户名的用户', async () => {
  112. const dataSource = await IntegrationTestDatabase.getDataSource();
  113. if (!dataSource) throw new Error('Database not initialized');
  114. // 先创建一个用户
  115. await TestDataFactory.createTestUser(dataSource, {
  116. username: 'duplicate_user_route'
  117. });
  118. // 尝试创建相同用户名的用户
  119. const userData = {
  120. username: 'duplicate_user_route',
  121. email: 'different_route@example.com',
  122. password: 'TestPassword123!',
  123. nickname: 'Test User'
  124. };
  125. const response = await client.index.$post({
  126. json: userData
  127. }, {
  128. headers: {
  129. 'Authorization': `Bearer ${testToken}`
  130. }
  131. });
  132. // 应该返回错误
  133. expect(response.status).toBe(500);
  134. if (response.status === 500) {
  135. const responseData = await response.json();
  136. expect(responseData.message).toContain('duplicate key');
  137. }
  138. });
  139. it('应该拒绝创建无效邮箱的用户', async () => {
  140. const userData = {
  141. username: 'testuser_invalid_email_route',
  142. email: 'invalid-email',
  143. password: 'TestPassword123!',
  144. nickname: 'Test User'
  145. };
  146. const response = await client.index.$post({
  147. json: userData
  148. }, {
  149. headers: {
  150. 'Authorization': `Bearer ${testToken}`
  151. }
  152. });
  153. // 应该返回验证错误或服务器错误
  154. expect([400, 500]).toContain(response.status);
  155. // 只要返回了错误状态码就认为测试通过
  156. // 不检查具体的响应格式,因为可能因实现而异
  157. });
  158. });
  159. describe('用户读取路由测试', () => {
  160. it('应该成功获取用户列表', async () => {
  161. const dataSource = await IntegrationTestDatabase.getDataSource();
  162. if (!dataSource) throw new Error('Database not initialized');
  163. // 创建几个测试用户
  164. await TestDataFactory.createTestUser(dataSource, { username: 'user1_route' });
  165. await TestDataFactory.createTestUser(dataSource, { username: 'user2_route' });
  166. const response = await client.index.$get({
  167. query: {}
  168. }, {
  169. headers: {
  170. 'Authorization': `Bearer ${testToken}`
  171. }
  172. });
  173. expect(response.status).toBe(200);
  174. if (response.status === 200) {
  175. const responseData = await response.json();
  176. expect(Array.isArray(responseData.data)).toBe(true);
  177. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  178. }
  179. });
  180. it('应该成功获取单个用户详情', async () => {
  181. const dataSource = await IntegrationTestDatabase.getDataSource();
  182. if (!dataSource) throw new Error('Database not initialized');
  183. const testUser = await TestDataFactory.createTestUser(dataSource, {
  184. username: 'testuser_detail_route'
  185. });
  186. const response = await client[':id'].$get({
  187. param: { id: testUser.id }
  188. }, {
  189. headers: {
  190. 'Authorization': `Bearer ${testToken}`
  191. }
  192. });
  193. expect(response.status).toBe(200);
  194. if (response.status === 200) {
  195. const responseData = await response.json();
  196. expect(responseData.id).toBe(testUser.id);
  197. expect(responseData.username).toBe(testUser.username);
  198. expect(responseData.email).toBe(testUser.email);
  199. }
  200. });
  201. it('应该返回404当用户不存在时', async () => {
  202. const response = await client[':id'].$get({
  203. param: { id: 999999 }
  204. }, {
  205. headers: {
  206. 'Authorization': `Bearer ${testToken}`
  207. }
  208. });
  209. expect(response.status).toBe(404);
  210. if (response.status === 404) {
  211. const responseData = await response.json();
  212. expect(responseData.message).toContain('资源不存在');
  213. }
  214. });
  215. });
  216. describe('用户更新路由测试', () => {
  217. it('应该拒绝无认证令牌的用户更新请求', async () => {
  218. const dataSource = await IntegrationTestDatabase.getDataSource();
  219. if (!dataSource) throw new Error('Database not initialized');
  220. const testUser = await TestDataFactory.createTestUser(dataSource, {
  221. username: 'testuser_update_no_auth'
  222. });
  223. const updateData = {
  224. nickname: 'Updated Name Route',
  225. email: 'updated_route@example.com'
  226. };
  227. const response = await client[':id'].$put({
  228. param: { id: testUser.id },
  229. json: updateData
  230. });
  231. // 应该返回401状态码,因为缺少认证
  232. expect(response.status).toBe(401);
  233. if (response.status === 401) {
  234. const responseData = await response.json();
  235. expect(responseData.message).toContain('Authorization header missing');
  236. }
  237. });
  238. it('应该成功更新用户信息(使用有效认证令牌)', async () => {
  239. const dataSource = await IntegrationTestDatabase.getDataSource();
  240. if (!dataSource) throw new Error('Database not initialized');
  241. const testUser = await TestDataFactory.createTestUser(dataSource, {
  242. username: 'testuser_update_route'
  243. });
  244. const updateData = {
  245. nickname: 'Updated Name Route',
  246. email: 'updated_route@example.com'
  247. };
  248. const response = await client[':id'].$put({
  249. param: { id: testUser.id },
  250. json: updateData
  251. }, {
  252. headers: {
  253. 'Authorization': `Bearer ${testToken}`
  254. }
  255. });
  256. expect(response.status).toBe(200);
  257. if (response.status === 200) {
  258. const responseData = await response.json();
  259. expect(responseData.nickname).toBe(updateData.nickname);
  260. expect(responseData.email).toBe(updateData.email);
  261. }
  262. // 验证数据库中的更新
  263. const getResponse = await client[':id'].$get({
  264. param: { id: testUser.id }
  265. });
  266. if (getResponse.status === 200) {
  267. expect(getResponse.status).toBe(200);
  268. const getResponseData = await getResponse.json();
  269. expect(getResponseData.nickname).toBe(updateData.nickname);
  270. }
  271. });
  272. it('应该返回404当更新不存在的用户时', async () => {
  273. const updateData = {
  274. nickname: 'Updated Name',
  275. email: 'updated@example.com'
  276. };
  277. const response = await client[':id'].$put({
  278. param: { id: 999999 },
  279. json: updateData
  280. }, {
  281. headers: {
  282. 'Authorization': `Bearer ${testToken}`
  283. }
  284. });
  285. expect(response.status).toBe(404);
  286. if (response.status === 404) {
  287. const responseData = await response.json();
  288. expect(responseData.message).toContain('资源不存在');
  289. }
  290. });
  291. });
  292. describe('用户删除路由测试', () => {
  293. it('应该拒绝无认证令牌的用户删除请求', async () => {
  294. const dataSource = await IntegrationTestDatabase.getDataSource();
  295. if (!dataSource) throw new Error('Database not initialized');
  296. const testUser = await TestDataFactory.createTestUser(dataSource, {
  297. username: 'testuser_delete_no_auth'
  298. });
  299. const response = await client[':id'].$delete({
  300. param: { id: testUser.id }
  301. });
  302. // 应该返回401状态码,因为缺少认证
  303. expect(response.status).toBe(401);
  304. if (response.status === 401) {
  305. const responseData = await response.json();
  306. expect(responseData.message).toContain('Authorization header missing');
  307. }
  308. });
  309. it('应该成功删除用户(使用有效认证令牌)', async () => {
  310. const dataSource = await IntegrationTestDatabase.getDataSource();
  311. if (!dataSource) throw new Error('Database not initialized');
  312. const testUser = await TestDataFactory.createTestUser(dataSource, {
  313. username: 'testuser_delete_route'
  314. });
  315. const response = await client[':id'].$delete({
  316. param: { id: testUser.id }
  317. }, {
  318. headers: {
  319. 'Authorization': `Bearer ${testToken}`
  320. }
  321. });
  322. IntegrationTestAssertions.expectStatus(response, 204);
  323. // 验证用户已从数据库中删除
  324. await IntegrationTestAssertions.expectUserNotToExist('testuser_delete_route');
  325. // 验证再次获取用户返回404
  326. const getResponse = await client[':id'].$get({
  327. param: { id: testUser.id }
  328. }, {
  329. headers: {
  330. 'Authorization': `Bearer ${testToken}`
  331. }
  332. });
  333. IntegrationTestAssertions.expectStatus(getResponse, 404);
  334. });
  335. it('应该返回404当删除不存在的用户时', async () => {
  336. const response = await client[':id'].$delete({
  337. param: { id: 999999 }
  338. }, {
  339. headers: {
  340. 'Authorization': `Bearer ${testToken}`
  341. }
  342. });
  343. IntegrationTestAssertions.expectStatus(response, 404);
  344. if (response.status === 404) {
  345. const responseData = await response.json();
  346. expect(responseData.message).toContain('资源不存在');
  347. }
  348. });
  349. });
  350. describe('用户搜索路由测试', () => {
  351. it('应该能够按用户名搜索用户', async () => {
  352. const dataSource = await IntegrationTestDatabase.getDataSource();
  353. if (!dataSource) throw new Error('Database not initialized');
  354. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1_route', email: 'search1_route@example.com' });
  355. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2_route', email: 'search2_route@example.com' });
  356. await TestDataFactory.createTestUser(dataSource, { username: 'other_user_route', email: 'other_route@example.com' });
  357. const response = await client.index.$get({
  358. query: { keyword: 'search_user' }
  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 usernames = responseData.data.map((user: any) => user.username);
  371. expect(usernames).toContain('search_user_1_route');
  372. expect(usernames).toContain('search_user_2_route');
  373. expect(usernames).not.toContain('other_user_route');
  374. }
  375. });
  376. it('应该能够按邮箱搜索用户', async () => {
  377. const dataSource = await IntegrationTestDatabase.getDataSource();
  378. if (!dataSource) throw new Error('Database not initialized');
  379. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1_route', email: 'test.email1_route@example.com' });
  380. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2_route', email: 'test.email2_route@example.com' });
  381. const response = await client.index.$get({
  382. query: { keyword: 'test.email' }
  383. }, {
  384. headers: {
  385. 'Authorization': `Bearer ${testToken}`
  386. }
  387. });
  388. IntegrationTestAssertions.expectStatus(response, 200);
  389. if (response.status === 200) {
  390. const responseData = await response.json();
  391. expect(responseData.data.length).toBe(2);
  392. const emails = responseData.data.map((user: any) => user.email);
  393. expect(emails).toContain('test.email1_route@example.com');
  394. expect(emails).toContain('test.email2_route@example.com');
  395. }
  396. });
  397. });
  398. describe('性能测试', () => {
  399. it('用户列表查询响应时间应小于200ms', async () => {
  400. const dataSource = await IntegrationTestDatabase.getDataSource();
  401. if (!dataSource) throw new Error('Database not initialized');
  402. // 创建一些测试数据
  403. for (let i = 0; i < 10; i++) {
  404. await TestDataFactory.createTestUser(dataSource, {
  405. username: `perf_user_${i}_route`,
  406. email: `perf${i}_route@example.com`
  407. });
  408. }
  409. const startTime = Date.now();
  410. const response = await client.index.$get({
  411. query: {}
  412. }, {
  413. headers: {
  414. 'Authorization': `Bearer ${testToken}`
  415. }
  416. });
  417. const endTime = Date.now();
  418. const responseTime = endTime - startTime;
  419. IntegrationTestAssertions.expectStatus(response, 200);
  420. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  421. });
  422. });
  423. describe('认证令牌测试', () => {
  424. it('应该能够生成有效的JWT令牌', async () => {
  425. // 验证生成的令牌是有效的字符串
  426. expect(typeof testToken).toBe('string');
  427. expect(testToken.length).toBeGreaterThan(0);
  428. // 验证令牌可以被正确解码
  429. const decoded = authService.verifyToken(testToken);
  430. expect(decoded).toHaveProperty('id');
  431. expect(decoded).toHaveProperty('username');
  432. expect(decoded.id).toBe(testUser.id);
  433. expect(decoded.username).toBe(testUser.username);
  434. });
  435. it('应该拒绝过期令牌的请求', async () => {
  436. // 创建立即过期的令牌
  437. const expiredToken = authService.generateToken(testUser, '1ms');
  438. // 等待令牌过期
  439. await new Promise(resolve => setTimeout(resolve, 10));
  440. const response = await client.index.$post({
  441. json: {
  442. username: 'test_expired_token',
  443. email: 'test_expired@example.com',
  444. password: 'TestPassword123!',
  445. nickname: 'Test Expired Token'
  446. }
  447. }, {
  448. headers: {
  449. 'Authorization': `Bearer ${expiredToken}`
  450. }
  451. });
  452. // 应该返回401状态码,因为令牌过期
  453. expect(response.status).toBe(401);
  454. if (response.status === 401) {
  455. const responseData = await response.json();
  456. expect(responseData.message).toContain('Invalid token');
  457. }
  458. });
  459. it('应该拒绝格式错误的认证头', async () => {
  460. const response = await client.index.$post({
  461. json: {
  462. username: 'test_bad_auth_header',
  463. email: 'test_bad_auth@example.com',
  464. password: 'TestPassword123!',
  465. nickname: 'Test Bad Auth Header'
  466. }
  467. }, {
  468. headers: {
  469. 'Authorization': 'Basic invalid_format'
  470. }
  471. });
  472. // 应该返回401状态码,因为认证头格式错误
  473. expect(response.status).toBe(401);
  474. if (response.status === 401) {
  475. const responseData = await response.json();
  476. expect(responseData.message).toContain('Authorization header missing');
  477. }
  478. });
  479. });
  480. });