Pytest Plugin Reference
简介
Playwright提供了一个Pytest插件用于编写端到端测试。要开始使用它,请参考入门指南。
使用方法
要运行您的测试,请使用 Pytest CLI。
pytest --browser webkit --headed
如果您想自动添加CLI参数而无需手动指定,可以使用pytest.ini文件:
# content of pytest.ini
[pytest]
# Run firefox with UI
addopts = --headed --browser firefox
CLI参数
请注意,CLI参数仅适用于默认的browser
、context
和page
夹具。如果您通过API调用(如browser.new_context())创建浏览器、上下文或页面,则不会应用CLI参数。
--headed
: 以有界面模式运行测试(默认:无界面)。--browser
: 在不同的浏览器中运行测试,可选chromium
、firefox
或webkit
。可以多次指定该参数(默认值:chromium
)。--browser-channel
要使用的浏览器渠道。--slowmo
通过指定的毫秒数减慢Playwright操作速度。有助于观察操作过程(默认值:0)。--device
Device 要模拟的设备。--output
测试生成产物的输出目录(默认:test-results
)。--tracing
是否记录每个测试的trace跟踪。on
、off
或retain-on-failure
(默认值:off
)。--video
是否为每个测试录制视频。可选值为on
、off
或retain-on-failure
(默认值:off
)。--screenshot
是否在每次测试后自动捕获截图。可选值为on
、off
或only-on-failure
(默认值:off
)。--full-page-screenshot
是否在失败时截取完整页面截图。默认情况下仅捕获视口区域。需要启用--screenshot
参数(默认值:off
)。
测试固件
该插件为pytest配置了Playwright专用的fixtures。要使用这些fixtures,请将fixture名称作为测试函数的参数。
def test_my_app_is_working(fixture_name):
pass
# Test using fixture_name
# ...
函数作用域: 这些fixture在测试函数中被请求时创建,并在测试结束时销毁。
context
: 为测试创建新的browser context。page
: 测试用的新browser page。new_context
: 允许为测试创建不同的browser contexts。适用于多用户场景。接受与browser.new_context()相同的参数。
会话作用域: 这些fixture在测试函数中请求时创建,并在所有测试结束时销毁。
playwright
: Playwright 实例。browser_type
: 当前浏览器的BrowserType实例。browser
: 由Playwright启动的Browser实例。browser_name
: 浏览器名称,字符串类型。browser_channel
: 浏览器通道字符串。is_chromium
,is_webkit
,is_firefox
: 分别对应各浏览器类型的布尔值。
自定义fixture选项: 对于browser
和context
fixtures,使用以下fixtures来定义自定义启动选项。
browser_type_launch_args
: 覆盖browser_type.launch()的启动参数。它应该返回一个字典。browser_context_args
: 覆盖browser.new_context()的选项。它应该返回一个字典。
也可以通过使用browser_context_args
标记来覆盖单个测试的上下文选项(browser.new_context()):
import pytest
@pytest.mark.browser_context_args(timezone_id="Europe/Berlin", locale="en-GB")
def test_browser_context_args(page):
assert page.evaluate("window.navigator.userAgent") == "Europe/Berlin"
assert page.evaluate("window.navigator.languages") == ["de-DE"]
并行性:同时运行多个测试
如果您的测试运行在多CPU的机器上,可以通过使用pytest-xdist
同时运行多个测试来加快测试套件的整体执行时间:
# install dependency
pip install pytest-xdist
# use the --numprocesses flag
pytest --numprocesses auto
根据硬件和测试性质的不同,您可以将numprocesses
设置为从2
到机器CPU数量的任意值。如果设置过高,可能会观察到意外行为。
有关pytest
选项的常规信息,请参阅运行测试。
示例
配置自动补全的类型提示
from playwright.sync_api import Page
def test_visit_admin_dashboard(page: Page):
page.goto("/admin")
# ...
如果您在使用带有Pylance的VSCode,可以通过启用python.testing.pytestEnabled
设置来推断这些类型,因此您不需要类型注解。
使用多个上下文
为了模拟多个用户,您可以创建多个BrowserContext
实例。
from playwright.sync_api import Page, BrowserContext
from pytest_playwright.pytest_playwright import CreateContextCallback
def test_foo(page: Page, new_context: CreateContextCallback) -> None:
page.goto("https://example.com")
context = new_context()
page2 = context.new_page()
# page and page2 are in different contexts
按浏览器跳过测试
import pytest
@pytest.mark.skip_browser("firefox")
def test_visit_example(page):
page.goto("https://example.com")
# ...
在特定浏览器上运行
import pytest
@pytest.mark.only_browser("chromium")
def test_visit_example(page):
page.goto("https://example.com")
# ...
使用自定义浏览器渠道运行,如Google Chrome或Microsoft Edge
pytest --browser-channel chrome
def test_example(page):
page.goto("https://example.com")
配置基础URL
使用base-url
参数启动Pytest。pytest-base-url
插件用于此目的,它允许您从配置、CLI参数或作为fixture设置基础URL。
pytest --base-url http://localhost:8080
def test_visit_example(page):
page.goto("/admin")
# -> Will result in http://localhost:8080/admin
忽略HTTPS错误
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"ignore_https_errors": True
}
使用自定义视口尺寸
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"viewport": {
"width": 1920,
"height": 1080,
}
}
设备模拟 / BrowserContext 选项覆盖
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
iphone_11 = playwright.devices['iPhone 11 Pro']
return {
**browser_context_args,
**iphone_11,
}
或者通过命令行界面 --device="iPhone 11 Pro"
与unittest.TestCase
一起使用
查看以下示例,了解如何与unittest.TestCase
一起使用。这有一个限制,即只能指定单个浏览器,在指定多个浏览器时不会生成多浏览器的矩阵。
import pytest
import unittest
from playwright.sync_api import Page
class MyTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def setup(self, page: Page):
self.page = page
def test_foobar(self):
self.page.goto("https://microsoft.com")
self.page.locator("#foobar").click()
assert self.page.evaluate("1 + 1") == 2
调试
与pdb一起使用
在测试代码中使用breakpoint()
语句可以暂停执行并进入pdb REPL交互环境。
def test_bing_is_working(page):
page.goto("https://bing.com")
breakpoint()
# ...
部署到CI
查看CI提供商的指南,将您的测试部署到CI/CD。
异步夹具
如果你想使用异步fixtures,可以使用pytest-playwright-asyncio
插件。请确保使用pytest-asyncio>=0.24.0
版本,并在测试中应用loop_scope=session
参数。
import pytest
from playwright.async_api import Page
@pytest.mark.asyncio(loop_scope="session")
async def test_foo(page: Page):
await page.goto("https://github.com")
# ...