# tests 目录 ## 🧪 用途 存放**单元测试与集成测试的代码和用例**。 ## 📋 测试类型 ### 1. 单元测试(Unit Tests) 测试单个函数或类的功能。 **特点**: - 快速执行 - 独立运行 - 测试单一功能 **示例**: ```python def test_data_processor_clean(): """测试数据清洗功能""" processor = KlineDataProcessor() df = create_test_data() result = processor.clean_data(df) assert result is not None assert len(result) > 0 assert result.isnull().sum().sum() == 0 # 无空值 ``` ### 2. 集成测试(Integration Tests) 测试多个模块的协作和完整流程。 **特点**: - 执行较慢 - 需要环境准备 - 测试完整流程 **示例**: ```python def test_socket_communication(): """测试 Socket 完整通信流程""" # 启动服务器 server = SimpleQTradeSocketServer() server.start() # 连接客户端 client = SimpleQTradeSocketClient() client.connect() # 发送消息 client.send({"type": "ping"}) # 接收响应 response = client.receive() assert response['type'] == 'pong' # 清理 client.disconnect() server.stop() ``` ## 🗂️ 目录结构(推荐) ``` tests/ ├── unit/ # 单元测试 │ ├── test_data_processor.py │ ├── test_grid_strategy.py │ └── test_database.py │ ├── integration/ # 集成测试 │ ├── test_socket_server.py │ ├── test_http_api.py │ └── test_strategy_flow.py │ ├── fixtures/ # 测试数据 │ ├── sample_kline.csv │ └── test_config.yaml │ └── conftest.py # pytest 配置 ``` ## 🚀 运行测试 ### 运行所有测试 ```bash pytest tests/ -v ``` ### 运行指定测试文件 ```bash pytest tests/test_simple_socket.py -v ``` ### 运行指定测试函数 ```bash pytest tests/test_simple_socket.py::test_connection -v ``` ### 带覆盖率报告 ```bash pytest tests/ --cov=src --cov-report=html ``` 查看覆盖率报告: 打开 `htmlcov/index.html` ### 只运行失败的测试 ```bash pytest --lf ``` ### 并行运行(需安装 pytest-xdist) ```bash pytest tests/ -n auto ``` ## ✍️ 编写测试 ### 1. 测试文件命名 - ✅ `test_*.py` - 测试文件 - ✅ `*_test.py` - 也可以 - ❌ `test.py` - 太通用,避免 ### 2. 测试函数命名 - ✅ `test_function_name()` - 测试某个功能 - ✅ `test_function_name_with_condition()` - 测试特定条件 - ❌ `my_test()` - 不以 test_ 开头 ### 3. 测试结构(AAA 模式) ```python def test_example(): # Arrange - 准备测试数据 data = {"key": "value"} processor = DataProcessor() # Act - 执行被测试的功能 result = processor.process(data) # Assert - 验证结果 assert result == expected_value ``` ### 4. 使用 fixtures ```python import pytest @pytest.fixture def sample_data(): """准备测试数据""" return {"symbol": "601398.SH", "price": 5.23} def test_with_fixture(sample_data): """使用 fixture 的测试""" assert sample_data['symbol'] == "601398.SH" ``` ## 📝 测试用例设计 ### 正常场景 测试正常输入和预期输出。 ```python def test_calculate_returns_normal(): df = pd.DataFrame({'close': [10, 11, 12]}) result = calculate_returns(df) assert len(result) == 3 ``` ### 边界条件 测试边界值和特殊情况。 ```python def test_calculate_returns_empty(): df = pd.DataFrame() with pytest.raises(ValueError): calculate_returns(df) ``` ### 异常情况 测试错误处理。 ```python def test_connect_with_wrong_port(): client = SocketClient(port=99999) with pytest.raises(ConnectionError): client.connect() ``` ## 🎯 测试覆盖率目标 | 模块 | 目标覆盖率 | | ------------ | ---------- | | 核心业务逻辑 | 90%+ | | 数据处理 | 85%+ | | 网络通信 | 80%+ | | 策略逻辑 | 90%+ | | 工具函数 | 70%+ | ## ⚡ 测试最佳实践 ### ✅ 应该做的 1. **测试要独立** - 不依赖其他测试 2. **测试要快速** - 单元测试毫秒级 3. **测试要明确** - 一个测试一个断言 4. **使用 fixtures** - 复用测试数据 5. **测试要可重复** - 每次结果一致 ### ❌ 不应该做的 1. ❌ 测试依赖外部服务(数据库、API)- 使用 mock 2. ❌ 测试包含随机性 - 固定随机种子 3. ❌ 测试修改全局状态 - 使用 fixtures 隔离 4. ❌ 测试写死路径 - 使用相对路径 5. ❌ 测试没有断言 - 每个测试必须有 assert ## 🛠️ 测试工具 ### pytest ```bash pip install pytest ``` 主要测试框架,功能强大。 ### pytest-cov ```bash pip install pytest-cov ``` 代码覆盖率报告。 ### pytest-mock ```bash pip install pytest-mock ``` Mock 和 Patch 工具。 ### pytest-xdist ```bash pip install pytest-xdist ``` 并行运行测试。 ## 📖 示例 完整示例请查看现有测试文件: - `tests/test_simple_socket.py` - Socket 测试 - `tests/test_socket_only.py` - 基础测试 ## 🐛 调试测试 ### 在失败时进入调试器 ```bash pytest --pdb ``` ### 查看打印输出 ```bash pytest -s ``` ### 只运行标记的测试 ```python @pytest.mark.slow def test_slow_operation(): pass # 运行 pytest -m slow ``` ## 📚 参考资料 - [pytest 官方文档](https://docs.pytest.org/) - [测试驱动开发(TDD)](https://en.wikipedia.org/wiki/Test-driven_development) - Python 测试最佳实践 --- **保持测试,保持质量!** ✨