断言
断言列表
🌐 List of assertions
软断言
🌐 Soft assertions
默认情况下,断言失败会终止测试执行。Playwright 还支持软断言:软断言失败不会终止测试执行,但会将测试标记为失败。
🌐 By default, failed assertion will terminate test execution. Playwright also supports soft assertions: failed soft assertions do not terminate test execution, but mark the test as failed.
# Make a few checks that will not stop the test when failed...
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")
# ... and continue the test to check more things.
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.7.3 或更高版本。
🌐 Note that soft assertions only work with the pytest-playwright (or pytest-playwright-asyncio) plugin, version 0.7.3 or newer.
自定义 Expect 消息
🌐 Custom Expect Message
你可以将自定义的期望消息作为第二个参数传递给 expect 函数,例如:
🌐 You can specify a custom expect message as a second argument to the expect function, for example:
expect(page.get_by_text("Name"), "should be logged in").to_be_visible()
当 Expect 失败时,错误将如下所示:
🌐 When expect fails, the error would look like this:
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
设置自定义超时
🌐 Setting a custom timeout
你可以为断言指定自定义超时时间,既可以全局设置,也可以针对单个断言设置。默认超时时间为 5 秒。
🌐 You can specify a custom timeout for assertions either globally or per assertion. The default timeout is 5 seconds.
全局超时
🌐 Global timeout
from playwright.sync_api import expect
expect.set_options(timeout=10_000)
每个断言超时
🌐 Per assertion timeout
from playwright.sync_api import expect
def test_foobar(page: Page) -> None:
expect(page.get_by_text("Name")).to_be_visible(timeout=10_000)