编写测试
Playwright 断言是专门为动态网页创建的。检查会自动重试,直到满足必要条件。Playwright 内置了 自动等待,这意味着它在执行操作之前会等待元素变为可操作状态。Playwright 提供了 expect 函数来编写断言。
查看下面的示例测试,了解如何使用 定位器 和 web first 断言编写测试。
import re
from playwright.sync_api import Page, expect
def test_homepage_has_Playwright_in_title_and_get_started_link_linking_to_the_intro_page(page: Page):
page.goto("https://playwright.dev/")
# Expect a title "to contain" a substring.
expect(page).to_have_title(re.compile("Playwright"))
# create a locator
get_started = page.get_by_role("link", name="Get started");
# Expect an attribute "to be strictly equal" to the value.
expect(get_started).to_have_attribute("href", "/docs/intro")
# Click the get started link.
get_started.click()
# Expects the URL to contain intro.
expect(page).to_have_url(re.compile(".*intro"))
断言
Playwright 提供了 expect 函数,它将等待直到满足预期条件。
import re
from playwright.sync_api import expect
expect(page).to_have_title(re.compile("Playwright"))
定位器
定位器 是 Playwright 自动等待和重试能力的核心部分。定位器代表了一种在任何时刻在页面上查找元素的方法,并用于对元素执行操作,如 .click .fill 等。
from playwright.sync_api import expect
get_started = page.get_by_role("link", name="Get started");
expect(get_started).to_have_attribute("href", "/docs/installation")
get_started.click()
测试隔离
Playwright Pytest 插件基于测试 fixture 的概念,例如传递给测试的 内置 page fixture。由于浏览器上下文(Browser Context),页面在测试之间是隔离的,这相当于一个全新的浏览器配置文件,每个测试都获得一个全新的环境,即使多个测试在一个浏览器中运行也是如此。
from playwright.sync_api import Page
def test_basic_test(page: Page):
# ...
使用测试钩子
您可以使用各种 fixtures 在测试之前或之后执行代码,并在它们之间共享对象。具有 autouse 的 function 作用域 fixture 行为类似于 beforeEach/afterEach。具有 autouse 的 module 作用域 fixture 行为类似于 beforeAll/afterAll,它在所有测试之前和之后运行。
import pytest
from playwright.sync_api import Page
@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
print("beforeEach")
# Go to the starting url before each test.
page.goto("https://playwright.dev/")
yield
print("afterEach")
def test_main_navigation(page: Page):
# Assertions use the expect API.
expect(page).to_have_url("https://playwright.dev/")