Skip to main content

Pytest 插件参考

介绍

¥Introduction

Playwright 提供了一个 Pytest 插件来编写端到端测试。要开始使用,请参阅 入门指南

¥Playwright provides a Pytest plugin to write end-to-end tests. To get started with it, refer to the getting started guide.

用法

¥Usage

要运行测试,请使用 Pytest CLI。

¥To run your tests, use Pytest CLI.

pytest --browser webkit --headed

如果你希望自动添加 CLI 参数而不指定它们,可以使用 pytest.ini 文件:

¥If you want to add the CLI arguments automatically without specifying them, you can use the pytest.ini file:

# content of pytest.ini
[pytest]
# Run firefox with UI
addopts = --headed --browser firefox

CLI 参数

¥CLI arguments

请注意,CLI 参数仅适用于默认的 browsercontextpage 装置。如果你使用类似 browser.new_context() 的 API 调用创建浏览器、上下文或页面,则 CLI 参数将不适用。

¥Note that CLI arguments are only applied to the default browser, context and page fixtures. If you create a browser, a context or a page with the API call like browser.new_context(), the CLI arguments are not applied.

  • --headed:以有头模式运行测试(默认值:无头模式)。

    ¥--headed: Run tests in headed mode (default: headless).

  • --browser:在不同的浏览器 chromiumfirefoxwebkit 中运行测试。可以多次指定(默认值:chromium)。

    ¥--browser: Run tests in a different browser chromium, firefox, or webkit. It can be specified multiple times (default: chromium).

  • --slowmo 将 Playwright 操作减慢指定的毫秒数。此方法有助于你了解正在发生的事情(默认值:0)。

    ¥--slowmo Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on (default: 0).

  • --device Device to be emulated.
  • --output 测试生成的工件目录(默认值:test-results)。

    ¥--output Directory for artifacts produced by tests (default: test-results).

  • --tracing 是否为每个测试记录一个 traceonoffretain-on-failure(默认值:off)。

    ¥--tracing Whether to record a trace for each test. on, off, or retain-on-failure (default: off).

  • --video 是否为每次测试录制视频。onoffretain-on-failure(默认值:off)。

    ¥--video Whether to record video for each test. on, off, or retain-on-failure (default: off).

  • --screenshot 每次测试后是否自动截图。onoffonly-on-failure(默认值:off)。

    ¥--screenshot Whether to automatically capture a screenshot after each test. on, off, or only-on-failure (default: off).

  • --full-page-screenshot 是否在失败时截取整页屏幕截图。默认情况下,仅捕获视口。需要启用 --screenshot(默认值:off)。

    ¥--full-page-screenshot Whether to take a full page screenshot on failure. By default, only the viewport is captured. Requires --screenshot to be enabled (default: off).

夹具

¥Fixtures

此插件用于配置 Playwright 特定的 Pytest 夹具。要使用这些 Fixture,请将 Fixture 名称作为测试函数的参数。

¥This plugin configures Playwright-specific fixtures for pytest. To use these fixtures, use the fixture name as an argument to the test function.

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

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

¥Function scope: These fixtures are created when requested in a test function and destroyed when the test ends.

会话范围:这些 Fixture 在测试函数中被请求时创建,并在所有测试结束时销毁。

¥Session scope: These fixtures are created when requested in a test function and destroyed when all tests end.

  • playwrightPlaywright 实例。

    ¥playwright: Playwright instance.

  • browser_type:当前浏览器的 BrowserType 实例。

    ¥browser_type: BrowserType instance of the current browser.

  • browser:Playwright 推出了 Browser 实例。

    ¥browser: Browser instance launched by Playwright.

  • browser_name:浏览器名称为字符串。

    ¥browser_name: Browser name as string.

  • browser_channel:浏览器通道为字符串。

    ¥browser_channel: Browser channel as string.

  • is_chromium, is_webkit, is_firefox:用于对应浏览器类型的布尔值。

    ¥is_chromium, is_webkit, is_firefox: Booleans for the respective browser types.

自定义装置选项:对于 browsercontext Fixture,请使用以下 Fixture 定义自定义启动选项。

¥Customizing fixture options: For browser and context fixtures, use the following fixtures to define custom launch options.

也可以使用 browser_context_args 标记覆盖单个测试的上下文选项 (browser.new_context()):

¥Its also possible to override the context options (browser.new_context()) for a single test by using the browser_context_args marker:

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"]

并行性:同时运行多个测试

¥Parallelism: Running Multiple Tests at Once

如果你的测试在具有大量 CPU 的机器上运行,你可以使用 pytest-xdist 同时运行多个测试来加快测试套件的整体执行时间:

¥If your tests are running on a machine with a lot of CPUs, you can speed up the overall execution time of your test suite by using pytest-xdist to run multiple tests at once:

# install dependency
pip install pytest-xdist
# use the --numprocesses flag
pytest --numprocesses auto

根据硬件和测试性质,你可以将 numprocesses 设置为从 2 到机器 CPU 数量的任意值。如果设置得太高,你可能会注意到意外行为。

¥Depending on the hardware and nature of your tests, you can set numprocesses to be anywhere from 2 to the number of CPUs on the machine. If set too high, you may notice unexpected behavior.

有关 pytest 选项的常规信息,请参阅 运行测试

¥See Running Tests for general information on pytest options.

示例

¥Examples

配置自动补齐的类型

¥Configure typings for auto-completion

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 设置来推断这些类型,因此你不需要类型注释。

¥If you're using VSCode with Pylance, these types can be inferred by enabling the python.testing.pytestEnabled setting so you don't need the type annotation.

使用多个上下文

¥Using multiple contexts

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

¥In order to simulate multiple users, you can create multiple BrowserContext instances.

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

按浏览器跳过测试

¥Skip test by browser

test_my_application.py
import pytest

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

在特定浏览器上运行

¥Run on a specific browser

conftest.py
import pytest

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

使用自定义浏览器通道(例如 Google Chrome 或 Microsoft Edge)运行

¥Run with a custom browser channel like Google Chrome or Microsoft Edge

pytest --browser-channel chrome
test_my_application.py
def test_example(page):
page.goto("https://example.com")

配置 base-url

¥Configure base-url

使用 base-url 参数启动 Pytest。pytest-base-url 插件允许你从配置、CLI 参数或 Fixture 中设置基本 URL。

¥Start Pytest with the base-url argument. The pytest-base-url plugin is used for that which allows you to set the base url from the config, CLI arg or as a fixture.

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 错误

¥Ignore HTTPS errors

conftest.py
import pytest

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

使用自定义视口大小

¥Use custom viewport size

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 选项覆盖

¥Device emulation / BrowserContext option overrides

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"

¥Or via the CLI --device="iPhone 11 Pro"

unittest.TestCase 一起使用

¥Using with unittest.TestCase

请参阅以下示例,了解如何将其与 unittest.TestCase 结合使用。这有一个限制,即只能指定一个浏览器,并且指定多个浏览器时不会生成多个浏览器的矩阵。

¥See the following example for using it with unittest.TestCase. This has a limitation, that only a single browser can be specified and no matrix of multiple browsers gets generated when specifying multiple.

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

调试

¥Debugging

与 pdb 一起使用

¥Use with pdb

在测试代码中使用 breakpoint() 语句暂停执行并获取 pdb REPL。

¥Use the breakpoint() statement in your test code to pause execution and get a pdb REPL.

def test_bing_is_working(page):
page.goto("https://bing.com")
breakpoint()
# ...

部署到 CI

¥Deploy to CI

请参阅 CI 提供商指南,了解如何将你的测试部署到 CI/CD。

¥See the guides for CI providers to deploy your tests to CI/CD.

异步 Fixtures

¥Async Fixtures

要使用异步 Fixture,请安装 pytest-playwright-asyncio

¥To use async fixtures, install pytest-playwright-asyncio.

确保你正在使用 pytest-asyncio>=0.26.0,并在配置 (pytest.ini/pyproject.toml/setup.cfg) 中设置 asyncio_default_test_loop_scope = session

¥Ensure you are using pytest-asyncio>=0.26.0 and set asyncio_default_test_loop_scope = session in your configuration (pytest.ini/pyproject.toml/setup.cfg).

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