pytest代理--MCP驱动的测试编写代理
一个AI代理 自动编写、运行和修复pytest测试 对于你的Python项目。建立在 模型上下文协议(MCP)
给它一个Python源代码目录,它将:
- 发现 您的源文件
- 阅读 理解其行为的代码
- 生成 全面的pytest测试(正常情况、边缘情况、错误处理)
- 执行 通过pytest进行测试
- 分析故障 并迭代地修复测试,直到它们通过
______________________________________________________________________
项目结构
pytest-agent/
├── src/
│ ├── mcp_server.py # MCP server — exposes test-writing tools
│ └── agent.py # Agent client — drives Claude in an agentic loop
├── example_project/
│ └── src/
│ └── calculator.py # Example project to test against
├── tests/ # Generated tests go here
└── pyproject.toml______________________________________________________________________
⚡ 快速开始
先决条件
- Python 3.11+
- 一 无烟煤API键 (在这里买一个)
1.安装依赖项
cd pytest-agent
pip install -e .或使用 紫外线:
cd pytest-agent
uv sync2.设置API密钥
创建一个 .env 文件在 pytest-agent/ 目录:
echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" > pytest-agent/.env3.运行代理
cd pytest-agent
python -m src.agent您将进入一个交互式聊天会话:
Starting MCP server and connecting...
Connected. Type your request (or 'quit' to exit).
You: Write tests for the example_project/src/calculator.py module
Agent is working...代理将自动发现源代码、编写测试、运行测试并修复任何故障——所有这些都在一个请求中完成。
______________________________________________________________________
MCP服务器工具
MCP服务器(src/mcp_server.py)公开了代理(或任何MCP客户端)可以调用的五个工具:
| 工具 | 说明 |
|---|---|
list_files | 递归列出所有 .py 目录中的文件 |
read_file | 读取文件内容 |
write_test_file | 将测试文件写入磁盘,根据需要创建目录 |
run_tests | 在路径上运行pytest,并返回通过/失败/错误计数 run_id |
get_test_results | 检索的详细结果(每个测试状态、故障追溯) run_id |
独立运行MCP服务器
您可以独立运行MCP服务器,并将其连接到任何兼容MCP的客户端:
cd pytest-agent
uv run python src/mcp_server.py服务器通过以下方式进行通信 标准 运输。
使用其他MCP客户端
将此添加到您的MCP客户端配置中(例如Claude Desktop、Cursor、VS Code)。
使用项目的Python环境进行配置
{
"mcpServers": {
"pytest-agent": {
"command": "/absolute/path/to/your/venv/bin/python",
"args": [
"/absolute/path/to/pytest-agent/src/mcp_server.py"
]
}
}
}______________________________________________________________________
使用示例
交互代理运行后,尝试以下提示:
You: Write tests for example_project/src/calculator.pyYou: Generate tests for all Python files in /path/to/my/project/srcYou: Read the file at example_project/src/calculator.py and write edge case tests for the divide method______________________________________________________________________
