跳至主要内容

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参数仅适用于默认的browsercontextpage夹具。如果您通过API调用(如browser.new_context())创建浏览器、上下文或页面,则不会应用CLI参数。

  • --headed: 以有界面模式运行测试(默认:无界面)。
  • --browser: 在不同的浏览器中运行测试,可选chromiumfirefoxwebkit。可以多次指定该参数(默认值:chromium)。
  • --browser-channel 要使用的浏览器渠道
  • --slowmo 通过指定的毫秒数减慢Playwright操作速度。有助于观察操作过程(默认值:0)。
  • --device Device 要模拟的设备。
  • --output 测试生成产物的输出目录(默认:test-results)。
  • --tracing 是否记录每个测试的trace跟踪。onoffretain-on-failure(默认值:off)。
  • --video 是否为每个测试录制视频。可选值为 onoffretain-on-failure(默认值:off)。
  • --screenshot 是否在每次测试后自动捕获截图。可选值为 onoffonly-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在测试函数中被请求时创建,并在测试结束时销毁。

会话作用域: 这些fixture在测试函数中请求时创建,并在所有测试结束时销毁。

  • playwright: Playwright 实例。
  • browser_type: 当前浏览器的BrowserType实例。
  • browser: 由Playwright启动的Browser实例。
  • browser_name: 浏览器名称,字符串类型。
  • browser_channel: 浏览器通道字符串。
  • is_chromium, is_webkit, is_firefox: 分别对应各浏览器类型的布尔值。

自定义fixture选项: 对于browsercontextfixtures,使用以下fixtures来定义自定义启动选项。

也可以通过使用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选项的常规信息,请参阅运行测试

示例

配置自动补全的类型提示

test_my_application.py
from playwright.sync_api import Page

def test_visit_admin_dashboard(page: Page):
page.goto("/admin")
# ...

如果您在使用带有Pylance的VSCode,可以通过启用python.testing.pytestEnabled设置来推断这些类型,因此您不需要类型注解。

使用多个上下文

为了模拟多个用户,您可以创建多个BrowserContext实例。

test_my_application.py
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

按浏览器跳过测试

test_my_application.py
import pytest

@pytest.mark.skip_browser("firefox")
def test_visit_example(page):
page.goto("https://example.com")
# ...

在特定浏览器上运行

conftest.py
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
test_my_application.py
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
test_my_application.py
def test_visit_example(page):
page.goto("/admin")
# -> Will result in http://localhost:8080/admin

忽略HTTPS错误

conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"ignore_https_errors": True
}

使用自定义视口尺寸

conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"viewport": {
"width": 1920,
"height": 1080,
}
}

设备模拟 / BrowserContext 选项覆盖

conftest.py
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")
# ...