How to use test_should_get_a_non_session_cookie 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_cookies.py

Source: test_browsercontext_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 datetime
16
17import pytest
18
19
20async def test_should_return_no_cookies_in_pristine_browser_context(context):
21    assert await context.cookies() == []
22
23
24async def test_should_get_a_cookie(context, page, server, is_firefox):
25    await page.goto(server.EMPTY_PAGE)
26    document_cookie = await page.evaluate(
27        """() => {
28    document.cookie = 'username=John Doe';
29    return document.cookie;
30  }"""
31    )
32    assert document_cookie == "username=John Doe"
33    assert await context.cookies() == [
34        {
35            "name": "username",
36            "value": "John Doe",
37            "domain": "localhost",
38            "path": "/",
39            "expires": -1,
40            "httpOnly": False,
41            "secure": False,
42            "sameSite": "None",
43        }
44    ]
45
46
47async def test_should_get_a_non_session_cookie(context, page, server, is_firefox):
48    await page.goto(server.EMPTY_PAGE)
49    # @see https://en.wikipedia.org/wiki/Year_2038_problem
50    date = int(datetime.datetime(2038, 1, 1).timestamp() * 1000)
51    document_cookie = await page.evaluate(
52        """timestamp => {
53    const date = new Date(timestamp);
54    document.cookie = `username=John Doe;expires=${date.toUTCString()}`;
55    return document.cookie;
56  }""",
57        date,
58    )
59    assert document_cookie == "username=John Doe"
60    assert await context.cookies() == [
61        {
62            "name": "username",
63            "value": "John Doe",
64            "domain": "localhost",
65            "path": "/",
66            "expires": date / 1000,
67            "httpOnly": False,
68            "secure": False,
69            "sameSite": "None",
70        }
71    ]
72
73
74async def test_should_properly_report_httpOnly_cookie(context, page, server):
75    server.set_route(
76        "/empty.html",
77        lambda r: (
78            r.setHeader("Set-Cookie", "name=value;httpOnly; Path=/"),
79            r.finish(),
80        ),
81    )
82
83    await page.goto(server.EMPTY_PAGE)
84    cookies = await context.cookies()
85    assert len(cookies) == 1
86    assert cookies[0]["httpOnly"] is True
87
88
89async def test_should_properly_report_strict_sameSite_cookie(
90    context, page, server, is_webkit, is_win
91):
92    if is_webkit and is_win:
93        pytest.skip()
94
95    server.set_route(
96        "/empty.html",
97        lambda r: (
98            r.setHeader("Set-Cookie", "name=value;sameSite=Strict"),
99            r.finish(),
100        ),
101    )
102    await page.goto(server.EMPTY_PAGE)
103    cookies = await context.cookies()
104    assert len(cookies) == 1
105    assert cookies[0]["sameSite"] == "Strict"
106
107
108async def test_should_properly_report_lax_sameSite_cookie(
109    context, page, server, is_webkit, is_win
110):
111    if is_webkit and is_win:
112        pytest.skip()
113
114    server.set_route(
115        "/empty.html",
116        lambda r: (
117            r.setHeader("Set-Cookie", "name=value;sameSite=Lax"),
118            r.finish(),
119        ),
120    )
121    await page.goto(server.EMPTY_PAGE)
122    cookies = await context.cookies()
123    assert len(cookies) == 1
124    assert cookies[0]["sameSite"] == "Lax"
125
126
127async def test_should_get_multiple_cookies(context, page, server, is_firefox):
128    await page.goto(server.EMPTY_PAGE)
129    document_cookie = await page.evaluate(
130        """() => {
131    document.cookie = 'username=John Doe';
132    document.cookie = 'password=1234';
133    return document.cookie.split('; ').sort().join('; ');
134  }"""
135    )
136    cookies = await context.cookies()
137    cookies.sort(key=lambda r: r["name"])
138    assert document_cookie == "password=1234; username=John Doe"
139    assert cookies == [
140        {
141            "name": "password",
142            "value": "1234",
143            "domain": "localhost",
144            "path": "/",
145            "expires": -1,
146            "httpOnly": False,
147            "secure": False,
148            "sameSite": "None",
149        },
150        {
151            "name": "username",
152            "value": "John Doe",
153            "domain": "localhost",
154            "path": "/",
155            "expires": -1,
156            "httpOnly": False,
157            "secure": False,
158            "sameSite": "None",
159        },
160    ]
161
162
163async def test_should_get_cookies_from_multiple_urls(context):
164    await context.add_cookies(
165        [
166            {"url": "https://foo.com", "name": "doggo", "value": "woofs"},
167            {"url": "https://bar.com", "name": "catto", "value": "purrs"},
168            {"url": "https://baz.com", "name": "birdo", "value": "tweets"},
169        ]
170    )
171    cookies = await context.cookies(["https://foo.com", "https://baz.com"])
172    cookies.sort(key=lambda r: r["name"])
173
174    assert cookies == [
175        {
176            "name": "birdo",
177            "value": "tweets",
178            "domain": "baz.com",
179            "path": "/",
180            "expires": -1,
181            "httpOnly": False,
182            "secure": True,
183            "sameSite": "None",
184        },
185        {
186            "name": "doggo",
187            "value": "woofs",
188            "domain": "foo.com",
189            "path": "/",
190            "expires": -1,
191            "httpOnly": False,
192            "secure": True,
193            "sameSite": "None",
194        },
195    ]
196
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)