How to use test_select_text_timeout_waiting_for_invisible_element 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_element_handle.py

Source: test_element_handle.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 pytest
16
17from playwright.sync_api import Error
18
19
20def test_bounding_box(page, server):
21    page.set_viewport_size({"width": 500, "height": 500})
22    page.goto(server.PREFIX + "/grid.html")
23    element_handle = page.query_selector(".box:nth-of-type(13)")
24    box = element_handle.bounding_box()
25    assert box == {"x": 100, "y": 50, "width": 50, "height": 50}
26
27
28def test_bounding_box_handle_nested_frames(page, server):
29    page.set_viewport_size({"width": 500, "height": 500})
30    page.goto(server.PREFIX + "/frames/nested-frames.html")
31    nested_frame = page.frame(name="dos")
32    element_handle = nested_frame.query_selector("div")
33    box = element_handle.bounding_box()
34    assert box == {"x": 24, "y": 224, "width": 268, "height": 18}
35
36
37def test_bounding_box_return_null_for_invisible_elements(page, server):
38    page.set_content('<div style="display:none">hi</div>')
39    element = page.query_selector("div")
40    assert element.bounding_box() is None
41
42
43def test_bounding_box_force_a_layout(page, server):
44    page.set_viewport_size({"width": 500, "height": 500})
45    page.set_content('<div style="width: 100px; height: 100px">hello</div>')
46    element_handle = page.query_selector("div")
47    page.evaluate('element => element.style.height = "200px"', element_handle)
48    box = element_handle.bounding_box()
49    assert box == {"x": 8, "y": 8, "width": 100, "height": 200}
50
51
52def test_bounding_box_with_SVG_nodes(page, server):
53    page.set_content(
54        """<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
55             <rect id="theRect" x="30" y="50" width="200" height="300"></rect>
56           </svg>"""
57    )
58    element = page.query_selector("#therect")
59    pw_bounding_box = element.bounding_box()
60    web_bounding_box = page.evaluate(
61        """e => {
62            rect = e.getBoundingClientRect()
63            return {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
64        }""",
65        element,
66    )
67    assert pw_bounding_box == web_bounding_box
68
69
70def test_bounding_box_with_page_scale(browser, server):
71    context = browser.new_context(
72        viewport={"width": 400, "height": 400, "is_mobile": True}
73    )
74    page = context.new_page()
75    page.goto(server.PREFIX + "/input/button.html")
76    button = page.query_selector("button")
77    button.evaluate(
78        """button => {
79            document.body.style.margin = '0'
80            button.style.borderWidth = '0'
81            button.style.width = '200px'
82            button.style.height = '20px'
83            button.style.marginLeft = '17px'
84            button.style.marginTop = '23px'
85        }"""
86    )
87
88    box = button.bounding_box()
89    assert round(box["x"] * 100) == 17 * 100
90    assert round(box["y"] * 100) == 23 * 100
91    assert round(box["width"] * 100) == 200 * 100
92    assert round(box["height"] * 100) == 20 * 100
93    context.close()
94
95
96def test_bounding_box_when_inline_box_child_is_outside_of_viewport(page, server):
97    page.set_content(
98        """
99            <style>
100            i {
101            position: absolute
102            top: -1000px
103            }
104            body {
105            margin: 0
106            font-size: 12px
107            }
108            </style>
109            <span><i>woof</i><b>doggo</b></span>
110        """
111    )
112    handle = page.query_selector("span")
113    box = handle.bounding_box()
114    web_bounding_box = handle.evaluate(
115        """e => {
116        rect = e.getBoundingClientRect();
117        return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};
118    }"""
119    )
120
121    def roundbox(b):
122        return {
123            "x": round(b["x"] * 100),
124            "y": round(b["y"] * 100),
125            "width": round(b["width"] * 100),
126            "height": round(b["height"] * 100),
127        }
128
129    assert roundbox(box) == roundbox(web_bounding_box)
130
131
132def test_content_frame(page, server, utils):
133    page.goto(server.EMPTY_PAGE)
134    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
135    element_handle = page.query_selector("#frame1")
136    frame = element_handle.content_frame()
137    assert frame == page.frames[1]
138
139
140def test_content_frame_for_non_iframes(page, server, utils):
141    page.goto(server.EMPTY_PAGE)
142    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
143    frame = page.frames[1]
144    element_handle = frame.evaluate_handle("document.body")
145    assert element_handle.content_frame() is None
146
147
148def test_content_frame_for_document_element(page, server, utils):
149    page.goto(server.EMPTY_PAGE)
150    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
151    frame = page.frames[1]
152    element_handle = frame.evaluate_handle("document.documentElement")
153    assert element_handle.content_frame() is None
154
155
156def test_owner_frame(page, server, utils):
157    page.goto(server.EMPTY_PAGE)
158    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
159    frame = page.frames[1]
160    element_handle = frame.evaluate_handle("document.body")
161    assert element_handle.owner_frame() == frame
162
163
164def test_owner_frame_for_cross_process_iframes(page, server, utils):
165    page.goto(server.EMPTY_PAGE)
166    utils.attach_frame(page, "frame1", server.CROSS_PROCESS_PREFIX + "/empty.html")
167    frame = page.frames[1]
168    element_handle = frame.evaluate_handle("document.body")
169    assert element_handle.owner_frame() == frame
170
171
172def test_owner_frame_for_document(page, server, utils):
173    page.goto(server.EMPTY_PAGE)
174    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
175    frame = page.frames[1]
176    element_handle = frame.evaluate_handle("document")
177    assert element_handle.owner_frame() == frame
178
179
180def test_owner_frame_for_iframe_elements(page, server, utils):
181    page.goto(server.EMPTY_PAGE)
182    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
183    frame = page.main_frame
184    element_handle = frame.evaluate_handle('document.querySelector("#frame1")')
185    print(element_handle)
186    assert element_handle.owner_frame() == frame
187
188
189def test_owner_frame_for_cross_frame_evaluations(page, server, utils):
190    page.goto(server.EMPTY_PAGE)
191    utils.attach_frame(page, "frame1", server.EMPTY_PAGE)
192    frame = page.main_frame
193    element_handle = frame.evaluate_handle(
194        'document.querySelector("#frame1").contentWindow.document.body'
195    )
196    assert element_handle.owner_frame() == frame.child_frames[0]
197
198
199def test_owner_frame_for_detached_elements(page, server):
200    page.goto(server.EMPTY_PAGE)
201    div_handle = page.evaluate_handle(
202        """() => {
203            div = document.createElement('div');
204            document.body.appendChild(div);
205            return div;
206        }"""
207    )
208
209    assert div_handle.owner_frame() == page.main_frame
210    page.evaluate(
211        """() => {
212            div = document.querySelector('div')
213            document.body.removeChild(div)
214        }"""
215    )
216    assert div_handle.owner_frame() == page.main_frame
217
218
219def test_click(page, server):
220    page.goto(server.PREFIX + "/input/button.html")
221    button = page.query_selector("button")
222    button.click()
223    assert page.evaluate("result") == "Clicked"
224
225
226def test_click_with_node_removed(page, server):
227    page.goto(server.PREFIX + "/input/button.html")
228    page.evaluate('delete window["Node"]')
229    button = page.query_selector("button")
230    button.click()
231    assert page.evaluate("result") == "Clicked"
232
233
234def test_click_for_shadow_dom_v1(page, server):
235    page.goto(server.PREFIX + "/shadow.html")
236    button_handle = page.evaluate_handle("button")
237    button_handle.click()
238    assert page.evaluate("clicked")
239
240
241def test_click_for_TextNodes(page, server):
242    page.goto(server.PREFIX + "/input/button.html")
243    buttonTextNode = page.evaluate_handle('document.querySelector("button").firstChild')
244    buttonTextNode.click()
245    assert page.evaluate("result") == "Clicked"
246
247
248def test_click_throw_for_detached_nodes(page, server):
249    page.goto(server.PREFIX + "/input/button.html")
250    button = page.query_selector("button")
251    page.evaluate("button => button.remove()", button)
252    with pytest.raises(Error) as exc_info:
253        button.click()
254    assert "Element is not attached to the DOM" in exc_info.value.message
255
256
257def test_click_throw_for_hidden_nodes_with_force(page, server):
258    page.goto(server.PREFIX + "/input/button.html")
259    button = page.query_selector("button")
260    page.evaluate('button => button.style.display = "none"', button)
261    with pytest.raises(Error) as exc_info:
262        button.click(force=True)
263    assert "Element is not visible" in exc_info.value.message
264
265
266def test_click_throw_for_recursively_hidden_nodes_with_force(page, server):
267    page.goto(server.PREFIX + "/input/button.html")
268    button = page.query_selector("button")
269    page.evaluate('button => button.parentElement.style.display = "none"', button)
270    with pytest.raises(Error) as exc_info:
271        button.click(force=True)
272    assert "Element is not visible" in exc_info.value.message
273
274
275def test_click_throw_for__br__elements_with_force(page, server):
276    page.set_content("hello<br>goodbye")
277    br = page.query_selector("br")
278    with pytest.raises(Error) as exc_info:
279        br.click(force=True)
280    assert "Element is outside of the viewport" in exc_info.value.message
281
282
283def test_double_click_the_button(page, server):
284    page.goto(server.PREFIX + "/input/button.html")
285    page.evaluate(
286        """() => {
287            window.double = false;
288            button = document.querySelector('button');
289            button.addEventListener('dblclick', event => {
290            window.double = true;
291            });
292        }"""
293    )
294    button = page.query_selector("button")
295    button.dblclick()
296    assert page.evaluate("double")
297    assert page.evaluate("result") == "Clicked"
298
299
300def test_hover(page, server):
301    page.goto(server.PREFIX + "/input/scrollable.html")
302    button = page.query_selector("#button-6")
303    button.hover()
304    assert page.evaluate('document.querySelector("button:hover").id') == "button-6"
305
306
307def test_hover_when_node_is_removed(page, server):
308    page.goto(server.PREFIX + "/input/scrollable.html")
309    page.evaluate('delete window["Node"]')
310    button = page.query_selector("#button-6")
311    button.hover()
312    assert page.evaluate('document.querySelector("button:hover").id') == "button-6"
313
314
315def test_scroll(page, server):
316    page.goto(server.PREFIX + "/offscreenbuttons.html")
317    for i in range(11):
318        button = page.query_selector(f"#btn{i}")
319        before = button.evaluate(
320            """button => {
321                return button.getBoundingClientRect().right - window.innerWidth
322            }"""
323        )
324
325        assert before == 10 * i
326        button.scroll_into_view_if_needed()
327        after = button.evaluate(
328            """button => {
329                return button.getBoundingClientRect().right - window.innerWidth
330            }"""
331        )
332
333        assert after <= 0
334        page.evaluate("() => window.scrollTo(0, 0)")
335
336
337def test_scroll_should_throw_for_detached_element(page, server):
338    page.set_content("<div>Hello</div>")
339    div = page.query_selector("div")
340    div.evaluate("div => div.remove()")
341    with pytest.raises(Error) as exc_info:
342        div.scroll_into_view_if_needed()
343    assert "Element is not attached to the DOM" in exc_info.value.message
344
345
346def test_should_timeout_waiting_for_visible(page):
347    page.set_content('<div style="display:none">Hello</div>')
348    div = page.query_selector("div")
349    with pytest.raises(Error) as exc_info:
350        div.scroll_into_view_if_needed(timeout=3000)
351    assert "element is not visible" in exc_info.value.message
352
353
354def test_fill_input(page, server):
355    page.goto(server.PREFIX + "/input/textarea.html")
356    handle = page.query_selector("input")
357    handle.fill("some value")
358    assert page.evaluate("result") == "some value"
359
360
361def test_fill_input_when_Node_is_removed(page, server):
362    page.goto(server.PREFIX + "/input/textarea.html")
363    page.evaluate('delete window["Node"]')
364    handle = page.query_selector("input")
365    handle.fill("some value")
366    assert page.evaluate("result") == "some value"
367
368
369def test_select_textarea(page, server, is_firefox):
370    page.goto(server.PREFIX + "/input/textarea.html")
371    textarea = page.query_selector("textarea")
372    textarea.evaluate('textarea => textarea.value = "some value"')
373    textarea.select_text()
374    if is_firefox:
375        assert textarea.evaluate("el => el.selectionStart") == 0
376        assert textarea.evaluate("el => el.selectionEnd") == 10
377    else:
378        assert page.evaluate("() => window.getSelection().toString()") == "some value"
379
380
381def test_select_input(page, server, is_firefox):
382    page.goto(server.PREFIX + "/input/textarea.html")
383    input = page.query_selector("input")
384    input.evaluate('input => input.value = "some value"')
385    input.select_text()
386    if is_firefox:
387        assert input.evaluate("el => el.selectionStart") == 0
388        assert input.evaluate("el => el.selectionEnd") == 10
389    else:
390        assert page.evaluate("() => window.getSelection().toString()") == "some value"
391
392
393def test_select_text_select_plain_div(page, server):
394    page.goto(server.PREFIX + "/input/textarea.html")
395    div = page.query_selector("div.plain")
396    div.select_text()
397    assert page.evaluate("() => window.getSelection().toString()") == "Plain div"
398
399
400def test_select_text_timeout_waiting_for_invisible_element(page, server):
401    page.goto(server.PREFIX + "/input/textarea.html")
402    textarea = page.query_selector("textarea")
403    textarea.evaluate('e => e.style.display = "none"')
404    with pytest.raises(Error) as exc_info:
405        textarea.select_text(timeout=3000)
406    assert "element is not visible" in exc_info.value.message
407
408
409def test_a_nice_preview(page, server):
410    page.goto(f"{server.PREFIX}/dom.html")
411    outer = page.query_selector("#outer")
412    inner = page.query_selector("#inner")
413    check = page.query_selector("#check")
414    text = inner.evaluate_handle("e => e.firstChild")
415    page.evaluate("1")  # Give them a chance to calculate the preview.
416    assert str(outer) == '[email protected]<div id="outer" name="value">…</div>'
417    assert str(inner) == '[email protected]<div id="inner">Text,↵more text</div>'
418    assert str(text) == "[email protected]#text=Text,↵more text"
419    assert (
420        str(check) == '[email protected]<input checked id="check" foo="bar"" type="checkbox"/>'
421    )
422
423
424def test_get_attribute(page, server):
425    page.goto(f"{server.PREFIX}/dom.html")
426    handle = page.query_selector("#outer")
427    assert handle.get_attribute("name") == "value"
428    assert page.get_attribute("#outer", "name") == "value"
429
430
431def test_inner_html(page, server):
432    page.goto(f"{server.PREFIX}/dom.html")
433    handle = page.query_selector("#outer")
434    assert handle.inner_html() == '<div id="inner">Text,\nmore text</div>'
435    assert page.inner_html("#outer") == '<div id="inner">Text,\nmore text</div>'
436
437
438def test_inner_text(page, server):
439    page.goto(f"{server.PREFIX}/dom.html")
440    handle = page.query_selector("#inner")
441    assert handle.inner_text() == "Text, more text"
442    assert page.inner_text("#inner") == "Text, more text"
443
444
445def test_inner_text_should_throw(page, server):
446    page.set_content("<svg>text</svg>")
447    with pytest.raises(Error) as exc_info1:
448        page.inner_text("svg")
449    assert "Not an HTMLElement" in exc_info1.value.message
450
451    handle = page.query_selector("svg")
452    with pytest.raises(Error) as exc_info2:
453        handle.inner_text()
454    assert "Not an HTMLElement" in exc_info2.value.message
455
456
457def test_text_content(page, server):
458    page.goto(f"{server.PREFIX}/dom.html")
459    handle = page.query_selector("#inner")
460    assert handle.text_content() == "Text,\nmore text"
461    assert page.text_content("#inner") == "Text,\nmore text"
462
463
464def test_check_the_box(page):
465    page.set_content('<input id="checkbox" type="checkbox"></input>')
466    input = page.query_selector("input")
467    input.check()
468    assert page.evaluate("checkbox.checked")
469
470
471def test_uncheck_the_box(page):
472    page.set_content('<input id="checkbox" type="checkbox" checked></input>')
473    input = page.query_selector("input")
474    input.uncheck()
475    assert page.evaluate("checkbox.checked") is False
476
477
478def test_select_single_option(page, server):
479    page.goto(server.PREFIX + "/input/select.html")
480    select = page.query_selector("select")
481    select.select_option(value="blue")
482    assert page.evaluate("result.onInput") == ["blue"]
483    assert page.evaluate("result.onChange") == ["blue"]
484
485
486def test_focus_a_button(page, server):
487    page.goto(server.PREFIX + "/input/button.html")
488    button = page.query_selector("button")
489    assert button.evaluate("button => document.activeElement === button") is False
490    button.focus()
491    assert button.evaluate("button => document.activeElement === button")
492
493
494def test_is_visible_and_is_hidden_should_work(page):
495    page.set_content("<div>Hi</div><span></span>")
496    div = page.query_selector("div")
497    assert div.is_visible()
498    assert div.is_hidden() is False
499    assert page.is_visible("div")
500    assert page.is_hidden("div") is False
501    span = page.query_selector("span")
502    assert span.is_visible() is False
503    assert span.is_hidden()
504    assert page.is_visible("span") is False
505    assert page.is_hidden("span")
506
507
508def test_is_enabled_and_is_disabled_should_work(page):
509    page.set_content(
510        """
511        <button disabled>button1</button>
512        <button>button2</button>
513        <div>div</div>
514    """
515    )
516    div = page.query_selector("div")
517    assert div.is_enabled()
518    assert div.is_disabled() is False
519    assert page.is_enabled("div")
520    assert page.is_disabled("div") is False
521    button1 = page.query_selector(":text('button1')")
522    assert button1.is_enabled() is False
523    assert button1.is_disabled()
524    assert page.is_enabled(":text('button1')") is False
525    assert page.is_disabled(":text('button1')")
526    button2 = page.query_selector(":text('button2')")
527    assert button2.is_enabled()
528    assert button2.is_disabled() is False
529    assert page.is_enabled(":text('button2')")
530    assert page.is_disabled(":text('button2')") is False
531
532
533def test_is_editable_should_work(page):
534    page.set_content("<input id=input1 disabled><textarea></textarea><input id=input2>")
535    page.eval_on_selector("textarea", "t => t.readOnly = true")
536    input1 = page.query_selector("#input1")
537    assert input1.is_editable() is False
538    assert page.is_editable("#input1") is False
539    input2 = page.query_selector("#input2")
540    assert input2.is_editable()
541    assert page.is_editable("#input2")
542    textarea = page.query_selector("textarea")
543    assert textarea.is_editable() is False
544    assert page.is_editable("textarea") is False
545
546
547def test_is_checked_should_work(page):
548    page.set_content('<input type="checkbox" checked><div>Not a checkbox</div>')
549    handle = page.query_selector("input")
550    assert handle.is_checked()
551    assert page.is_checked("input")
552    handle.evaluate("input => input.checked = false")
553    assert handle.is_checked() is False
554    assert page.is_checked("input") is False
555    with pytest.raises(Error) as exc_info:
556        page.is_checked("div")
557    assert "Not a checkbox or radio button" in exc_info.value.message
558
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)