Skip to main content

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 佈置。如果您使用 API 呼叫(如 browser.new_context())建立瀏覽器、情境或頁面,CLI 參數將不會套用。

  • --headed:以有頭模式執行測試(預設:無頭)。
  • --browser:在不同瀏覽器 chromiumfirefoxwebkit 中執行測試。可多次指定(預設:chromium)。
  • --browser-channel 要使用的瀏覽器通道
  • --slowmo 以指定的毫秒數減慢 Playwright 操作。對於觀察執行過程很有用(預設:0)。
  • --device 要模擬的裝置
  • --output 測試產生的工件目錄(預設:test-results)。
  • --tracing 是否為每個測試記錄追蹤onoffretain-on-failure(預設:off)。
  • --video 是否為每個測試記錄影片。onoffretain-on-failure(預設:off)。
  • --screenshot 是否在每個測試後自動擷取螢幕截圖。onoffonly-on-failure(預設:off)。
  • --full-page-screenshot 是否在失敗時擷取完整頁面螢幕截圖。預設情況下,只會擷取檢視區。需要啟用 --screenshot(預設:off)。

佈置

此外掛會設定 Playwright 專用的 pytest 佈置。要使用這些佈置,請在測試函式中使用佈置名稱作為參數。

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

函式範圍:這些佈置會在測試函式中被請求時建立,並在測試結束時銷毀。

工作階段範圍:這些佈置會在測試函式中被請求時建立,並在所有測試結束時銷毀。

  • playwrightPlaywright 實例。
  • browser_type:目前瀏覽器的 BrowserType 實例。
  • browser:Playwright 啟動的 Browser 實例。
  • browser_name:瀏覽器名稱字串。
  • browser_channel:瀏覽器通道字串。
  • is_chromiumis_webkitis_firefox:各自瀏覽器類型的布林值。

自訂佈置選項:對於 browsercontext 佈置,請使用以下佈置來定義自訂啟動選項。

您也可以使用 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 參數或作為佈置來設定基底 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,
}

或透過 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。

非同步佈置

要使用非同步佈置,請安裝 pytest-playwright-asyncio

確保您使用 pytest-asyncio>=0.26.0 並在您的組態設定(pytest.ini/pyproject.toml/setup.cfg)中設定 asyncio_default_test_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")
# ...