How to use test_should_work_with_empty_url 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_popup.py

Source: test_popup.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 asyncio
16from typing import List
17
18from playwright.async_api import Browser, Route
19
20
21async def test_link_navigation_inherit_user_agent_from_browser_context(
22    browser: Browser, server
23):
24    context = await browser.new_context(user_agent="hey")
25
26    page = await context.new_page()
27    await page.goto(server.EMPTY_PAGE)
28    await page.set_content(
29        '<a target=_blank rel=noopener href="/popup/popup.html">link</a>'
30    )
31    request_waitable = asyncio.create_task(server.wait_for_request("/popup/popup.html"))
32    await asyncio.sleep(0)  # execute scheduled tasks, but don't await them
33    async with context.expect_page() as page_info:
34        await page.click("a")
35    popup = await page_info.value
36    await popup.wait_for_load_state("domcontentloaded")
37    user_agent = await popup.evaluate("window.initialUserAgent")
38    request = await request_waitable
39    assert user_agent == "hey"
40    assert request.requestHeaders.getRawHeaders("user-agent") == ["hey"]
41    await context.close()
42
43
44async def test_link_navigation_respect_routes_from_browser_context(context, server):
45    page = await context.new_page()
46    await page.goto(server.EMPTY_PAGE)
47    await page.set_content('<a target=_blank rel=noopener href="empty.html">link</a>')
48
49    intercepted: List[bool] = []
50
51    async def handle_request(route: Route) -> None:
52        intercepted.append(True)
53        await route.continue_()
54
55    await context.route("**/empty.html", handle_request)
56    async with context.expect_page():
57        await page.click("a"),
58    assert intercepted == [True]
59
60
61async def test_window_open_inherit_user_agent_from_browser_context(
62    browser: Browser, server
63):
64    context = await browser.new_context(user_agent="hey")
65
66    page = await context.new_page()
67    await page.goto(server.EMPTY_PAGE)
68    request_promise = asyncio.create_task(server.wait_for_request("/dummy.html"))
69    await asyncio.sleep(0)  # execute scheduled tasks, but don't await them
70    user_agent = await page.evaluate(
71        """url => {
72            win = window.open(url)
73            return win.navigator.userAgent
74        }""",
75        server.PREFIX + "/dummy.html",
76    )
77    request = await request_promise
78    assert user_agent == "hey"
79    assert request.requestHeaders.getRawHeaders("user-agent") == ["hey"]
80    await context.close()
81
82
83async def test_should_inherit_extra_headers_from_browser_context(
84    browser: Browser, server
85):
86    context = await browser.new_context(extra_http_headers={"foo": "bar"})
87
88    page = await context.new_page()
89    await page.goto(server.EMPTY_PAGE)
90    request_promise = asyncio.create_task(server.wait_for_request("/dummy.html"))
91    await asyncio.sleep(0)  # execute scheduled tasks, but don't await them
92    await page.evaluate(
93        "url => window._popup = window.open(url)", server.PREFIX + "/dummy.html"
94    )
95    request = await request_promise
96    assert request.requestHeaders.getRawHeaders("foo") == ["bar"]
97    await context.close()
98
99
100async def test_should_inherit_offline_from_browser_context(context, server):
101    page = await context.new_page()
102    await page.goto(server.EMPTY_PAGE)
103    await context.set_offline(True)
104    online = await page.evaluate(
105        """url => {
106            win = window.open(url)
107            return win.navigator.onLine
108        }""",
109        server.PREFIX + "/dummy.html",
110    )
111    assert online is False
112
113
114async def test_should_inherit_http_credentials_from_browser_context(
115    browser: Browser, server
116):
117    server.set_auth("/title.html", b"user", b"pass")
118    context = await browser.new_context(
119        http_credentials={"username": "user", "password": "pass"}
120    )
121    page = await context.new_page()
122    await page.goto(server.EMPTY_PAGE)
123    async with page.expect_popup() as popup_info:
124        await page.evaluate(
125            "url => window._popup = window.open(url)", server.PREFIX + "/title.html"
126        )
127    popup = await popup_info.value
128    await popup.wait_for_load_state("domcontentloaded")
129    assert await popup.title() == "Woof-Woof"
130    await context.close()
131
132
133async def test_should_inherit_touch_support_from_browser_context(
134    browser: Browser, server
135):
136    context = await browser.new_context(
137        viewport={"width": 400, "height": 500}, has_touch=True
138    )
139
140    page = await context.new_page()
141    await page.goto(server.EMPTY_PAGE)
142    has_touch = await page.evaluate(
143        """() => {
144            win = window.open('')
145            return 'ontouchstart' in win
146        }"""
147    )
148
149    assert has_touch
150    await context.close()
151
152
153async def test_should_inherit_viewport_size_from_browser_context(
154    browser: Browser, server
155):
156    context = await browser.new_context(viewport={"width": 400, "height": 500})
157
158    page = await context.new_page()
159    await page.goto(server.EMPTY_PAGE)
160    size = await page.evaluate(
161        """() => {
162            win = window.open('about:blank')
163            return { width: win.innerWidth, height: win.innerHeight }
164        }"""
165    )
166
167    assert size == {"width": 400, "height": 500}
168    await context.close()
169
170
171async def test_should_use_viewport_size_from_window_features(browser: Browser, server):
172    context = await browser.new_context(viewport={"width": 700, "height": 700})
173    page = await context.new_page()
174    await page.goto(server.EMPTY_PAGE)
175    size = None
176    async with page.expect_popup() as popup_info:
177        size = await page.evaluate(
178            """() => {
179                win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=300,top=0,left=0')
180                return { width: win.innerWidth, height: win.innerHeight }
181            }"""
182        )
183    popup = await popup_info.value
184    await popup.set_viewport_size({"width": 500, "height": 400})
185    await popup.wait_for_load_state()
186    resized = await popup.evaluate(
187        "() => ({ width: window.innerWidth, height: window.innerHeight })"
188    )
189    await context.close()
190    assert size == {"width": 600, "height": 300}
191    assert resized == {"width": 500, "height": 400}
192
193
194async def test_should_respect_routes_from_browser_context(context, server):
195    page = await context.new_page()
196    await page.goto(server.EMPTY_PAGE)
197
198    def handle_request(route, request, intercepted):
199        asyncio.create_task(route.continue_())
200        intercepted.append(True)
201
202    intercepted = []
203    await context.route(
204        "**/empty.html",
205        lambda route, request: handle_request(route, request, intercepted),
206    )
207
208    async with page.expect_popup():
209        await page.evaluate(
210            "url => window.__popup = window.open(url)", server.EMPTY_PAGE
211        )
212    assert len(intercepted) == 1
213
214
215async def test_browser_context_add_init_script_should_apply_to_an_in_process_popup(
216    context, server
217):
218    await context.add_init_script("window.injected = 123")
219    page = await context.new_page()
220    await page.goto(server.EMPTY_PAGE)
221    injected = await page.evaluate(
222        """() => {
223            const win = window.open('about:blank');
224            return win.injected;
225        }"""
226    )
227
228    assert injected == 123
229
230
231async def test_browser_context_add_init_script_should_apply_to_a_cross_process_popup(
232    context, server
233):
234    await context.add_init_script("window.injected = 123")
235    page = await context.new_page()
236    await page.goto(server.EMPTY_PAGE)
237    async with page.expect_popup() as popup_info:
238        await page.evaluate(
239            "url => window.open(url)", server.CROSS_PROCESS_PREFIX + "/title.html"
240        )
241    popup = await popup_info.value
242    assert await popup.evaluate("injected") == 123
243    await popup.reload()
244    assert await popup.evaluate("injected") == 123
245
246
247async def test_should_expose_function_from_browser_context(context, server):
248    await context.expose_function("add", lambda a, b: a + b)
249    page = await context.new_page()
250    await page.goto(server.EMPTY_PAGE)
251    added = await page.evaluate(
252        """async () => {
253            win = window.open('about:blank')
254            return win.add(9, 4)
255        }"""
256    )
257
258    assert added == 13
259
260
261async def test_should_work(context):
262    page = await context.new_page()
263    async with page.expect_popup() as popup_info:
264        await page.evaluate('window.__popup = window.open("about:blank")')
265    popup = await popup_info.value
266    assert await page.evaluate("!!window.opener") is False
267    assert await popup.evaluate("!!window.opener")
268
269
270async def test_should_work_with_window_features(context, server):
271    page = await context.new_page()
272    await page.goto(server.EMPTY_PAGE)
273    async with page.expect_popup() as popup_info:
274        await page.evaluate(
275            'window.__popup = window.open(window.location.href, "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0")'
276        )
277    popup = await popup_info.value
278    assert await page.evaluate("!!window.opener") is False
279    assert await popup.evaluate("!!window.opener")
280
281
282async def test_window_open_emit_for_immediately_closed_popups(context):
283    page = await context.new_page()
284    async with page.expect_popup() as popup_info:
285        await page.evaluate(
286            """() => {
287                win = window.open('about:blank')
288                win.close()
289            }"""
290        )
291    popup = await popup_info.value
292    assert popup
293
294
295async def test_should_emit_for_immediately_closed_popups(context, server):
296    page = await context.new_page()
297    await page.goto(server.EMPTY_PAGE)
298    async with page.expect_popup() as popup_info:
299        await page.evaluate(
300            """() => {
301                win = window.open(window.location.href)
302                win.close()
303            }"""
304        )
305    popup = await popup_info.value
306    assert popup
307
308
309async def test_should_be_able_to_capture_alert(context):
310    page = await context.new_page()
311    evaluate_promise = asyncio.create_task(
312        page.evaluate(
313            """() => {
314                const win = window.open('')
315                win.alert('hello')
316            }"""
317        )
318    )
319
320    popup = await page.wait_for_event("popup")
321    dialog = await popup.wait_for_event("dialog")
322    assert dialog.message == "hello"
323    await dialog.dismiss()
324    await evaluate_promise
325
326
327async def test_should_work_with_empty_url(context):
328    page = await context.new_page()
329    async with page.expect_popup() as popup_info:
330        await page.evaluate("() => window.__popup = window.open('')")
331    popup = await popup_info.value
332    assert await page.evaluate("!!window.opener") is False
333    assert await popup.evaluate("!!window.opener")
334
335
336async def test_should_work_with_noopener_and_no_url(context):
337    page = await context.new_page()
338    async with page.expect_popup() as popup_info:
339        await page.evaluate(
340            '() => window.__popup = window.open(undefined, null, "noopener")'
341        )
342    popup = await popup_info.value
343    # Chromium reports 'about:blank#blocked' here.
344    assert popup.url.split("#")[0] == "about:blank"
345    assert await page.evaluate("!!window.opener") is False
346    assert await popup.evaluate("!!window.opener") is False
347
348
349async def test_should_work_with_noopener_and_about_blank(context):
350    page = await context.new_page()
351    async with page.expect_popup() as popup_info:
352        await page.evaluate(
353            '() => window.__popup = window.open("about:blank", null, "noopener")'
354        )
355    popup = await popup_info.value
356    assert await page.evaluate("!!window.opener") is False
357    assert await popup.evaluate("!!window.opener") is False
358
359
360async def test_should_work_with_noopener_and_url(context, server):
361    page = await context.new_page()
362    await page.goto(server.EMPTY_PAGE)
363    async with page.expect_popup() as popup_info:
364        await page.evaluate(
365            'url => window.__popup = window.open(url, null, "noopener")',
366            server.EMPTY_PAGE,
367        )
368    popup = await popup_info.value
369    assert await page.evaluate("!!window.opener") is False
370    assert await popup.evaluate("!!window.opener") is False
371
372
373async def test_should_work_with_clicking_target__blank(context, server):
374    page = await context.new_page()
375    await page.goto(server.EMPTY_PAGE)
376    await page.set_content(
377        '<a target=_blank rel="opener" href="/one-style.html">yo</a>'
378    )
379    async with page.expect_popup() as popup_info:
380        await page.click("a")
381    popup = await popup_info.value
382    assert await page.evaluate("!!window.opener") is False
383    assert await popup.evaluate("!!window.opener")
384
385
386async def test_should_work_with_fake_clicking_target__blank_and_rel_noopener(
387    context, server
388):
389    page = await context.new_page()
390    await page.goto(server.EMPTY_PAGE)
391    await page.set_content(
392        '<a target=_blank rel=noopener href="/one-style.html">yo</a>'
393    )
394    async with page.expect_popup() as popup_info:
395        await page.eval_on_selector("a", "a => a.click()")
396    popup = await popup_info.value
397    assert await page.evaluate("!!window.opener") is False
398    assert await popup.evaluate("!!window.opener") is False
399
400
401async def test_should_work_with_clicking_target__blank_and_rel_noopener(
402    context, server
403):
404    page = await context.new_page()
405    await page.goto(server.EMPTY_PAGE)
406    await page.set_content(
407        '<a target=_blank rel=noopener href="/one-style.html">yo</a>'
408    )
409    async with page.expect_popup() as popup_info:
410        await page.click("a")
411    popup = await popup_info.value
412    assert await page.evaluate("!!window.opener") is False
413    assert await popup.evaluate("!!window.opener") is False
414
415
416async def test_should_not_treat_navigations_as_new_popups(context, server):
417    page = await context.new_page()
418    await page.goto(server.EMPTY_PAGE)
419    await page.set_content(
420        '<a target=_blank rel=noopener href="/one-style.html">yo</a>'
421    )
422    async with page.expect_popup() as popup_info:
423        await page.click("a")
424    popup = await popup_info.value
425    handled_popups = []
426    page.on(
427        "popup",
428        lambda popup: handled_popups.append(True),
429    )
430
431    await popup.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")
432    assert len(handled_popups) == 0
433
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)