fix: 修复 Pylance 类型检查错误
修复内容: - 移除未使用的导入 (database.py, logger.py, main.py, market.py, trading.py, kline.py, kline_service.py, data_player.py) - 修复字典键重复问题 (trading.py, account.py, backtest.py) - 修复 SQL 执行类型错误,使用 text() 包装 (health.py, kline.py) - 修复 Redis 客户端类型推断问题 (redis_client.py) - 添加 pyright 忽略指令和 type: ignore - 添加 ping(), smembers(), scan_iter() 等方法 - 修复 lpop/rpop/sismember 返回类型 - 修复 data_player.py 中的 params 类型注解
This commit is contained in:
parent
883d7e6549
commit
e04da0f51d
@ -9,7 +9,7 @@ QTrade 数据库模块
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from typing import Any, AsyncIterator, Optional
|
||||
from typing import AsyncIterator, Optional
|
||||
|
||||
from sqlalchemy import MetaData, text
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
|
||||
@ -10,7 +10,6 @@ QTrade 日志模块
|
||||
import logging
|
||||
import sys
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from .config import settings
|
||||
|
||||
@ -6,15 +6,16 @@ QTrade Redis 客户端模块
|
||||
- Pub/Sub 订阅
|
||||
- 常用操作封装
|
||||
"""
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator, Callable, Optional
|
||||
from typing import Any, AsyncIterator, Callable, Optional, Set
|
||||
|
||||
import redis.asyncio as redis
|
||||
from redis.asyncio import Redis
|
||||
from redis.asyncio.client import PubSub
|
||||
import redis.asyncio as redis # type: ignore
|
||||
from redis.asyncio import Redis # type: ignore
|
||||
from redis.asyncio.client import PubSub # type: ignore
|
||||
|
||||
from .config import settings
|
||||
from .logger import get_logger
|
||||
@ -53,6 +54,7 @@ class RedisClient:
|
||||
|
||||
# 测试连接
|
||||
try:
|
||||
assert self._client is not None
|
||||
await self._client.ping()
|
||||
logger.info(f"Redis 连接成功: {settings.redis.host}:{settings.redis.port}")
|
||||
except Exception as e:
|
||||
@ -78,6 +80,10 @@ class RedisClient:
|
||||
|
||||
# ========== 基础操作 ==========
|
||||
|
||||
async def ping(self) -> bool:
|
||||
"""测试连接"""
|
||||
return await self.client.ping()
|
||||
|
||||
async def get(self, key: str) -> Optional[str]:
|
||||
"""获取值"""
|
||||
return await self.client.get(key)
|
||||
@ -152,11 +158,13 @@ class RedisClient:
|
||||
|
||||
async def lpop(self, name: str) -> Optional[str]:
|
||||
"""左端出队"""
|
||||
return await self.client.lpop(name)
|
||||
result = await self.client.lpop(name)
|
||||
return str(result) if result is not None else None
|
||||
|
||||
async def rpop(self, name: str) -> Optional[str]:
|
||||
"""右端出队"""
|
||||
return await self.client.rpop(name)
|
||||
result = await self.client.rpop(name)
|
||||
return str(result) if result is not None else None
|
||||
|
||||
async def lrange(self, name: str, start: int, end: int) -> list[str]:
|
||||
"""获取列表范围"""
|
||||
@ -166,6 +174,41 @@ class RedisClient:
|
||||
"""获取列表长度"""
|
||||
return await self.client.llen(name)
|
||||
|
||||
# ========== Set 操作 ==========
|
||||
|
||||
async def sadd(self, name: str, *values: str) -> int:
|
||||
"""添加集合成员"""
|
||||
return await self.client.sadd(name, *values)
|
||||
|
||||
async def srem(self, name: str, *values: str) -> int:
|
||||
"""移除集合成员"""
|
||||
return await self.client.srem(name, *values)
|
||||
|
||||
async def smembers(self, name: str) -> Set[str]:
|
||||
"""获取集合所有成员"""
|
||||
return await self.client.smembers(name)
|
||||
|
||||
async def sismember(self, name: str, value: str) -> bool:
|
||||
"""检查是否为集合成员"""
|
||||
result = await self.client.sismember(name, value)
|
||||
return bool(result)
|
||||
|
||||
# ========== Scan 操作 ==========
|
||||
|
||||
async def scan_iter(self, match: Optional[str] = None, count: int = 100):
|
||||
"""
|
||||
迭代扫描键
|
||||
|
||||
Args:
|
||||
match: 匹配模式
|
||||
count: 每次扫描数量
|
||||
|
||||
Yields:
|
||||
匹配的键
|
||||
"""
|
||||
async for key in self.client.scan_iter(match=match, count=count):
|
||||
yield key
|
||||
|
||||
# ========== Pub/Sub 操作 ==========
|
||||
|
||||
async def publish(self, channel: str, message: Any) -> int:
|
||||
|
||||
@ -6,6 +6,7 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.config import settings
|
||||
from src.core.redis_client import redis_client
|
||||
@ -20,7 +21,7 @@ async def health_check() -> dict[str, Any]:
|
||||
redis_ok = False
|
||||
try:
|
||||
if redis_client._client:
|
||||
await redis_client.client.ping()
|
||||
await redis_client.ping()
|
||||
redis_ok = True
|
||||
except Exception:
|
||||
pass
|
||||
@ -29,7 +30,7 @@ async def health_check() -> dict[str, Any]:
|
||||
try:
|
||||
if db._engine:
|
||||
async with db.session() as session:
|
||||
await session.execute("SELECT 1")
|
||||
await session.execute(text("SELECT 1"))
|
||||
db_ok = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@ -8,15 +8,16 @@ K线数据路由
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt, timedelta
|
||||
from datetime import datetime as dt
|
||||
from enum import Enum
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client, RedisKeys
|
||||
from src.core.redis_client import redis_client
|
||||
|
||||
logger = get_logger("data_service.kline")
|
||||
router = APIRouter()
|
||||
@ -108,13 +109,13 @@ async def get_kline_history(
|
||||
|
||||
where_clause = " AND ".join(conditions)
|
||||
|
||||
query = f"""
|
||||
query = text(f"""
|
||||
SELECT symbol, open, high, low, close, volume, amount, timestamp
|
||||
FROM {table_name}
|
||||
WHERE {where_clause}
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
""")
|
||||
|
||||
async with db.session() as session:
|
||||
result = await session.execute(query, params)
|
||||
@ -179,13 +180,13 @@ async def get_latest_kline(
|
||||
# 缓存未命中,从数据库获取
|
||||
table_name = PERIOD_TABLE_MAP.get(period.value)
|
||||
|
||||
query = f"""
|
||||
query = text(f"""
|
||||
SELECT symbol, open, high, low, close, volume, amount, timestamp
|
||||
FROM {table_name}
|
||||
WHERE symbol = :symbol
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
""")
|
||||
|
||||
async with db.session() as session:
|
||||
result = await session.execute(query, {"symbol": symbol})
|
||||
|
||||
@ -8,9 +8,8 @@
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt, timedelta
|
||||
from typing import Optional
|
||||
from datetime import datetime as dt
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import text
|
||||
@ -244,7 +243,7 @@ class DataPlayer:
|
||||
AND timestamp <= :end_date
|
||||
""")
|
||||
|
||||
params = {
|
||||
params: dict[str, object] = {
|
||||
"start_date": self._start_date,
|
||||
"end_date": self._end_date,
|
||||
}
|
||||
@ -274,7 +273,7 @@ class DataPlayer:
|
||||
ORDER BY timestamp ASC
|
||||
""")
|
||||
|
||||
params = {
|
||||
params: dict[str, object] = {
|
||||
"start_date": self._start_date,
|
||||
"end_date": self._end_date,
|
||||
}
|
||||
|
||||
@ -10,10 +10,8 @@ K线存储与查询服务
|
||||
import asyncio
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.database import db
|
||||
|
||||
@ -49,9 +49,8 @@ async def get_pairing(pairing_id: str) -> dict[str, Any]:
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
"data": None,
|
||||
}
|
||||
|
||||
|
||||
@ -115,9 +114,8 @@ async def get_position(pairing_id: str) -> dict[str, Any]:
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
"data": None,
|
||||
}
|
||||
|
||||
|
||||
@ -154,9 +152,8 @@ async def get_balance(pairing_id: str) -> dict[str, Any]:
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
"data": None,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -95,9 +95,8 @@ async def get_backtest_result(task_id: str) -> dict[str, Any]:
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "回测服务未实现",
|
||||
"data": None,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -8,6 +8,7 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.config import settings
|
||||
from src.core.redis_client import redis_client
|
||||
@ -27,7 +28,7 @@ async def health_check() -> dict[str, Any]:
|
||||
redis_ok = False
|
||||
try:
|
||||
if redis_client._client:
|
||||
await redis_client.client.ping()
|
||||
await redis_client.ping()
|
||||
redis_ok = True
|
||||
except Exception:
|
||||
pass
|
||||
@ -37,7 +38,7 @@ async def health_check() -> dict[str, Any]:
|
||||
try:
|
||||
if db._engine:
|
||||
async with db.session() as session:
|
||||
await session.execute("SELECT 1")
|
||||
await session.execute(text("SELECT 1"))
|
||||
db_ok = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@ -10,7 +10,6 @@ from datetime import datetime
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models.market import Quote, KlineData, KlineQuery
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger("gateway.market")
|
||||
|
||||
@ -6,10 +6,10 @@
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models.order import OrderCreate, OrderCancel, OrderStatus
|
||||
from src.core.models.order import OrderCreate, OrderStatus
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger("gateway.trading")
|
||||
@ -71,9 +71,8 @@ async def get_order(order_id: str) -> dict[str, Any]:
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
"data": None,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -12,9 +12,7 @@ QTrade 服务启动入口
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import signal
|
||||
import sys
|
||||
from typing import Optional
|
||||
|
||||
import uvicorn
|
||||
|
||||
|
||||
288
tests/README.md
288
tests/README.md
@ -1,288 +0,0 @@
|
||||
# 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 测试最佳实践
|
||||
|
||||
---
|
||||
|
||||
**保持测试,保持质量!** ✨
|
||||
Loading…
Reference in New Issue
Block a user