users.integration.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. expect(response.status).toBe(201);
  61. if (response.status === 201) {
  62. const responseData = await response.json();
  63. expect(responseData).toHaveProperty('id');
  64. expect(responseData.username).toBe(userData.username);
  65. expect(responseData.email).toBe(userData.email);
  66. expect(responseData.name).toBe(userData.name);
  67. // 断言数据库中存在用户
  68. await IntegrationTestAssertions.expectUserToExist(userData.username);
  69. }
  70. });
  71. it('应该拒绝创建重复用户名的用户', async () => {
  72. const dataSource = IntegrationTestDatabase.getDataSource();
  73. if (!dataSource) throw new Error('Database not initialized');
  74. // 先创建一个用户
  75. const existingUser = await TestDataFactory.createTestUser(dataSource, {
  76. username: 'duplicate_user'
  77. });
  78. // 尝试创建相同用户名的用户
  79. const userData = {
  80. username: 'duplicate_user',
  81. email: 'different@example.com',
  82. password: 'TestPassword123!',
  83. name: 'Test User'
  84. };
  85. const response = await client.users.$post({
  86. json: userData
  87. },
  88. {
  89. headers: {
  90. 'Authorization': `Bearer ${testToken}`
  91. }
  92. });
  93. // 应该返回错误
  94. expect(response.status).toBe(500);
  95. if (response.status === 500) {
  96. const responseData = await response.json();
  97. expect(responseData.message).toContain('用户已存在');
  98. }
  99. });
  100. it('应该拒绝创建无效邮箱的用户', async () => {
  101. const userData = {
  102. username: 'testuser_invalid_email',
  103. email: 'invalid-email',
  104. password: 'TestPassword123!',
  105. name: 'Test User'
  106. };
  107. const response = await client.users.$post({
  108. json: userData
  109. },
  110. {
  111. headers: {
  112. 'Authorization': `Bearer ${testToken}`
  113. }
  114. });
  115. // 应该返回验证错误
  116. expect(response.status).toBe(400);
  117. if (response.status === 400) {
  118. const responseData = await response.json();
  119. expect(responseData.code).toBe(400);
  120. }
  121. });
  122. });
  123. // describe('用户读取测试', () => {
  124. // it('应该成功获取用户列表', async () => {
  125. // const dataSource = IntegrationTestDatabase.getDataSource();
  126. // if (!dataSource) throw new Error('Database not initialized');
  127. // // 创建几个测试用户
  128. // await TestDataFactory.createTestUser(dataSource, { username: 'user1' });
  129. // await TestDataFactory.createTestUser(dataSource, { username: 'user2' });
  130. // const response = await client.users.$get({
  131. // query: {}
  132. // },
  133. // {
  134. // headers: {
  135. // 'Authorization': `Bearer ${testToken}`
  136. // }
  137. // });
  138. // expect(response.status).toBe(200);
  139. // if (response.status === 200) {
  140. // const responseData = await response.json();
  141. // expect(Array.isArray(responseData.data)).toBe(true);
  142. // expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  143. // }
  144. // });
  145. // it('应该成功获取单个用户详情', async () => {
  146. // const dataSource = IntegrationTestDatabase.getDataSource();
  147. // if (!dataSource) throw new Error('Database not initialized');
  148. // const testUser = await TestDataFactory.createTestUser(dataSource, {
  149. // username: 'testuser_detail'
  150. // });
  151. // const response = await client.users[':id'].$get({
  152. // param: { id: testUser.id.toString() }
  153. // },
  154. // {
  155. // headers: {
  156. // 'Authorization': `Bearer ${testToken}`
  157. // }
  158. // });
  159. // expect(response.status).toBe(200);
  160. // if (response.status === 200) {
  161. // const responseData = await response.json();
  162. // expect(responseData.id).toBe(testUser.id);
  163. // expect(responseData.username).toBe(testUser.username);
  164. // expect(responseData.email).toBe(testUser.email);
  165. // }
  166. // });
  167. // it('应该返回404当用户不存在时', async () => {
  168. // const response = await client.users[':id'].$get({
  169. // param: { id: '999999' }
  170. // },
  171. // {
  172. // headers: {
  173. // 'Authorization': `Bearer ${testToken}`
  174. // }
  175. // });
  176. // expect(response.status).toBe(404);
  177. // if (response.status === 404) {
  178. // const responseData = await response.json();
  179. // expect(responseData.message).toContain('用户不存在');
  180. // }
  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_update'
  189. // });
  190. // const updateData = {
  191. // name: 'Updated Name',
  192. // email: 'updated@example.com'
  193. // };
  194. // const response = await client.users[':id'].$put({
  195. // param: { id: testUser.id.toString() },
  196. // json: updateData
  197. // },
  198. // {
  199. // headers: {
  200. // 'Authorization': `Bearer ${testToken}`
  201. // }
  202. // });
  203. // expect(response.status).toBe(200);
  204. // if (response.status === 200) {
  205. // const responseData = await response.json();
  206. // expect(responseData.name).toBe(updateData.name);
  207. // expect(responseData.email).toBe(updateData.email);
  208. // }
  209. // // 验证数据库中的更新
  210. // const getResponse = await client.users[':id'].$get({
  211. // param: { id: testUser.id.toString() }
  212. // });
  213. // expect(getResponse.status).toBe(200);
  214. // if (getResponse.status === 200) {
  215. // const getResponseData = await getResponse.json();
  216. // expect(getResponseData.name).toBe(updateData.name);
  217. // }
  218. // });
  219. // it('应该返回404当更新不存在的用户时', async () => {
  220. // const updateData = {
  221. // name: 'Updated Name',
  222. // email: 'updated@example.com'
  223. // };
  224. // const response = await client.users[':id'].$put({
  225. // param: { id: '999999' },
  226. // json: updateData
  227. // },
  228. // {
  229. // headers: {
  230. // 'Authorization': `Bearer ${testToken}`
  231. // }
  232. // });
  233. // expect(response.status).toBe(404);
  234. // if (response.status === 404) {
  235. // const responseData = await response.json();
  236. // expect(responseData.message).toContain('用户不存在');
  237. // }
  238. // });
  239. // });
  240. // describe('用户删除测试', () => {
  241. // it('应该成功删除用户', async () => {
  242. // const dataSource = IntegrationTestDatabase.getDataSource();
  243. // if (!dataSource) throw new Error('Database not initialized');
  244. // const testUser = await TestDataFactory.createTestUser(dataSource, {
  245. // username: 'testuser_delete'
  246. // });
  247. // const response = await client.users[':id'].$delete({
  248. // param: { id: testUser.id.toString() }
  249. // },
  250. // {
  251. // headers: {
  252. // 'Authorization': `Bearer ${testToken}`
  253. // }
  254. // });
  255. // IntegrationTestAssertions.expectStatus(response, 204);
  256. // // 验证用户已从数据库中删除
  257. // await IntegrationTestAssertions.expectUserNotToExist('testuser_delete');
  258. // // 验证再次获取用户返回404
  259. // const getResponse = await client.users[':id'].$get({
  260. // param: { id: testUser.id.toString() }
  261. // });
  262. // IntegrationTestAssertions.expectStatus(getResponse, 404);
  263. // });
  264. // it('应该返回404当删除不存在的用户时', async () => {
  265. // const response = await client.users[':id'].$delete({
  266. // param: { id: '999999' }
  267. // },
  268. // {
  269. // headers: {
  270. // 'Authorization': `Bearer ${testToken}`
  271. // }
  272. // });
  273. // IntegrationTestAssertions.expectStatus(response, 404);
  274. // if (response.status === 404) {
  275. // const responseData = await response.json();
  276. // expect(responseData.message).toContain('用户不存在');
  277. // }
  278. // });
  279. // });
  280. // describe('用户搜索测试', () => {
  281. // it('应该能够按用户名搜索用户', async () => {
  282. // const dataSource = IntegrationTestDatabase.getDataSource();
  283. // if (!dataSource) throw new Error('Database not initialized');
  284. // await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1', email: 'search1@example.com' });
  285. // await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2', email: 'search2@example.com' });
  286. // await TestDataFactory.createTestUser(dataSource, { username: 'other_user', email: 'other@example.com' });
  287. // const response = await client.users.$get({
  288. // query: { keyword: 'search_user' }
  289. // },
  290. // {
  291. // headers: {
  292. // 'Authorization': `Bearer ${testToken}`
  293. // }
  294. // });
  295. // IntegrationTestAssertions.expectStatus(response, 200);
  296. // if (response.status === 200) {
  297. // const responseData = await response.json();
  298. // expect(Array.isArray(responseData.data)).toBe(true);
  299. // expect(responseData.data.length).toBe(2);
  300. // // 验证搜索结果包含正确的用户
  301. // const usernames = responseData.data.map((user: any) => user.username);
  302. // expect(usernames).toContain('search_user_1');
  303. // expect(usernames).toContain('search_user_2');
  304. // expect(usernames).not.toContain('other_user');
  305. // }
  306. // });
  307. // it('应该能够按邮箱搜索用户', async () => {
  308. // const dataSource = IntegrationTestDatabase.getDataSource();
  309. // if (!dataSource) throw new Error('Database not initialized');
  310. // await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1', email: 'test.email1@example.com' });
  311. // await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2', email: 'test.email2@example.com' });
  312. // const response = await client.users.$get({
  313. // query: { keyword: 'test.email' }
  314. // },
  315. // {
  316. // headers: {
  317. // 'Authorization': `Bearer ${testToken}`
  318. // }
  319. // });
  320. // IntegrationTestAssertions.expectStatus(response, 200);
  321. // if (response.status === 200) {
  322. // const responseData = await response.json();
  323. // expect(responseData.data.length).toBe(2);
  324. // const emails = responseData.data.map((user: any) => user.email);
  325. // expect(emails).toContain('test.email1@example.com');
  326. // expect(emails).toContain('test.email2@example.com');
  327. // }
  328. // });
  329. // });
  330. // describe('性能测试', () => {
  331. // it('用户列表查询响应时间应小于200ms', async () => {
  332. // const dataSource = IntegrationTestDatabase.getDataSource();
  333. // if (!dataSource) throw new Error('Database not initialized');
  334. // // 创建一些测试数据
  335. // for (let i = 0; i < 10; i++) {
  336. // await TestDataFactory.createTestUser(dataSource, {
  337. // username: `perf_user_${i}`,
  338. // email: `perf${i}@example.com`
  339. // });
  340. // }
  341. // const startTime = Date.now();
  342. // const response = await client.users.$get({
  343. // query: {}
  344. // },
  345. // {
  346. // headers: {
  347. // 'Authorization': `Bearer ${testToken}`
  348. // }
  349. // });
  350. // const endTime = Date.now();
  351. // const responseTime = endTime - startTime;
  352. // IntegrationTestAssertions.expectStatus(response, 200);
  353. // expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  354. // });
  355. // });
  356. });