跳到主要內容

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 fixture。如果您使用 API 呼叫 (例如 browser.new_context()) 建立瀏覽器、context 或頁面,則 CLI 引數不會套用。

  • --headed:在有 head 模式下執行測試 (預設:headless)。
  • --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)。

Fixture

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

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

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

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

  • playwrightPlaywright 執行個體。
  • browser_type:目前瀏覽器的 BrowserType 執行個體。
  • browser:Playwright 啟動的 Browser 執行個體。
  • browser_name:瀏覽器名稱 (字串)。
  • browser_channel:瀏覽器通道 (字串)。
  • is_chromiumis_webkitis_firefox:各瀏覽器類型的布林值。

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

也可以使用 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 設定來推斷這些類型,因此您不需要類型標註。

使用多個 context

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

Async Fixture

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