| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511 |
- import { describe, it, expect, beforeEach } from 'vitest';
- import { testClient } from 'hono/testing';
- import {
- IntegrationTestDatabase,
- setupIntegrationDatabaseHooks,
- TestDataFactory
- } from '~/utils/server/integration-test-db';
- import { IntegrationTestAssertions } from '~/utils/server/integration-test-utils';
- import { adminRoutesRoutesExport } from '@/server/api';
- import { AuthService } from '@/server/modules/auth/auth.service';
- import { UserService } from '@/server/modules/users/user.service';
- import { VehicleType } from '@/server/modules/routes/route.schema';
- // 设置集成测试钩子
- setupIntegrationDatabaseHooks()
- describe('路线管理API集成测试', () => {
- let client: ReturnType<typeof testClient<typeof adminRoutesRoutesExport>>['api']['v1']['admin'];
- let testToken: string;
- beforeEach(async () => {
- // 创建测试客户端
- client = testClient(adminRoutesRoutesExport).api.v1.admin;
- // 创建测试用户并生成token
- const dataSource = await IntegrationTestDatabase.getDataSource();
- const userService = new UserService(dataSource);
- const authService = new AuthService(userService);
- // 确保admin用户存在
- const user = await authService.ensureAdminExists();
- // 生成admin用户的token
- testToken = authService.generateToken(user);
- });
- describe('路线创建测试', () => {
- it('应该成功创建路线', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- // 先创建一个活动
- const testActivity = await TestDataFactory.createTestActivity(dataSource);
- const routeData = {
- name: '测试路线',
- startLocationId: 1,
- endLocationId: 2,
- pickupPoint: '北京西站',
- dropoffPoint: '上海南站',
- departureTime: '2025-10-17T08:00:00.000Z',
- vehicleType: VehicleType.BUS,
- price: 200,
- seatCount: 40,
- availableSeats: 40,
- activityId: testActivity.id
- };
- const response = await client.routes.$post({
- json: routeData,
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- // 断言响应
- expect(response.status).toBe(201);
- if (response.status === 201) {
- const responseData = await response.json();
- expect(responseData).toHaveProperty('id');
- expect(responseData.name).toBe(routeData.name);
- expect(responseData.pickupPoint).toBe(routeData.pickupPoint);
- expect(responseData.dropoffPoint).toBe(routeData.dropoffPoint);
- expect(responseData.vehicleType).toBe(routeData.vehicleType);
- expect(responseData.price).toBe(routeData.price);
- expect(responseData.seatCount).toBe(routeData.seatCount);
- expect(responseData.availableSeats).toBe(routeData.availableSeats);
- expect(responseData.isDisabled).toBe(0); // 默认启用
- // 断言数据库中存在路线
- await IntegrationTestAssertions.expectRouteToExist(responseData.id);
- }
- });
- it('应该拒绝创建无效车型的路线', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- const testActivity = await TestDataFactory.createTestActivity(dataSource);
- const routeData = {
- name: '测试路线',
- startLocationId: 1,
- endLocationId: 2,
- pickupPoint: '北京西站',
- dropoffPoint: '上海南站',
- departureTime: '2025-10-17T08:00:00.000Z',
- vehicleType: 'invalid_vehicle' as any, // 无效车型,应该验证失败
- price: 200,
- seatCount: 40,
- availableSeats: 40,
- activityId: testActivity.id
- };
- const response = await client.routes.$post({
- json: routeData,
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- // 应该返回验证错误
- expect([400, 500]).toContain(response.status);
- });
- it('应该拒绝创建价格为负数的路线', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- const testActivity = await TestDataFactory.createTestActivity(dataSource);
- const routeData = {
- name: '测试路线',
- startLocationId: 1,
- endLocationId: 2,
- pickupPoint: '北京西站',
- dropoffPoint: '上海南站',
- departureTime: '2025-10-17T08:00:00.000Z',
- vehicleType: VehicleType.BUS,
- price: -100, // 负数价格
- seatCount: 40,
- availableSeats: 40,
- activityId: testActivity.id
- };
- const response = await client.routes.$post({
- json: routeData,
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- // 应该返回验证错误
- expect([400, 500]).toContain(response.status);
- });
- });
- describe('路线读取测试', () => {
- it('应该成功获取路线列表', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- // 创建几个测试路线
- await TestDataFactory.createTestRoute(dataSource, { name: '路线1', vehicleType: VehicleType.BUS });
- await TestDataFactory.createTestRoute(dataSource, { name: '路线2', vehicleType: VehicleType.MINIBUS });
- const response = await client.routes.$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 = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- const testRoute = await TestDataFactory.createTestRoute(dataSource, {
- name: '测试路线详情'
- });
- const response = await client.routes[':id'].$get({
- param: { id: testRoute.id }
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- expect(response.status).toBe(200);
- if (response.status === 200) {
- const responseData = await response.json();
- expect(responseData.id).toBe(testRoute.id);
- expect(responseData.name).toBe(testRoute.name);
- expect(responseData.vehicleType).toBe(testRoute.vehicleType);
- }
- });
- it('应该返回404当路线不存在时', async () => {
- const response = await client.routes[':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 = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- const testRoute = await TestDataFactory.createTestRoute(dataSource, {
- name: '测试路线更新'
- });
- const updateData = {
- name: '更新后的路线名称',
- startLocationId: 3,
- price: 300
- };
- const response = await client.routes[':id'].$put({
- param: { id: testRoute.id },
- 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.startLocationId).toBe(updateData.startLocationId);
- expect(parseFloat(responseData.price as unknown as string)).toBe(updateData.price);
- }
- // 验证数据库中的更新
- const getResponse = await client.routes[':id'].$get({
- param: { id: testRoute.id }
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- if (getResponse.status === 200) {
- expect(getResponse.status).toBe(200);
- const getResponseData = await getResponse.json();
- expect(getResponseData.name).toBe(updateData.name);
- }
- });
- it('应该成功启用/禁用路线', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- const testRoute = await TestDataFactory.createTestRoute(dataSource, {
- name: '测试状态切换',
- isDisabled: 0 // 启用状态
- });
- // 禁用路线
- const disableResponse = await client.routes[':id'].$put({
- param: { id: testRoute.id },
- json: { isDisabled: 1 } // 禁用
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- expect(disableResponse.status).toBe(200);
- if (disableResponse.status === 200) {
- const disableData = await disableResponse.json();
- expect(disableData.isDisabled).toBe(1);
- }
- // 重新启用路线
- const enableResponse = await client.routes[':id'].$put({
- param: { id: testRoute.id },
- json: { isDisabled: 0 } // 启用
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- expect(enableResponse.status).toBe(200);
- if (enableResponse.status === 200) {
- const enableData = await enableResponse.json();
- expect(enableData.isDisabled).toBe(0);
- }
- });
- it('应该返回404当更新不存在的路线时', async () => {
- const updateData = {
- name: '更新后的名称'
- };
- const response = await client.routes[':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 = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- const testRoute = await TestDataFactory.createTestRoute(dataSource, {
- name: '测试路线删除'
- });
- const response = await client.routes[':id'].$delete({
- param: { id: testRoute.id }
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- IntegrationTestAssertions.expectStatus(response, 204);
- // 验证路线已从数据库中删除
- await IntegrationTestAssertions.expectRouteNotToExist(testRoute.id);
- // 验证再次获取路线返回404
- const getResponse = await client.routes[':id'].$get({
- param: { id: testRoute.id }
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- IntegrationTestAssertions.expectStatus(getResponse, 404);
- });
- it('应该返回404当删除不存在的路线时', async () => {
- const response = await client.routes[':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 = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- await TestDataFactory.createTestRoute(dataSource, { name: '搜索路线1', startLocationId: 1 });
- await TestDataFactory.createTestRoute(dataSource, { name: '搜索路线2', startLocationId: 2 });
- await TestDataFactory.createTestRoute(dataSource, { name: '其他路线', startLocationId: 3 });
- const response = await client.routes.$get({
- query: { keyword: '搜索路线' }
- },
- {
- 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 names = responseData.data.map((route) => route.name);
- expect(names).toContain('搜索路线1');
- expect(names).toContain('搜索路线2');
- expect(names).not.toContain('其他路线');
- }
- });
- it('应该能够按出发地搜索路线', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- await TestDataFactory.createTestRoute(dataSource, { name: '路线1', startLocationId: 1 });
- await TestDataFactory.createTestRoute(dataSource, { name: '路线2', startLocationId: 1 });
- const response = await client.routes.$get({
- query: { keyword: '北京' }
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- IntegrationTestAssertions.expectStatus(response, 200);
- if (response.status === 200) {
- const responseData = await response.json();
- expect(responseData.data.length).toBe(2);
- const names = responseData.data.map((route) => route.name);
- expect(names).toContain('路线1');
- expect(names).toContain('路线2');
- }
- });
- it('应该能够按车型筛选路线', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- await TestDataFactory.createTestRoute(dataSource, { name: '大巴路线1', vehicleType: VehicleType.BUS });
- await TestDataFactory.createTestRoute(dataSource, { name: '大巴路线2', vehicleType: VehicleType.BUS });
- await TestDataFactory.createTestRoute(dataSource, { name: '中巴路线', vehicleType: VehicleType.MINIBUS });
- const response = await client.routes.$get({
- query: { filters: JSON.stringify({ vehicleType: 'bus' }) }
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- IntegrationTestAssertions.expectStatus(response, 200);
- if (response.status === 200) {
- const responseData = await response.json();
- expect(responseData.data.length).toBe(2);
- const vehicleTypes = responseData.data.map((route) => route.vehicleType);
- expect(vehicleTypes.every((type: string) => type === 'bus')).toBe(true);
- }
- });
- });
- describe('性能测试', () => {
- it('路线列表查询响应时间应小于200ms', async () => {
- const dataSource = await IntegrationTestDatabase.getDataSource();
- if (!dataSource) throw new Error('Database not initialized');
- // 创建一些测试数据
- for (let i = 0; i < 10; i++) {
- await TestDataFactory.createTestRoute(dataSource, {
- name: `性能测试路线_${i}`,
- startLocationId: i + 1,
- endLocationId: i + 2
- });
- }
- const startTime = Date.now();
- const response = await client.routes.$get({
- query: {}
- },
- {
- headers: {
- 'Authorization': `Bearer ${testToken}`
- }
- });
- const endTime = Date.now();
- const responseTime = endTime - startTime;
- IntegrationTestAssertions.expectStatus(response, 200);
- expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
- });
- });
- });
|