users.integration.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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('duplicate key');
  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. // 根据实际实现,可能是400验证错误或500服务器错误
  113. expect([400, 500]).toContain(response.status);
  114. if (response.status === 400) {
  115. const responseData = await response.json();
  116. // 检查是否有code属性
  117. if (responseData.code !== undefined) {
  118. expect(responseData.code).toBe(400);
  119. }
  120. // 检查是否有message属性
  121. if (responseData.message !== undefined) {
  122. expect(typeof responseData.message).toBe('string');
  123. }
  124. } else if (response.status === 500) {
  125. const responseData = await response.json();
  126. expect(responseData.message).toBeDefined();
  127. }
  128. });
  129. });
  130. describe('用户读取测试', () => {
  131. it('应该成功获取用户列表', async () => {
  132. const dataSource = IntegrationTestDatabase.getDataSource();
  133. if (!dataSource) throw new Error('Database not initialized');
  134. // 创建几个测试用户
  135. await TestDataFactory.createTestUser(dataSource, { username: 'user1' });
  136. await TestDataFactory.createTestUser(dataSource, { username: 'user2' });
  137. const response = await client.users.$get({
  138. query: {}
  139. },
  140. {
  141. headers: {
  142. 'Authorization': `Bearer ${testToken}`
  143. }
  144. });
  145. expect(response.status).toBe(200);
  146. if (response.status === 200) {
  147. const responseData = await response.json();
  148. expect(Array.isArray(responseData.data)).toBe(true);
  149. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  150. }
  151. });
  152. it('应该成功获取单个用户详情', async () => {
  153. const dataSource = IntegrationTestDatabase.getDataSource();
  154. if (!dataSource) throw new Error('Database not initialized');
  155. const testUser = await TestDataFactory.createTestUser(dataSource, {
  156. username: 'testuser_detail'
  157. });
  158. const response = await client.users[':id'].$get({
  159. param: { id: testUser.id }
  160. },
  161. {
  162. headers: {
  163. 'Authorization': `Bearer ${testToken}`
  164. }
  165. });
  166. expect(response.status).toBe(200);
  167. if (response.status === 200) {
  168. const responseData = await response.json();
  169. expect(responseData.id).toBe(testUser.id);
  170. expect(responseData.username).toBe(testUser.username);
  171. expect(responseData.email).toBe(testUser.email);
  172. }
  173. });
  174. it('应该返回404当用户不存在时', async () => {
  175. const response = await client.users[':id'].$get({
  176. param: { id: 999999 }
  177. },
  178. {
  179. headers: {
  180. 'Authorization': `Bearer ${testToken}`
  181. }
  182. });
  183. expect(response.status).toBe(404);
  184. if (response.status === 404) {
  185. const responseData = await response.json();
  186. expect(responseData.message).toContain('资源不存在');
  187. }
  188. });
  189. });
  190. describe('用户更新测试', () => {
  191. it('应该成功更新用户信息', async () => {
  192. const dataSource = IntegrationTestDatabase.getDataSource();
  193. if (!dataSource) throw new Error('Database not initialized');
  194. const testUser = await TestDataFactory.createTestUser(dataSource, {
  195. username: 'testuser_update'
  196. });
  197. const updateData = {
  198. name: 'Updated Name',
  199. email: 'updated@example.com'
  200. };
  201. const response = await client.users[':id'].$put({
  202. param: { id: testUser.id },
  203. json: updateData
  204. },
  205. {
  206. headers: {
  207. 'Authorization': `Bearer ${testToken}`
  208. }
  209. });
  210. expect(response.status).toBe(200);
  211. if (response.status === 200) {
  212. const responseData = await response.json();
  213. expect(responseData.name).toBe(updateData.name);
  214. expect(responseData.email).toBe(updateData.email);
  215. }
  216. // 验证数据库中的更新
  217. const getResponse = await client.users[':id'].$get({
  218. param: { id: testUser.id }
  219. },
  220. {
  221. headers: {
  222. 'Authorization': `Bearer ${testToken}`
  223. }
  224. });
  225. if (getResponse.status === 200) {
  226. expect(getResponse.status).toBe(200);
  227. const getResponseData = await getResponse.json();
  228. expect(getResponseData.name).toBe(updateData.name);
  229. }else{
  230. const getResponseData = await getResponse.json();
  231. process.stderr.write('message:'+ getResponseData.message +"\n");
  232. }
  233. });
  234. it('应该返回404当更新不存在的用户时', async () => {
  235. const updateData = {
  236. name: 'Updated Name',
  237. email: 'updated@example.com'
  238. };
  239. const response = await client.users[':id'].$put({
  240. param: { id: 999999 },
  241. json: updateData
  242. },
  243. {
  244. headers: {
  245. 'Authorization': `Bearer ${testToken}`
  246. }
  247. });
  248. expect(response.status).toBe(404);
  249. if (response.status === 404) {
  250. const responseData = await response.json();
  251. expect(responseData.message).toContain('资源不存在');
  252. }
  253. });
  254. });
  255. describe('用户删除测试', () => {
  256. it('应该成功删除用户', async () => {
  257. const dataSource = IntegrationTestDatabase.getDataSource();
  258. if (!dataSource) throw new Error('Database not initialized');
  259. const testUser = await TestDataFactory.createTestUser(dataSource, {
  260. username: 'testuser_delete'
  261. });
  262. const response = await client.users[':id'].$delete({
  263. param: { id: testUser.id }
  264. },
  265. {
  266. headers: {
  267. 'Authorization': `Bearer ${testToken}`
  268. }
  269. });
  270. IntegrationTestAssertions.expectStatus(response, 204);
  271. // 验证用户已从数据库中删除
  272. await IntegrationTestAssertions.expectUserNotToExist('testuser_delete');
  273. // 验证再次获取用户返回404
  274. const getResponse = await client.users[':id'].$get({
  275. param: { id: testUser.id }
  276. },
  277. {
  278. headers: {
  279. 'Authorization': `Bearer ${testToken}`
  280. }
  281. });
  282. IntegrationTestAssertions.expectStatus(getResponse, 404);
  283. });
  284. it('应该返回404当删除不存在的用户时', async () => {
  285. const response = await client.users[':id'].$delete({
  286. param: { id: 999999 }
  287. },
  288. {
  289. headers: {
  290. 'Authorization': `Bearer ${testToken}`
  291. }
  292. });
  293. IntegrationTestAssertions.expectStatus(response, 404);
  294. if (response.status === 404) {
  295. const responseData = await response.json();
  296. expect(responseData.message).toContain('资源不存在');
  297. }
  298. });
  299. });
  300. describe('用户搜索测试', () => {
  301. it('应该能够按用户名搜索用户', async () => {
  302. const dataSource = IntegrationTestDatabase.getDataSource();
  303. if (!dataSource) throw new Error('Database not initialized');
  304. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1', email: 'search1@example.com' });
  305. await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2', email: 'search2@example.com' });
  306. await TestDataFactory.createTestUser(dataSource, { username: 'other_user', email: 'other@example.com' });
  307. const response = await client.users.$get({
  308. query: { keyword: 'search_user' }
  309. },
  310. {
  311. headers: {
  312. 'Authorization': `Bearer ${testToken}`
  313. }
  314. });
  315. IntegrationTestAssertions.expectStatus(response, 200);
  316. if (response.status === 200) {
  317. const responseData = await response.json();
  318. expect(Array.isArray(responseData.data)).toBe(true);
  319. expect(responseData.data.length).toBe(2);
  320. // 验证搜索结果包含正确的用户
  321. const usernames = responseData.data.map((user: any) => user.username);
  322. expect(usernames).toContain('search_user_1');
  323. expect(usernames).toContain('search_user_2');
  324. expect(usernames).not.toContain('other_user');
  325. }
  326. });
  327. it('应该能够按邮箱搜索用户', async () => {
  328. const dataSource = IntegrationTestDatabase.getDataSource();
  329. if (!dataSource) throw new Error('Database not initialized');
  330. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1', email: 'test.email1@example.com' });
  331. await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2', email: 'test.email2@example.com' });
  332. const response = await client.users.$get({
  333. query: { keyword: 'test.email' }
  334. },
  335. {
  336. headers: {
  337. 'Authorization': `Bearer ${testToken}`
  338. }
  339. });
  340. IntegrationTestAssertions.expectStatus(response, 200);
  341. if (response.status === 200) {
  342. const responseData = await response.json();
  343. expect(responseData.data.length).toBe(2);
  344. const emails = responseData.data.map((user: any) => user.email);
  345. expect(emails).toContain('test.email1@example.com');
  346. expect(emails).toContain('test.email2@example.com');
  347. }
  348. });
  349. });
  350. describe('性能测试', () => {
  351. it('用户列表查询响应时间应小于200ms', async () => {
  352. const dataSource = IntegrationTestDatabase.getDataSource();
  353. if (!dataSource) throw new Error('Database not initialized');
  354. // 创建一些测试数据
  355. for (let i = 0; i < 10; i++) {
  356. await TestDataFactory.createTestUser(dataSource, {
  357. username: `perf_user_${i}`,
  358. email: `perf${i}@example.com`
  359. });
  360. }
  361. const startTime = Date.now();
  362. const response = await client.users.$get({
  363. query: {}
  364. },
  365. {
  366. headers: {
  367. 'Authorization': `Bearer ${testToken}`
  368. }
  369. });
  370. const endTime = Date.now();
  371. const responseTime = endTime - startTime;
  372. IntegrationTestAssertions.expectStatus(response, 200);
  373. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  374. });
  375. });
  376. });