users.integration.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. TestDataFactory
  6. } from '../../../__test_utils__/integration-test-db';
  7. import { IntegrationTestAssertions } from '../../../__test_utils__/integration-test-utils';
  8. import { userRoutes } from '../../../api';
  9. import { AuthService } from '../../../modules/auth/auth.service';
  10. import { UserService } from '../../../modules/users/user.service';
  11. // 设置集成测试钩子
  12. beforeAll(async () => {
  13. await IntegrationTestDatabase.initialize();
  14. });
  15. afterEach(async () => {
  16. await IntegrationTestDatabase.clearAllData();
  17. });
  18. afterAll(async () => {
  19. await IntegrationTestDatabase.cleanup();
  20. });
  21. describe('用户API集成测试 (使用hono/testing)', () => {
  22. let client: ReturnType<typeof testClient<typeof userRoutes>>['api']['v1'];
  23. let testToken: string;
  24. beforeEach(async () => {
  25. // 创建测试客户端
  26. client = testClient(userRoutes).api.v1;
  27. // 创建测试用户并生成token
  28. const dataSource = IntegrationTestDatabase.getDataSource();
  29. if (!dataSource) throw new Error('Database not initialized');
  30. const userService = new UserService(dataSource);
  31. const authService = new AuthService(userService);
  32. // 确保admin用户存在
  33. await authService.ensureAdminExists();
  34. // 生成admin用户的token
  35. testToken = authService.generateToken({
  36. id: 1,
  37. username: 'admin',
  38. roles: []
  39. } as any);
  40. // 设置默认认证头 - 需要在每个请求中手动添加
  41. });
  42. describe('用户创建测试', () => {
  43. it('应该成功创建用户', async () => {
  44. const userData = {
  45. username: 'testuser_create',
  46. email: 'testcreate@example.com',
  47. password: 'TestPassword123!',
  48. name: 'Test User',
  49. phone: '13800138000'
  50. };
  51. const response = await client.users.$post({
  52. json: userData,
  53. },
  54. {
  55. headers: {
  56. 'Authorization': `Bearer ${testToken}`
  57. }
  58. });
  59. // 断言响应
  60. console.log('Response status:', response.status);
  61. console.log('Response headers:', Object.fromEntries(response.headers.entries()));
  62. try {
  63. const responseData = await response.json();
  64. console.log('Response data:', responseData);
  65. } catch (e) {
  66. console.log('Cannot parse response as JSON');
  67. }
  68. expect(response.status).toBe(201);
  69. expect(response.data).toHaveProperty('id');
  70. expect(response.data.username).toBe(userData.username);
  71. expect(response.data.email).toBe(userData.email);
  72. expect(response.data.name).toBe(userData.name);
  73. // 断言数据库中存在用户
  74. await IntegrationTestAssertions.expectUserToExist(userData.username);
  75. });
  76. it('应该拒绝创建重复用户名的用户', async () => {
  77. const dataSource = IntegrationTestDatabase.getDataSource();
  78. if (!dataSource) throw new Error('Database not initialized');
  79. // 先创建一个用户
  80. const existingUser = await TestDataFactory.createTestUser(dataSource, {
  81. username: 'duplicate_user'
  82. });
  83. // 尝试创建相同用户名的用户
  84. const userData = {
  85. username: 'duplicate_user',
  86. email: 'different@example.com',
  87. password: 'TestPassword123!',
  88. name: 'Test User'
  89. };
  90. const response = await client.users.$post({
  91. json: userData
  92. });
  93. // 应该返回错误
  94. expect(response.status).toBe(500);
  95. expect(response.data.message).toContain('用户已存在');
  96. });
  97. it('应该拒绝创建无效邮箱的用户', async () => {
  98. const userData = {
  99. username: 'testuser_invalid_email',
  100. email: 'invalid-email',
  101. password: 'TestPassword123!',
  102. name: 'Test User'
  103. };
  104. const response = await client.users.$post({
  105. json: userData
  106. });
  107. // 应该返回验证错误
  108. expect(response.status).toBe(400);
  109. expect(response.data.code).toBe(400);
  110. });
  111. });
  112. describe('用户读取测试', () => {
  113. it('应该成功获取用户列表', async () => {
  114. const dataSource = IntegrationTestDatabase.getDataSource();
  115. if (!dataSource) throw new Error('Database not initialized');
  116. // 创建几个测试用户
  117. await TestDataFactory.createTestUser(dataSource, { username: 'user1' });
  118. await TestDataFactory.createTestUser(dataSource, { username: 'user2' });
  119. const response = await client.users.$get();
  120. expect(response.status).toBe(200);
  121. expect(Array.isArray(response.data.data)).toBe(true);
  122. expect(response.data.data.length).toBeGreaterThanOrEqual(2);
  123. });
  124. it('应该成功获取单个用户详情', async () => {
  125. const dataSource = IntegrationTestDatabase.getDataSource();
  126. if (!dataSource) throw new Error('Database not initialized');
  127. const testUser = await TestDataFactory.createTestUser(dataSource, {
  128. username: 'testuser_detail'
  129. });
  130. const response = await client.users[':id'].$get({
  131. param: { id: testUser.id.toString() }
  132. });
  133. expect(response.status).toBe(200);
  134. expect(response.data.id).toBe(testUser.id);
  135. expect(response.data.username).toBe(testUser.username);
  136. expect(response.data.email).toBe(testUser.email);
  137. });
  138. it('应该返回404当用户不存在时', async () => {
  139. const response = await client.users[':id'].$get({
  140. param: { id: '999999' }
  141. });
  142. expect(response.status).toBe(404);
  143. expect(response.data.message).toContain('用户不存在');
  144. });
  145. });
  146. describe('用户更新测试', () => {
  147. it('应该成功更新用户信息', async () => {
  148. const dataSource = IntegrationTestDatabase.getDataSource();
  149. if (!dataSource) throw new Error('Database not initialized');
  150. const testUser = await TestDataFactory.createTestUser(dataSource, {
  151. username: 'testuser_update'
  152. });
  153. const updateData = {
  154. name: 'Updated Name',
  155. email: 'updated@example.com'
  156. };
  157. const response = await client.users[':id'].$put({
  158. param: { id: testUser.id.toString() },
  159. json: updateData
  160. });
  161. expect(response.status).toBe(200);
  162. expect(response.data.name).toBe(updateData.name);
  163. expect(response.data.email).toBe(updateData.email);
  164. // 验证数据库中的更新
  165. const getResponse = await client.users[':id'].$get({
  166. param: { id: testUser.id.toString() }
  167. });
  168. expect(getResponse.data.name).toBe(updateData.name);
  169. });
  170. it('应该返回404当更新不存在的用户时', async () => {
  171. const updateData = {
  172. name: 'Updated Name',
  173. email: 'updated@example.com'
  174. };
  175. const response = await client.users[':id'].$put({
  176. param: { id: '999999' },
  177. json: updateData
  178. });
  179. expect(response.status).toBe(404);
  180. expect(response.data.message).toContain('用户不存在');
  181. });
  182. });
  183. describe('用户删除测试', () => {
  184. it('应该成功删除用户', async () => {
  185. const dataSource = IntegrationTestDatabase.getDataSource();
  186. if (!dataSource) throw new Error('Database not initialized');
  187. const testUser = await TestDataFactory.createTestUser(dataSource, {
  188. username: 'testuser_delete'
  189. });
  190. const response = await client.users[':id'].$delete({
  191. param: { id: testUser.id.toString() }
  192. });
  193. IntegrationTestAssertions.expectStatus(response, 204);
  194. // 验证用户已从数据库中删除
  195. await IntegrationTestAssertions.expectUserNotToExist('testuser_delete');
  196. // 验证再次获取用户返回404
  197. const getResponse = await client.users[':id'].$get({
  198. param: { id: testUser.id.toString() }
  199. });
  200. IntegrationTestAssertions.expectStatus(getResponse, 404);
  201. });
  202. it('应该返回404当删除不存在的用户时', async () => {
  203. const response = await client.users[':id'].$delete({
  204. param: { id: '999999' }
  205. });
  206. IntegrationTestAssertions.expectStatus(response, 404);
  207. expect(response.data.message).toContain('用户不存在');
  208. });
  209. });
  210. describe('用户搜索测试', () => {
  211. it('应该能够按用户名搜索用户', async () => {
  212. const dataSource = IntegrationTestDatabase.getDataSource();
  213. if (!dataSource) throw new Error('Database not initialized');
  214. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1', email: 'search1@example.com' });
  215. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2', email: 'search2@example.com' });
  216. await TestDataFactory.createTestUser(dataSource, { username: 'other_user', email: 'other@example.com' });
  217. const response = await client.users.$get({
  218. query: { keyword: 'search_user' }
  219. });
  220. IntegrationTestAssertions.expectStatus(response, 200);
  221. expect(Array.isArray(response.data.data)).toBe(true);
  222. expect(response.data.data.length).toBe(2);
  223. // 验证搜索结果包含正确的用户
  224. const usernames = response.data.data.map((user: any) => user.username);
  225. expect(usernames).toContain('search_user_1');
  226. expect(usernames).toContain('search_user_2');
  227. expect(usernames).not.toContain('other_user');
  228. });
  229. it('应该能够按邮箱搜索用户', async () => {
  230. const dataSource = IntegrationTestDatabase.getDataSource();
  231. if (!dataSource) throw new Error('Database not initialized');
  232. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1', email: 'test.email1@example.com' });
  233. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2', email: 'test.email2@example.com' });
  234. const response = await client.users.$get({
  235. query: { keyword: 'test.email' }
  236. });
  237. IntegrationTestAssertions.expectStatus(response, 200);
  238. expect(response.data.data.length).toBe(2);
  239. const emails = response.data.data.map((user: any) => user.email);
  240. expect(emails).toContain('test.email1@example.com');
  241. expect(emails).toContain('test.email2@example.com');
  242. });
  243. });
  244. describe('性能测试', () => {
  245. it('用户列表查询响应时间应小于200ms', async () => {
  246. const dataSource = IntegrationTestDatabase.getDataSource();
  247. if (!dataSource) throw new Error('Database not initialized');
  248. // 创建一些测试数据
  249. for (let i = 0; i < 10; i++) {
  250. await TestDataFactory.createTestUser(dataSource, {
  251. username: `perf_user_${i}`,
  252. email: `perf${i}@example.com`
  253. });
  254. }
  255. const startTime = Date.now();
  256. const response = await client.users.$get();
  257. const endTime = Date.now();
  258. const responseTime = endTime - startTime;
  259. IntegrationTestAssertions.expectStatus(response, 200);
  260. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  261. });
  262. });
  263. });