跳到主要内容

Pytest 插件参考

简介

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 fixtures。如果您使用 API 调用(如 browser.new_context())创建浏览器、上下文或页面,则 CLI 参数将不适用。

  • --headed: 在有头模式下运行测试(默认:headless)。
  • --browser: 在不同的浏览器 chromiumfirefoxwebkit 中运行测试。可以多次指定(默认:chromium)。
  • --browser-channel 浏览器通道 以供使用。
  • --slowmo 减慢 Playwright 操作指定毫秒数。方便您查看正在发生的事情(默认:0)。
  • --device 要模拟的设备
  • --output 用于存放测试生成的 artifacts 的目录(默认:test-results)。
  • --tracing 是否为每个测试记录 traceonoffretain-on-failure(默认:off)。
  • --video 是否为每个测试录制视频。onoffretain-on-failure(默认:off)。
  • --screenshot 是否在每次测试后自动捕获屏幕截图。onoffonly-on-failure(默认:off)。
  • --full-page-screenshot 是否在失败时截取完整页面屏幕截图。默认情况下,仅捕获视口。需要启用 --screenshot(默认:off)。

Fixtures

此插件为 pytest 配置了 Playwright 特定的 fixtures。要使用这些 fixtures,请使用 fixture 名称作为测试函数的参数。

def test_my_app_is_working(fixture_name):
pass
# Test using fixture_name
# ...

函数作用域:这些 fixtures 在测试函数中被请求时创建,并在测试结束时销毁。

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

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

自定义 fixture 选项:对于 browsercontext fixtures,请使用以下 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")
# ...

如果您将 VSCode 与 Pylance 结合使用,则可以通过启用 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")

配置 base-url

使用 base-url 参数启动 Pytest。pytest-base-url 插件用于此目的,它允许您从配置、CLI 参数或作为 fixture 设置 base url。

pytest --base-url https://127.0.0.1:8080
test_my_application.py
def test_visit_example(page):
page.goto("/admin")
# -> Will result in https://127.0.0.1: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,
}

或通过 CLI --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

如果您想使用异步 fixtures,可以使用 pytest-playwright-asyncio 插件。请确保使用 pytest-asyncio>=0.24.0 并使您的测试使用 loop_scope=sesion

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