Quellcode durchsuchen

✅ test(users): 完善用户API集成测试

- 移除admin token生成的硬编码,使用ensureAdminExists返回的用户对象
- 恢复并启用用户读取测试套件,包括列表查询、详情查询和404测试
- 恢复并启用用户更新测试套件,包括更新功能和404测试
- 恢复并启用用户删除测试套件,包括删除功能和404测试
- 恢复并启用用户搜索测试套件,包括按用户名和邮箱搜索
- 恢复并启用性能测试套件,验证用户列表查询响应时间

🔧 chore(config): 优化vitest配置

- 移除watchExclude配置,使用默认忽略规则
- 修复配置文件末尾的语法错误,添加逗号分隔符
yourname vor 2 Monaten
Ursprung
Commit
78945886ba
2 geänderte Dateien mit 276 neuen und 288 gelöschten Zeilen
  1. 275 279
      src/server/api/users/__tests__/users.integration.test.ts
  2. 1 9
      vitest.config.ts

+ 275 - 279
src/server/api/users/__tests__/users.integration.test.ts

@@ -38,14 +38,10 @@ describe('用户API集成测试 (使用hono/testing)', () => {
     const authService = new AuthService(userService);
 
     // 确保admin用户存在
-    await authService.ensureAdminExists();
+    const user = await authService.ensureAdminExists();
 
     // 生成admin用户的token
-    testToken = authService.generateToken({
-      id: 1,
-      username: 'admin',
-      roles: []
-    } as any);
+    testToken = authService.generateToken(user);
 
     // 设置默认认证头 - 需要在每个请求中手动添加
   });
@@ -143,277 +139,277 @@ describe('用户API集成测试 (使用hono/testing)', () => {
     });
   });
 
-  // describe('用户读取测试', () => {
-  //   it('应该成功获取用户列表', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     // 创建几个测试用户
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'user1' });
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'user2' });
-
-  //     const response = await client.users.$get({
-  //       query: {}
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     expect(response.status).toBe(200);
-  //     if (response.status === 200) {
-  //       const responseData = await response.json();
-  //       expect(Array.isArray(responseData.data)).toBe(true);
-  //       expect(responseData.data.length).toBeGreaterThanOrEqual(2);
-  //     }
-  //   });
-
-  //   it('应该成功获取单个用户详情', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     const testUser = await TestDataFactory.createTestUser(dataSource, {
-  //       username: 'testuser_detail'
-  //     });
-
-  //     const response = await client.users[':id'].$get({
-  //       param: { id: testUser.id.toString() }
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     expect(response.status).toBe(200);
-  //     if (response.status === 200) {
-  //       const responseData = await response.json();
-  //       expect(responseData.id).toBe(testUser.id);
-  //       expect(responseData.username).toBe(testUser.username);
-  //       expect(responseData.email).toBe(testUser.email);
-  //     }
-  //   });
-
-  //   it('应该返回404当用户不存在时', async () => {
-  //     const response = await client.users[':id'].$get({
-  //       param: { id: '999999' }
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     expect(response.status).toBe(404);
-  //     if (response.status === 404) {
-  //       const responseData = await response.json();
-  //       expect(responseData.message).toContain('用户不存在');
-  //     }
-  //   });
-  // });
-
-  // describe('用户更新测试', () => {
-  //   it('应该成功更新用户信息', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     const testUser = await TestDataFactory.createTestUser(dataSource, {
-  //       username: 'testuser_update'
-  //     });
-
-  //     const updateData = {
-  //       name: 'Updated Name',
-  //       email: 'updated@example.com'
-  //     };
-
-  //     const response = await client.users[':id'].$put({
-  //       param: { id: testUser.id.toString() },
-  //       json: updateData
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     expect(response.status).toBe(200);
-  //     if (response.status === 200) {
-  //       const responseData = await response.json();
-  //       expect(responseData.name).toBe(updateData.name);
-  //       expect(responseData.email).toBe(updateData.email);
-  //     }
-
-  //     // 验证数据库中的更新
-  //     const getResponse = await client.users[':id'].$get({
-  //       param: { id: testUser.id.toString() }
-  //     });
-  //     expect(getResponse.status).toBe(200);
-  //     if (getResponse.status === 200) {
-  //       const getResponseData = await getResponse.json();
-  //       expect(getResponseData.name).toBe(updateData.name);
-  //     }
-  //   });
-
-  //   it('应该返回404当更新不存在的用户时', async () => {
-  //     const updateData = {
-  //       name: 'Updated Name',
-  //       email: 'updated@example.com'
-  //     };
-
-  //     const response = await client.users[':id'].$put({
-  //       param: { id: '999999' },
-  //       json: updateData
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     expect(response.status).toBe(404);
-  //     if (response.status === 404) {
-  //       const responseData = await response.json();
-  //       expect(responseData.message).toContain('用户不存在');
-  //     }
-  //   });
-  // });
-
-  // describe('用户删除测试', () => {
-  //   it('应该成功删除用户', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     const testUser = await TestDataFactory.createTestUser(dataSource, {
-  //       username: 'testuser_delete'
-  //     });
-
-  //     const response = await client.users[':id'].$delete({
-  //       param: { id: testUser.id.toString() }
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     IntegrationTestAssertions.expectStatus(response, 204);
-
-  //     // 验证用户已从数据库中删除
-  //     await IntegrationTestAssertions.expectUserNotToExist('testuser_delete');
-
-  //     // 验证再次获取用户返回404
-  //     const getResponse = await client.users[':id'].$get({
-  //       param: { id: testUser.id.toString() }
-  //     });
-  //     IntegrationTestAssertions.expectStatus(getResponse, 404);
-  //   });
-
-  //   it('应该返回404当删除不存在的用户时', async () => {
-  //     const response = await client.users[':id'].$delete({
-  //       param: { id: '999999' }
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     IntegrationTestAssertions.expectStatus(response, 404);
-  //     if (response.status === 404) {
-  //       const responseData = await response.json();
-  //       expect(responseData.message).toContain('用户不存在');
-  //     }
-  //   });
-  // });
-
-  // describe('用户搜索测试', () => {
-  //   it('应该能够按用户名搜索用户', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1', email: 'search1@example.com' });
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2', email: 'search2@example.com' });
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'other_user', email: 'other@example.com' });
-
-  //     const response = await client.users.$get({
-  //       query: { keyword: 'search_user' }
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     IntegrationTestAssertions.expectStatus(response, 200);
-  //     if (response.status === 200) {
-  //       const responseData = await response.json();
-  //       expect(Array.isArray(responseData.data)).toBe(true);
-  //       expect(responseData.data.length).toBe(2);
-
-  //       // 验证搜索结果包含正确的用户
-  //       const usernames = responseData.data.map((user: any) => user.username);
-  //       expect(usernames).toContain('search_user_1');
-  //       expect(usernames).toContain('search_user_2');
-  //       expect(usernames).not.toContain('other_user');
-  //     }
-  //   });
-
-  //   it('应该能够按邮箱搜索用户', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1', email: 'test.email1@example.com' });
-  //     await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2', email: 'test.email2@example.com' });
-
-  //     const response = await client.users.$get({
-  //       query: { keyword: 'test.email' }
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-
-  //     IntegrationTestAssertions.expectStatus(response, 200);
-  //     if (response.status === 200) {
-  //       const responseData = await response.json();
-  //       expect(responseData.data.length).toBe(2);
-
-  //       const emails = responseData.data.map((user: any) => user.email);
-  //       expect(emails).toContain('test.email1@example.com');
-  //       expect(emails).toContain('test.email2@example.com');
-  //     }
-  //   });
-  // });
-
-  // describe('性能测试', () => {
-  //   it('用户列表查询响应时间应小于200ms', async () => {
-  //     const dataSource = IntegrationTestDatabase.getDataSource();
-  //     if (!dataSource) throw new Error('Database not initialized');
-
-  //     // 创建一些测试数据
-  //     for (let i = 0; i < 10; i++) {
-  //       await TestDataFactory.createTestUser(dataSource, {
-  //         username: `perf_user_${i}`,
-  //         email: `perf${i}@example.com`
-  //       });
-  //     }
-
-  //     const startTime = Date.now();
-  //     const response = await client.users.$get({
-  //       query: {}
-  //     },
-  //     {
-  //       headers: {
-  //         'Authorization': `Bearer ${testToken}`
-  //       }
-  //     });
-  //     const endTime = Date.now();
-  //     const responseTime = endTime - startTime;
-
-  //     IntegrationTestAssertions.expectStatus(response, 200);
-  //     expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
-  //   });
-  // });
+  describe('用户读取测试', () => {
+    it('应该成功获取用户列表', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      // 创建几个测试用户
+      await TestDataFactory.createTestUser(dataSource, { username: 'user1' });
+      await TestDataFactory.createTestUser(dataSource, { username: 'user2' });
+
+      const response = await client.users.$get({
+        query: {}
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      expect(response.status).toBe(200);
+      if (response.status === 200) {
+        const responseData = await response.json();
+        expect(Array.isArray(responseData.data)).toBe(true);
+        expect(responseData.data.length).toBeGreaterThanOrEqual(2);
+      }
+    });
+
+    it('应该成功获取单个用户详情', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      const testUser = await TestDataFactory.createTestUser(dataSource, {
+        username: 'testuser_detail'
+      });
+
+      const response = await client.users[':id'].$get({
+        param: { id: testUser.id.toString() }
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      expect(response.status).toBe(200);
+      if (response.status === 200) {
+        const responseData = await response.json();
+        expect(responseData.id).toBe(testUser.id);
+        expect(responseData.username).toBe(testUser.username);
+        expect(responseData.email).toBe(testUser.email);
+      }
+    });
+
+    it('应该返回404当用户不存在时', async () => {
+      const response = await client.users[':id'].$get({
+        param: { id: '999999' }
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      expect(response.status).toBe(404);
+      if (response.status === 404) {
+        const responseData = await response.json();
+        expect(responseData.message).toContain('用户不存在');
+      }
+    });
+  });
+
+  describe('用户更新测试', () => {
+    it('应该成功更新用户信息', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      const testUser = await TestDataFactory.createTestUser(dataSource, {
+        username: 'testuser_update'
+      });
+
+      const updateData = {
+        name: 'Updated Name',
+        email: 'updated@example.com'
+      };
+
+      const response = await client.users[':id'].$put({
+        param: { id: testUser.id.toString() },
+        json: updateData
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      expect(response.status).toBe(200);
+      if (response.status === 200) {
+        const responseData = await response.json();
+        expect(responseData.name).toBe(updateData.name);
+        expect(responseData.email).toBe(updateData.email);
+      }
+
+      // 验证数据库中的更新
+      const getResponse = await client.users[':id'].$get({
+        param: { id: testUser.id.toString() }
+      });
+      expect(getResponse.status).toBe(200);
+      if (getResponse.status === 200) {
+        const getResponseData = await getResponse.json();
+        expect(getResponseData.name).toBe(updateData.name);
+      }
+    });
+
+    it('应该返回404当更新不存在的用户时', async () => {
+      const updateData = {
+        name: 'Updated Name',
+        email: 'updated@example.com'
+      };
+
+      const response = await client.users[':id'].$put({
+        param: { id: '999999' },
+        json: updateData
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      expect(response.status).toBe(404);
+      if (response.status === 404) {
+        const responseData = await response.json();
+        expect(responseData.message).toContain('用户不存在');
+      }
+    });
+  });
+
+  describe('用户删除测试', () => {
+    it('应该成功删除用户', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      const testUser = await TestDataFactory.createTestUser(dataSource, {
+        username: 'testuser_delete'
+      });
+
+      const response = await client.users[':id'].$delete({
+        param: { id: testUser.id.toString() }
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      IntegrationTestAssertions.expectStatus(response, 204);
+
+      // 验证用户已从数据库中删除
+      await IntegrationTestAssertions.expectUserNotToExist('testuser_delete');
+
+      // 验证再次获取用户返回404
+      const getResponse = await client.users[':id'].$get({
+        param: { id: testUser.id.toString() }
+      });
+      IntegrationTestAssertions.expectStatus(getResponse, 404);
+    });
+
+    it('应该返回404当删除不存在的用户时', async () => {
+      const response = await client.users[':id'].$delete({
+        param: { id: '999999' }
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      IntegrationTestAssertions.expectStatus(response, 404);
+      if (response.status === 404) {
+        const responseData = await response.json();
+        expect(responseData.message).toContain('用户不存在');
+      }
+    });
+  });
+
+  describe('用户搜索测试', () => {
+    it('应该能够按用户名搜索用户', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1', email: 'search1@example.com' });
+      await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2', email: 'search2@example.com' });
+      await TestDataFactory.createTestUser(dataSource, { username: 'other_user', email: 'other@example.com' });
+
+      const response = await client.users.$get({
+        query: { keyword: 'search_user' }
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      IntegrationTestAssertions.expectStatus(response, 200);
+      if (response.status === 200) {
+        const responseData = await response.json();
+        expect(Array.isArray(responseData.data)).toBe(true);
+        expect(responseData.data.length).toBe(2);
+
+        // 验证搜索结果包含正确的用户
+        const usernames = responseData.data.map((user: any) => user.username);
+        expect(usernames).toContain('search_user_1');
+        expect(usernames).toContain('search_user_2');
+        expect(usernames).not.toContain('other_user');
+      }
+    });
+
+    it('应该能够按邮箱搜索用户', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1', email: 'test.email1@example.com' });
+      await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2', email: 'test.email2@example.com' });
+
+      const response = await client.users.$get({
+        query: { keyword: 'test.email' }
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+
+      IntegrationTestAssertions.expectStatus(response, 200);
+      if (response.status === 200) {
+        const responseData = await response.json();
+        expect(responseData.data.length).toBe(2);
+
+        const emails = responseData.data.map((user: any) => user.email);
+        expect(emails).toContain('test.email1@example.com');
+        expect(emails).toContain('test.email2@example.com');
+      }
+    });
+  });
+
+  describe('性能测试', () => {
+    it('用户列表查询响应时间应小于200ms', async () => {
+      const dataSource = IntegrationTestDatabase.getDataSource();
+      if (!dataSource) throw new Error('Database not initialized');
+
+      // 创建一些测试数据
+      for (let i = 0; i < 10; i++) {
+        await TestDataFactory.createTestUser(dataSource, {
+          username: `perf_user_${i}`,
+          email: `perf${i}@example.com`
+        });
+      }
+
+      const startTime = Date.now();
+      const response = await client.users.$get({
+        query: {}
+      },
+      {
+        headers: {
+          'Authorization': `Bearer ${testToken}`
+        }
+      });
+      const endTime = Date.now();
+      const responseTime = endTime - startTime;
+
+      IntegrationTestAssertions.expectStatus(response, 200);
+      expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
+    });
+  });
 });

+ 1 - 9
vitest.config.ts

@@ -52,14 +52,6 @@ export default defineConfig({
     // 测试超时
     testTimeout: 10000,
 
-    // 监听模式忽略
-    watchExclude: [
-      '**/node_modules/**',
-      '**/dist/**',
-      '**/build/**',
-      '**/coverage/**'
-    ],
-
     // 设置文件
     setupFiles: ['./src/test/setup.ts'],
 
@@ -70,6 +62,6 @@ export default defineConfig({
       '@/server': resolve(__dirname, './src/server'),
       '@/share': resolve(__dirname, './src/share'),
       '@/test': resolve(__dirname, './test')
-    }
+    },
   }
 })