How to use test_should_support_reduced_motion 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_defaultbrowsercontext.py

Source: test_defaultbrowsercontext.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
16import os
17
18import pytest
19
20from playwright._impl._api_types import Error
21
22
23@pytest.fixture()
24async def launch_persistent(tmpdir, launch_arguments, browser_type):
25    context = None
26
27    async def _launch(**options):
28        nonlocal context
29        if context:
30            raise ValueError("can only launch one persitent context")
31        context = await browser_type.launch_persistent_context(
32            str(tmpdir), **{**launch_arguments, **options}
33        )
34        return (context.pages[0], context)
35
36    yield _launch
37    await context.close()
38
39
40async def test_context_cookies_should_work(server, launch_persistent, is_chromium):
41    (page, context) = await launch_persistent()
42    await page.goto(server.EMPTY_PAGE)
43    document_cookie = await page.evaluate(
44        """() => {
45    document.cookie = 'username=John Doe';
46    return document.cookie;
47  }"""
48    )
49
50    assert document_cookie == "username=John Doe"
51    assert await page.context.cookies() == [
52        {
53            "name": "username",
54            "value": "John Doe",
55            "domain": "localhost",
56            "path": "/",
57            "expires": -1,
58            "httpOnly": False,
59            "secure": False,
60            "sameSite": "Lax" if is_chromium else "None",
61        }
62    ]
63
64
65async def test_context_add_cookies_should_work(server, launch_persistent, is_chromium):
66    (page, context) = await launch_persistent()
67    await page.goto(server.EMPTY_PAGE)
68    await page.context.add_cookies(
69        [{"url": server.EMPTY_PAGE, "name": "username", "value": "John Doe"}]
70    )
71    assert await page.evaluate("() => document.cookie") == "username=John Doe"
72    assert await page.context.cookies() == [
73        {
74            "name": "username",
75            "value": "John Doe",
76            "domain": "localhost",
77            "path": "/",
78            "expires": -1,
79            "httpOnly": False,
80            "secure": False,
81            "sameSite": "Lax" if is_chromium else "None",
82        }
83    ]
84
85
86async def test_context_clear_cookies_should_work(server, launch_persistent):
87    (page, context) = await launch_persistent()
88    await page.goto(server.EMPTY_PAGE)
89    await page.context.add_cookies(
90        [
91            {"url": server.EMPTY_PAGE, "name": "cookie1", "value": "1"},
92            {"url": server.EMPTY_PAGE, "name": "cookie2", "value": "2"},
93        ]
94    )
95    assert await page.evaluate("document.cookie") == "cookie1=1; cookie2=2"
96    await page.context.clear_cookies()
97    await page.reload()
98    assert await page.context.cookies([]) == []
99    assert await page.evaluate("document.cookie") == ""
100
101
102async def test_should_not_block_third_party_cookies(
103    server, launch_persistent, is_chromium, is_firefox
104):
105    (page, context) = await launch_persistent()
106    await page.goto(server.EMPTY_PAGE)
107    await page.evaluate(
108        """src => {
109    let fulfill;
110    const promise = new Promise(x => fulfill = x);
111    const iframe = document.createElement('iframe');
112    document.body.appendChild(iframe);
113    iframe.onload = fulfill;
114    iframe.src = src;
115    return promise;
116  }""",
117        server.CROSS_PROCESS_PREFIX + "/grid.html",
118    )
119    document_cookie = await page.frames[1].evaluate(
120        """() => {
121    document.cookie = 'username=John Doe';
122    return document.cookie;
123  }"""
124    )
125
126    await page.wait_for_timeout(2000)
127    allows_third_party = is_firefox
128    assert document_cookie == ("username=John Doe" if allows_third_party else "")
129    cookies = await context.cookies(server.CROSS_PROCESS_PREFIX + "/grid.html")
130    if allows_third_party:
131        assert cookies == [
132            {
133                "domain": "127.0.0.1",
134                "expires": -1,
135                "httpOnly": False,
136                "name": "username",
137                "path": "/",
138                "sameSite": "None",
139                "secure": False,
140                "value": "John Doe",
141            }
142        ]
143    else:
144        assert cookies == []
145
146
147async def test_should_support_viewport_option(launch_persistent, utils):
148    (page, context) = await launch_persistent(viewport={"width": 456, "height": 789})
149    await utils.verify_viewport(page, 456, 789)
150    page2 = await context.new_page()
151    await utils.verify_viewport(page2, 456, 789)
152
153
154async def test_should_support_device_scale_factor_option(launch_persistent, utils):
155    (page, context) = await launch_persistent(device_scale_factor=3)
156    assert await page.evaluate("window.devicePixelRatio") == 3
157
158
159async def test_should_support_user_agent_option(launch_persistent, server):
160    (page, context) = await launch_persistent(user_agent="foobar")
161    assert await page.evaluate("() => navigator.userAgent") == "foobar"
162    [request, _] = await asyncio.gather(
163        server.wait_for_request("/empty.html"),
164        page.goto(server.EMPTY_PAGE),
165    )
166    assert request.getHeader("user-agent") == "foobar"
167
168
169async def test_should_support_bypass_csp_option(launch_persistent, server):
170    (page, context) = await launch_persistent(bypass_csp=True)
171    await page.goto(server.PREFIX + "/csp.html")
172    await page.add_script_tag(content="window.__injected = 42;")
173    assert await page.evaluate("() => window.__injected") == 42
174
175
176async def test_should_support_javascript_enabled_option(launch_persistent, is_webkit):
177    (page, context) = await launch_persistent(java_script_enabled=False)
178    await page.goto('data:text/html, <script>var something = "forbidden"</script>')
179    with pytest.raises(Error) as exc:
180        await page.evaluate("something")
181    if is_webkit:
182        assert "Can't find variable: something" in exc.value.message
183    else:
184        assert "something is not defined" in exc.value.message
185
186
187async def test_should_support_http_credentials_option(server, launch_persistent):
188    (page, context) = await launch_persistent(
189        http_credentials={"username": "user", "password": "pass"}
190    )
191    server.set_auth("/playground.html", "user", "pass")
192    response = await page.goto(server.PREFIX + "/playground.html")
193    assert response.status == 200
194
195
196async def test_should_support_offline_option(server, launch_persistent):
197    (page, context) = await launch_persistent(offline=True)
198    with pytest.raises(Error):
199        await page.goto(server.EMPTY_PAGE)
200
201
202async def test_should_support_has_touch_option(server, launch_persistent):
203    (page, context) = await launch_persistent(has_touch=True)
204    await page.goto(server.PREFIX + "/mobile.html")
205    assert await page.evaluate('() => "ontouchstart" in window')
206
207
208@pytest.mark.skip_browser("firefox")
209async def test_should_work_in_persistent_context(server, launch_persistent):
210    # Firefox does not support mobile.
211    (page, context) = await launch_persistent(
212        viewport={"width": 320, "height": 480}, is_mobile=True
213    )
214    await page.goto(server.PREFIX + "/empty.html")
215    assert await page.evaluate("() => window.innerWidth") == 980
216
217
218async def test_should_support_color_scheme_option(server, launch_persistent):
219    (page, context) = await launch_persistent(color_scheme="dark")
220    assert (
221        await page.evaluate('() => matchMedia("(prefers-color-scheme: light)").matches')
222        is False
223    )
224    assert await page.evaluate(
225        '() => matchMedia("(prefers-color-scheme: dark)").matches'
226    )
227
228
229async def test_should_support_timezone_id_option(launch_persistent):
230    (page, context) = await launch_persistent(timezone_id="America/Jamaica")
231    assert (
232        await page.evaluate("() => new Date(1479579154987).toString()")
233        == "Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)"
234    )
235
236
237async def test_should_support_locale_option(launch_persistent):
238    (page, context) = await launch_persistent(locale="fr-CH")
239    assert await page.evaluate("() => navigator.language") == "fr-CH"
240
241
242async def test_should_support_geolocation_and_permission_option(
243    server, launch_persistent
244):
245    (page, context) = await launch_persistent(
246        geolocation={"longitude": 10, "latitude": 10}, permissions=["geolocation"]
247    )
248    await page.goto(server.EMPTY_PAGE)
249    geolocation = await page.evaluate(
250        """() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
251    resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
252  }))"""
253    )
254    assert geolocation == {"latitude": 10, "longitude": 10}
255
256
257async def test_should_support_ignore_https_errors_option(
258    https_server, launch_persistent
259):
260    (page, context) = await launch_persistent(ignore_https_errors=True)
261    response = await page.goto(https_server.EMPTY_PAGE)
262    assert response.ok
263
264
265async def test_should_support_extra_http_headers_option(server, launch_persistent):
266    (page, context) = await launch_persistent(extra_http_headers={"foo": "bar"})
267    [request, _] = await asyncio.gather(
268        server.wait_for_request("/empty.html"),
269        page.goto(server.EMPTY_PAGE),
270    )
271    assert request.getHeader("foo") == "bar"
272
273
274async def test_should_accept_user_data_dir(server, tmpdir, launch_persistent):
275    (page, context) = await launch_persistent()
276    # Note: we need an open page to make sure its functional.
277    assert len(os.listdir(tmpdir)) > 0
278    await context.close()
279    assert len(os.listdir(tmpdir)) > 0
280
281
282async def test_should_restore_state_from_userDataDir(
283    browser_type, launch_arguments, server, tmp_path_factory
284):
285    user_data_dir1 = tmp_path_factory.mktemp("test")
286    browser_context = await browser_type.launch_persistent_context(
287        user_data_dir1, **launch_arguments
288    )
289    page = await browser_context.new_page()
290    await page.goto(server.EMPTY_PAGE)
291    await page.evaluate('() => localStorage.hey = "hello"')
292    await browser_context.close()
293
294    browser_context2 = await browser_type.launch_persistent_context(
295        user_data_dir1, **launch_arguments
296    )
297    page2 = await browser_context2.new_page()
298    await page2.goto(server.EMPTY_PAGE)
299    assert await page2.evaluate("() => localStorage.hey") == "hello"
300    await browser_context2.close()
301
302    user_data_dir2 = tmp_path_factory.mktemp("test")
303    browser_context3 = await browser_type.launch_persistent_context(
304        user_data_dir2, **launch_arguments
305    )
306    page3 = await browser_context3.new_page()
307    await page3.goto(server.EMPTY_PAGE)
308    assert await page3.evaluate("() => localStorage.hey") != "hello"
309    await browser_context3.close()
310
311
312async def test_should_restore_cookies_from_userDataDir(
313    browser_type,
314    launch_arguments,
315    tmp_path_factory,
316    server,
317    is_chromium,
318    is_win,
319    is_mac,
320):
321    if is_chromium and (is_win or is_mac):
322        pytest.skip()
323    userDataDir = tmp_path_factory.mktemp("1")
324    browser_context = await browser_type.launch_persistent_context(
325        userDataDir, **launch_arguments
326    )
327    page = await browser_context.new_page()
328    await page.goto(server.EMPTY_PAGE)
329    document_cookie = await page.evaluate(
330        """() => {
331    document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT';
332    return document.cookie;
333  }"""
334    )
335
336    assert document_cookie == "doSomethingOnlyOnce=true"
337    await browser_context.close()
338
339    browser_context2 = await browser_type.launch_persistent_context(
340        userDataDir, **launch_arguments
341    )
342    page2 = await browser_context2.new_page()
343    await page2.goto(server.EMPTY_PAGE)
344    assert await page2.evaluate("() => document.cookie") == "doSomethingOnlyOnce=true"
345    await browser_context2.close()
346
347    userDataDir2 = tmp_path_factory.mktemp("2")
348    browser_context3 = await browser_type.launch_persistent_context(
349        userDataDir2, **launch_arguments
350    )
351    page3 = await browser_context3.new_page()
352    await page3.goto(server.EMPTY_PAGE)
353    assert await page3.evaluate("() => document.cookie") != "doSomethingOnlyOnce=true"
354    await browser_context3.close()
355
356
357async def test_should_have_default_url_when_launching_browser(launch_persistent):
358    (page, context) = await launch_persistent()
359    urls = list(map(lambda p: p.url, context.pages))
360    assert urls == ["about:blank"]
361
362
363@pytest.mark.skip_browser("firefox")
364async def test_should_throw_if_page_argument_is_passed(
365    browser_type, server, tmpdir, launch_arguments
366):
367    options = {**launch_arguments, "args": [server.EMPTY_PAGE]}
368    with pytest.raises(Error) as exc:
369        await browser_type.launch_persistent_context(tmpdir, **options)
370    assert "can not specify page" in exc.value.message
371
372
373async def test_should_fire_close_event_for_a_persistent_context(launch_persistent):
374    (page, context) = await launch_persistent()
375    fired_event = asyncio.Future()
376    context.on("close", lambda: fired_event.set_result(True))
377    await context.close()
378    await fired_event
379
380
381async def test_should_support_reduced_motion(launch_persistent):
382    (page, context) = await launch_persistent(reduced_motion="reduce")
383    assert await page.evaluate("matchMedia('(prefers-reduced-motion: reduce)').matches")
384
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)