users.integration.test.ts 13 KB

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