How to use new method of Microsoft.Playwright.NUnit.Worker class

Best Playwright-dotnet code snippet using Microsoft.Playwright.NUnit.Worker.new

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageEventRequestTests.cs

Source: PageEventRequestTests.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 PageEventRequestTests : PageTestEx
34    {
35        [PlaywrightTest("page-event-request.spec.ts", "should fire for navigation requests")]
36        public async Task ShouldFireForNavigationRequests()
37        {
38            var requests = new List<IRequest>();
39            Page.Request += (_, e) => requests.Add(e);
40            await Page.GotoAsync(Server.EmptyPage);
41            Assert.That(requests, Has.Count.EqualTo(1));
42        }
43
44        [PlaywrightTest("page-event-request.spec.ts", "should fire for iframes")]
45        public async Task ShouldFireForIframes()
46        {
47            var requests = new List<IRequest>();
48            Page.Request += (_, e) => requests.Add(e);
49            await Page.GotoAsync(Server.EmptyPage);
50            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
51            Assert.AreEqual(2, requests.Count);
52        }
53
54        [PlaywrightTest("page-event-request.spec.ts", "should fire for fetches")]
55        public async Task ShouldFireForFetches()
56        {
57            var requests = new List<IRequest>();
58            Page.Request += (_, e) => requests.Add(e);
59            await Page.GotoAsync(Server.EmptyPage);
60            await Page.EvaluateAsync("fetch('/empty.html')");
61            Assert.AreEqual(2, requests.Count);
62        }
63
64        [PlaywrightTest("page-event-request.spec.ts", "should report requests and responses handled by service worker")]
65        public async Task ShouldReportRequestsAndResponsesHandledByServiceWorker()
66        {
67            await Page.GotoAsync(Server.Prefix + "/serviceworkers/fetchdummy/sw.html");
68            await Page.EvaluateAsync("() => window.activationPromise");
69
70            var (request, swResponse) = await TaskUtils.WhenAll(
71                Page.WaitForRequestAsync("**/*"),
72                Page.EvaluateAsync<string>("() => fetchDummy('foo')"));
73
74            Assert.AreEqual("responseFromServiceWorker:foo", swResponse);
75            Assert.AreEqual(Server.Prefix + "/serviceworkers/fetchdummy/foo", request.Url);
76            var response = await request.ResponseAsync();
77            Assert.AreEqual(Server.Prefix + "/serviceworkers/fetchdummy/foo", response.Url);
78            Assert.AreEqual("responseFromServiceWorker:foo", await response.TextAsync());
79        }
80    }
81}
82
Full Screen

WorkersTests.cs

Source: WorkersTests.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.Text.Json;
28using System.Threading.Tasks;
29using Microsoft.Playwright.NUnit;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    public class WorkersTests : PageTestEx
35    {
36        [PlaywrightTest("workers.spec.ts", "Page.workers")]
37        public async Task PageWorkers()
38        {
39            await TaskUtils.WhenAll(
40                Page.WaitForWorkerAsync(),
41                Page.GotoAsync(Server.Prefix + "/worker/worker.html"));
42            var worker = Page.Workers.First();
43            StringAssert.Contains("worker.js", worker.Url);
44
45            Assert.AreEqual("worker function result", await worker.EvaluateAsync<string>("() => self['workerFunction']()"));
46
47            await Page.GotoAsync(Server.EmptyPage);
48            Assert.IsEmpty(Page.Workers);
49        }
50
51        [PlaywrightTest("workers.spec.ts", "should emit created and destroyed events")]
52        public async Task ShouldEmitCreatedAndDestroyedEvents()
53        {
54            var workerCreatedTcs = new TaskCompletionSource<IWorker>();
55            Page.Worker += (_, e) => workerCreatedTcs.TrySetResult(e);
56
57            var workerObj = await Page.EvaluateHandleAsync("() => new Worker(URL.createObjectURL(new Blob(['1'], {type: 'application/javascript'})))");
58            var worker = await workerCreatedTcs.Task;
59            var workerThisObj = await worker.EvaluateHandleAsync("() => this");
60            var workerDestroyedTcs = new TaskCompletionSource<IWorker>();
61            worker.Close += (sender, _) => workerDestroyedTcs.TrySetResult((IWorker)sender);
62            await Page.EvaluateAsync("workerObj => workerObj.terminate()", workerObj);
63            Assert.AreEqual(worker, await workerDestroyedTcs.Task);
64            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => workerThisObj.GetPropertyAsync("self"));
65            StringAssert.IsMatch("(Worker was closed)|(Target closed)", exception.Message);
66        }
67
68        [PlaywrightTest("workers.spec.ts", "should report console logs")]
69        public async Task ShouldReportConsoleLogs()
70        {
71            var (message, _) = await TaskUtils.WhenAll(
72                Page.WaitForConsoleMessageAsync(),
73                Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))")
74            );
75
76            Assert.AreEqual("1", message.Text);
77        }
78
79        [PlaywrightTest("workers.spec.ts", "should have JSHandles for console logs")]
80        public async Task ShouldHaveJSHandlesForConsoleLogs()
81        {
82            var consoleTcs = new TaskCompletionSource<IConsoleMessage>();
83            Page.Console += (_, e) => consoleTcs.TrySetResult(e);
84
85            await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1,2,3,this)'], {type: 'application/javascript'})))");
86            var log = await consoleTcs.Task;
87            if (TestConstants.IsFirefox)
88            {
89                Assert.AreEqual("1 2 3 [email protected]", log.Text);
90            }
91            else
92            {
93                Assert.AreEqual("1 2 3 DedicatedWorkerGlobalScope", log.Text);
94            }
95            Assert.AreEqual(4, log.Args.Count());
96            string json = await (await log.Args.ElementAt(3).GetPropertyAsync("origin")).JsonValueAsync<string>();
97            Assert.AreEqual("null", json);
98        }
99
100        [PlaywrightTest("workers.spec.ts", "should evaluate")]
101        public async Task ShouldEvaluate()
102        {
103            var workerCreatedTask = Page.WaitForWorkerAsync();
104            await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))");
105
106            await workerCreatedTask;
107            Assert.AreEqual(2, await workerCreatedTask.Result.EvaluateAsync<int>("1+1"));
108        }
109
110        [PlaywrightTest("workers.spec.ts", "should report errors")]
111        public async Task ShouldReportErrors()
112        {
113            var errorTcs = new TaskCompletionSource<string>();
114            Page.PageError += (_, e) => errorTcs.TrySetResult(e);
115
116            await Page.EvaluateAsync(@"() => new Worker(URL.createObjectURL(new Blob([`
117              setTimeout(() => {
118                // Do a console.log just to check that we do not confuse it with an error.
119                console.log('hey');
120                throw new Error('this is my error');
121              })
122            `], {type: 'application/javascript'})))");
123            string errorLog = await errorTcs.Task;
124            StringAssert.Contains("this is my error", errorLog);
125        }
126
127        [PlaywrightTest("workers.spec.ts", "should clear upon navigation")]
128        public async Task ShouldClearUponNavigation()
129        {
130            await Page.GotoAsync(Server.EmptyPage);
131            var workerCreatedTask = Page.WaitForWorkerAsync();
132            await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))");
133            var worker = await workerCreatedTask;
134
135            Assert.That(Page.Workers, Has.Count.EqualTo(1));
136            bool destroyed = false;
137            worker.Close += (_, _) => destroyed = true;
138
139            await Page.GotoAsync(Server.Prefix + "/one-style.html");
140            Assert.True(destroyed);
141            Assert.IsEmpty(Page.Workers);
142        }
143
144        [PlaywrightTest("workers.spec.ts", "should clear upon cross-process navigation")]
145        public async Task ShouldClearUponCrossProcessNavigation()
146        {
147            await Page.GotoAsync(Server.EmptyPage);
148            var workerCreatedTask = Page.WaitForWorkerAsync();
149            await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))");
150            var worker = await workerCreatedTask;
151
152            Assert.That(Page.Workers, Has.Count.EqualTo(1));
153            bool destroyed = false;
154            worker.Close += (_, _) => destroyed = true;
155
156            await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");
157            Assert.True(destroyed);
158            Assert.IsEmpty(Page.Workers);
159        }
160
161        [PlaywrightTest("workers.spec.ts", "should report network activity")]
162        public async Task ShouldReportNetworkActivity()
163        {
164            var (worker, _) = await TaskUtils.WhenAll(
165                Page.WaitForWorkerAsync(),
166                Page.GotoAsync(Server.Prefix + "/worker/worker.html")
167            );
168
169            string url = Server.Prefix + "/one-style.css";
170            var requestTask = Page.WaitForRequestAsync(url);
171            var responseTask = Page.WaitForResponseAsync(url);
172
173            await worker.EvaluateAsync<JsonElement>("url => fetch(url).then(response => response.text()).then(console.log)", url);
174
175            await TaskUtils.WhenAll(requestTask, responseTask);
176
177            Assert.AreEqual(url, requestTask.Result.Url);
178            Assert.AreEqual(requestTask.Result, responseTask.Result.Request);
179            Assert.True(responseTask.Result.Ok);
180        }
181
182        [PlaywrightTest("workers.spec.ts", "should report network activity on worker creation")]
183        public async Task ShouldReportNetworkActivityOnWorkerCreation()
184        {
185            await Page.GotoAsync(Server.EmptyPage);
186            string url = Server.Prefix + "/one-style.css";
187
188            var requestTask = Page.WaitForRequestAsync(url);
189            var responseTask = Page.WaitForResponseAsync(url);
190
191            await Page.EvaluateAsync(@"url => new Worker(URL.createObjectURL(new Blob([`
192                fetch(""${url}"").then(response => response.text()).then(console.log);
193              `], { type: 'application/javascript'})))", url);
194
195            await TaskUtils.WhenAll(requestTask, responseTask);
196
197            Assert.AreEqual(url, requestTask.Result.Url);
198            Assert.AreEqual(requestTask.Result, responseTask.Result.Request);
199            Assert.True(responseTask.Result.Ok);
200        }
201
202        [PlaywrightTest("workers.spec.ts", "should format number using context locale")]
203        public async Task ShouldFormatNumberUsingContextLocale()
204        {
205            await using var context = await Browser.NewContextAsync(new() { Locale = "ru-RU" });
206            var page = await context.NewPageAsync();
207            await page.GotoAsync(Server.EmptyPage);
208            var (worker, _) = await TaskUtils.WhenAll(
209                page.WaitForWorkerAsync(),
210                page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))"));
211
212            Assert.AreEqual("10\u00A0000,2", await worker.EvaluateAsync<string>("() => (10000.20).toLocaleString()"));
213        }
214    }
215}
216
Full Screen

HttpService.cs

Source: HttpService.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.Threading.Tasks;
26using Microsoft.Playwright.NUnit;
27using Microsoft.Playwright.Tests.TestServer;
28
29namespace Microsoft.Playwright.Tests
30{
31    public class HttpService : IWorkerService
32    {
33        public SimpleServer Server { get; internal set; }
34        public SimpleServer HttpsServer { get; internal set; }
35
36        public static Task<HttpService> Register(WorkerAwareTest test)
37        {
38            var workerIndex = test.WorkerIndex;
39            return test.RegisterService("Http", async () =>
40            {
41                var http = new HttpService
42                {
43                    Server = SimpleServer.Create(8907 + workerIndex * 2, TestUtils.FindParentDirectory("Playwright.Tests.TestServer")),
44                    HttpsServer = SimpleServer.CreateHttps(8907 + workerIndex * 2 + 1, TestUtils.FindParentDirectory("Playwright.Tests.TestServer"))
45                };
46                await Task.WhenAll(http.Server.StartAsync(), http.HttpsServer.StartAsync());
47                return http;
48            });
49        }
50
51        public Task ResetAsync()
52        {
53            Server.Reset();
54            HttpsServer.Reset();
55            return Task.CompletedTask;
56        }
57
58        public Task DisposeAsync()
59        {
60            return Task.WhenAll(Server.StopAsync(), HttpsServer.StopAsync());
61        }
62    }
63}
64
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 new code on LambdaTest Cloud Grid

Execute automation tests with new 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)