How to use not_to_have_id method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_assertions.py

Source: test_assertions.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License")
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import re
16from datetime import datetime
17
18import pytest
19
20from playwright.sync_api import Browser, Page, expect
21from tests.server import Server
22
23
24def test_assertions_page_to_have_title(page: Page, server: Server) -> None:
25    page.goto(server.EMPTY_PAGE)
26    page.set_content("<title>new title</title>")
27    expect(page).to_have_title("new title")
28    expect(page).to_have_title(re.compile("new title"))
29    with pytest.raises(AssertionError):
30        expect(page).to_have_title("not the current title", timeout=100)
31    with pytest.raises(AssertionError):
32        expect(page).to_have_title(re.compile("not the current title"), timeout=100)
33    with pytest.raises(AssertionError):
34        expect(page).not_to_have_title(re.compile("new title"), timeout=100)
35    with pytest.raises(AssertionError):
36        expect(page).not_to_have_title("new title", timeout=100)
37    expect(page).not_to_have_title("great title", timeout=100)
38    page.evaluate(
39        """
40        setTimeout(() => {
41            document.title = 'great title';
42        }, 2000);
43    """
44    )
45    expect(page).to_have_title("great title")
46    expect(page).to_have_title(re.compile("great title"))
47
48
49def test_assertions_page_to_have_url(page: Page, server: Server) -> None:
50    page.goto(server.EMPTY_PAGE)
51    expect(page).to_have_url(server.EMPTY_PAGE)
52    expect(page).to_have_url(re.compile(r".*/empty\.html"))
53    with pytest.raises(AssertionError):
54        expect(page).to_have_url("nooooo", timeout=100)
55    with pytest.raises(AssertionError):
56        expect(page).to_have_url(re.compile("not-the-url"), timeout=100)
57    page.evaluate(
58        """
59        setTimeout(() => {
60            window.location = window.location.origin + '/grid.html';
61        }, 2000);
62    """
63    )
64    expect(page).to_have_url(server.PREFIX + "/grid.html")
65    expect(page).not_to_have_url(server.EMPTY_PAGE, timeout=100)
66    with pytest.raises(AssertionError):
67        expect(page).not_to_have_url(re.compile(r".*/grid\.html"), timeout=100)
68    with pytest.raises(AssertionError):
69        expect(page).not_to_have_url(server.PREFIX + "/grid.html", timeout=100)
70    expect(page).to_have_url(re.compile(r".*/grid\.html"))
71    expect(page).not_to_have_url("**/empty.html", timeout=100)
72
73
74def test_assertions_page_to_have_url_with_base_url(
75    browser: Browser, server: Server
76) -> None:
77    page = browser.new_page(base_url=server.PREFIX)
78    page.goto("/empty.html")
79    expect(page).to_have_url("/empty.html")
80    expect(page).to_have_url(re.compile(r".*/empty\.html"))
81    page.close()
82
83
84def test_assertions_locator_to_contain_text(page: Page, server: Server) -> None:
85    page.goto(server.EMPTY_PAGE)
86    page.set_content("<div id=foobar>kek</div>")
87    expect(page.locator("div#foobar")).to_contain_text("kek")
88    expect(page.locator("div#foobar")).not_to_contain_text("bar", timeout=100)
89    with pytest.raises(AssertionError):
90        expect(page.locator("div#foobar")).to_contain_text("bar", timeout=100)
91
92    page.set_content("<div>Text \n1</div><div>Text2</div><div>Text3</div>")
93    expect(page.locator("div")).to_contain_text(["ext     1", re.compile("ext3")])
94
95
96def test_assertions_locator_to_have_attribute(page: Page, server: Server) -> None:
97    page.goto(server.EMPTY_PAGE)
98    page.set_content("<div id=foobar>kek</div>")
99    expect(page.locator("div#foobar")).to_have_attribute("id", "foobar")
100    expect(page.locator("div#foobar")).to_have_attribute("id", re.compile("foobar"))
101    expect(page.locator("div#foobar")).not_to_have_attribute("id", "kek", timeout=100)
102    with pytest.raises(AssertionError):
103        expect(page.locator("div#foobar")).to_have_attribute("id", "koko", timeout=100)
104
105
106def test_assertions_locator_to_have_class(page: Page, server: Server) -> None:
107    page.goto(server.EMPTY_PAGE)
108    page.set_content("<div class=foobar>kek</div>")
109    expect(page.locator("div.foobar")).to_have_class("foobar")
110    expect(page.locator("div.foobar")).to_have_class(["foobar"])
111    expect(page.locator("div.foobar")).to_have_class(re.compile("foobar"))
112    expect(page.locator("div.foobar")).to_have_class([re.compile("foobar")])
113    expect(page.locator("div.foobar")).not_to_have_class("kekstar", timeout=100)
114    with pytest.raises(AssertionError):
115        expect(page.locator("div.foobar")).to_have_class("oh-no", timeout=100)
116
117
118def test_assertions_locator_to_have_count(page: Page, server: Server) -> None:
119    page.goto(server.EMPTY_PAGE)
120    page.set_content("<div class=foobar>kek</div><div class=foobar>kek</div>")
121    expect(page.locator("div.foobar")).to_have_count(2)
122    expect(page.locator("div.foobar")).not_to_have_count(42, timeout=100)
123    with pytest.raises(AssertionError):
124        expect(page.locator("div.foobar")).to_have_count(42, timeout=100)
125
126
127def test_assertions_locator_to_have_css(page: Page, server: Server) -> None:
128    page.goto(server.EMPTY_PAGE)
129    page.set_content("<div class=foobar style='color: rgb(234, 74, 90);'>kek</div>")
130    expect(page.locator("div.foobar")).to_have_css("color", "rgb(234, 74, 90)")
131    expect(page.locator("div.foobar")).not_to_have_css(
132        "color", "rgb(42, 42, 42)", timeout=100
133    )
134    with pytest.raises(AssertionError):
135        expect(page.locator("div.foobar")).to_have_css(
136            "color", "rgb(42, 42, 42)", timeout=100
137        )
138
139
140def test_assertions_locator_to_have_id(page: Page, server: Server) -> None:
141    page.goto(server.EMPTY_PAGE)
142    page.set_content("<div class=foobar id=kek>kek</div>")
143    expect(page.locator("div.foobar")).to_have_id("kek")
144    expect(page.locator("div.foobar")).not_to_have_id("top", timeout=100)
145    with pytest.raises(AssertionError):
146        expect(page.locator("div.foobar")).to_have_id("top", timeout=100)
147
148
149def test_assertions_locator_to_have_js_property(page: Page, server: Server) -> None:
150    page.goto(server.EMPTY_PAGE)
151    page.set_content("<div></div>")
152    page.eval_on_selector(
153        "div", "e => e.foo = { a: 1, b: 'string', c: new Date(1627503992000) }"
154    )
155    expect(page.locator("div")).to_have_js_property(
156        "foo",
157        {"a": 1, "b": "string", "c": datetime.utcfromtimestamp(1627503992000 / 1000)},
158    )
159
160
161def test_assertions_locator_to_have_text(page: Page, server: Server) -> None:
162    page.goto(server.EMPTY_PAGE)
163    page.set_content("<div id=foobar>kek</div>")
164    expect(page.locator("div#foobar")).to_have_text("kek")
165    expect(page.locator("div#foobar")).not_to_have_text("top", timeout=100)
166
167    page.set_content("<div>Text    \n1</div><div>Text   2a</div>")
168    # Should only normalize whitespace in the first item.
169    expect(page.locator("div")).to_have_text(["Text  1", re.compile(r"Text   \d+a")])
170
171
172def test_assertions_locator_to_have_value(page: Page, server: Server) -> None:
173    page.goto(server.EMPTY_PAGE)
174    page.set_content("<input type=text id=foo>")
175    my_input = page.locator("#foo")
176    expect(my_input).to_have_value("")
177    expect(my_input).not_to_have_value("bar", timeout=100)
178    my_input.fill("kektus")
179    expect(my_input).to_have_value("kektus")
180
181
182def test_assertions_locator_to_be_checked(page: Page, server: Server) -> None:
183    page.goto(server.EMPTY_PAGE)
184    page.set_content("<input type=checkbox>")
185    my_checkbox = page.locator("input")
186    expect(my_checkbox).not_to_be_checked()
187    with pytest.raises(AssertionError):
188        expect(my_checkbox).to_be_checked(timeout=100)
189    expect(my_checkbox).to_be_checked(timeout=100, checked=False)
190    with pytest.raises(AssertionError):
191        expect(my_checkbox).to_be_checked(timeout=100, checked=True)
192    my_checkbox.check()
193    expect(my_checkbox).to_be_checked(timeout=100, checked=True)
194    with pytest.raises(AssertionError):
195        expect(my_checkbox).to_be_checked(timeout=100, checked=False)
196    expect(my_checkbox).to_be_checked()
197
198
199def test_assertions_locator_to_be_disabled_enabled(page: Page, server: Server) -> None:
200    page.goto(server.EMPTY_PAGE)
201    page.set_content("<input type=checkbox>")
202    my_checkbox = page.locator("input")
203    expect(my_checkbox).not_to_be_disabled()
204    expect(my_checkbox).to_be_enabled()
205    with pytest.raises(AssertionError):
206        expect(my_checkbox).to_be_disabled(timeout=100)
207    my_checkbox.evaluate("e => e.disabled = true")
208    expect(my_checkbox).to_be_disabled()
209    with pytest.raises(AssertionError):
210        expect(my_checkbox).to_be_enabled(timeout=100)
211
212
213def test_assertions_locator_to_be_editable(page: Page, server: Server) -> None:
214    page.goto(server.EMPTY_PAGE)
215    page.set_content("<input></input><button disabled>Text</button>")
216    expect(page.locator("button")).not_to_be_editable()
217    expect(page.locator("input")).to_be_editable()
218    with pytest.raises(AssertionError):
219        expect(page.locator("button")).to_be_editable(timeout=100)
220
221
222def test_assertions_locator_to_be_empty(page: Page, server: Server) -> None:
223    page.goto(server.EMPTY_PAGE)
224    page.set_content(
225        "<input value=text name=input1></input><input name=input2></input>"
226    )
227    expect(page.locator("input[name=input1]")).not_to_be_empty()
228    expect(page.locator("input[name=input2]")).to_be_empty()
229    with pytest.raises(AssertionError):
230        expect(page.locator("input[name=input1]")).to_be_empty(timeout=100)
231
232
233def test_assertions_locator_to_be_focused(page: Page, server: Server) -> None:
234    page.goto(server.EMPTY_PAGE)
235    page.set_content("<input type=checkbox>")
236    my_checkbox = page.locator("input")
237    with pytest.raises(AssertionError):
238        expect(my_checkbox).to_be_focused(timeout=100)
239    my_checkbox.focus()
240    expect(my_checkbox).to_be_focused()
241
242
243def test_assertions_locator_to_be_hidden_visible(page: Page, server: Server) -> None:
244    page.goto(server.EMPTY_PAGE)
245    page.set_content("<div style='width: 50px; height: 50px;'>Something</div>")
246    my_checkbox = page.locator("div")
247    expect(my_checkbox).to_be_visible()
248    with pytest.raises(AssertionError):
249        expect(my_checkbox).to_be_hidden(timeout=100)
250    my_checkbox.evaluate("e => e.style.display = 'none'")
251    expect(my_checkbox).to_be_hidden()
252    with pytest.raises(AssertionError):
253        expect(my_checkbox).to_be_visible(timeout=100)
254
255
256def test_assertions_should_serialize_regexp_correctly(
257    page: Page, server: Server
258) -> None:
259    page.goto(server.EMPTY_PAGE)
260    page.set_content("<div>iGnOrEcAsE</div>")
261    expect(page.locator("div")).to_have_text(re.compile(r"ignorecase", re.IGNORECASE))
262    page.set_content(
263        """<div>start
264some
265lines
266between
267end</div>"""
268    )
269    expect(page.locator("div")).to_have_text(re.compile(r"start.*end", re.DOTALL))
270    page.set_content(
271        """<div>line1
272line2
273line3</div>"""
274    )
275    expect(page.locator("div")).to_have_text(re.compile(r"^line2$", re.MULTILINE))
276
277
278def test_assertions_response_is_ok_pass(page: Page, server: Server) -> None:
279    response = page.request.get(server.EMPTY_PAGE)
280    expect(response).to_be_ok()
281
282
283def test_assertions_response_is_ok_pass_with_not(page: Page, server: Server) -> None:
284    response = page.request.get(server.PREFIX + "/unknown")
285    expect(response).not_to_be_ok()
286
287
288def test_assertions_response_is_ok_fail(page: Page, server: Server) -> None:
289    response = page.request.get(server.PREFIX + "/unknown")
290    with pytest.raises(AssertionError) as excinfo:
291        expect(response).to_be_ok()
292    error_message = str(excinfo.value)
293    assert ("→ GET " + server.PREFIX + "/unknown") in error_message
294    assert "← 404 Not Found" in error_message
295
Full Screen

_assertions.py

Source: _assertions.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15from typing import Any, List, Pattern, Union
16from urllib.parse import urljoin
17
18from playwright._impl._api_structures import ExpectedTextValue, FrameExpectOptions
19from playwright._impl._fetch import APIResponse
20from playwright._impl._locator import Locator
21from playwright._impl._page import Page
22from playwright._impl._str_utils import escape_regex_flags
23
24
25class AssertionsBase:
26    def __init__(self, locator: Locator, is_not: bool = False) -> None:
27        self._actual_locator = locator
28        self._loop = locator._loop
29        self._dispatcher_fiber = locator._dispatcher_fiber
30        self._is_not = is_not
31
32    async def _expect_impl(
33        self,
34        expression: str,
35        expect_options: FrameExpectOptions,
36        expected: Any,
37        message: str,
38    ) -> None:
39        __tracebackhide__ = True
40        expect_options["isNot"] = self._is_not
41        if expect_options.get("timeout") is None:
42            expect_options["timeout"] = 5_000
43        if expect_options["isNot"]:
44            message = message.replace("expected to", "expected not to")
45        if "useInnerText" in expect_options and expect_options["useInnerText"] is None:
46            del expect_options["useInnerText"]
47        result = await self._actual_locator._expect(expression, expect_options)
48        if result["matches"] == self._is_not:
49            actual = result.get("received")
50            log = "\n".join(result.get("log", "")).strip()
51            if log:
52                log = "\nCall log:\n" + log
53            if expected is not None:
54                raise AssertionError(
55                    f"{message} '{expected}'\nActual value: {actual} {log}"
56                )
57            raise AssertionError(f"{message}\nActual value: {actual} {log}")
58
59
60class PageAssertions(AssertionsBase):
61    def __init__(self, page: Page, is_not: bool = False) -> None:
62        super().__init__(page.locator(":root"), is_not)
63        self._actual_page = page
64
65    @property
66    def _not(self) -> "PageAssertions":
67        return PageAssertions(self._actual_page, not self._is_not)
68
69    async def to_have_title(
70        self, title_or_reg_exp: Union[Pattern, str], timeout: float = None
71    ) -> None:
72        expected_values = to_expected_text_values(
73            [title_or_reg_exp], normalize_white_space=True
74        )
75        __tracebackhide__ = True
76        await self._expect_impl(
77            "to.have.title",
78            FrameExpectOptions(expectedText=expected_values, timeout=timeout),
79            title_or_reg_exp,
80            "Page title expected to be",
81        )
82
83    async def not_to_have_title(
84        self, title_or_reg_exp: Union[Pattern, str], timeout: float = None
85    ) -> None:
86        __tracebackhide__ = True
87        await self._not.to_have_title(title_or_reg_exp, timeout)
88
89    async def to_have_url(
90        self, url_or_reg_exp: Union[str, Pattern], timeout: float = None
91    ) -> None:
92        __tracebackhide__ = True
93        base_url = self._actual_page.context._options.get("baseURL")
94        if isinstance(url_or_reg_exp, str) and base_url:
95            url_or_reg_exp = urljoin(base_url, url_or_reg_exp)
96        expected_text = to_expected_text_values([url_or_reg_exp])
97        await self._expect_impl(
98            "to.have.url",
99            FrameExpectOptions(expectedText=expected_text, timeout=timeout),
100            url_or_reg_exp,
101            "Page URL expected to be",
102        )
103
104    async def not_to_have_url(
105        self, url_or_reg_exp: Union[Pattern, str], timeout: float = None
106    ) -> None:
107        __tracebackhide__ = True
108        await self._not.to_have_url(url_or_reg_exp, timeout)
109
110
111class LocatorAssertions(AssertionsBase):
112    def __init__(self, locator: Locator, is_not: bool = False) -> None:
113        super().__init__(locator, is_not)
114        self._actual_locator = locator
115
116    @property
117    def _not(self) -> "LocatorAssertions":
118        return LocatorAssertions(self._actual_locator, not self._is_not)
119
120    async def to_contain_text(
121        self,
122        expected: Union[List[Union[Pattern, str]], Pattern, str],
123        use_inner_text: bool = None,
124        timeout: float = None,
125    ) -> None:
126        __tracebackhide__ = True
127        if isinstance(expected, list):
128            expected_text = to_expected_text_values(
129                expected, match_substring=True, normalize_white_space=True
130            )
131            await self._expect_impl(
132                "to.contain.text.array",
133                FrameExpectOptions(
134                    expectedText=expected_text,
135                    useInnerText=use_inner_text,
136                    timeout=timeout,
137                ),
138                expected,
139                "Locator expected to contain text",
140            )
141        else:
142            expected_text = to_expected_text_values(
143                [expected], match_substring=True, normalize_white_space=True
144            )
145            await self._expect_impl(
146                "to.have.text",
147                FrameExpectOptions(
148                    expectedText=expected_text,
149                    useInnerText=use_inner_text,
150                    timeout=timeout,
151                ),
152                expected,
153                "Locator expected to contain text",
154            )
155
156    async def not_to_contain_text(
157        self,
158        expected: Union[List[Union[Pattern, str]], Pattern, str],
159        use_inner_text: bool = None,
160        timeout: float = None,
161    ) -> None:
162        __tracebackhide__ = True
163        await self._not.to_contain_text(expected, use_inner_text, timeout)
164
165    async def to_have_attribute(
166        self,
167        name: str,
168        value: Union[str, Pattern],
169        timeout: float = None,
170    ) -> None:
171        __tracebackhide__ = True
172        expected_text = to_expected_text_values([value])
173        await self._expect_impl(
174            "to.have.attribute",
175            FrameExpectOptions(
176                expressionArg=name, expectedText=expected_text, timeout=timeout
177            ),
178            value,
179            "Locator expected to have attribute",
180        )
181
182    async def not_to_have_attribute(
183        self,
184        name: str,
185        value: Union[str, Pattern],
186        timeout: float = None,
187    ) -> None:
188        __tracebackhide__ = True
189        await self._not.to_have_attribute(name, value, timeout)
190
191    async def to_have_class(
192        self,
193        expected: Union[List[Union[Pattern, str]], Pattern, str],
194        timeout: float = None,
195    ) -> None:
196        __tracebackhide__ = True
197        if isinstance(expected, list):
198            expected_text = to_expected_text_values(expected)
199            await self._expect_impl(
200                "to.have.class.array",
201                FrameExpectOptions(expectedText=expected_text, timeout=timeout),
202                expected,
203                "Locator expected to have class",
204            )
205        else:
206            expected_text = to_expected_text_values([expected])
207            await self._expect_impl(
208                "to.have.class",
209                FrameExpectOptions(expectedText=expected_text, timeout=timeout),
210                expected,
211                "Locator expected to have class",
212            )
213
214    async def not_to_have_class(
215        self,
216        expected: Union[List[Union[Pattern, str]], Pattern, str],
217        timeout: float = None,
218    ) -> None:
219        __tracebackhide__ = True
220        await self._not.to_have_class(expected, timeout)
221
222    async def to_have_count(
223        self,
224        count: int,
225        timeout: float = None,
226    ) -> None:
227        __tracebackhide__ = True
228        await self._expect_impl(
229            "to.have.count",
230            FrameExpectOptions(expectedNumber=count, timeout=timeout),
231            count,
232            "Locator expected to have count",
233        )
234
235    async def not_to_have_count(
236        self,
237        count: int,
238        timeout: float = None,
239    ) -> None:
240        __tracebackhide__ = True
241        await self._not.to_have_count(count, timeout)
242
243    async def to_have_css(
244        self,
245        name: str,
246        value: Union[str, Pattern],
247        timeout: float = None,
248    ) -> None:
249        __tracebackhide__ = True
250        expected_text = to_expected_text_values([value])
251        await self._expect_impl(
252            "to.have.css",
253            FrameExpectOptions(
254                expressionArg=name, expectedText=expected_text, timeout=timeout
255            ),
256            value,
257            "Locator expected to have CSS",
258        )
259
260    async def not_to_have_css(
261        self,
262        name: str,
263        value: Union[str, Pattern],
264        timeout: float = None,
265    ) -> None:
266        __tracebackhide__ = True
267        await self._not.to_have_css(name, value, timeout)
268
269    async def to_have_id(
270        self,
271        id: Union[str, Pattern],
272        timeout: float = None,
273    ) -> None:
274        __tracebackhide__ = True
275        expected_text = to_expected_text_values([id])
276        await self._expect_impl(
277            "to.have.id",
278            FrameExpectOptions(expectedText=expected_text, timeout=timeout),
279            id,
280            "Locator expected to have ID",
281        )
282
283    async def not_to_have_id(
284        self,
285        id: Union[str, Pattern],
286        timeout: float = None,
287    ) -> None:
288        __tracebackhide__ = True
289        await self._not.to_have_id(id, timeout)
290
291    async def to_have_js_property(
292        self,
293        name: str,
294        value: Any,
295        timeout: float = None,
296    ) -> None:
297        __tracebackhide__ = True
298        await self._expect_impl(
299            "to.have.property",
300            FrameExpectOptions(
301                expressionArg=name, expectedValue=value, timeout=timeout
302            ),
303            value,
304            "Locator expected to have JS Property",
305        )
306
307    async def not_to_have_js_property(
308        self,
309        name: str,
310        value: Any,
311        timeout: float = None,
312    ) -> None:
313        __tracebackhide__ = True
314        await self._not.to_have_js_property(name, value, timeout)
315
316    async def to_have_value(
317        self,
318        value: Union[str, Pattern],
319        timeout: float = None,
320    ) -> None:
321        __tracebackhide__ = True
322        expected_text = to_expected_text_values([value])
323        await self._expect_impl(
324            "to.have.value",
325            FrameExpectOptions(expectedText=expected_text, timeout=timeout),
326            value,
327            "Locator expected to have Value",
328        )
329
330    async def not_to_have_value(
331        self,
332        value: Union[str, Pattern],
333        timeout: float = None,
334    ) -> None:
335        __tracebackhide__ = True
336        await self._not.to_have_value(value, timeout)
337
338    async def to_have_text(
339        self,
340        expected: Union[List[Union[Pattern, str]], Pattern, str],
341        use_inner_text: bool = None,
342        timeout: float = None,
343    ) -> None:
344        __tracebackhide__ = True
345        if isinstance(expected, list):
346            expected_text = to_expected_text_values(
347                expected, normalize_white_space=True
348            )
349            await self._expect_impl(
350                "to.have.text.array",
351                FrameExpectOptions(
352                    expectedText=expected_text,
353                    useInnerText=use_inner_text,
354                    timeout=timeout,
355                ),
356                expected,
357                "Locator expected to have text",
358            )
359        else:
360            expected_text = to_expected_text_values(
361                [expected], normalize_white_space=True
362            )
363            await self._expect_impl(
364                "to.have.text",
365                FrameExpectOptions(
366                    expectedText=expected_text,
367                    useInnerText=use_inner_text,
368                    timeout=timeout,
369                ),
370                expected,
371                "Locator expected to have text",
372            )
373
374    async def not_to_have_text(
375        self,
376        expected: Union[List[Union[Pattern, str]], Pattern, str],
377        use_inner_text: bool = None,
378        timeout: float = None,
379    ) -> None:
380        __tracebackhide__ = True
381        await self._not.to_have_text(expected, use_inner_text, timeout)
382
383    async def to_be_checked(
384        self,
385        timeout: float = None,
386        checked: bool = None,
387    ) -> None:
388        __tracebackhide__ = True
389        await self._expect_impl(
390            "to.be.checked"
391            if checked is None or checked is True
392            else "to.be.unchecked",
393            FrameExpectOptions(timeout=timeout),
394            None,
395            "Locator expected to be checked",
396        )
397
398    async def not_to_be_checked(
399        self,
400        timeout: float = None,
401    ) -> None:
402        __tracebackhide__ = True
403        await self._not.to_be_checked(timeout)
404
405    async def to_be_disabled(
406        self,
407        timeout: float = None,
408    ) -> None:
409        __tracebackhide__ = True
410        await self._expect_impl(
411            "to.be.disabled",
412            FrameExpectOptions(timeout=timeout),
413            None,
414            "Locator expected to be disabled",
415        )
416
417    async def not_to_be_disabled(
418        self,
419        timeout: float = None,
420    ) -> None:
421        __tracebackhide__ = True
422        await self._not.to_be_disabled(timeout)
423
424    async def to_be_editable(
425        self,
426        timeout: float = None,
427    ) -> None:
428        __tracebackhide__ = True
429        await self._expect_impl(
430            "to.be.editable",
431            FrameExpectOptions(timeout=timeout),
432            None,
433            "Locator expected to be editable",
434        )
435
436    async def not_to_be_editable(
437        self,
438        timeout: float = None,
439    ) -> None:
440        __tracebackhide__ = True
441        await self._not.to_be_editable(timeout)
442
443    async def to_be_empty(
444        self,
445        timeout: float = None,
446    ) -> None:
447        __tracebackhide__ = True
448        await self._expect_impl(
449            "to.be.empty",
450            FrameExpectOptions(timeout=timeout),
451            None,
452            "Locator expected to be empty",
453        )
454
455    async def not_to_be_empty(
456        self,
457        timeout: float = None,
458    ) -> None:
459        __tracebackhide__ = True
460        await self._not.to_be_empty(timeout)
461
462    async def to_be_enabled(
463        self,
464        timeout: float = None,
465    ) -> None:
466        __tracebackhide__ = True
467        await self._expect_impl(
468            "to.be.enabled",
469            FrameExpectOptions(timeout=timeout),
470            None,
471            "Locator expected to be enabled",
472        )
473
474    async def not_to_be_enabled(
475        self,
476        timeout: float = None,
477    ) -> None:
478        __tracebackhide__ = True
479        await self._not.to_be_enabled(timeout)
480
481    async def to_be_hidden(
482        self,
483        timeout: float = None,
484    ) -> None:
485        __tracebackhide__ = True
486        await self._expect_impl(
487            "to.be.hidden",
488            FrameExpectOptions(timeout=timeout),
489            None,
490            "Locator expected to be hidden",
491        )
492
493    async def not_to_be_hidden(
494        self,
495        timeout: float = None,
496    ) -> None:
497        __tracebackhide__ = True
498        await self._not.to_be_hidden(timeout)
499
500    async def to_be_visible(
501        self,
502        timeout: float = None,
503    ) -> None:
504        __tracebackhide__ = True
505        await self._expect_impl(
506            "to.be.visible",
507            FrameExpectOptions(timeout=timeout),
508            None,
509            "Locator expected to be visible",
510        )
511
512    async def not_to_be_visible(
513        self,
514        timeout: float = None,
515    ) -> None:
516        __tracebackhide__ = True
517        await self._not.to_be_visible(timeout)
518
519    async def to_be_focused(
520        self,
521        timeout: float = None,
522    ) -> None:
523        __tracebackhide__ = True
524        await self._expect_impl(
525            "to.be.focused",
526            FrameExpectOptions(timeout=timeout),
527            None,
528            "Locator expected to be focused",
529        )
530
531    async def not_to_be_focused(
532        self,
533        timeout: float = None,
534    ) -> None:
535        __tracebackhide__ = True
536        await self._not.to_be_focused(timeout)
537
538
539class APIResponseAssertions:
540    def __init__(self, response: APIResponse, is_not: bool = False) -> None:
541        self._loop = response._loop
542        self._dispatcher_fiber = response._dispatcher_fiber
543        self._is_not = is_not
544        self._actual = response
545
546    @property
547    def _not(self) -> "APIResponseAssertions":
548        return APIResponseAssertions(self._actual, not self._is_not)
549
550    async def to_be_ok(
551        self,
552    ) -> None:
553        __tracebackhide__ = True
554        if self._is_not is not self._actual.ok:
555            return
556        message = f"Response status expected to be within [200..299] range, was '{self._actual.status}'"
557        if self._is_not:
558            message = message.replace("expected to", "expected not to")
559        log_list = await self._actual._fetch_log()
560        log = "\n".join(log_list).strip()
561        if log:
562            message += f"\n Call log:\n{log}"
563        raise AssertionError(message)
564
565    async def not_to_be_ok(self) -> None:
566        __tracebackhide__ = True
567        await self._not.to_be_ok()
568
569
570def expected_regex(
571    pattern: Pattern, match_substring: bool, normalize_white_space: bool
572) -> ExpectedTextValue:
573    expected = ExpectedTextValue(
574        regexSource=pattern.pattern,
575        regexFlags=escape_regex_flags(pattern),
576        matchSubstring=match_substring,
577        normalizeWhiteSpace=normalize_white_space,
578    )
579    return expected
580
581
582def to_expected_text_values(
583    items: Union[List[Pattern], List[str], List[Union[str, Pattern]]],
584    match_substring: bool = False,
585    normalize_white_space: bool = False,
586) -> List[ExpectedTextValue]:
587    out: List[ExpectedTextValue] = []
588    assert isinstance(items, list)
589    for item in items:
590        if isinstance(item, str):
591            out.append(
592                ExpectedTextValue(
593                    string=item,
594                    matchSubstring=match_substring,
595                    normalizeWhiteSpace=normalize_white_space,
596                )
597            )
598        elif isinstance(item, Pattern):
599            out.append(expected_regex(item, match_substring, normalize_white_space))
600    return out
601
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)