user.routes.integration.test.ts 18 KB

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