Skip to content

Commit 49b691a

Browse files
authored
test: add cookie test files (microsoft#142)
1 parent e860dd8 commit 49b691a

File tree

3 files changed

+626
-0
lines changed

3 files changed

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

0 commit comments

Comments
 (0)