How to use ShouldWork method of Microsoft.Playwright.Tests.GeolocationTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.GeolocationTests.ShouldWork

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

GeolocationTests.cs

Source: GeolocationTests.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.Collections.Generic;
27using System.Threading.Tasks;
28using Microsoft.Playwright.NUnit;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    public class GeolocationTests : PageTestEx
34    {
35        [PlaywrightTest("geolocation.spec.ts", "should work")]
36        public async Task ShouldWork()
37        {
38            await Context.GrantPermissionsAsync(new[] { "geolocation" });
39            await Page.GotoAsync(Server.EmptyPage);
40            await Context.SetGeolocationAsync(new()
41            {
42                Longitude = 10,
43                Latitude = 10
44            });
45            var geolocation = await Page.EvaluateAsync<Geolocation>(
46                @"() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
47                    resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
48                }))");
49            AssertEqual(10, 10, geolocation);
50        }
51
52        [PlaywrightTest("geolocation.spec.ts", "should throw when invalid longitude")]
53        public async Task ShouldThrowWhenInvalidLongitude()
54        {
55            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() =>
56                Context.SetGeolocationAsync(new()
57                {
58                    Longitude = 200,
59                    Latitude = 100
60                }));
61            StringAssert.Contains("geolocation.longitude", exception.Message);
62            StringAssert.Contains("failed", exception.Message);
63        }
64
65        [PlaywrightTest("geolocation.spec.ts", "should isolate contexts")]
66        public async Task ShouldIsolateContexts()
67        {
68            await Context.GrantPermissionsAsync(new[] { "geolocation" });
69            await Context.SetGeolocationAsync(new()
70            {
71                Longitude = 10,
72                Latitude = 10
73            });
74            await Page.GotoAsync(Server.EmptyPage);
75
76
77            await using var context2 = await Browser.NewContextAsync(new()
78            {
79                Permissions = new[] { "geolocation" },
80                Geolocation = new() { Latitude = 20, Longitude = 20 },
81            });
82
83            var page2 = await context2.NewPageAsync();
84            await page2.GotoAsync(Server.EmptyPage);
85
86            var geolocation = await Page.EvaluateAsync<Geolocation>(
87                @"() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
88                    resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
89                }))");
90            AssertEqual(10, 10, geolocation);
91
92            var geolocation2 = await page2.EvaluateAsync<Geolocation>(
93                @"() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
94                    resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
95                }))");
96            AssertEqual(20, 20, geolocation2);
97        }
98
99        [PlaywrightTest("geolocation.spec.ts", "should not modify passed default options object")]
100        [Skip(SkipAttribute.Targets.Firefox)]
101        public async Task ShouldNotModifyPassedDefaultOptionsObject()
102        {
103            var geolocation = new Geolocation { Latitude = 10, Longitude = 10 };
104            BrowserNewContextOptions options = new() { Geolocation = geolocation };
105            await using var context = await Browser.NewContextAsync(options);
106            await Page.GotoAsync(Server.EmptyPage);
107            await Context.SetGeolocationAsync(new()
108            {
109                Longitude = 20,
110                Latitude = 20
111            });
112            Assert.AreEqual(options.Geolocation.Latitude, geolocation.Latitude);
113            Assert.AreEqual(options.Geolocation.Longitude, geolocation.Longitude);
114        }
115
116        [PlaywrightTest("geolocation.spec.ts", "should use context options")]
117        public async Task ShouldUseContextOptions()
118        {
119            var options = new BrowserNewContextOptions()
120            {
121                Geolocation = new()
122                {
123                    Latitude = 10,
124                    Longitude = 10
125                },
126                Permissions = new[] { "geolocation" },
127            };
128
129            await using var context = await Browser.NewContextAsync(options);
130            var page = await context.NewPageAsync();
131            await page.GotoAsync(Server.EmptyPage);
132
133            var geolocation = await page.EvaluateAsync<Geolocation>(@"() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
134                resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
135            }))");
136            Assert.AreEqual(options.Geolocation.Latitude, geolocation.Latitude);
137            Assert.AreEqual(options.Geolocation.Longitude, geolocation.Longitude);
138        }
139
140        [PlaywrightTest("geolocation.spec.ts", "watchPosition should be notified")]
141        public async Task WatchPositionShouldBeNotified()
142        {
143            await Context.GrantPermissionsAsync(new[] { "geolocation" });
144            await Page.GotoAsync(Server.EmptyPage);
145
146            var messages = new List<string>();
147            Page.Console += (_, e) => messages.Add(e.Text);
148
149            await Context.SetGeolocationAsync(new()
150            {
151                Longitude = 0,
152                Latitude = 0
153            });
154
155            await Page.EvaluateAsync<Geolocation>(@"() => {
156                navigator.geolocation.watchPosition(pos => {
157                    const coords = pos.coords;
158                    console.log(`lat=${coords.latitude} lng=${coords.longitude}`);
159                }, err => {});
160            }");
161
162            await Page.RunAndWaitForConsoleMessageAsync(async () =>
163            {
164                await Context.SetGeolocationAsync(new() { Latitude = 0, Longitude = 10 });
165            }, new()
166            {
167                Predicate = e => e.Text.Contains("lat=0 lng=10")
168            });
169
170            await TaskUtils.WhenAll(
171                Page.WaitForConsoleMessageAsync(new()
172                {
173                    Predicate = e => e.Text.Contains("lat=20 lng=30")
174                }),
175                Context.SetGeolocationAsync(new() { Latitude = 20, Longitude = 30 }));
176
177            await TaskUtils.WhenAll(
178                Page.WaitForConsoleMessageAsync(new()
179                {
180                    Predicate = e => e.Text.Contains("lat=40 lng=50")
181                }),
182                Context.SetGeolocationAsync(new() { Latitude = 40, Longitude = 50 }));
183
184            string allMessages = string.Join("|", messages);
185            StringAssert.Contains("lat=0 lng=10", allMessages);
186            StringAssert.Contains("lat=20 lng=30", allMessages);
187            StringAssert.Contains("lat=40 lng=50", allMessages);
188        }
189
190        [PlaywrightTest("geolocation.spec.ts", "should use context options for popup")]
191        public async Task ShouldUseContextOptionsForPopup()
192        {
193            await Context.GrantPermissionsAsync(new[] { "geolocation" });
194            await Context.SetGeolocationAsync(new()
195            {
196                Longitude = 10,
197                Latitude = 10,
198            });
199
200            var popupTask = Page.WaitForPopupAsync();
201
202            await TaskUtils.WhenAll(
203                popupTask,
204                Page.EvaluateAsync("url => window._popup = window.open(url)", Server.Prefix + "/geolocation.html"));
205
206            await popupTask.Result.WaitForLoadStateAsync();
207            var geolocation = await popupTask.Result.EvaluateAsync<Geolocation>("() => window.geolocationPromise");
208            Assert.AreEqual(10, geolocation.Longitude);
209            Assert.AreEqual(10, geolocation.Longitude);
210        }
211
212        void AssertEqual(float lat, float lon, Geolocation geolocation)
213        {
214            Assert.AreEqual(lat, geolocation.Latitude);
215            Assert.AreEqual(lon, geolocation.Longitude);
216        }
217    }
218}
219
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

Trigger ShouldWork code on LambdaTest Cloud Grid

Execute automation tests with ShouldWork on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
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)