users.integration.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. {
  210. headers: {
  211. 'Authorization': `Bearer ${testToken}`
  212. }
  213. });
  214. if (getResponse.status === 200) {
  215. expect(getResponse.status).toBe(200);
  216. const getResponseData = await getResponse.json();
  217. expect(getResponseData.name).toBe(updateData.name);
  218. }else{
  219. const getResponseData = await getResponse.json();
  220. process.stderr.write('message:'+ getResponseData.message +"\n");
  221. }
  222. });
  223. it('应该返回404当更新不存在的用户时', async () => {
  224. const updateData = {
  225. name: 'Updated Name',
  226. email: 'updated@example.com'
  227. };
  228. const response = await client.users[':id'].$put({
  229. param: { id: 999999 },
  230. json: updateData
  231. },
  232. {
  233. headers: {
  234. 'Authorization': `Bearer ${testToken}`
  235. }
  236. });
  237. expect(response.status).toBe(404);
  238. if (response.status === 404) {
  239. const responseData = await response.json();
  240. expect(responseData.message).toContain('用户不存在');
  241. }
  242. });
  243. });
  244. describe('用户删除测试', () => {
  245. it('应该成功删除用户', async () => {
  246. const dataSource = IntegrationTestDatabase.getDataSource();
  247. if (!dataSource) throw new Error('Database not initialized');
  248. const testUser = await TestDataFactory.createTestUser(dataSource, {
  249. username: 'testuser_delete'
  250. });
  251. const response = await client.users[':id'].$delete({
  252. param: { id: testUser.id }
  253. },
  254. {
  255. headers: {
  256. 'Authorization': `Bearer ${testToken}`
  257. }
  258. });
  259. IntegrationTestAssertions.expectStatus(response, 204);
  260. // 验证用户已从数据库中删除
  261. await IntegrationTestAssertions.expectUserNotToExist('testuser_delete');
  262. // 验证再次获取用户返回404
  263. const getResponse = await client.users[':id'].$get({
  264. param: { id: testUser.id }
  265. });
  266. IntegrationTestAssertions.expectStatus(getResponse, 404);
  267. });
  268. it('应该返回404当删除不存在的用户时', async () => {
  269. const response = await client.users[':id'].$delete({
  270. param: { id: 999999 }
  271. },
  272. {
  273. headers: {
  274. 'Authorization': `Bearer ${testToken}`
  275. }
  276. });
  277. IntegrationTestAssertions.expectStatus(response, 404);
  278. if (response.status === 404) {
  279. const responseData = await response.json();
  280. expect(responseData.message).toContain('用户不存在');
  281. }
  282. });
  283. });
  284. describe('用户搜索测试', () => {
  285. it('应该能够按用户名搜索用户', async () => {
  286. const dataSource = IntegrationTestDatabase.getDataSource();
  287. if (!dataSource) throw new Error('Database not initialized');
  288. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1', email: 'search1@example.com' });
  289. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2', email: 'search2@example.com' });
  290. await TestDataFactory.createTestUser(dataSource, { username: 'other_user', email: 'other@example.com' });
  291. const response = await client.users.$get({
  292. query: { keyword: 'search_user' }
  293. },
  294. {
  295. headers: {
  296. 'Authorization': `Bearer ${testToken}`
  297. }
  298. });
  299. IntegrationTestAssertions.expectStatus(response, 200);
  300. if (response.status === 200) {
  301. const responseData = await response.json();
  302. expect(Array.isArray(responseData.data)).toBe(true);
  303. expect(responseData.data.length).toBe(2);
  304. // 验证搜索结果包含正确的用户
  305. const usernames = responseData.data.map((user: any) => user.username);
  306. expect(usernames).toContain('search_user_1');
  307. expect(usernames).toContain('search_user_2');
  308. expect(usernames).not.toContain('other_user');
  309. }
  310. });
  311. it('应该能够按邮箱搜索用户', async () => {
  312. const dataSource = IntegrationTestDatabase.getDataSource();
  313. if (!dataSource) throw new Error('Database not initialized');
  314. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1', email: 'test.email1@example.com' });
  315. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2', email: 'test.email2@example.com' });
  316. const response = await client.users.$get({
  317. query: { keyword: 'test.email' }
  318. },
  319. {
  320. headers: {
  321. 'Authorization': `Bearer ${testToken}`
  322. }
  323. });
  324. IntegrationTestAssertions.expectStatus(response, 200);
  325. if (response.status === 200) {
  326. const responseData = await response.json();
  327. expect(responseData.data.length).toBe(2);
  328. const emails = responseData.data.map((user: any) => user.email);
  329. expect(emails).toContain('test.email1@example.com');
  330. expect(emails).toContain('test.email2@example.com');
  331. }
  332. });
  333. });
  334. describe('性能测试', () => {
  335. it('用户列表查询响应时间应小于200ms', async () => {
  336. const dataSource = IntegrationTestDatabase.getDataSource();
  337. if (!dataSource) throw new Error('Database not initialized');
  338. // 创建一些测试数据
  339. for (let i = 0; i < 10; i++) {
  340. await TestDataFactory.createTestUser(dataSource, {
  341. username: `perf_user_${i}`,
  342. email: `perf${i}@example.com`
  343. });
  344. }
  345. const startTime = Date.now();
  346. const response = await client.users.$get({
  347. query: {}
  348. },
  349. {
  350. headers: {
  351. 'Authorization': `Bearer ${testToken}`
  352. }
  353. });
  354. const endTime = Date.now();
  355. const responseTime = endTime - startTime;
  356. IntegrationTestAssertions.expectStatus(response, 200);
  357. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  358. });
  359. });
  360. });