pytest-selenium的作用和常用操作-来自ai(qwen3-235b-a22b)-个人留存
pytest-selenium
是一个专为 Web 应用自动化测试 设计的 pytest
插件,它简化了 Selenium
与 pytest
的集成,提供了浏览器驱动管理、自动截图、参数化测试等核心功能 。以下是其作用及具体用法详解:
🔧 作用与核心功能
1. 浏览器驱动管理
- 自动管理浏览器驱动(如 ChromeDriver、GeckoDriver),支持多种浏览器(Chrome、Firefox、Edge 等)。
- 通过命令行参数指定浏览器类型,无需手动初始化驱动 。
2. 自动截图与失败处理
- 测试失败时自动生成截图,便于定位问题。
- 支持自定义截图路径和命名规则 。
3. 参数化测试
- 支持多浏览器并行测试(如同时测试 Chrome 和 Firefox)。
- 结合
pytest
的参数化功能,覆盖多种测试场景 。
4. 集成测试报告
- 可与
pytest-html
插件结合,生成带截图的 HTML 报告 。
📦 安装与依赖
bash
# 安装 pytest-selenium
pip install pytest-selenium
# 安装 pytest 和 selenium(必须单独安装)
pip install pytest selenium
# 下载浏览器驱动(如 ChromeDriver)
依赖说明:
- 必须单独安装
pytest
和selenium
,插件本身不包含这些依赖 。 - 需下载对应浏览器的驱动(如 ChromeDriver)并配置环境变量 。
🧪 常用用法与代码示例
1. 基础用法:启动浏览器并执行测试
python
# test_example.py
def test_title(browser): # browser 是 pytest-selenium 提供的 fixture
browser.get("https://example.com")
assert "Example Domain" in browser.title
运行命令:
bash
# 指定浏览器类型(Chrome)
pytest test_example.py --driver Chrome
- 说明 :
browser
是pytest-selenium
内置的 fixture,自动管理浏览器生命周期。--driver
参数指定浏览器类型(如Chrome
,Firefox
)。
2. 参数化测试:多浏览器并行执行
python
# test_multi_browser.py
import pytest
@pytest.mark.parametrize("browser", ["Chrome", "Firefox"], indirect=True)
def test_multi_browser(browser):
browser.get("https://example.com")
assert "Example Domain" in browser.title
运行命令:
bash
pytest test_multi_browser.py --driver-list Chrome Firefox
- 说明 :
- 使用
@pytest.mark.parametrize
实现多浏览器并行测试。 --driver-list
参数指定多个浏览器类型 。
- 使用
3. 失败自动截图
python
# test_fail_screenshot.py
def test_fail(browser):
browser.get("https://example.com")
assert "Not Exist" in browser.title # 故意失败
运行命令:
bash
pytest test_fail_screenshot.py --driver Chrome --screenshot-on-fail
- 说明 :
--screenshot-on-fail
启用失败截图功能。- 截图默认保存在
test-results/screenshots/
目录下 。
4. 自定义截图路径
bash
# 自定义截图目录
pytest test_fail_screenshot.py --driver Chrome --screenshot-dir ./my_screenshots
- 说明 :
--screenshot-dir
指定截图保存路径 。
5. 结合 pytest-html 生成报告
bash
# 安装 pytest-html
pip install pytest-html
# 生成 HTML 报告
pytest test_example.py --driver Chrome --html=report.html --self-contained-html
- 说明 :
--html
生成 HTML 测试报告。--self-contained-html
将截图嵌入报告中 。
🚀 高级用法
1. 并行执行测试
bash
# 安装 pytest-xdist
pip install pytest-xdist
# 并行执行测试(4 个浏览器实例)
pytest test_example.py --driver Chrome -n 4
- 说明 :
-n
参数指定并行进程数,提升测试效率 。
2. 远程执行(Grid)
bash
# 指定 Selenium Grid 地址
pytest test_example.py --driver Remote --capability browserName chrome
- 说明 :
--driver Remote
启用远程执行模式。--capability
设置远程节点的浏览器类型 。
📌 注意事项
- 浏览器驱动版本:确保驱动版本与浏览器版本匹配,否则可能引发兼容性问题 。
- 清理资源 :测试结束后调用
browser.quit()
释放资源。 - 环境隔离:避免多个测试用例共享浏览器会话导致状态污染 。
✅ 总结
pytest-selenium
通过 内置 fixture 和命令行参数 简化了 Web 自动化测试流程,支持多浏览器、失败截图、参数化测试等核心功能 。结合 pytest-html
和 pytest-xdist
插件,可进一步提升测试效率和报告可视化能力。