断言
介绍
Playwright 包含 Web 特定的断言,它们会自动重试直到满足预期条件。考虑以下示例:
python
expect(page.get_by_test_id("status")).to_have_text("Submitted")Playwright 将重新测试具有测试 ID status 的元素,直到它具有 "Submitted" 文本。它将反复重新获取元素并检查,直到满足条件或达到超时。
默认情况下,断言的超时时间为 5 秒。
自动重试断言
以下断言将重试,直到断言通过或达到断言超时。
软断言
默认情况下,失败的断言将终止测试执行。Playwright 还支持软断言:失败的软断言不会终止测试执行,但会将测试标记为失败。
python
# 进行一些不会在失败时停止测试的检查...
expect.soft(page.get_by_test_id("status")).to_have_text("Success")
expect.soft(page.get_by_test_id("eta")).to_have_text("1 day")
# ...然后继续测试以检查更多内容。
page.get_by_role("link", name="next page").click()
expect.soft(page.get_by_role("heading", name="Make another order")).to_be_visible()请注意,软断言仅适用于 pytest-playwright(或 pytest-playwright-asyncio)插件,版本 0.8.0 或更新版本。
自定义 Expect 消息
你可以将自定义 expect 消息指定为 expect 函数的第二个参数,例如:
python
expect(page.get_by_text("Name"), "should be logged in").to_be_visible()当 expect 失败时,错误将如下所示:
bash
def test_foobar(page: Page) -> None:
> expect(page.get_by_text("Name"), "should be logged in").to_be_visible()
E AssertionError: should be logged in
E Actual value: None
E Call log:
E LocatorAssertions.to_be_visible with timeout 5000ms
E waiting for get_by_text("Name")
E waiting for get_by_text("Name")
tests/test_foobar.py:22: AssertionError设置自定义超时
你可以为断言指定全局超时或按断言指定超时。默认超时为 5 秒。
全局超时
python
from playwright.sync_api import expect
expect.set_options(timeout=10_000)按断言超时
python
from playwright.sync_api import expect
def test_foobar(page: Page) -> None:
expect(page.get_by_text("Name")).to_be_visible(timeout=10_000)