How to use test_should_set_a_cookie_with_a_path 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_add_cookies.py

Source: test_browsercontext_add_cookies.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 datetime
17
18import pytest
19
20from playwright.async_api import Error
21
22
23async def test_should_work(context, page, server):
24    await page.goto(server.EMPTY_PAGE)
25    await context.add_cookies(
26        [{"url": server.EMPTY_PAGE, "name": "password", "value": "123456"}]
27    )
28    assert await page.evaluate("() => document.cookie") == "password=123456"
29
30
31async def test_should_roundtrip_cookie(context, page, server):
32    await page.goto(server.EMPTY_PAGE)
33    # @see https://en.wikipedia.org/wiki/Year_2038_problem
34    date = int(datetime.datetime(2038, 1, 1).timestamp() * 1000)
35    document_cookie = await page.evaluate(
36        """timestamp => {
37    const date = new Date(timestamp);
38    document.cookie = `username=John Doe;expires=${date.toUTCString()}`;
39    return document.cookie;
40  }""",
41        date,
42    )
43    assert document_cookie == "username=John Doe"
44    cookies = await context.cookies()
45    await context.clear_cookies()
46    assert await context.cookies() == []
47    await context.add_cookies(cookies)
48    assert await context.cookies() == cookies
49
50
51async def test_should_send_cookie_header(server, context):
52    cookie = []
53
54    def handler(request):
55        cookie.extend(request.requestHeaders.getRawHeaders("cookie"))
56        request.finish()
57
58    server.set_route("/empty.html", handler)
59    await context.add_cookies(
60        [{"url": server.EMPTY_PAGE, "name": "cookie", "value": "value"}]
61    )
62    page = await context.new_page()
63    await page.goto(server.EMPTY_PAGE)
64    assert cookie == ["cookie=value"]
65
66
67async def test_should_isolate_cookies_in_browser_contexts(context, server, browser):
68    another_context = await browser.new_context()
69    await context.add_cookies(
70        [{"url": server.EMPTY_PAGE, "name": "isolatecookie", "value": "page1value"}]
71    )
72    await another_context.add_cookies(
73        [{"url": server.EMPTY_PAGE, "name": "isolatecookie", "value": "page2value"}]
74    )
75
76    cookies_1 = await context.cookies()
77    cookies_2 = await another_context.cookies()
78    assert len(cookies_1) == 1
79    assert len(cookies_2) == 1
80    assert cookies_1[0]["name"] == "isolatecookie"
81    assert cookies_1[0]["value"] == "page1value"
82    assert cookies_2[0]["name"] == "isolatecookie"
83    assert cookies_2[0]["value"] == "page2value"
84    await another_context.close()
85
86
87async def test_should_isolate_session_cookies(context, server, browser):
88    server.set_route(
89        "/setcookie.html",
90        lambda r: (
91            r.setHeader("Set-Cookie", "session=value"),
92            r.finish(),
93        ),
94    )
95
96    page_1 = await context.new_page()
97    await page_1.goto(server.PREFIX + "/setcookie.html")
98    ##
99    page_2 = await context.new_page()
100    await page_2.goto(server.EMPTY_PAGE)
101    cookies_2 = await context.cookies()
102    assert len(cookies_2) == 1
103    assert ",".join(list(map(lambda c: c["value"], cookies_2))) == "value"
104    ##
105    context_b = await browser.new_context()
106    page_3 = await context_b.new_page()
107    await page_3.goto(server.EMPTY_PAGE)
108    cookies_3 = await context_b.cookies()
109    assert cookies_3 == []
110    await context_b.close()
111
112
113async def test_should_isolate_persistent_cookies(context, server, browser):
114    server.set_route(
115        "/setcookie.html",
116        lambda r: (
117            r.setHeader("Set-Cookie", "persistent=persistent-value; max-age=3600"),
118            r.finish(),
119        ),
120    )
121
122    page = await context.new_page()
123    await page.goto(server.PREFIX + "/setcookie.html")
124
125    context_1 = context
126    context_2 = await browser.new_context()
127    [page_1, page_2] = await asyncio.gather(context_1.new_page(), context_2.new_page())
128    await asyncio.gather(page_1.goto(server.EMPTY_PAGE), page_2.goto(server.EMPTY_PAGE))
129    [cookies_1, cookies_2] = await asyncio.gather(
130        context_1.cookies(), context_2.cookies()
131    )
132    assert len(cookies_1) == 1
133    assert cookies_1[0]["name"] == "persistent"
134    assert cookies_1[0]["value"] == "persistent-value"
135    assert len(cookies_2) == 0
136    await context_2.close()
137
138
139async def test_should_isolate_send_cookie_header(server, context, browser):
140    cookie = []
141
142    def handler(request):
143        cookie.extend(request.requestHeaders.getRawHeaders("cookie") or [])
144        request.finish()
145
146    server.set_route("/empty.html", handler)
147
148    await context.add_cookies(
149        [{"url": server.EMPTY_PAGE, "name": "sendcookie", "value": "value"}]
150    )
151
152    page_1 = await context.new_page()
153    await page_1.goto(server.EMPTY_PAGE)
154    assert cookie == ["sendcookie=value"]
155    cookie.clear()
156    ##
157    context_2 = await browser.new_context()
158    page_2 = await context_2.new_page()
159    await page_2.goto(server.EMPTY_PAGE)
160    assert cookie == []
161    await context_2.close()
162
163
164async def test_should_isolate_cookies_between_launches(browser_factory, server):
165    browser_1 = await browser_factory()
166    context_1 = await browser_1.new_context()
167    await context_1.add_cookies(
168        [
169            {
170                "url": server.EMPTY_PAGE,
171                "name": "cookie-in-context-1",
172                "value": "value",
173                "expires": int(datetime.datetime.now().timestamp() + 10000),
174            }
175        ]
176    )
177    await browser_1.close()
178
179    browser_2 = await browser_factory()
180    context_2 = await browser_2.new_context()
181    cookies = await context_2.cookies()
182    assert cookies == []
183    await browser_2.close()
184
185
186async def test_should_set_multiple_cookies(context, page, server):
187    await page.goto(server.EMPTY_PAGE)
188    await context.add_cookies(
189        [
190            {"url": server.EMPTY_PAGE, "name": "multiple-1", "value": "123456"},
191            {"url": server.EMPTY_PAGE, "name": "multiple-2", "value": "bar"},
192        ]
193    )
194    assert (
195        await page.evaluate(
196            """() => {
197    const cookies = document.cookie.split(';');
198    return cookies.map(cookie => cookie.trim()).sort();
199  }"""
200        )
201        == ["multiple-1=123456", "multiple-2=bar"]
202    )
203
204
205async def test_should_have_expires_set_to_neg_1_for_session_cookies(context, server):
206    await context.add_cookies(
207        [{"url": server.EMPTY_PAGE, "name": "expires", "value": "123456"}]
208    )
209    cookies = await context.cookies()
210    assert cookies[0]["expires"] == -1
211
212
213async def test_should_set_cookie_with_reasonable_defaults(context, server):
214    await context.add_cookies(
215        [{"url": server.EMPTY_PAGE, "name": "defaults", "value": "123456"}]
216    )
217    cookies = await context.cookies()
218    cookies.sort(key=lambda r: r["name"])
219    assert cookies == [
220        {
221            "name": "defaults",
222            "value": "123456",
223            "domain": "localhost",
224            "path": "/",
225            "expires": -1,
226            "httpOnly": False,
227            "secure": False,
228            "sameSite": "None",
229        }
230    ]
231
232
233async def test_should_set_a_cookie_with_a_path(context, page, server):
234    await page.goto(server.PREFIX + "/grid.html")
235    await context.add_cookies(
236        [
237            {
238                "domain": "localhost",
239                "path": "/grid.html",
240                "name": "gridcookie",
241                "value": "GRID",
242            }
243        ]
244    )
245    assert await context.cookies() == [
246        {
247            "name": "gridcookie",
248            "value": "GRID",
249            "domain": "localhost",
250            "path": "/grid.html",
251            "expires": -1,
252            "httpOnly": False,
253            "secure": False,
254            "sameSite": "None",
255        }
256    ]
257    assert await page.evaluate("document.cookie") == "gridcookie=GRID"
258    await page.goto(server.EMPTY_PAGE)
259    assert await page.evaluate("document.cookie") == ""
260    await page.goto(server.PREFIX + "/grid.html")
261    assert await page.evaluate("document.cookie") == "gridcookie=GRID"
262
263
264async def test_should_not_set_a_cookie_with_blank_page_url(context, server):
265    with pytest.raises(Error) as exc_info:
266        await context.add_cookies(
267            [
268                {"url": server.EMPTY_PAGE, "name": "example-cookie", "value": "best"},
269                {"url": "about:blank", "name": "example-cookie-blank", "value": "best"},
270            ]
271        )
272    assert (
273        'Blank page can not have cookie "example-cookie-blank"'
274        in exc_info.value.message
275    )
276
277
278async def test_should_not_set_a_cookie_on_a_data_url_page(context):
279    with pytest.raises(Error) as exc_info:
280        await context.add_cookies(
281            [
282                {
283                    "url": "data:,Hello%2C%20World!",
284                    "name": "example-cookie",
285                    "value": "best",
286                }
287            ]
288        )
289    assert (
290        'Data URL page can not have cookie "example-cookie"' in exc_info.value.message
291    )
292
293
294async def test_should_default_to_setting_secure_cookie_for_https_websites(
295    context, page, server
296):
297    await page.goto(server.EMPTY_PAGE)
298    SECURE_URL = "https://example.com"
299    await context.add_cookies([{"url": SECURE_URL, "name": "foo", "value": "bar"}])
300    [cookie] = await context.cookies(SECURE_URL)
301    assert cookie["secure"]
302
303
304async def test_should_be_able_to_set_unsecure_cookie_for_http_website(
305    context, page, server
306):
307    await page.goto(server.EMPTY_PAGE)
308    HTTP_URL = "http://example.com"
309    await context.add_cookies([{"url": HTTP_URL, "name": "foo", "value": "bar"}])
310    [cookie] = await context.cookies(HTTP_URL)
311    assert not cookie["secure"]
312
313
314async def test_should_set_a_cookie_on_a_different_domain(context, page, server):
315    await page.goto(server.EMPTY_PAGE)
316    await context.add_cookies(
317        [{"url": "https://www.example.com", "name": "example-cookie", "value": "best"}]
318    )
319    assert await page.evaluate("document.cookie") == ""
320    assert await context.cookies("https://www.example.com") == [
321        {
322            "name": "example-cookie",
323            "value": "best",
324            "domain": "www.example.com",
325            "path": "/",
326            "expires": -1,
327            "httpOnly": False,
328            "secure": True,
329            "sameSite": "None",
330        }
331    ]
332
333
334async def test_should_set_cookies_for_a_frame(context, page, server):
335    await page.goto(server.EMPTY_PAGE)
336    await context.add_cookies(
337        [{"url": server.PREFIX, "name": "frame-cookie", "value": "value"}]
338    )
339    await page.evaluate(
340        """src => {
341    let fulfill;
342    const promise = new Promise(x => fulfill = x);
343    const iframe = document.createElement('iframe');
344    document.body.appendChild(iframe);
345    iframe.onload = fulfill;
346    iframe.src = src;
347    return promise;
348  }""",
349        server.PREFIX + "/grid.html",
350    )
351
352    assert await page.frames[1].evaluate("document.cookie") == "frame-cookie=value"
353
354
355async def test_should_not_block_third_party_cookies(
356    context, page, server, is_chromium, is_firefox
357):
358    await page.goto(server.EMPTY_PAGE)
359    await page.evaluate(
360        """src => {
361    let fulfill;
362    const promise = new Promise(x => fulfill = x);
363    const iframe = document.createElement('iframe');
364    document.body.appendChild(iframe);
365    iframe.onload = fulfill;
366    iframe.src = src;
367    return promise;
368  }""",
369        server.CROSS_PROCESS_PREFIX + "/grid.html",
370    )
371    await page.frames[1].evaluate("document.cookie = 'username=John Doe'")
372    await page.wait_for_timeout(2000)
373    allows_third_party = is_chromium or is_firefox
374    cookies = await context.cookies(server.CROSS_PROCESS_PREFIX + "/grid.html")
375
376    if allows_third_party:
377        assert cookies == [
378            {
379                "domain": "127.0.0.1",
380                "expires": -1,
381                "httpOnly": False,
382                "name": "username",
383                "path": "/",
384                "sameSite": "None",
385                "secure": False,
386                "value": "John Doe",
387            }
388        ]
389    else:
390        assert cookies == []
391
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)