Playwright与PyTest的结合为Web自动化测试注入了强大动能。通过Playwright的现代化跨浏览器自动化功能,又能借助PyTest成熟测试框架的结构化、可扩展性来高效管理和组织测试用例。我会带你了解如何将这两者结合使用。
为了让你快速上手,我先用一个流程图来概括Playwright与PyTest结合使用的核心步骤和关键配置:
下面我们来详细看看各个环节。
首先,你需要安装pytest
和pytest-playwright
插件,并安装Playwright所需的浏览器驱动。
# 1. 安装pytest和pytest-playwright插件
pip install pytest pytest-playwright
# 2. 安装Playwright浏览器驱动(安装较慢,耐心等待)
playwright install
创建一个测试文件(如test_example.py
),PyTest会自动发现以test_
开头的文件或函数。
import pytest
from playwright.sync_api import Page
# 使用page fixture,它由pytest-playwright提供
def test_visit_baidu(page: Page): # 将page fixture作为参数注入
page.goto("https://www.baidu.com")
page.fill('//*[@id="kw"]', "Playwright") # 使用XPath定位搜索框并输入
page.click('#su') # 使用CSS选择器定位并点击“百度一下”按钮
assert "Playwright" in page.title() # 断言页面标题包含特定文本
print(page.title) # 打印当前页面标题
PyTest-P laywright提供了丰富的命令行参数(CLI)来灵活控制测试行为:
参数 (--) | 说明 | 示例 |
---|---|---|
--headed | 在有头模式(显示浏览器UI)下运行测试(默认:无头模式) | pytest --headed |
--browser | 指定浏览器(chromium, firefox, webkit)。可多次指定 | pytest --browser chromium --browser firefox |
--slowmo | 减慢操作速度(毫秒),便于观察 | pytest --slowmo 1000 |
--video | 录制视频(on, off, retain-on-failure) | pytest --video on |
--screenshot | 截屏(on, off, only-on-failure) | pytest --screenshot on |
--tracing | 记录追踪信息(on, off, retain-on-failure),用于调试 | pytest --tracing on |
--numprocesses | 使用pytest-xdist进行并行测试 | pytest --numprocesses auto |
你可以通过pytest.ini
文件预设这些参数,避免每次手动输入:
# pytest.ini
[pytest]
addopts = --headed --browser chromium --slowmo 100 --video on --screenshot on
Fixtures是PyTest的核心功能,用于设置和清理测试环境。pytest-playwright
提供了开箱即用的fixtures。
1. 使用内置Fixtures最常用的是page
fixture,它为你提供了一个全新的浏览器页面。
def test_my_app(page: Page):
page.goto("https://example.com")
# ... 你的测试逻辑
2. Fixture的作用域 (Scope)Fixtures可以有不同的作用域,控制其创建和销毁的频率。
@pytest.fixture(scope='module') # 该fixture在整个模块中只执行一次
def browser():
with sync_playwright() as p:
browser = p.chromium.launch()
yield browser # 提供浏览器实例给测试用例
browser.close() # 所有测试完成后关闭浏览器
def test_example_1(browser): # 在不同的测试中复用同一个浏览器实例
page = browser.new_page()
# ...
3. 覆盖Fixtures的默认选项你可以自定义浏览器或上下文的启动参数。
# conftest.py
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {**browser_context_args, "ignore_https_errors": True} # 忽略HTTPS错误
# 或在测试用例中直接标记以覆盖特定上下文的选项
@pytest.mark.browser_context_args(timezone_id="Europe/Berlin", locale="de-DE")
def test_with_custom_timezone(page):
# 这个测试将在欧洲/柏林时区运行
1. 并行测试:使用pytest-xdist插件可以显著缩短大型测试集的运行时间。
pip install pytest-xdist
pytest --numprocesses auto # 根据CPU核心数自动创建worker进程
2. 跳过测试:可以使用PyTest的skip标记根据条件跳过测试。
import pytest
@pytest.mark.skip("skip this test for now") # 无条件跳过
def test_skip_example():
pass
@pytest.mark.skip_browser("firefox") # 自定义标记(需实现),跳过特定浏览器
def test_skip_firefox(page):
pass
3. 录制生成代码:Playwright的Codegen功能可以录制你的操作并生成PyTest代码。
playwright codegen --target python-pytest -o test_recording.py https://baidu.com
4. 页面对象模式 (Page Object Model):对于复杂项目,强烈建议使用页面对象模式来分离页面元素定位和操作逻辑,提高代码的可维护性和可读性。
# 示例:一个简单的页面对象
class BaiduPage:
def __init__(self, page: Page):
self.page = page
self.search_input = page.locator("#kw")
self.search_button = page.locator("#su")
def search(self, keyword):
self.search_input.fill(keyword)
self.search_button.click() # 在测试中使用
def test_using_pom(page: Page):
baidu_page = BaiduPage(page)
baidu_page.search("Playwright") # ... 断言
5. 移动端模拟与多浏览器测试:Playwright可以模拟移动设备,并利用PyTest的参数化功能进行多浏览器测试。
import pytest
from playwright.sync_api import sync_playwright
# 多浏览器参数化测试
@pytest.mark.parametrize("browser_type", ["chromium", "firefox", "webkit"])
def test_cross_browser(browser_type):
with sync_playwright() as p:
browser = getattr(p, browser_type).launch()
# ... 测试逻辑
browser.close()
# 移动端模拟
def test_mobile_emulation(playwright):# 使用playwright fixture
iphone_12 = playwright.devices['iPhone 12 Pro']
browser = playwright.webkit.launch()
context = browser.new_context(**iphone_12)
page = context.new_page()
page.goto("https://m.example.com")
# ... 移动端测试逻辑
browser.close()
page
)。async/await
),如需使用异步,请确保使用async def
定义测试函数,并使用from playwright.async_api import Page
。locator
),如page.locator('css=button').click()
,并配合page.wait_for_selector()
等等待方法避免竞态条件。-v
或-s
参数(如pytest -v -s
)可以获取更详细的输出和打印语句。Playwright与PyTest的结合,为你提供了一个功能全面、易于编写且易于维护的现代Web自动化测试方案。从简单的脚本到复杂的企业级测试套件,这个组合都能应对自如。
希望这份指南能帮助你快速上手。实践出真知,多写多试,你就会越来越熟练。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。