AI自动化测试框架

一个基于Python和Selenium的生产级AI自动化测试框架,能够根据自然语言描述生成可维护的测试代码。

  • by solosza
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 solosza/py-selenium-framework-mcp

使用说明

人工智能辅助QA自动化框架

一个生产级Python Selenium框架 人工智能驱动的测试生成用简单的英语描述你想测试什么,人工智能会生成完整、可维护的测试自动化代码。


所得

  • AI根据需求生成测试 -描述用户故事,获取可用的测试代码
  • 生产级架构 -可扩展的4层模式(角色>任务>页面>Web界面)
  • 一致的代码模式 -每个生成的测试都遵循相同的结构
  • 与您的AI工具配合使用 -Claude Code、Cursor、Windsurf或任何与MCP兼容的代理

运作原理

1. You describe: "As a registered user, I want to login and view my account"
2. AI discovers page elements automatically (via Playwright)
3. AI generates: Page Objects, Tasks, Roles, and Tests
4. You run: pytest tests/your_test.py

生成的代码遵循严格的架构模式——没有意大利面条,也没有“每个工程师写得都不一样”的问题。


先决条件

安装前,请确保:

需求 版本 检查命令 下载
Python 3.11+ python --version python.org
Node.js 18+ node --version nodejs.org
Chrome 最新 打开Chrome>帮助>关于 google.com/chrome
Git 任何 git --version git-scm.com
MCP兼容AI - - 克劳德代码、光标或风帆

AI代理选项

该框架需要一个与MCP兼容的AI编码代理:

代理 MCP支持 注意事项
克劳德代码 原生 推荐-最佳MCP集成
光标 通过配置 需要MCP配置
帆板运动 通过配置 需要MCP配置

安装

步骤1:克隆存储库

git clone https://github.com/isagawa-qa/isagawa-qa.git
cd py-selenium-framework-mcp

第二步:创建虚拟环境

Windows(PowerShell):

python -m venv venv
.\venv\Scripts\Activate.ps1

Windows(命令提示符):

python -m venv venv
venv\Scripts\activate.bat

macOS/Linux:

python3 -m venv venv
source venv/bin/activate

步骤3:安装Python依赖项

# Core framework dependencies
pip install -r requirements.txt

# MCP server dependencies
pip install -r mcp_server/requirements.txt

步骤4:验证安装

# Check Selenium is installed
python -c "import selenium; print(f'Selenium {selenium.__version__} installed')"

# Check pytest is installed
pytest --version

# Check MCP dependencies
python -c "import mcp; print('MCP SDK installed')"

MCP服务器设置

该框架使用两个MCP服务器:

  1. qa自动化 -生成测试自动化代码
  2. 剧作家 -通过浏览器自动化发现页面元素

第一步:找到你的Python路径

窗户:

where python
# Example output: C:\Users\YourName\AppData\Local\Programs\Python\Python311\python.exe

macOS/Linux:

which python3
# Example output: /usr/local/bin/python3

步骤2:创建MCP配置

创建或编辑 .mcp.json 在项目根目录中:

Windows配置:

{
  "mcpServers": {
    "qa-automation": {
      "command": "C:/Users/YOUR_USERNAME/AppData/Local/Programs/Python/Python311/python.exe",
      "args": ["D:/path/to/py-selenium-framework-mcp/mcp_server/server.py"],
      "cwd": "D:/path/to/py-selenium-framework-mcp/mcp_server"
    },
    "playwright": {
      "command": "cmd",
      "args": ["/c", "npx", "-y", "@playwright/mcp@latest"]
    }
  }
}

macOS/Linux配置:

{
  "mcpServers": {
    "qa-automation": {
      "command": "/usr/local/bin/python3",
      "args": ["/path/to/py-selenium-framework-mcp/mcp_server/server.py"],
      "cwd": "/path/to/py-selenium-framework-mcp/mcp_server"
    },
    "playwright": {
      "command": "npx",
      "args": ["-y", "@playwright/mcp@latest"]
    }
  }
}

重要提示:

  • 替换 YOUR_USERNAME 使用您的实际Windows用户名
  • 替换 /path/to/ 使用您的实际项目路径
  • 使用 正斜杠 (/)即使在Windows上
  • 使用 绝对路径 可靠性

步骤3:安装Playwright浏览器

Playwright MCP服务器需要安装浏览器:

npx playwright install chromium

步骤4:验证MCP服务器

克劳德代码:

# List configured servers
claude mcp list

# You should see both qa-automation and playwright listed

光标/风帆:

  • 打开设置/首选项
  • 导航到MCP配置
  • 验证两台服务器都已列出并启用

步骤5:测试MCP连接

在你的AI代理中,问:

What MCP tools are available?

您应该看到以下工具:

  • mcp__qa-automation__generate_page_object
  • mcp__qa-automation__generate_task
  • mcp__qa-automation__generate_role
  • mcp__playwright__browser_navigate
  • mcp__playwright__browser_snapshot

快速入门:生成您的第一个测试

选项A:使用工作流命令(推荐)

在Claude Code中,运行:

/qa-workflow

然后提供您的要求:

As a guest user, I want to browse the Women category on automationpractice.pl

AI将:

  1. 导航到网站并发现元素
  2. 生成页面对象、任务、角色和测试
  3. 将文件保存到正确的位置
  4. 运行测试

选项B:手动对话

与您的AI代理开始对话:

I want to create a test for this requirement:

As a registered user, I want to login to automationpractice.pl

URL: http://www.automationpractice.pl/index.php?controller=authentication

Use static credentials from tests/data/test_users.json

运行测试

运行所有测试

pytest tests/ -v

运行特定测试文件

pytest tests/auth/test_login.py -v

使用HTML报告运行

pytest tests/ -v --html=tests/_reports/report.html --self-contained-html

在无头模式下运行(无浏览器窗口)

pytest tests/ -v --headless

查看测试报告

跑步后 --html,打开 tests/_reports/report.html 在您的浏览器中。


架构:4层模式

生成的代码遵循严格的4层架构:

┌─────────────────────────────────────────────────────────────┐
│  TEST                                                        │
│  • Arrange, Act, Assert                                      │
│  • Calls ONE role method                                     │
│  • Asserts via Page Object state methods                     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  ROLE                                                        │
│  • User personas (GuestUser, RegisteredUser)                 │
│  • Orchestrates multiple tasks into workflows                │
│  • Example: login > browse > add to cart > checkout          │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  TASK                                                        │
│  • Single business operations (login, add_to_cart)           │
│  • Calls page object methods                                 │
│  • Domain-focused, not UI-focused                            │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  PAGE OBJECT                                                 │
│  • One class per page/component                              │
│  • Contains all locators                                     │
│  • Atomic methods: click, type, select                       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  WEB INTERFACE                                               │
│  • Selenium wrapper                                          │
│  • Handles waits, logging, screenshots                       │
│  • Single point of browser interaction                       │
└─────────────────────────────────────────────────────────────┘

为什么这很重要

问题 这个框架是如何解决的
UI更改中断测试 定位符在一个地方(页面对象)
测试很难阅读 测试只断言,逻辑在角色/任务中
代码重复 任务在测试中可重用
不同的编码风格 AI生成一致的模式
难以吸纳新团队成员 层次分明,到处都是相同的模式

黄金法则

1. Locators ONLY in Page Objects
2. Tasks/Roles return NOTHING (None)
3. Tests assert via Page Object state-check methods
4. No inheritance - composition only
5. One responsibility per layer

项目结构

py-selenium-framework-mcp/
├── framework/                    # Reusable framework code
│   ├── interfaces/
│   │   └── web_interface.py      # Selenium wrapper
│   ├── pages/                    # Page Objects (UI elements)
│   │   ├── auth/                 # Login, registration pages
│   │   └── catalog/              # Product pages
│   ├── tasks/                    # Business operations
│   │   └── auth/                 # Login, logout tasks
│   ├── roles/                    # User personas
│   │   └── auth/                 # RegisteredUser, GuestUser
│   └── resources/
│       ├── config/               # Environment settings
│       └── utilities/            # Logging, helpers
│
├── tests/                        # Test files
│   ├── conftest.py               # Pytest fixtures
│   ├── data/                     # Test data (JSON)
│   │   └── test_users.json       # User credentials
│   ├── auth/                     # Authentication tests
│   └── catalog/                  # Catalog tests
│
├── mcp_server/                   # AI integration
│   ├── server.py                 # MCP server entry
│   ├── tools/                    # Code generation tools
│   └── requirements.txt          # MCP dependencies
│
└── .mcp.json                     # MCP configuration

配置

环境配置

编辑 framework/resources/config/environment_config.json:

{
  "DEFAULT": {
    "url": "http://www.automationpractice.pl/index.php",
    "browser": "chrome",
    "headless": false,
    "implicit_wait": 10
  }
}

测试用户

编辑 tests/data/test_users.json:

{
  "registered_user": {
    "email": "your-test-email@example.com",
    "password": "YourTestPassword123"
  }
}

测试数据策略

生成需要凭据的测试时,您有三个选项:

策略 描述 何时使用
静态 使用来自的现有帐户 tests/data/test_users.json 仅登录测试
动态 注册新用户,保存以供以后测试 注册流程
自足 在同一测试中注册和使用 独立测试

在提供需求时,告诉AI你想要哪种策略。


工作流命名

为避免覆盖以前测试运行中的文件,请使用唯一的工作流名称:

# First test on ParaBank
workflow_name: "parabank"

# Subsequent tests
workflow_name: "parabank2"
workflow_name: "parabank_login"
workflow_name: "parabank_transfer"

文件生成于:

  • framework/pages/{workflow_name}/
  • framework/tasks/{workflow_name}/
  • framework/roles/{workflow_name}/
  • tests/{workflow_name}/

故障排除

MCP服务器未启动

症状: AI代理找不到MCP工具

解决:

  1. 检查Python路径是否正确:

    # Windows
    where python
    
    # macOS/Linux
    which python3
    
  2. 验证中的路径 .mcp.json 是绝对的,使用正斜杠

  3. 配置更改后重新启动AI代理

  4. 手动测试MCP服务器:

    python mcp_server/server.py
    # Should start without errors
    

剧作家MCP不工作

症状: 元素发现失败,浏览器无法打开

解决:

  1. 安装Playwright浏览器:

    npx playwright install chromium
    
  2. 手动测试剧作家MCP:

    npx -y @playwright/mcp@latest
    
  3. Windows用户:确保使用 cmd /c npx 在 .mcp.json

ChromeDriver版本不匹配

症状: SessionNotCreatedException 错误

解决方案: 该框架使用 webdriver-manager 它会自动下载正确的驱动程序。将Chrome浏览器更新至最新版本。

找不到元素/超时

症状: TimeoutException 试运行期间

解决:

  1. 增加超时时间 framework/resources/config/environment_config.json
  2. 检查目标网站是否可访问
  3. 验证定位器是否与当前页面结构匹配

导入错误

症状: ModuleNotFoundError 运行测试时

解决:

  1. 确保虚拟环境已激活
  2. 重新安装依赖关系:
    pip install -r requirements.txt
    pip install -r mcp_server/requirements.txt
    

对于手动测试人员:您的学习路径

自动化新手?这是如何映射到手动测试的:

手动测试 框架层
“我正在以访客用户身份进行测试” 角色(访客用户)
“我需要浏览产品” 任务(browse_category)
“我单击女性菜单链接” 页面对象(单击方法)
“我验证产品是否显示” 测试(断言)

阅读一个简单的测试

def test_browse_women_category(web_interface, config):
    # Arrange - Set up
    guest = GuestUser(web_interface, config["url"])
    product_list_page = ProductListPage(web_interface)

    # Act - Do the action
    guest.browse_category("Women")

    # Assert - Verify result
    assert product_list_page.has_products(), "Products should be displayed"

这个测试读起来像一个用户故事。


支持


许可证

框架代码(MIT): 免费使用、修改和分发。

看 许可证.md 完整条款。


专为希望AI以正确方式编写测试的QA工程师而设计。