pytest-playwright 是 Playwright 官方提供的 pytest 插件。装上它之后,你不用手动创建浏览器和页面,框架帮你搞定一切。这篇文章整理插件的所有配置项、fixture 和常用参数。
1. 安装
pip install pytest pytest-playwright
不需要额外的配置,安装后 pytest 会自动加载插件。
2. 内置 Fixture
插件提供了几个核心 fixture,测试函数直接声明参数就能用。
2.1 page
最常用的 fixture。每个测试函数拿到一个独立的页面实例,测试结束后自动关闭。
def test_example(page):
page.goto("https://example.com")
assert page.title() == "Example Domain"
- 作用域:function(每个测试函数一个)
- 隔离:每个 page 属于独立的浏览器上下文,cookie/localStorage 互不影响
2.2 browser
获取浏览器实例。当你需要在一个测试里创建多个上下文或多个页面时用这个。
def test_multiple_contexts(browser):
ctx1 = browser.new_context()
page1 = ctx1.new_page()
page1.goto("https://example.com/page1")
ctx2 = browser.new_context()
page2 = ctx2.new_page()
page2.goto("https://example.com/page2")
ctx1.close()
ctx2.close()
- 作用域:session(整个测试会话共享一个浏览器实例)
- 注意:手动创建的上下文和页面需要手动关闭
2.3 browser_context
获取浏览器上下文。当你需要为特定测试定制上下文参数(viewport、locale 等)时用。
def test_mobile_view(browser_context):
page = browser_context.new_page()
page.goto("https://example.com")
2.4 browser_name
当前运行的浏览器名称,返回 "chromium"、"firefox" 或 "webkit"。
def test_browser_specific(page, browser_name):
if browser_name == "webkit":
page.goto("https://example.com/safari-only")
else:
page.goto("https://example.com")
2.5 browser_channel
浏览器发行渠道,如 "chrome"、"msedge"。如果没指定则为 None。
def test_channel(page, browser_channel):
if browser_channel == "msedge":
# Edge 特有逻辑
pass
2.6 browser_type_launch_args
覆盖浏览器启动参数,返回一个字典。在 conftest.py 中定义 browser_type_launch_args fixture 来定制:
@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
return {
**browser_type_launch_args,
"headless": False,
"slow_mo": 500,
"args": ["--disable-gpu"],
}
2.7 browser_context_args
覆盖浏览器上下文参数。这是定制上下文最常用的方式:
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"viewport": {"width": 1920, "height": 1080},
"locale": "zh-CN",
"timezone_id": "Asia/Shanghai",
"ignore_https_errors": True,
"storage_state": "auth.json",
}
2.8 is_chromium / is_firefox / is_webkit
布尔值 fixture,判断当前浏览器类型:
def test_something(page, is_chromium):
if is_chromium:
page.goto("https://chromium-only.example.com")
2.9 playwright
获取 Playwright 实例,可以创建多个浏览器:
def test_cross_browser(playwright):
for browser_type in [playwright.chromium, playwright.firefox, playwright.webkit]:
browser = browser_type.launch()
page = browser.new_page()
page.goto("https://example.com")
browser.close()
3. Fixture 作用域
| Fixture | 默认作用域 | 说明 |
|---|---|---|
playwright |
session | Playwright 实例,整个会话一个 |
browser_type |
session | 浏览器类型 |
browser |
session | 浏览器实例,整个会话一个 |
browser_context |
function | 上下文,每个测试一个 |
page |
function | 页面,每个测试一个 |
可以自定义作用域,比如让上下文在模块级别共享:
@pytest.fixture(scope="module")
def browser_context_args(browser_context_args):
return {**browser_context_args, "storage_state": "auth.json"}
4. 命令行参数
4.1 --browser
pytest --browser chromium
pytest --browser firefox
pytest --browser webkit
pytest --browser channel:chrome
pytest --browser channel:msedge
# 多个浏览器
pytest --browser chromium --browser firefox --browser webkit
4.2 --headed
显示浏览器窗口(有头模式):
pytest --headed
4.3 --slowmo
每步操作间隔的毫秒数:
pytest --slowmo 1000
4.4 --device
模拟移动设备:
pytest --device="iPhone 13"
pytest --device="Pixel 5"
pytest --device="iPad Pro 11"
4.5 --output
产物输出目录,默认是 test-results:
pytest --output=my-results
4.6 --video
录屏策略:
pytest --video on # 总是录制
pytest --video off # 不录制(默认)
pytest --video retain-on-failure # 仅失败时保留
4.7 --screenshot
截图策略:
pytest --screenshot on # 总是截图
pytest --screenshot off # 不截图(默认)
pytest --screenshot only-on-failure # 仅失败时截图
4.8 --tracing
追踪策略:
pytest --tracing on # 总是生成
pytest --tracing off # 不生成(默认)
pytest --tracing retain-on-failure # 仅失败时保留
4.9 --base-url
设置基础 URL,之后 page.goto() 可以使用相对路径:
pytest --base-url https://staging.example.com
def test_navigation(page):
page.goto("/login") # 实际访问 https://staging.example.com/login
page.goto("/dashboard") # 实际访问 https://staging.example.com/dashboard
5. 配置文件
在 pytest.ini 中预设默认参数:
[pytest]
addopts =
--browser chromium
--headed=false
--retries 1
--video retain-on-failure
--tracing retain-on-failure
--base-url http://localhost:3000
6. 自定义 Fixture 示例
6.1 登录态复用
# conftest.py
import pytest
from playwright.sync_api import BrowserContext
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {**browser_context_args, "storage_state": "auth.json"}
@pytest.fixture(scope="session")
def auth_state(playwright, browser_type_launch_args):
"""生成并保存登录态,后续测试复用"""
browser = playwright.chromium.launch(**browser_type_launch_args)
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com/login")
page.get_by_label("用户名").fill("admin")
page.get_by_label("密码").fill("secret")
page.get_by_role("button", name="登录").click()
page.wait_for_url("**/dashboard")
context.storage_state(path="auth.json")
context.close()
browser.close()
6.2 截图 on failure
import pytest
from playwright.sync_api import Page
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, "rep_" + rep.when, rep)
@pytest.fixture(autouse=True)
def screenshot_on_failure(page: Page, request):
yield
if hasattr(request.node, "rep_call") and request.node.rep_call.failed:
page.screenshot(path=f"screenshots/{request.node.name}.png")
6.3 测试数据清理
@pytest.fixture
def cleanup(page: Page):
"""测试后清理创建的测试数据"""
yield
# 测试结束后清理
page.goto("https://example.com/admin/cleanup")
page.get_by_role("button", name="清理测试数据").click()
7. 小结
pagefixture 是最常用的,99% 的场景用它就够了。browser_context_args是定制上下文的首选方式,在conftest.py里统一配置。- 命令行参数覆盖配置文件,
--video、--tracing、--screenshot的retain-on-failure是 CI 上的标准配置。 --base-url让你在不同环境之间轻松切换。