How to use DefaultBrowserContext1Tests class of Microsoft.Playwright.Tests package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.DefaultBrowserContext1Tests

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

DefaultBrowserContext1Tests.cs

Source: DefaultBrowserContext1Tests.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.IO;
26using System.Linq;
27using System.Net;
28using System.Threading.Tasks;
29using Microsoft.AspNetCore.Http;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    public class DefaultBrowserContext1Tests : PlaywrightTestEx
35    {
36        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.cookies() should work")]
37        public async Task ContextCookiesShouldWork()
38        {
39            var (tmp, context, page) = await LaunchPersistentAsync();
40
41            await page.GotoAsync(Server.EmptyPage);
42
43            string documentCookie = await page.EvaluateAsync<string>(@"() => {
44              document.cookie = 'username=John Doe';
45              return document.cookie;
46            }");
47
48            Assert.AreEqual("username=John Doe", documentCookie);
49            var cookie = (await page.Context.CookiesAsync()).Single();
50            Assert.AreEqual("username", cookie.Name);
51            Assert.AreEqual("John Doe", cookie.Value);
52            Assert.AreEqual("localhost", cookie.Domain);
53            Assert.AreEqual("/", cookie.Path);
54            Assert.AreEqual(-1, cookie.Expires);
55            Assert.IsFalse(cookie.HttpOnly);
56            Assert.IsFalse(cookie.Secure);
57            Assert.AreEqual(TestConstants.IsChromium ? SameSiteAttribute.Lax : SameSiteAttribute.None, cookie.SameSite);
58
59            await context.DisposeAsync();
60            tmp.Dispose();
61        }
62
63        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.addCookies() should work")]
64        public async Task ContextAddCookiesShouldWork()
65        {
66            var (tmp, context, page) = await LaunchPersistentAsync();
67
68            await page.GotoAsync(Server.EmptyPage);
69            await context.AddCookiesAsync(new[]
70            {
71                new Cookie
72                {
73                    Url = Server.EmptyPage,
74                    Name = "username",
75                    Value = "John Doe",
76                }
77            });
78
79            Assert.AreEqual("username=John Doe", await page.EvaluateAsync<string>(@"() => document.cookie"));
80
81            var cookie = (await page.Context.CookiesAsync()).Single();
82            Assert.AreEqual("username", cookie.Name);
83            Assert.AreEqual("John Doe", cookie.Value);
84            Assert.AreEqual("localhost", cookie.Domain);
85            Assert.AreEqual("/", cookie.Path);
86            Assert.AreEqual(-1, cookie.Expires);
87            Assert.IsFalse(cookie.HttpOnly);
88            Assert.IsFalse(cookie.Secure);
89            Assert.AreEqual(TestConstants.IsChromium ? SameSiteAttribute.Lax : SameSiteAttribute.None, cookie.SameSite);
90
91            await context.DisposeAsync();
92            tmp.Dispose();
93        }
94
95        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "context.clearCookies() should work")]
96        public async Task ContextClearCookiesShouldWork()
97        {
98            var (tmp, context, page) = await LaunchPersistentAsync();
99
100            await page.GotoAsync(Server.EmptyPage);
101            await context.AddCookiesAsync(new[]
102            {
103                new Cookie
104                {
105                    Url = Server.EmptyPage,
106                    Name = "cookie1",
107                    Value = "1",
108                },
109                new Cookie
110                {
111                    Url = Server.EmptyPage,
112                    Name = "cookie2",
113                    Value = "2",
114                },
115            });
116
117            Assert.AreEqual("cookie1=1; cookie2=2", await page.EvaluateAsync<string>(@"() => document.cookie"));
118
119            await context.ClearCookiesAsync();
120            await page.ReloadAsync();
121            Assert.That(await page.Context.CookiesAsync(), Is.Empty);
122            Assert.That(await page.EvaluateAsync<string>(@"() => document.cookie"), Is.Empty);
123
124            await context.DisposeAsync();
125            tmp.Dispose();
126        }
127
128        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should(not) block third party cookies")]
129        public async Task ShouldNotBlockThirdPartyCookies()
130        {
131            var (tmp, context, page) = await LaunchPersistentAsync();
132
133            await page.GotoAsync(Server.EmptyPage);
134            await page.EvaluateAsync(@"src => {
135                  let fulfill;
136                  const promise = new Promise(x => fulfill = x);
137                  const iframe = document.createElement('iframe');
138                  document.body.appendChild(iframe);
139                  iframe.onload = fulfill;
140                  iframe.src = src;
141                  return promise;
142                }", Server.CrossProcessPrefix + "/grid.html");
143
144            await page.FirstChildFrame().EvaluateAsync<string>("document.cookie = 'username=John Doe'");
145            await page.WaitForTimeoutAsync(2000);
146            bool allowsThirdParty = TestConstants.IsFirefox;
147            var cookies = await context.CookiesAsync(new[] { Server.CrossProcessPrefix + "/grid.html" });
148
149            if (allowsThirdParty)
150            {
151                Assert.That(cookies, Has.Count.EqualTo(1));
152                var cookie = cookies.First();
153                Assert.AreEqual("127.0.0.1", cookie.Domain);
154                Assert.AreEqual(cookie.Expires, -1);
155                Assert.IsFalse(cookie.HttpOnly);
156                Assert.AreEqual("username", cookie.Name);
157                Assert.AreEqual("/", cookie.Path);
158                Assert.AreEqual(TestConstants.IsChromium ? SameSiteAttribute.Lax : SameSiteAttribute.None, cookie.SameSite);
159                Assert.IsFalse(cookie.Secure);
160                Assert.AreEqual("John Doe", cookie.Value);
161            }
162            else
163            {
164                Assert.That(cookies, Is.Empty);
165            }
166
167            await context.DisposeAsync();
168            tmp.Dispose();
169        }
170
171        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support viewport option")]
172        public async Task ShouldSupportViewportOption()
173        {
174            var (tmp, context, page) = await LaunchPersistentAsync(new()
175            {
176                ViewportSize = new()
177                {
178                    Width = 456,
179                    Height = 789
180                }
181            });
182
183            await TestUtils.VerifyViewportAsync(page, 456, 789);
184            page = await context.NewPageAsync();
185            await TestUtils.VerifyViewportAsync(page, 456, 789);
186
187            await context.DisposeAsync();
188            tmp.Dispose();
189        }
190
191        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support deviceScaleFactor option")]
192        public async Task ShouldSupportDeviceScaleFactorOption()
193        {
194            var (tmp, context, page) = await LaunchPersistentAsync(new()
195            {
196                DeviceScaleFactor = 3
197            });
198
199            Assert.AreEqual(3, await page.EvaluateAsync<int>("window.devicePixelRatio"));
200
201            await context.DisposeAsync();
202            tmp.Dispose();
203        }
204
205        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support userAgent option")]
206        public async Task ShouldSupportUserAgentOption()
207        {
208            var (tmp, context, page) = await LaunchPersistentAsync(new()
209            {
210                UserAgent = "foobar"
211            });
212
213            string userAgent = string.Empty;
214
215            await TaskUtils.WhenAll(
216                Server.WaitForRequest("/empty.html", r => userAgent = r.Headers["user-agent"]),
217                page.GotoAsync(Server.EmptyPage));
218
219            Assert.AreEqual("foobar", userAgent);
220
221            await context.DisposeAsync();
222            tmp.Dispose();
223        }
224
225        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support bypassCSP option")]
226        public async Task ShouldSupportBypassCSPOption()
227        {
228            var (tmp, context, page) = await LaunchPersistentAsync(new()
229            {
230                BypassCSP = true
231            });
232
233            await page.GotoAsync(Server.Prefix + "/csp.html");
234            await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });
235            Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));
236
237            await context.DisposeAsync();
238            tmp.Dispose();
239        }
240
241        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support javascriptEnabled option")]
242        public async Task ShouldSupportJavascriptEnabledOption()
243        {
244            var (tmp, context, page) = await LaunchPersistentAsync(new()
245            {
246                JavaScriptEnabled = false
247            });
248
249            await page.GotoAsync("data:text/html, <script>var something = \"forbidden\"</script>");
250            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.EvaluateAsync("something"));
251
252            if (TestConstants.IsWebKit)
253            {
254                StringAssert.Contains("Can't find variable: something", exception.Message);
255            }
256            else
257            {
258                StringAssert.Contains("something is not defined", exception.Message);
259            }
260
261            await context.DisposeAsync();
262            tmp.Dispose();
263        }
264
265        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support httpCredentials option")]
266        public async Task ShouldSupportHttpCredentialsOption()
267        {
268            var (tmp, context, page) = await LaunchPersistentAsync(new()
269            {
270                HttpCredentials = new()
271                {
272                    Username = "user",
273                    Password = "pass",
274                }
275            });
276
277            Server.SetAuth("/playground.html", "user", "pass");
278            var response = await page.GotoAsync(Server.Prefix + "/playground.html");
279            Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
280
281            await context.DisposeAsync();
282            tmp.Dispose();
283        }
284
285        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support offline option")]
286        public async Task ShouldSupportOfflineOption()
287        {
288            var (tmp, context, page) = await LaunchPersistentAsync(new()
289            {
290                Offline = true
291            });
292
293            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync(Server.EmptyPage));
294
295            await context.DisposeAsync();
296            tmp.Dispose();
297        }
298
299        [PlaywrightTest("defaultbrowsercontext-1.spec.ts", "should support acceptDownloads option")]
300        public async Task ShouldSupportAcceptDownloadsOption()
301        {
302            var (tmp, context, page) = await LaunchPersistentAsync();
303            Server.SetRoute("/download", context =>
304            {
305                context.Response.Headers["Content-Type"] = "application/octet-stream";
306                context.Response.Headers["Content-Disposition"] = "attachment";
307                return context.Response.WriteAsync("Hello world");
308            });
309            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
310            var downloadTask = page.WaitForDownloadAsync();
311
312            await TaskUtils.WhenAll(
313                downloadTask,
314                page.ClickAsync("a"));
315            var download = downloadTask.Result;
316            var path = await download.PathAsync();
317            Assert.AreEqual(File.Exists(path), true);
318            Assert.AreEqual(File.ReadAllText(path), "Hello world");
319        }
320
321        private async Task<(TempDirectory tmp, IBrowserContext context, IPage page)> LaunchPersistentAsync(BrowserTypeLaunchPersistentContextOptions options = null)
322        {
323            var tmp = new TempDirectory();
324            var context = await BrowserType.LaunchPersistentContextAsync(
325                tmp.Path,
326                options: options);
327            var page = context.Pages.First();
328
329            return (tmp, context, page);
330        }
331    }
332}
333
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)