pytest测试生成代理

一个基于模型上下文协议(MCP)的AI代理,能自动为Python项目编写、运行和修复pytest测试。

  • by PushpakAg
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 PushpakAg/testagent-mcp

使用说明

pytest代理--MCP驱动的测试编写代理

一个AI代理 自动编写、运行和修复pytest测试 对于你的Python项目。建立在 模型上下文协议(MCP)

给它一个Python源代码目录,它将:

  1. 发现 您的源文件
  2. 阅读 理解其行为的代码
  3. 生成 全面的pytest测试(正常情况、边缘情况、错误处理)
  4. 执行 通过pytest进行测试
  5. 分析故障 并迭代地修复测试,直到它们通过

项目结构

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

⚡ 快速开始

先决条件

1.安装依赖项

cd pytest-agent
pip install -e .

或使用 紫外线:

cd pytest-agent
uv sync

2.设置API密钥

创建一个 .env 文件在 pytest-agent/ 目录:

echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" > pytest-agent/.env

3.运行代理

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.py
You: Generate tests for all Python files in /path/to/my/project/src
You: Read the file at example_project/src/calculator.py and write edge case tests for the divide method