This repository was archived by the owner on May 27, 2026. It is now read-only.
forked from microsoft/playwright-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_browsercontext_storage_state.py
More file actions
174 lines (159 loc) · 5.95 KB
/
Copy pathtest_browsercontext_storage_state.py
File metadata and controls
174 lines (159 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from pathlib import Path
from playwright.sync_api import Browser, BrowserContext, Page, StorageState
from tests.server import Server
def test_should_capture_local_storage(context: BrowserContext) -> None:
page1 = context.new_page()
page1.route("**/*", lambda route: route.fulfill(body="<html></html>"))
page1.goto("https://www.example.com")
page1.evaluate("localStorage['name1'] = 'value1'")
page1.goto("https://www.domain.com")
page1.evaluate("localStorage['name2'] = 'value2'")
state = context.storage_state()
origins = state["origins"]
assert origins
assert len(origins) == 2
assert origins[0] == {
"origin": "https://www.domain.com",
"localStorage": [{"name": "name2", "value": "value2"}],
}
assert origins[1] == {
"origin": "https://www.example.com",
"localStorage": [{"name": "name1", "value": "value1"}],
}
def test_should_set_local_storage(browser: Browser) -> None:
storage_state: StorageState = {
"origins": [
{
"origin": "https://www.example.com",
"localStorage": [{"name": "name1", "value": "value1"}],
}
]
}
# We intentionally hide the indexed_db part in our API for now
storage_state["origins"][0]["indexedDB"] = [ # type: ignore
{
"name": "db",
"version": 42,
"stores": [
{
"name": "store",
"autoIncrement": False,
"records": [{"key": "bar", "value": "foo"}],
"indexes": [],
}
],
}
]
context = browser.new_context(storage_state=storage_state)
page = context.new_page()
page.route("**/*", lambda route: route.fulfill(body="<html></html>"))
page.goto("https://www.example.com")
local_storage = page.evaluate("window.localStorage")
assert local_storage == {"name1": "value1"}
indexed_db = page.evaluate(
"""async () => {
return new Promise((resolve, reject) => {
const openRequest = indexedDB.open('db', 42);
openRequest.addEventListener('success', () => {
const db = openRequest.result;
const transaction = db.transaction('store', 'readonly');
const getRequest = transaction.objectStore('store').get('bar');
getRequest.addEventListener('success', () => resolve(getRequest.result));
getRequest.addEventListener('error', () => reject(getRequest.error));
});
openRequest.addEventListener('error', () => reject(openRequest.error));
});
}"""
)
assert indexed_db == "foo"
context.close()
def test_should_round_trip_through_the_file(
browser: Browser, context: BrowserContext, tmp_path: Path
) -> None:
page1 = context.new_page()
page1.route(
"**/*",
lambda route: route.fulfill(body="<html></html>"),
)
page1.goto("https://www.example.com")
page1.evaluate(
"""() => {
localStorage["name1"] = "value1"
document.cookie = "username=John Doe"
return document.cookie
}"""
)
path = tmp_path / "storage-state.json"
state = context.storage_state(path=path)
with open(path, "r") as f:
written = json.load(f)
assert state == written
context2 = browser.new_context(storage_state=path)
page2 = context2.new_page()
page2.route(
"**/*",
lambda route: route.fulfill(body="<html></html>"),
)
page2.goto("https://www.example.com")
local_storage = page2.evaluate("window.localStorage")
assert local_storage == {"name1": "value1"}
cookie = page2.evaluate("document.cookie")
assert cookie == "username=John Doe"
context2.close()
def test_should_serialise_indexed_db(page: Page, server: Server) -> None:
page.goto(server.EMPTY_PAGE)
page.evaluate(
"""async () => {
await new Promise((resolve, reject) => {
const openRequest = indexedDB.open('db', 42);
openRequest.onupgradeneeded = () => {
openRequest.result.createObjectStore('store');
};
openRequest.onsuccess = () => {
const request = openRequest.result.transaction('store', 'readwrite')
.objectStore('store')
.put('foo', 'bar');
request.addEventListener('success', resolve);
request.addEventListener('error', reject);
};
});
}"""
)
assert page.context.storage_state() == {"cookies": [], "origins": []}
assert page.context.storage_state(indexed_db=True) == {
"cookies": [],
"origins": [
{
"origin": f"http://localhost:{server.PORT}",
"localStorage": [],
"indexedDB": [
{
"name": "db",
"version": 42,
"stores": [
{
"name": "store",
"autoIncrement": False,
"records": [{"key": "bar", "value": "foo"}],
"indexes": [],
}
],
}
],
}
],
}