forked from microsoft/playwright-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrowserContextStorageStateTests.cs
More file actions
203 lines (182 loc) · 9.29 KB
/
BrowserContextStorageStateTests.cs
File metadata and controls
203 lines (182 loc) · 9.29 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
* MIT License
*
* Copyright (c) Microsoft Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Microsoft.Playwright.Tests;
public sealed class BrowserContextStorageStateTests : PageTestEx
{
[PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture local storage")]
public async Task ShouldCaptureLocalStorage()
{
var page1 = await Context.NewPageAsync();
await page1.RouteAsync("**/*", (route) =>
{
route.FulfillAsync(new() { Body = "<html></html>" });
});
await page1.GotoAsync("https://www.example.com");
await page1.EvaluateAsync(@"() =>
{
localStorage['name1'] = 'value1';
}");
await page1.GotoAsync("https://www.domain.com");
await page1.EvaluateAsync(@"() =>
{
localStorage['name2'] = 'value2';
}");
string storage = await Context.StorageStateAsync();
// TODO: think about IVT-in the StorageState and serializing
string expected = @"{""cookies"":[],""origins"":[{""origin"":""https://www.domain.com"",""localStorage"":[{""name"":""name2"",""value"":""value2""}]},{""origin"":""https://www.example.com"",""localStorage"":[{""name"":""name1"",""value"":""value1""}]}]}";
Assert.AreEqual(expected, storage);
}
[PlaywrightTest("browsercontext-storage-state.spec.ts", "should set local storage")]
public async Task ShouldSetLocalStorage()
{
var context = await Browser.NewContextAsync(new()
{
StorageState = "{\"cookies\":[],\"origins\":[{\"origin\":\"https://www.example.com\",\"localStorage\":[{\"name\":\"name1\",\"value\":\"value1\"}]}]}",
});
var page = await context.NewPageAsync();
await page.RouteAsync("**/*", (route) =>
{
route.FulfillAsync(new() { Body = "<html></html>" });
});
await page.GotoAsync("https://www.example.com");
var localStorage = await page.EvaluateAsync<string[]>("Object.keys(window.localStorage)");
Assert.AreEqual(localStorage, new string[] { "name1" });
var name1Value = await page.EvaluateAsync<string>("window.localStorage.getItem('name1')");
Assert.AreEqual(name1Value, "value1");
}
[PlaywrightTest("browsercontext-storage-state.spec.ts", "should round-trip through the file")]
public async Task ShouldRoundTripThroughTheFile()
{
var page1 = await Context.NewPageAsync();
await page1.RouteAsync("**/*", (route) =>
{
route.FulfillAsync(new() { Body = "<html></html>" });
});
await page1.GotoAsync("https://www.example.com");
await page1.EvaluateAsync(@"async () =>
{
localStorage['name1'] = 'value1';
document.cookie = 'username=John Doe';
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);
};
});
return document.cookie;
}");
using var tempDir = new TempDirectory();
string path = Path.Combine(tempDir.Path, "storage-state.json");
string storage = await Context.StorageStateAsync(new() { IndexedDB = true, Path = path });
Assert.AreEqual(storage, File.ReadAllText(path));
await using var context = await Browser.NewContextAsync(new() { StorageStatePath = path });
var page2 = await context.NewPageAsync();
await page2.RouteAsync("**/*", (route) =>
{
route.FulfillAsync(new() { Body = "<html></html>" });
});
await page2.GotoAsync("https://www.example.com");
Assert.AreEqual("value1", await page2.EvaluateAsync<string>("localStorage['name1']"));
Assert.AreEqual("username=John Doe", await page2.EvaluateAsync<string>("document.cookie"));
var idbValue = await page2.EvaluateAsync<string>(@"
() => {
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.AreEqual("foo", idbValue);
}
[PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture cookies")]
public async Task ShouldCaptureCookies()
{
Server.SetRoute("/setcookie.html", context =>
{
context.Response.Cookies.Append("a", "b");
context.Response.Cookies.Append("empty", "");
return Task.CompletedTask;
});
await Page.GotoAsync(Server.Prefix + "/setcookie.html");
CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await Page.EvaluateAsync<string[]>(@"() =>
{
const cookies = document.cookie.split(';');
return cookies.map(cookie => cookie.trim()).sort();
}"));
var storageState = await Context.StorageStateAsync();
StringAssert.Contains(@"""name"":""a"",""value"":""b""", storageState);
StringAssert.Contains(@"""name"":""empty"",""value"":""""", storageState);
StringAssert.DoesNotContain(@"""url"":null", storageState);
await using var context2 = await Browser.NewContextAsync(new() { StorageState = storageState });
var page2 = await context2.NewPageAsync();
await page2.GotoAsync(Server.EmptyPage);
CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await page2.EvaluateAsync<string[]>(@"() =>
{
const cookies = document.cookie.split(';');
return cookies.map(cookie => cookie.trim()).sort();
}"));
}
[PlaywrightTest("browsercontext-storage-state.spec.ts", "should serialize storageState with lone surrogates")]
public async Task ShouldSerializeStorageStateWithLoneSurrogates()
{
await Page.GotoAsync(Server.EmptyPage);
await Page.EvaluateAsync(@"chars => window.localStorage.setItem('foo', String.fromCharCode(55934))");
string storageState = await Context.StorageStateAsync();
// It should get replaced by the utf8 replacement char (U+FFFD)
StringAssert.Contains(@"""value"":""\uFFFD""", storageState);
}
[PlaywrightTest("browsercontext-storage-state.spec.ts", "should set local storage via setStorageState")]
public async Task ShouldSetLocalStorageViaSetStorageState()
{
await using var context = await Browser.NewContextAsync();
var page = await context.NewPageAsync();
await page.RouteAsync("**/*", (route) =>
{
route.FulfillAsync(new() { Body = "<html></html>" });
});
await page.GotoAsync("https://www.example.com");
var localStorage = await page.EvaluateAsync<string>("window.localStorage.getItem('name1')");
Assert.IsNull(localStorage);
using var tempDir = new TempDirectory();
string path = Path.Combine(tempDir.Path, "storage-state.json");
File.WriteAllText(path, @"{""cookies"":[],""origins"":[{""origin"":""https://www.example.com"",""localStorage"":[{""name"":""name1"",""value"":""value1""}]}]}");
await context.SetStorageStateAsync(path);
await page.GotoAsync("https://www.example.com");
localStorage = await page.EvaluateAsync<string>("window.localStorage.getItem('name1')");
Assert.AreEqual("value1", localStorage);
}
}