How to use ShouldRespectDeviceScaleFactor method of Microsoft.Playwright.Tests.BrowserContextBasicTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.BrowserContextBasicTests.ShouldRespectDeviceScaleFactor

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BrowserContextBasicTests.cs

Source: BrowserContextBasicTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Modifications copyright (c) Microsoft Corporation.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25
26using System.Linq;
27using System.Net;
28using System.Threading.Tasks;
29using Microsoft.AspNetCore.Http;
30using Microsoft.Playwright.NUnit;
31using NUnit.Framework;
32
33namespace Microsoft.Playwright.Tests
34{
35    public class BrowserContextBasicTests : BrowserTestEx
36    {
37        [PlaywrightTest("browsercontext-basic.spec.ts", "should create new context")]
38        public async Task ShouldCreateNewContext()
39        {
40            await using var browser = await BrowserType.LaunchAsync();
41            Assert.IsEmpty(browser.Contexts);
42            await using var context = await browser.NewContextAsync();
43            Assert.That(browser.Contexts, Has.Length.EqualTo(1));
44            CollectionAssert.Contains(browser.Contexts, context);
45            Assert.AreEqual(browser, context.Browser);
46            await context.CloseAsync();
47            Assert.IsEmpty(browser.Contexts);
48            Assert.AreEqual(browser, context.Browser);
49        }
50
51        [PlaywrightTest("browsercontext-basic.spec.ts", "window.open should use parent tab context")]
52        public async Task WindowOpenShouldUseParentTabContext()
53        {
54            await using var context = await Browser.NewContextAsync();
55            var page = await context.NewPageAsync();
56            await page.GotoAsync(Server.EmptyPage);
57            var popupTargetCompletion = new TaskCompletionSource<IPage>();
58            page.Popup += (_, e) => popupTargetCompletion.SetResult(e);
59
60            var (popupTarget, _) = await TaskUtils.WhenAll(
61                popupTargetCompletion.Task,
62                page.EvaluateAsync("url => window.open(url)", Server.EmptyPage)
63            );
64
65            Assert.AreEqual(context, popupTarget.Context);
66            await context.CloseAsync();
67        }
68
69        [PlaywrightTest("browsercontext-basic.spec.ts", "should isolate localStorage and cookies")]
70        public async Task ShouldIsolateLocalStorageAndCookies()
71        {
72            // Create two incognito contexts.
73            await using var browser = await BrowserType.LaunchAsync();
74            var context1 = await browser.NewContextAsync();
75            var context2 = await browser.NewContextAsync();
76            Assert.IsEmpty(context1.Pages);
77            Assert.IsEmpty(context2.Pages);
78
79            // Create a page in first incognito context.
80            var page1 = await context1.NewPageAsync();
81            await page1.GotoAsync(Server.EmptyPage);
82            await page1.EvaluateAsync(@"() => {
83                localStorage.setItem('name', 'page1');
84                document.cookie = 'name=page1';
85            }");
86
87            Assert.That(context1.Pages, Has.Count.EqualTo(1));
88            Assert.IsEmpty(context2.Pages);
89
90            // Create a page in second incognito context.
91            var page2 = await context2.NewPageAsync();
92            await page2.GotoAsync(Server.EmptyPage);
93            await page2.EvaluateAsync(@"() => {
94                localStorage.setItem('name', 'page2');
95                document.cookie = 'name=page2';
96            }");
97
98            Assert.That(context1.Pages, Has.Count.EqualTo(1));
99            Assert.AreEqual(page1, context1.Pages.FirstOrDefault());
100            Assert.That(context2.Pages, Has.Count.EqualTo(1));
101            Assert.AreEqual(page2, context2.Pages.FirstOrDefault());
102
103            // Make sure pages don't share localstorage or cookies.
104            Assert.AreEqual("page1", await page1.EvaluateAsync<string>("() => localStorage.getItem('name')"));
105            Assert.AreEqual("name=page1", await page1.EvaluateAsync<string>("() => document.cookie"));
106            Assert.AreEqual("page2", await page2.EvaluateAsync<string>("() => localStorage.getItem('name')"));
107            Assert.AreEqual("name=page2", await page2.EvaluateAsync<string>("() => document.cookie"));
108
109            // Cleanup contexts.
110            await TaskUtils.WhenAll(context1.CloseAsync(), context2.CloseAsync());
111            Assert.IsEmpty(browser.Contexts);
112        }
113
114        [PlaywrightTest("browsercontext-basic.spec.ts", "should propagate default viewport to the page")]
115        public async Task ShouldPropagateDefaultViewportToThePage()
116        {
117            await using var context = await Browser.NewContextAsync(new()
118            {
119                ViewportSize = new()
120                {
121                    Width = 456,
122                    Height = 789
123                }
124            });
125
126            var page = await context.NewPageAsync();
127            await TestUtils.VerifyViewportAsync(page, 456, 789);
128        }
129
130        [PlaywrightTest("browsercontext-basic.spec.ts", "should make a copy of default viewport")]
131        public async Task ShouldMakeACopyOfDefaultViewport()
132        {
133            var viewport = new ViewportSize
134            {
135                Width = 456,
136                Height = 789
137            };
138
139            await using var context = await Browser.NewContextAsync(new() { ViewportSize = viewport });
140
141            viewport.Width = 567;
142
143            var page = await context.NewPageAsync();
144
145            await TestUtils.VerifyViewportAsync(page, 456, 789);
146        }
147
148        [PlaywrightTest("browsercontext-basic.spec.ts", "should respect deviceScaleFactor")]
149        public async Task ShouldRespectDeviceScaleFactor()
150        {
151            await using var context = await Browser.NewContextAsync(new()
152            {
153                DeviceScaleFactor = 3
154            });
155
156            var page = await context.NewPageAsync();
157            Assert.AreEqual(3, await page.EvaluateAsync<int>("window.devicePixelRatio"));
158        }
159
160        [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow deviceScaleFactor with null viewport")]
161        public async Task ShouldNotAllowDeviceScaleFactorWithViewportDisabled()
162        {
163            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()
164            {
165                ViewportSize = ViewportSize.NoViewport,
166                DeviceScaleFactor = 3,
167            }));
168            Assert.AreEqual("\"deviceScaleFactor\" option is not supported with null \"viewport\"", exception.Message);
169        }
170
171        [PlaywrightTest("browsercontext-basic.spec.ts", "should not allow isMobile with null viewport")]
172        public async Task ShouldNotAllowIsMobileWithViewportDisabled()
173        {
174            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Browser.NewContextAsync(new()
175            {
176                ViewportSize = ViewportSize.NoViewport,
177                IsMobile = true,
178            }));
179            Assert.AreEqual("\"isMobile\" option is not supported with null \"viewport\"", exception.Message);
180        }
181
182        [PlaywrightTest("browsercontext-basic.spec.ts", "close() should work for empty context")]
183        public async Task CloseShouldWorkForEmptyContext()
184        {
185            var context = await Browser.NewContextAsync();
186            await context.CloseAsync();
187        }
188
189        [PlaywrightTest("browsercontext-basic.spec.ts", "close() should abort waitForEvent")]
190        public async Task CloseShouldAbortWaitForEvent()
191        {
192            var context = await Browser.NewContextAsync();
193            var waitTask = context.WaitForPageAsync();
194            await context.CloseAsync();
195            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => waitTask);
196            Assert.AreEqual("Context closed", exception.Message);
197        }
198
199        [PlaywrightTest("browsercontext-basic.spec.ts", "should not report frameless pages on error")]
200        public async Task ShouldNotReportFramelessPagesOnError()
201        {
202            var context = await Browser.NewContextAsync();
203            var page = await context.NewPageAsync();
204            Server.SetRoute("/empty.html", context =>
205            {
206                context.Response.ContentType = "text/html";
207                return context.Response.WriteAsync($"<a href=\"{Server.EmptyPage}\" target=\"_blank\">Click me</a>");
208            });
209
210            IPage popup = null;
211            context.Page += (_, e) => popup = e;
212            await page.GotoAsync(Server.EmptyPage);
213            await page.ClickAsync("'Click me'");
214            await context.CloseAsync();
215
216            if (popup != null)
217            {
218                Assert.True(popup.IsClosed);
219                Assert.NotNull(popup.MainFrame);
220            }
221        }
222
223        [PlaywrightTest("browsercontext-basic.spec.ts", "close() should be callable twice")]
224        public async Task CloseShouldBeCallableTwice()
225        {
226            var context = await Browser.NewContextAsync();
227            await TaskUtils.WhenAll(context.CloseAsync(), context.CloseAsync());
228            await context.CloseAsync();
229        }
230
231        [PlaywrightTest("browsercontext-basic.spec.ts", "should return all of the pages")]
232        public async Task ShouldReturnAllOfThePages()
233        {
234            await using var context = await Browser.NewContextAsync();
235            var page = await context.NewPageAsync();
236            var second = await context.NewPageAsync();
237
238            Assert.AreEqual(2, context.Pages.Count);
239            CollectionAssert.Contains(context.Pages, page);
240            CollectionAssert.Contains(context.Pages, second);
241        }
242
243        [PlaywrightTest("browsercontext-basic.spec.ts", "BrowserContext.pages()", "should close all belonging pages once closing context")]
244        public async Task ShouldCloseAllBelongingPagesOnceClosingContext()
245        {
246            await using var context = await Browser.NewContextAsync();
247            await context.NewPageAsync();
248
249            Assert.That(context.Pages, Has.Count.EqualTo(1));
250
251            await context.CloseAsync();
252
253            Assert.IsEmpty(context.Pages);
254        }
255
256        [PlaywrightTest("browsercontext-basic.spec.ts", "should disable javascript")]
257        public async Task ShouldDisableJavascript()
258        {
259            await using (var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false }))
260            {
261                var page = await context.NewPageAsync();
262                await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");
263
264                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.EvaluateAsync("something"));
265
266                StringAssert.Contains(
267                    TestConstants.IsWebKit ? "Can't find variable: something" : "something is not defined",
268                    exception.Message);
269            }
270
271            await using (var context = await Browser.NewContextAsync())
272            {
273                var page = await context.NewPageAsync();
274                await page.GotoAsync("data:text/html, <script>var something = 'forbidden'</script>");
275                Assert.AreEqual("forbidden", await page.EvaluateAsync<string>("something"));
276            }
277        }
278
279        [PlaywrightTest("browsercontext-basic.spec.ts", "should be able to navigate after disabling javascript")]
280        public async Task ShouldBeAbleToNavigateAfterDisablingJavascript()
281        {
282            await using var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false });
283            var page = await context.NewPageAsync();
284            await page.GotoAsync(Server.EmptyPage);
285        }
286
287        [PlaywrightTest("browsercontext-basic.spec.ts", "should work with offline option")]
288        public async Task ShouldWorkWithOfflineOption()
289        {
290            await using var context = await Browser.NewContextAsync(new() { Offline = true });
291            var page = await context.NewPageAsync();
292            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync(Server.EmptyPage));
293            await context.SetOfflineAsync(false);
294            var response = await page.GotoAsync(Server.EmptyPage);
295            Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
296        }
297
298        [PlaywrightTest("browsercontext-basic.spec.ts", "should emulate navigator.onLine")]
299        [Skip(SkipAttribute.Targets.Firefox)]
300        public async Task ShouldEmulateNavigatorOnLine()
301        {
302            await using var context = await Browser.NewContextAsync();
303            var page = await context.NewPageAsync();
304            Assert.True(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));
305            await context.SetOfflineAsync(true);
306            Assert.False(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));
307            await context.SetOfflineAsync(false);
308            Assert.True(await page.EvaluateAsync<bool>("() => window.navigator.onLine"));
309        }
310    }
311}
312
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)