本项目采用分层测试架构,包括单元测试和集成测试,确保代码质量和系统稳定性。遵循pytest最佳实践,使用统一的conftest.py配置管理,支持测试类型隔离和环境配置。
tests/unit/):快速执行,无外部依赖,适合CI一级流水线tests/interface/):真实HTTP请求,测试完整业务流程backend/tests/ ├── utils/ # 统一的测试工具库 │ ├── mock_utils.py # Mock工具和装饰器 │ ├── test_data_utils.py # 测试数据生成和验证工具 │ └── database_utils.py # 数据库工具和fixtures │ ├── unit/ # 单元测试 - 快速、无外部依赖 │ ├── test_imports.py # 模块导入测试 │ ├── test_image_service.py # 图片服务测试 │ ├── test_cos_service.py # COS存储服务测试 │ ├── test_svg_elements.py # SVG元素解析测试 │ └── test_*.py # 其他单元测试 │ ├── interface/ # 接口集成测试 │ ├── test_basic.py # 基础接口测试 │ ├── test_images.py # 图片接口测试 │ └── test_*.py # 其他集成测试 │ ├── conftest.py # 全局测试配置和fixtures(唯一) ├── pytest.ini # pytest配置 ├── run_unit_tests.py # 单元测试专用运行脚本 ├── run_integration_tests.py # 集成测试专用运行脚本 ├── run_all_tests.py # 完整测试运行脚本 └── README.md # 本文档
项目采用单一conftest.py模式,位于tests根目录,包含:
根据测试标记自动配置环境:
# 单元测试环境
@pytest.mark.unit → 内存数据库 + Mock COS配置
# 集成测试环境
@pytest.mark.integration → 可配置测试数据库
# 在 tests/unit/ 目录下创建
tests/unit/test_[模块名].py
# 示例
tests/unit/test_image_service.py
tests/unit/test_cos_service.py
"""
[模块名]单元测试
遵循项目测试规范:快速执行,无外部依赖
"""
import pytest
from unittest.mock import MagicMock, patch, AsyncMock
from app.services.[模块名] import [服务类]
@pytest.mark.unit
@pytest.mark.[功能标记]
class Test[服务类]:
"""[服务类]单元测试类"""
def test_[测试方法名](self):
"""测试[功能描述]"""
# 使用mock对象进行测试
mock_session = MagicMock()
# 执行测试
result = await [服务类].[方法名](mock_session, ...)
# 验证结果
assert result is not None
@pytest.mark.unit # 标记为单元测试
@pytest.mark.asyncio # 异步测试标记
@pytest.mark.[service_name] # 服务模块标记
# 运行所有单元测试
python tests/run_unit_tests.py
# 运行特定测试文件
python tests/run_unit_tests.py tests/unit/test_image_service.py
# 生成覆盖率报告
python tests/run_unit_tests.py --cov=app --cov-report=html
# 运行所有单元测试
pytest tests/unit/ -m unit -v
# 运行特定功能模块测试
pytest tests/unit/ -m "unit and image_service"
pytest tests/unit/ -m "unit and cos_service"
# 运行特定测试文件
pytest tests/unit/test_image_service.py -v
# 使用专用运行脚本
python tests/run_integration_tests.py
# 直接使用pytest
pytest tests/interface/ -m integration -v
# 运行特定接口测试
pytest tests/interface/test_images.py -v
# 运行所有测试(单元+集成)
python tests/run_all_tests.py
# 或直接使用pytest
pytest tests/ -v
tests/utils/mock_utils.py 中的工具AsyncMock 处理异步方法TestDataGenerator 生成测试数据TestDataValidator 验证数据结构@pytest.mark.asyncio 标记异步测试# 详细输出
pytest -v --tb=short
# 调试特定测试
pytest tests/unit/test_image_service.py::TestImageService::test_create_image_success -v -s
# 查看测试覆盖率
pytest --cov=app --cov-report=term-missing
本测试框架提供了完整的测试解决方案:
通过遵循这些规范,您可以构建高质量、可维护的测试套件,确保代码质量和系统稳定性。