How to use test_offline_should_work_with_initial_option 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_browsercontext.py

Source: test_browsercontext.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
16
17import pytest
18
19from playwright.async_api import Error
20
21
22async def test_page_event_should_create_new_context(browser):
23    assert len(browser.contexts) == 0
24    context = await browser.new_context()
25    assert len(browser.contexts) == 1
26    assert context in browser.contexts
27    await context.close()
28    assert len(browser.contexts) == 0
29
30
31async def test_window_open_should_use_parent_tab_context(browser, server):
32    context = await browser.new_context()
33    page = await context.new_page()
34    await page.goto(server.EMPTY_PAGE)
35    async with page.expect_popup() as page_info:
36        await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)
37    popup = await page_info.value
38    assert popup.context == context
39    await context.close()
40
41
42async def test_page_event_should_isolate_localStorage_and_cookies(browser, server):
43    # Create two incognito contexts.
44    context1 = await browser.new_context()
45    context2 = await browser.new_context()
46    assert len(context1.pages) == 0
47    assert len(context2.pages) == 0
48
49    # Create a page in first incognito context.
50    page1 = await context1.new_page()
51    await page1.goto(server.EMPTY_PAGE)
52    await page1.evaluate(
53        """() => {
54            localStorage.setItem('name', 'page1')
55            document.cookie = 'name=page1'
56        }"""
57    )
58
59    assert len(context1.pages) == 1
60    assert len(context2.pages) == 0
61
62    # Create a page in second incognito context.
63    page2 = await context2.new_page()
64    await page2.goto(server.EMPTY_PAGE)
65    await page2.evaluate(
66        """() => {
67            localStorage.setItem('name', 'page2')
68            document.cookie = 'name=page2'
69        }"""
70    )
71
72    assert len(context1.pages) == 1
73    assert len(context2.pages) == 1
74    assert context1.pages[0] == page1
75    assert context2.pages[0] == page2
76
77    # Make sure pages don't share localstorage or cookies.
78    assert await page1.evaluate("localStorage.getItem('name')") == "page1"
79    assert await page1.evaluate("document.cookie") == "name=page1"
80    assert await page2.evaluate("localStorage.getItem('name')") == "page2"
81    assert await page2.evaluate("document.cookie") == "name=page2"
82
83    # Cleanup contexts.
84    await asyncio.gather(context1.close(), context2.close())
85    assert browser.contexts == []
86
87
88async def test_page_event_should_propagate_default_viewport_to_the_page(browser, utils):
89    context = await browser.new_context(viewport={"width": 456, "height": 789})
90    page = await context.new_page()
91    await utils.verify_viewport(page, 456, 789)
92    await context.close()
93
94
95async def test_page_event_should_respect_device_scale_factor(browser):
96    context = await browser.new_context(device_scale_factor=3)
97    page = await context.new_page()
98    assert await page.evaluate("window.devicePixelRatio") == 3
99    await context.close()
100
101
102async def test_page_event_should_not_allow_device_scale_factor_with_null_viewport(
103    browser,
104):
105    with pytest.raises(Error) as exc_info:
106        await browser.new_context(no_viewport=True, device_scale_factor=1)
107    assert (
108        exc_info.value.message
109        == '"deviceScaleFactor" option is not supported with null "viewport"'
110    )
111
112
113async def test_page_event_should_not_allow_is_mobile_with_null_viewport(browser):
114    with pytest.raises(Error) as exc_info:
115        await browser.new_context(no_viewport=True, is_mobile=True)
116    assert (
117        exc_info.value.message
118        == '"isMobile" option is not supported with null "viewport"'
119    )
120
121
122async def test_close_should_work_for_empty_context(browser):
123    context = await browser.new_context()
124    await context.close()
125
126
127async def test_close_should_abort_wait_for_event(browser):
128    context = await browser.new_context()
129    with pytest.raises(Error) as exc_info:
130        async with context.expect_page():
131            await context.close()
132    assert "Context closed" in exc_info.value.message
133
134
135async def test_close_should_be_callable_twice(browser):
136    context = await browser.new_context()
137    await asyncio.gather(
138        context.close(),
139        context.close(),
140    )
141    await context.close()
142
143
144async def test_user_agent_should_work(browser, server):
145    async def baseline():
146        context = await browser.new_context()
147        page = await context.new_page()
148        assert "Mozilla" in await page.evaluate("navigator.userAgent")
149        await context.close()
150
151    await baseline()
152
153    async def override():
154        context = await browser.new_context(user_agent="foobar")
155        page = await context.new_page()
156        [request, _] = await asyncio.gather(
157            server.wait_for_request("/empty.html"),
158            page.goto(server.EMPTY_PAGE),
159        )
160        assert request.getHeader("user-agent") == "foobar"
161        await context.close()
162
163    await override()
164
165
166async def test_user_agent_should_work_for_subframes(browser, server, utils):
167    context = await browser.new_context(user_agent="foobar")
168    page = await context.new_page()
169    [request, _] = await asyncio.gather(
170        server.wait_for_request("/empty.html"),
171        utils.attach_frame(page, "frame1", server.EMPTY_PAGE),
172    )
173    assert request.getHeader("user-agent") == "foobar"
174    await context.close()
175
176
177async def test_user_agent_should_emulate_device_user_agent(playwright, browser, server):
178    context = await browser.new_context(
179        user_agent=playwright.devices["iPhone 6"]["user_agent"]
180    )
181    page = await context.new_page()
182    await page.goto(server.PREFIX + "/mobile.html")
183    assert "iPhone" in await page.evaluate("navigator.userAgent")
184    await context.close()
185
186
187async def test_user_agent_should_make_a_copy_of_default_options(browser, server):
188    options = {"user_agent": "foobar"}
189    context = await browser.new_context(**options)
190    options["user_agent"] = "wrong"
191    page = await context.new_page()
192    [request, _] = await asyncio.gather(
193        server.wait_for_request("/empty.html"),
194        page.goto(server.EMPTY_PAGE),
195    )
196    assert request.getHeader("user-agent") == "foobar"
197    await context.close()
198
199
200async def test_page_event_should_bypass_csp_meta_tag(browser, server):
201    async def baseline():
202        context = await browser.new_context()
203        page = await context.new_page()
204        await page.goto(server.PREFIX + "/csp.html")
205        try:
206            await page.add_script_tag(content="window.__injected = 42;")
207        except Error:
208            pass
209        assert await page.evaluate("window.__injected") is None
210        await context.close()
211
212    await baseline()
213
214    # By-pass CSP and try one more time.
215    async def override():
216        context = await browser.new_context(bypass_csp=True)
217        page = await context.new_page()
218        await page.goto(server.PREFIX + "/csp.html")
219        await page.add_script_tag(content="window.__injected = 42;")
220        assert await page.evaluate("() => window.__injected") == 42
221        await context.close()
222
223    await override()
224
225
226async def test_page_event_should_bypass_csp_header(browser, server):
227    # Make sure CSP prohibits add_script_tag.
228    server.set_csp("/empty.html", 'default-src "self"')
229
230    async def baseline():
231        context = await browser.new_context()
232        page = await context.new_page()
233        await page.goto(server.EMPTY_PAGE)
234        try:
235            await page.add_script_tag(content="window.__injected = 42;")
236        except Error:
237            pass
238        assert await page.evaluate("() => window.__injected") is None
239        await context.close()
240
241    await baseline()
242
243    # By-pass CSP and try one more time.
244    async def override():
245        context = await browser.new_context(bypass_csp=True)
246        page = await context.new_page()
247        await page.goto(server.EMPTY_PAGE)
248        await page.add_script_tag(content="window.__injected = 42;")
249        assert await page.evaluate("window.__injected") == 42
250        await context.close()
251
252    await override()
253
254
255async def test_page_event_should_bypass_after_cross_process_navigation(browser, server):
256    context = await browser.new_context(bypass_csp=True)
257    page = await context.new_page()
258    await page.goto(server.PREFIX + "/csp.html")
259    await page.add_script_tag(content="window.__injected = 42;")
260    assert await page.evaluate("window.__injected") == 42
261
262    await page.goto(server.CROSS_PROCESS_PREFIX + "/csp.html")
263    await page.add_script_tag(content="window.__injected = 42;")
264    assert await page.evaluate("window.__injected") == 42
265    await context.close()
266
267
268async def test_page_event_should_bypass_csp_in_iframes_as_well(browser, server, utils):
269    async def baseline():
270        # Make sure CSP prohibits add_script_tag in an iframe.
271        context = await browser.new_context()
272        page = await context.new_page()
273        await page.goto(server.EMPTY_PAGE)
274        frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")
275        try:
276            await frame.add_script_tag(content="window.__injected = 42;")
277        except Error:
278            pass
279        assert await frame.evaluate("window.__injected") is None
280        await context.close()
281
282    await baseline()
283
284    # By-pass CSP and try one more time.
285    async def override():
286        context = await browser.new_context(bypass_csp=True)
287        page = await context.new_page()
288        await page.goto(server.EMPTY_PAGE)
289        frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")
290        try:
291            await frame.add_script_tag(content="window.__injected = 42;")
292        except Error:
293            pass
294        assert await frame.evaluate("window.__injected") == 42
295        await context.close()
296
297    await override()
298
299
300async def test_csp_should_work(browser, is_webkit):
301    async def baseline():
302        context = await browser.new_context(java_script_enabled=False)
303        page = await context.new_page()
304        await page.goto('data:text/html, <script>var something = "forbidden"</script>')
305        with pytest.raises(Error) as exc_info:
306            await page.evaluate("something")
307            if is_webkit:
308                assert "Can't find variable: something" in exc_info.value.message
309            else:
310                assert "something is not defined" in exc_info.value.message
311        await context.close()
312
313    await baseline()
314
315    async def override():
316        context = await browser.new_context()
317        page = await context.new_page()
318        await page.goto('data:text/html, <script>var something = "forbidden"</script>')
319        assert await page.evaluate("something") == "forbidden"
320        await context.close()
321
322    await override()
323
324
325async def test_csp_should_be_able_to_navigate_after_disabling_javascript(
326    browser, server
327):
328    context = await browser.new_context(java_script_enabled=False)
329    page = await context.new_page()
330    await page.goto(server.EMPTY_PAGE)
331    await context.close()
332
333
334async def test_pages_should_return_all_of_the_pages(context, server):
335    page = await context.new_page()
336    second = await context.new_page()
337    all_pages = context.pages
338    assert len(all_pages) == 2
339    assert page in all_pages
340    assert second in all_pages
341
342
343async def test_pages_should_close_all_belonging_pages_once_closing_context(context):
344    await context.new_page()
345    assert len(context.pages) == 1
346    await context.close()
347    assert context.pages == []
348
349
350async def test_expose_binding_should_work(context):
351    binding_source = []
352
353    def binding(source, a, b):
354        binding_source.append(source)
355        return a + b
356
357    await context.expose_binding("add", lambda source, a, b: binding(source, a, b))
358
359    page = await context.new_page()
360    result = await page.evaluate("add(5, 6)")
361    assert binding_source[0]["context"] == context
362    assert binding_source[0]["page"] == page
363    assert binding_source[0]["frame"] == page.main_frame
364    assert result == 11
365
366
367async def test_expose_function_should_work(context):
368    await context.expose_function("add", lambda a, b: a + b)
369    page = await context.new_page()
370    await page.expose_function("mul", lambda a, b: a * b)
371    await context.expose_function("sub", lambda a, b: a - b)
372    result = await page.evaluate(
373        """async function() {
374      return { mul: await mul(9, 4), add: await add(9, 4), sub: await sub(9, 4) }
375    }"""
376    )
377
378    assert result == {"mul": 36, "add": 13, "sub": 5}
379
380
381async def test_expose_function_should_throw_for_duplicate_registrations(
382    context, server
383):
384    await context.expose_function("foo", lambda: None)
385    await context.expose_function("bar", lambda: None)
386    with pytest.raises(Error) as exc_info:
387        await context.expose_function("foo", lambda: None)
388    assert exc_info.value.message == 'Function "foo" has been already registered'
389    page = await context.new_page()
390    with pytest.raises(Error) as exc_info:
391        await page.expose_function("foo", lambda: None)
392    assert (
393        exc_info.value.message
394        == 'Function "foo" has been already registered in the browser context'
395    )
396    await page.expose_function("baz", lambda: None)
397    with pytest.raises(Error) as exc_info:
398        await context.expose_function("baz", lambda: None)
399    assert (
400        exc_info.value.message
401        == 'Function "baz" has been already registered in one of the pages'
402    )
403
404
405async def test_expose_function_should_be_callable_from_inside_add_init_script(
406    context, server
407):
408    args = []
409    await context.expose_function("woof", lambda arg: args.append(arg))
410    await context.add_init_script("woof('context')")
411    page = await context.new_page()
412    await page.add_init_script("woof('page')")
413    args = []
414    await page.reload()
415    assert args == ["context", "page"]
416
417
418async def test_expose_bindinghandle_should_work(context):
419    targets = []
420
421    def logme(t):
422        targets.append(t)
423        return 17
424
425    page = await context.new_page()
426    await page.expose_binding("logme", lambda source, t: logme(t), handle=True)
427    result = await page.evaluate("logme({ foo: 42 })")
428    assert (await targets[0].evaluate("x => x.foo")) == 42
429    assert result == 17
430
431
432async def test_route_should_intercept(context, server):
433    intercepted = []
434
435    def handle(route, request):
436        intercepted.append(True)
437        assert "empty.html" in request.url
438        assert request.headers["user-agent"]
439        assert request.method == "GET"
440        assert request.post_data is None
441        assert request.is_navigation_request
442        assert request.resource_type == "document"
443        assert request.frame == page.main_frame
444        assert request.frame.url == "about:blank"
445        asyncio.create_task(route.continue_())
446
447    await context.route("**/empty.html", lambda route, request: handle(route, request))
448    page = await context.new_page()
449    response = await page.goto(server.EMPTY_PAGE)
450    assert response.ok
451    assert intercepted == [True]
452    await context.close()
453
454
455async def test_route_should_unroute(context, server):
456    page = await context.new_page()
457
458    intercepted = []
459
460    def handler(route, request, ordinal):
461        intercepted.append(ordinal)
462        asyncio.create_task(route.continue_())
463
464    def handler1(route, request):
465        handler(route, request, 1)
466
467    await context.route("**/empty.html", handler1)
468    await context.route(
469        "**/empty.html", lambda route, request: handler(route, request, 2)
470    )
471    await context.route(
472        "**/empty.html", lambda route, request: handler(route, request, 3)
473    )
474    await context.route("**/*", lambda route, request: handler(route, request, 4))
475
476    await page.goto(server.EMPTY_PAGE)
477    assert intercepted == [1]
478
479    intercepted = []
480    await context.unroute("**/empty.html", handler1)
481    await page.goto(server.EMPTY_PAGE)
482    assert intercepted == [2]
483
484    intercepted = []
485    await context.unroute("**/empty.html")
486    await page.goto(server.EMPTY_PAGE)
487    assert intercepted == [4]
488
489
490async def test_route_should_yield_to_page_route(context, server):
491    await context.route(
492        "**/empty.html",
493        lambda route, request: asyncio.create_task(
494            route.fulfill(status=200, body="context")
495        ),
496    )
497
498    page = await context.new_page()
499    await page.route(
500        "**/empty.html",
501        lambda route, request: asyncio.create_task(
502            route.fulfill(status=200, body="page")
503        ),
504    )
505
506    response = await page.goto(server.EMPTY_PAGE)
507    assert response.ok
508    assert await response.text() == "page"
509
510
511async def test_route_should_fall_back_to_context_route(context, server):
512    await context.route(
513        "**/empty.html",
514        lambda route, request: asyncio.create_task(
515            route.fulfill(status=200, body="context")
516        ),
517    )
518
519    page = await context.new_page()
520    await page.route(
521        "**/non-empty.html",
522        lambda route, request: asyncio.create_task(
523            route.fulfill(status=200, body="page")
524        ),
525    )
526
527    response = await page.goto(server.EMPTY_PAGE)
528    assert response.ok
529    assert await response.text() == "context"
530
531
532async def test_auth_should_fail_without_credentials(context, server):
533    server.set_auth("/empty.html", b"user", b"pass")
534    page = await context.new_page()
535    response = await page.goto(server.EMPTY_PAGE)
536    assert response.status == 401
537
538
539async def test_auth_should_work_with_correct_credentials(browser, server):
540    server.set_auth("/empty.html", b"user", b"pass")
541    context = await browser.new_context(
542        http_credentials={"username": "user", "password": "pass"}
543    )
544    page = await context.new_page()
545    response = await page.goto(server.EMPTY_PAGE)
546    assert response.status == 200
547    await context.close()
548
549
550async def test_auth_should_fail_with_wrong_credentials(browser, server):
551    server.set_auth("/empty.html", b"user", b"pass")
552    context = await browser.new_context(
553        http_credentials={"username": "foo", "password": "bar"}
554    )
555    page = await context.new_page()
556    response = await page.goto(server.EMPTY_PAGE)
557    assert response.status == 401
558    await context.close()
559
560
561async def test_auth_should_return_resource_body(browser, server):
562    server.set_auth("/playground.html", b"user", b"pass")
563    context = await browser.new_context(
564        http_credentials={"username": "user", "password": "pass"}
565    )
566    page = await context.new_page()
567    response = await page.goto(server.PREFIX + "/playground.html")
568    assert response.status == 200
569    assert await page.title() == "Playground"
570    assert "Playground" in await response.text()
571    await context.close()
572
573
574async def test_offline_should_work_with_initial_option(browser, server):
575    context = await browser.new_context(offline=True)
576    page = await context.new_page()
577    with pytest.raises(Error) as exc_info:
578        await page.goto(server.EMPTY_PAGE)
579    assert exc_info.value
580    await context.set_offline(False)
581    response = await page.goto(server.EMPTY_PAGE)
582    assert response.status == 200
583    await context.close()
584
585
586async def test_offline_should_emulate_navigator_online(context, server):
587    page = await context.new_page()
588    assert await page.evaluate("window.navigator.onLine")
589    await context.set_offline(True)
590    assert await page.evaluate("window.navigator.onLine") is False
591    await context.set_offline(False)
592    assert await page.evaluate("window.navigator.onLine")
593
594
595async def test_page_event_should_have_url(context, server):
596    page = await context.new_page()
597    async with context.expect_page() as other_page_info:
598        await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)
599    other_page = await other_page_info.value
600    assert other_page.url == server.EMPTY_PAGE
601
602
603async def test_page_event_should_have_url_after_domcontentloaded(context, server):
604    page = await context.new_page()
605    async with context.expect_page() as other_page_info:
606        await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)
607    other_page = await other_page_info.value
608    await other_page.wait_for_load_state("domcontentloaded")
609    assert other_page.url == server.EMPTY_PAGE
610
611
612async def test_page_event_should_have_about_blank_url_with_domcontentloaded(
613    context, server
614):
615    page = await context.new_page()
616    async with context.expect_page() as other_page_info:
617        await page.evaluate("url => window.open(url)", "about:blank")
618    other_page = await other_page_info.value
619    await other_page.wait_for_load_state("domcontentloaded")
620    assert other_page.url == "about:blank"
621
622
623async def test_page_event_should_have_about_blank_for_empty_url_with_domcontentloaded(
624    context, server
625):
626    page = await context.new_page()
627    async with context.expect_page() as other_page_info:
628        await page.evaluate("window.open()")
629    other_page = await other_page_info.value
630    await other_page.wait_for_load_state("domcontentloaded")
631    assert other_page.url == "about:blank"
632
633
634async def test_page_event_should_report_when_a_new_page_is_created_and_closed(
635    context, server
636):
637    page = await context.new_page()
638    async with context.expect_page() as page_info:
639        await page.evaluate(
640            "url => window.open(url)", server.CROSS_PROCESS_PREFIX + "/empty.html"
641        )
642    other_page = await page_info.value
643
644    # The url is about:blank in FF when 'page' event is fired.
645    assert server.CROSS_PROCESS_PREFIX in other_page.url
646    assert await other_page.evaluate("['Hello', 'world'].join(' ')") == "Hello world"
647    assert await other_page.query_selector("body")
648
649    all_pages = context.pages
650    assert page in all_pages
651    assert other_page in all_pages
652
653    close_event_received = []
654    other_page.once("close", lambda: close_event_received.append(True))
655    await other_page.close()
656    assert close_event_received == [True]
657
658    all_pages = context.pages
659    assert page in all_pages
660    assert other_page not in all_pages
661
662
663async def test_page_event_should_report_initialized_pages(context, server):
664    async with context.expect_page() as page_info:
665        await context.new_page()
666    new_page = await page_info.value
667    assert new_page.url == "about:blank"
668
669    async with context.expect_page() as popup_info:
670        await new_page.evaluate("window.open('about:blank')")
671    popup = await popup_info.value
672    assert popup.url == "about:blank"
673
674
675async def test_page_event_should_have_an_opener(context, server):
676    page = await context.new_page()
677    await page.goto(server.EMPTY_PAGE)
678    async with context.expect_page() as page_info:
679        await page.goto(server.PREFIX + "/popup/window-open.html"),
680    popup = await page_info.value
681    assert popup.url == server.PREFIX + "/popup/popup.html"
682    assert await popup.opener() == page
683    assert await page.opener() is None
684
685
686async def test_page_event_should_fire_page_lifecycle_events(context, server):
687    events = []
688
689    def handle_page(page):
690        events.append("CREATED: " + page.url)
691        page.on("close", lambda: events.append("DESTROYED: " + page.url))
692
693    context.on("page", handle_page)
694
695    page = await context.new_page()
696    await page.goto(server.EMPTY_PAGE)
697    await page.close()
698    assert events == ["CREATED: about:blank", f"DESTROYED: {server.EMPTY_PAGE}"]
699
700
701@pytest.mark.skip_browser("webkit")
702async def test_page_event_should_work_with_shift_clicking(context, server):
703    # WebKit: Shift+Click does not open a new window.
704    page = await context.new_page()
705    await page.goto(server.EMPTY_PAGE)
706    await page.set_content('<a href="/one-style.html">yo</a>')
707    async with context.expect_page() as page_info:
708        await page.click("a", modifiers=["Shift"])
709    popup = await page_info.value
710    assert await popup.opener() is None
711
712
713@pytest.mark.only_browser("chromium")
714async def test_page_event_should_work_with_ctrl_clicking(context, server, is_mac):
715    # Firefox: reports an opener in this case.
716    # WebKit: Ctrl+Click does not open a new tab.
717    page = await context.new_page()
718    await page.goto(server.EMPTY_PAGE)
719    await page.set_content('<a href="/one-style.html">yo</a>')
720    async with context.expect_page() as popup_info:
721        await page.click("a", modifiers=["Meta" if is_mac else "Control"])
722    popup = await popup_info.value
723    assert await popup.opener() is None
724
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)