Playwright for Python: Affirmations

1. Supported assertions

Playwright supports the following types of assertions:

affirmation describe
expect(locator).to_be_checked() Checkbox is checked
expect(locator).to_be_disabled() The element is disabled
expect(locator).to_be_editable() The element is editable
expect(locator).to_be_empty() Container is empty
expect(locator).to_be_enabled() element is available
expect(locator).to_be_focused() Element has focus
expect(locator).to_be_hidden() Element is not visible
expect(locator).to_be_visible() element is visible
expect(locator).to_contain_text() Element contains text
expect(locator).to_have_attribute() The element has a DOM attribute
expect(locator).to_have_class() Elements have class attributes
expect(locator).to_have_count() List has exact number of child elements
expect(locator).to_have_css() Elements have CSS properties
expect(locator).to_have_id() Element has ID
expect(locator).to_have_js_property() Elements have JS attributes
expect(locator).to_have_text() Element matches text
expect(locator).to_have_value() The input box has a value
expect(locator).to_have_values() The selection box has selected options.
expect(page).to_have_title() The page has a title
expect(page).to_have_url() The page has a URL
expect(response).to_be_ok() Response status is normal

2. Specify a custom error message for the assertion

We can specify a custom error message as the second parameter of the expect function, for example:

#test_demo.py
import re
from playwright.sync_api import Page, expect
import pytest


def test_gitlink_demo(page: Page):
    # 访问地址
    page.goto("https://www.gitlink.org.cn/")
    # 断言网页标题=GitLink
    expect(page, "检查网页标题是否正确").to_have_title(re.compile("gitlink"))
	
# main.py
import pytest 

pytest.main(['--headed', '--browser=chromium', "--browser-channel=chrome"])

After running, if the assertion fails, the effect will be as follows:
Insert image description here

3. Customize timeout time

We can specify custom timeouts globally or individually for each assertion. The default timeout is 5 seconds.

Note: If a custom timeout is specified globally and individually for each assertion at the same time, the individual specification takes precedence over the global specification.

3.1 Global designation

# conftest.py

from playwright.sync_api import expect

expect.set_options(timeout=10_000)

3.2 Individual designation

# test_demo.py

import re
from playwright.sync_api import Page, expect
import pytest


@pytest.mark.skip_browser("webkit")
def test_gitlink_demo(page: Page):
    # 访问地址
    page.goto("")
    # 断言网页标题=GitLink
    expect(page, "检查网页标题是否正确").to_have_title(re.compile("gitlink"), timeout=20_000)

Guess you like

Origin blog.csdn.net/FloraCHY/article/details/132696177