跳到主要內容

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())建立瀏覽器、context 或 page,則 CLI 引數不會套用。

  • --headed: 在有頭模式下執行測試(預設:無頭模式)。
  • --browser: 在不同的瀏覽器 chromiumfirefoxwebkit 中執行測試。可以多次指定(預設:chromium)。
  • --browser-channel 要使用的 瀏覽器管道
  • --slowmo 以指定的毫秒數減慢 Playwright 操作。方便您查看正在發生的事情(預設:0)。
  • --device 要模擬的裝置
  • --output 測試產生的artifacts目錄(預設:test-results)。
  • --tracing 是否為每個測試記錄追蹤onoffretain-on-failure(預設:off)。
  • --video 是否為每個測試錄製影片。onoffretain-on-failure(預設:off)。
  • --screenshot 是否在每次測試後自動擷取螢幕截圖。onoffonly-on-failure(預設:off)。
  • --full-page-screenshot 是否在失敗時擷取完整頁面螢幕截圖。預設情況下,僅擷取 viewport。需要啟用 --screenshot(預設:off)。

Fixtures

此插件為 pytest 設定 Playwright 特定的 fixtures。若要使用這些 fixtures,請使用 fixture 名稱作為測試函式的引數。

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

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

Session 範圍:這些 fixtures 在測試函式中請求時建立,並在所有測試結束時銷毀。

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

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

也可以使用 browser_context_args 標記來覆寫單一測試的 context 選項 (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 設定來推斷這些類型,因此您不需要類型註釋。

使用多個 contexts

為了模擬多個使用者,您可以建立多個 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
}

使用自訂 viewport 大小

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。

Async Fixtures

如果您想要使用 async 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")
# ...