How to use ShouldRestoreCookiesFromUserDataDir method of Microsoft.Playwright.Tests.DefaultBrowsercontext2Tests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.DefaultBrowsercontext2Tests.ShouldRestoreCookiesFromUserDataDir

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

DefaultBrowsercontext2Tests.cs

Source: DefaultBrowsercontext2Tests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System.Collections.Generic;
26using System.IO;
27using System.Linq;
28using System.Threading.Tasks;
29using Microsoft.Playwright.NUnit;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    /// <playwright-file>defaultbrowsercontext-2.spec.ts</playwright-file>
35    public class DefaultBrowsercontext2Tests : PlaywrightTestEx
36    {
37        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support hasTouch option")]
38        public async Task ShouldSupportHasTouchOption()
39        {
40            var (tmp, context, page) = await LaunchAsync(new()
41            {
42                HasTouch = true
43            });
44
45            await page.GotoAsync(Server.Prefix + "/mobile.html");
46            Assert.True(await page.EvaluateAsync<bool>("() => 'ontouchstart' in window"));
47
48            await context.DisposeAsync();
49            tmp.Dispose();
50        }
51
52        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should work in persistent context")]
53        [Skip(SkipAttribute.Targets.Firefox)]
54        public async Task ShouldWorkInPersistentContext()
55        {
56            var (tmp, context, page) = await LaunchAsync(new()
57            {
58                ViewportSize = new()
59                {
60                    Width = 320,
61                    Height = 480,
62                },
63                IsMobile = true,
64            });
65
66            await page.GotoAsync(Server.EmptyPage);
67            Assert.AreEqual(980, await page.EvaluateAsync<int>("() => window.innerWidth"));
68
69            await context.DisposeAsync();
70            tmp.Dispose();
71        }
72
73        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support colorScheme option")]
74        public async Task ShouldSupportColorSchemeOption()
75        {
76            var (tmp, context, page) = await LaunchAsync(new()
77            {
78                ColorScheme = ColorScheme.Dark,
79            });
80
81            Assert.False(await page.EvaluateAsync<bool?>("() => matchMedia('(prefers-color-scheme: light)').matches"));
82            Assert.True(await page.EvaluateAsync<bool?>("() => matchMedia('(prefers-color-scheme: dark)').matches"));
83
84            await context.DisposeAsync();
85            tmp.Dispose();
86        }
87
88        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support reducedMotion option")]
89        public async Task ShouldSupportReducedMotionOption()
90        {
91            var (tmp, context, page) = await LaunchAsync(new()
92            {
93                ReducedMotion = ReducedMotion.Reduce
94            });
95
96            Assert.True(await page.EvaluateAsync<bool?>("() => matchMedia('(prefers-reduced-motion: reduce)').matches"));
97            Assert.False(await page.EvaluateAsync<bool?>("() => matchMedia('(prefers-reduced-motion: no-preference)').matches"));
98
99            await context.DisposeAsync();
100            tmp.Dispose();
101        }
102
103        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support timezoneId option")]
104        public async Task ShouldSupportTimezoneIdOption()
105        {
106            var (tmp, context, page) = await LaunchAsync(new()
107            {
108                TimezoneId = "America/Jamaica",
109            });
110
111            Assert.AreEqual("Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)", await page.EvaluateAsync<string>("() => new Date(1479579154987).toString()"));
112
113            await context.DisposeAsync();
114            tmp.Dispose();
115        }
116
117        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support locale option")]
118        public async Task ShouldSupportLocaleOption()
119        {
120            var (tmp, context, page) = await LaunchAsync(new()
121            {
122                Locale = "fr-CH",
123            });
124
125            Assert.AreEqual("fr-CH", await page.EvaluateAsync<string>("() => navigator.language"));
126
127            await context.DisposeAsync();
128            tmp.Dispose();
129        }
130
131        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support geolocation and permissions options")]
132        public async Task ShouldSupportGeolocationAndPermissionsOptions()
133        {
134            var (tmp, context, page) = await LaunchAsync(new()
135            {
136                Geolocation = new()
137                {
138                    Latitude = 10,
139                    Longitude = 10,
140                },
141                Permissions = new[] { "geolocation" },
142            });
143
144            await page.GotoAsync(Server.EmptyPage);
145            var geolocation = await page.EvaluateAsync<Geolocation>(@"() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
146                resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
147            }))");
148            Assert.AreEqual(10, geolocation.Latitude);
149            Assert.AreEqual(10, geolocation.Longitude);
150
151            await context.DisposeAsync();
152            tmp.Dispose();
153        }
154
155        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support ignoreHTTPSErrors option")]
156        public async Task ShouldSupportIgnoreHTTPSErrorsOption()
157        {
158            var (tmp, context, page) = await LaunchAsync(new()
159            {
160                IgnoreHTTPSErrors = true
161            });
162
163            var response = await page.GotoAsync(HttpsServer.Prefix + "/empty.html");
164            Assert.True(response.Ok);
165
166            await context.DisposeAsync();
167            tmp.Dispose();
168        }
169
170        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should support extraHTTPHeaders option")]
171        public async Task ShouldSupportExtraHTTPHeadersOption()
172        {
173            var (tmp, context, page) = await LaunchAsync(new()
174            {
175                ExtraHTTPHeaders = new Dictionary<string, string>
176                {
177                    ["foo"] = "bar",
178                },
179            });
180
181            string fooHeader = string.Empty;
182
183            await TaskUtils.WhenAll(
184                Server.WaitForRequest("/empty.html", r => fooHeader = r.Headers["foo"]),
185                page.GotoAsync(Server.EmptyPage));
186
187            Assert.AreEqual("bar", fooHeader);
188
189            await context.DisposeAsync();
190            tmp.Dispose();
191        }
192
193        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should accept userDataDir")]
194        public async Task ShouldAcceptUserDataDir()
195        {
196            var (tmp, context, _) = await LaunchAsync();
197            Assert.IsNotEmpty(new DirectoryInfo(tmp.Path).GetDirectories());
198            await context.CloseAsync();
199            Assert.IsNotEmpty(new DirectoryInfo(tmp.Path).GetDirectories());
200
201            tmp.Dispose();
202        }
203
204        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should restore state from userDataDir")]
205        public async Task ShouldRestoreStateFromUserDataDir()
206        {
207            using var userDataDir = new TempDirectory();
208
209            await using (var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))
210            {
211                var page = await browserContext.NewPageAsync();
212                await page.GotoAsync(Server.EmptyPage);
213                await page.EvaluateAsync("() => localStorage.hey = 'hello'");
214            }
215
216            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))
217            {
218                var page = await browserContext2.NewPageAsync();
219                await page.GotoAsync(Server.EmptyPage);
220                Assert.AreEqual("hello", await page.EvaluateAsync<string>("() => localStorage.hey"));
221            }
222
223            using var userDataDir2 = new TempDirectory();
224            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir2.Path))
225            {
226                var page = await browserContext2.NewPageAsync();
227                await page.GotoAsync(Server.EmptyPage);
228                Assert.That("hello", Is.Not.EqualTo(await page.EvaluateAsync<string>("() => localStorage.hey")));
229            }
230        }
231
232        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should restore cookies from userDataDir")]
233        [Skip(SkipAttribute.Targets.Chromium | SkipAttribute.Targets.Windows)]
234        public async Task ShouldRestoreCookiesFromUserDataDir()
235        {
236            using var userDataDir = new TempDirectory();
237
238            await using (var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))
239            {
240                var page = await browserContext.NewPageAsync();
241                await page.GotoAsync(Server.EmptyPage);
242                string documentCookie = await page.EvaluateAsync<string>(@"() => {
243                    document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT';
244                    return document.cookie;
245                }");
246
247                Assert.AreEqual("doSomethingOnlyOnce=true", documentCookie);
248            }
249
250            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))
251            {
252                var page = await browserContext2.NewPageAsync();
253                await page.GotoAsync(Server.EmptyPage);
254                Assert.AreEqual("doSomethingOnlyOnce=true", await page.EvaluateAsync<string>("() => document.cookie"));
255            }
256
257            using var userDataDir2 = new TempDirectory();
258            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir2.Path))
259            {
260                var page = await browserContext2.NewPageAsync();
261                await page.GotoAsync(Server.EmptyPage);
262                Assert.That("doSomethingOnlyOnce=true", Is.Not.EqualTo(await page.EvaluateAsync<string>("() => document.cookie")));
263            }
264        }
265
266        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should have default URL when launching browser")]
267        public async Task ShouldHaveDefaultURLWhenLaunchingBrowser()
268        {
269            var (tmp, context, page) = await LaunchAsync();
270
271            string[] urls = context.Pages.Select(p => p.Url).ToArray();
272            Assert.AreEqual(new[] { "about:blank" }, urls);
273
274            await context.DisposeAsync();
275            tmp.Dispose();
276        }
277
278        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should throw if page argument is passed")]
279        [Skip(SkipAttribute.Targets.Firefox)]
280        public async Task ShouldThrowIfPageArgumentIsPassed()
281        {
282            using var tmp = new TempDirectory();
283            var args = new[] { Server.EmptyPage };
284            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() =>
285                BrowserType.LaunchPersistentContextAsync(tmp.Path, new() { Args = args }));
286        }
287
288        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should fire close event for a persistent context")]
289        public async Task ShouldFireCloseEventForAPersistentContext()
290        {
291            var (tmp, context, _) = await LaunchAsync();
292            bool closed = false;
293            context.Close += (_, _) => closed = true;
294            await context.CloseAsync();
295
296            Assert.True(closed);
297
298            await context.DisposeAsync();
299            tmp.Dispose();
300        }
301
302        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should respect selectors")]
303        public async Task ShouldRespectSelectors()
304        {
305            var (tmp, context, page) = await LaunchAsync();
306            const string defaultContextCSS = @"({
307                create(root, target) {},
308                query(root, selector) {
309                    return root.querySelector(selector);
310                },
311                queryAll(root, selector) {
312                    return Array.from(root.querySelectorAll(selector));
313                }
314            })";
315
316            await TestUtils.RegisterEngineAsync(Playwright, "defaultContextCSS", defaultContextCSS);
317            await page.SetContentAsync("<div>hello</div>");
318            Assert.AreEqual("hello", await page.InnerHTMLAsync("css=div"));
319            Assert.AreEqual("hello", await page.InnerHTMLAsync("defaultContextCSS=div"));
320
321            await context.DisposeAsync();
322            tmp.Dispose();
323        }
324
325        private async Task<(TempDirectory tmp, IBrowserContext context, IPage page)> LaunchAsync(BrowserTypeLaunchPersistentContextOptions options = null)
326        {
327            var tmp = new TempDirectory();
328            var context = await BrowserType.LaunchPersistentContextAsync(tmp.Path, options);
329            var page = context.Pages.First();
330
331            return (tmp, context, page);
332        }
333    }
334}
335
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
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)