主题: 基于 pytest + Playwright 的 UI 自动化测试框架
技术选型
| 浏览器驱动 | Playwright | 内置浏览器管理,速度快,API 简洁,与 pytest 集成成熟 |
| 设计模式 | POM (Page Object Model) | 页面逻辑与测试分离,维护性强 |
| 配置管理 | pytest.ini + conftest.py | 标准 pytest 生态做法,简洁够用 |
| 报告 | Allure | 可视化报告,支持步骤标记、截图附件 |
项目结构
ui-test-framework/
├── pytest.ini # pytest 配置
├── conftest.py # fixtures:browser 生命周期管理
├── pages/ # Page Object 层
│ ├── __init__.py
│ └── baidu_page.py # 百度首页 + 搜索结果页
├── tests/ # 测试用例层
│ ├── __init__.py
│ └── test_baidu_search.py # 搜索"世界杯赛程"测试
├── utils/ # 工具层
│ ├── __init__.py
│ └── driver.py # Playwright browser 工厂
└── requirements.txt # 依赖
分层职责
- pages/ — 封装百度首页的搜索框、搜索按钮等元素定位和操作方法
- tests/ — 纯测试逻辑,调用 Page 方法,断言结果
- utils/ — Playwright browser 实例的创建与销毁
- conftest.py — 为每个测试函数自动注入 browser 和 page 对象
测试流程
Allure 集成
- 运行: pytest –alluredir=reports/allure-results
- 生成: allure generate reports/allure-results -o reports/allure-report –clean
- 查看: allure open reports/allure-report
- 使用 allure.step() 标记步骤,失败自动截图
依赖
- pytest
- pytest-playwright
- allure-pytest
- playwright