本目录存放 MCP Gateway 的单元测试和集成测试,覆盖本地 stdio 模式、公网 HTTP 模式、Redis session、认证客户端、工具转发和安全工具函数。
tests/
├── test_rate_limiter.py # 简单滑动窗口限流
├── test_gateway_session_store_unit.py # 公网 Gateway Redis session 存储
├── test_request_context.py # 从 header、Bearer、cookie 解析 gateway_session_id
├── test_scoped_auth_client.py # 公网模式授权码换票客户端
├── test_scoped_api_client.py # 公网模式工具转发客户端
├── test_public_gateway_unit.py # PublicGatewayApp 业务路由和 session 校验
├── test_security.py # session ID、hash、常量时间比较
├── test_public_server_integration.py # HTTP 服务集成测试
├── test_run_coverage.py # 覆盖率脚本回归测试
└── test_*.py # 既有本地 Gateway 测试
python -m unittest discover -s tests -p "test_*.py"
python -m unittest tests.test_rate_limiter
python -m unittest tests.test_rate_limiter.TestSimpleRateLimiter
python -m unittest tests.test_rate_limiter.TestSimpleRateLimiter.test_allows_requests_within_limit
python -m unittest discover -s tests -p "test_*.py" -v
单元测试覆盖:
集成测试覆盖:
/health。initialize、tools/list、tools/call。当前测试使用 Python 标准库:
unittestunittest.mockhttp.clientthreading不需要额外安装测试依赖。
test_<module_name>.py。Test<ClassName>。test_<scenario>。HTTP 测试服务可能还未启动完成。可适当增加 setUpClass 中的等待时间:
sleep(1.0)
确认每个测试前重置 mock:
def setUp(self):
self.mock_object.reset_mock()
使用便捷脚本:
# 运行测试并生成所有覆盖率报告
python run_coverage.py
# 运行并自动在浏览器中打开 HTML 报告
python run_coverage.py --open
如需手动生成覆盖率报告,需要额外安装 coverage:
pip install coverage
# 运行测试并收集覆盖率数据
coverage run -m unittest discover -s tests -p "test_*.py"
# 生成控制台报告
coverage report
# 生成 HTML 报告
coverage html
# 生成 XML 报告(用于 CI/CD)
coverage xml
运行覆盖率测试后,会生成三种报告:
htmlcov/index.html
coverage.xml)| 模块 | 覆盖率 |
|---|---|
| 新增模块(Public 模式) | |
constants.py |
100% ✅ |
services/api_client.py |
100% ✅ |
services/gateway_session_store.py |
100% ✅ |
services/scoped_api_client.py |
100% ✅ |
services/scoped_auth_client.py |
100% ✅ |
tools/query_track.py |
100% ✅ |
utils/rate_limiter.py |
100% ✅ |
utils/security.py |
100% ✅ |
services/request_context.py |
97.37% ✅ |
public_gateway.py |
95.31% ✅ |
services/auth_client.py |
94.59% ✅ |
config.py |
93.18% ✅ |
| 现有模块 | |
public_server.py |
83.47% |
app.py |
74.58% |
tools/query_order.py |
80.95% |
mcp_protocol.py |
80.28% |
tools/bind_auth_code.py |
75.00% |
services/token_store.py |
52.40% |
| 总体 | 80.80% ✅ |
覆盖率通过 .coveragerc 配置:
run_coverage.py# pragma: no cover 注释、调试代码、if __name__ == '__main__'对于低覆盖率的文件:
app.py)中 serve-public 和异常分支的集成测试GitHub Actions 工作流示例:
- name: Run tests with coverage
run: |
pip install coverage
coverage run -m unittest discover -s tests -p "test_*.py"
coverage report --fail-under=80
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
coverage html 会在 htmlcov/ 目录生成 HTML 报告。