测试规范
后端测试
框架
- pytest — 测试框架
- pytest-asyncio — 异步测试支持
- SQLite — 测试数据库(非 PostgreSQL)
运行测试
cd apps/backend
# 运行所有测试
pytest
# 跳过数据库测试(纯单元测试)
pytest -m no_db
# 运行指定文件
pytest tests/test_auth.py
# 运行指定测试
pytest tests/test_auth.py::test_login
# 带覆盖率
pytest --cov=app --cov-report=html
测试结构
apps/backend/tests/
├── conftest.py # 测试配置和 fixtures
├── test_auth.py # 认证测试
├── test_projects.py # 项目测试
├── test_training.py # 训练任务测试
└── test_services/ # 服务层测试
编写测试
# tests/test_projects.py
import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_create_project(client: AsyncClient, auth_headers: dict):
response = await client.post(
"/api/projects",
json={"name": "Test Project", "description": "Test"},
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["name"] == "Test Project"
@pytest.mark.no_db
def test_pure_calculation():
"""纯单元测试,不需要数据库"""
assert 1 + 1 == 2
pytest 配置
# pytest.ini
[pytest]
asyncio_mode = "auto"
markers =
no_db: marks tests as not requiring database
前端测试
框架
- Vitest — 测试框架
- jsdom — DOM 环境
- @testing-library/react — React 组件测试
运行测试
cd apps/frontend
# 运行所有测试
npm test
# 监听模式
npm run test:watch
# 带覆盖率
npm test -- --coverage
编写测试
// src/components/__tests__/Button.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from '../Button';
describe('Button', () => {
it('renders correctly', () => {
render(<Button>Click me</Button>);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
it('calls onClick when clicked', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Click</Button>);
fireEvent.click(screen.getByText('Click'));
expect(handleClick).toHaveBeenCalledOnce();
});
});
E2E 测试(Admin)
管理后台使用 Playwright 进行 E2E 测试:
cd apps/admin
# 运行 E2E 测试
npm run test:e2e
# 带 UI
npm run test:e2e:ui
CI 集成
测试在 CI 流水线中自动运行:
# .github/workflows/ci.yml
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install -r requirements.txt
- run: pytest
test-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm -w frontend test