users.integration.test.ts 13 KB

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