How to use ShouldIntercept method of Microsoft.Playwright.Tests.BrowserContextRouteTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.BrowserContextRouteTests.ShouldIntercept

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BrowserContextRouteTests.cs

Source: BrowserContextRouteTests.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;
26using System.Collections.Generic;
27using System.Net;
28using System.Net.Http;
29using System.Threading.Tasks;
30using Microsoft.Playwright.NUnit;
31using NUnit.Framework;
32
33namespace Microsoft.Playwright.Tests
34{
35    public class BrowserContextRouteTests : BrowserTestEx
36    {
37        [PlaywrightTest("browsercontext-route.spec.ts", "should intercept")]
38        public async Task ShouldIntercept()
39        {
40            bool intercepted = false;
41
42            await using var context = await Browser.NewContextAsync();
43            IPage page = null;
44
45            await context.RouteAsync("**/empty.html", (route) =>
46            {
47                intercepted = true;
48
49                StringAssert.Contains("empty.html", route.Request.Url);
50#pragma warning disable 0612
51                Assert.False(string.IsNullOrEmpty(route.Request.Headers["user-agent"]));
52#pragma warning restore 0612
53                Assert.AreEqual(HttpMethod.Get.Method, route.Request.Method);
54                Assert.Null(route.Request.PostData);
55                Assert.True(route.Request.IsNavigationRequest);
56                Assert.AreEqual("document", route.Request.ResourceType);
57                Assert.AreEqual(page.MainFrame, route.Request.Frame);
58                Assert.AreEqual("about:blank", page.MainFrame.Url);
59
60                route.ContinueAsync();
61            });
62
63            page = await context.NewPageAsync();
64            var response = await page.GotoAsync(Server.EmptyPage);
65            Assert.True(response.Ok);
66            Assert.True(intercepted);
67        }
68
69        [PlaywrightTest("browsercontext-route.spec.ts", "should unroute")]
70        public async Task ShouldUnroute()
71        {
72            await using var context = await Browser.NewContextAsync();
73            var page = await context.NewPageAsync();
74            var intercepted = new List<int>();
75
76
77            await context.RouteAsync("**/*", route =>
78            {
79                intercepted.Add(1);
80                route.ContinueAsync();
81            });
82
83            await context.RouteAsync("**/empty.html", (route) =>
84            {
85                intercepted.Add(2);
86                route.ContinueAsync();
87            });
88
89            await context.RouteAsync("**/empty.html", (route) =>
90            {
91                intercepted.Add(3);
92                route.ContinueAsync();
93            });
94
95            Action<IRoute> handler4 = (route) =>
96            {
97                intercepted.Add(4);
98                route.ContinueAsync();
99            };
100            await context.RouteAsync("**/empty.html", handler4);
101
102            await page.GotoAsync(Server.EmptyPage);
103            Assert.AreEqual(new List<int>() { 4 }, intercepted);
104
105            intercepted.Clear();
106            await context.UnrouteAsync("**/empty.html", handler4);
107            await page.GotoAsync(Server.EmptyPage);
108            Assert.AreEqual(new List<int>() { 3 }, intercepted);
109
110            intercepted.Clear();
111            await context.UnrouteAsync("**/empty.html");
112            await page.GotoAsync(Server.EmptyPage);
113            Assert.AreEqual(new List<int>() { 1 }, intercepted);
114        }
115
116        [PlaywrightTest]
117        public async Task ShouldUnroutePageWithBaseUrl()
118        {
119            var options = new BrowserNewContextOptions();
120            options.BaseURL = Server.Prefix;
121
122            await using var context = await Browser.NewContextAsync(options);
123            var page = await context.NewPageAsync();
124            var intercepted = new List<int>();
125
126            await page.RouteAsync("/empty.html", (route) =>
127            {
128                intercepted.Add(1);
129                route.ContinueAsync();
130            });
131
132            Action<IRoute> handler2 = (route) =>
133            {
134                intercepted.Add(2);
135                route.ContinueAsync();
136            };
137            await page.RouteAsync("/empty.html", handler2);
138
139            await page.GotoAsync(Server.EmptyPage);
140            Assert.AreEqual(new List<int>() { 2 }, intercepted);
141
142            intercepted.Clear();
143            await page.UnrouteAsync("/empty.html", handler2);
144            await page.GotoAsync(Server.EmptyPage);
145            Assert.AreEqual(new List<int>() { 1 }, intercepted);
146        }
147
148        [PlaywrightTest("browsercontext-route.spec.ts", "should yield to page.route")]
149        public async Task ShouldYieldToPageRoute()
150        {
151            await using var context = await Browser.NewContextAsync();
152            await context.RouteAsync("**/empty.html", (route) =>
153            {
154                route.FulfillAsync(new() { Status = (int)HttpStatusCode.OK, Body = "context" });
155            });
156
157            var page = await context.NewPageAsync();
158            await page.RouteAsync("**/empty.html", (route) =>
159            {
160                route.FulfillAsync(new() { Status = (int)HttpStatusCode.OK, Body = "page" });
161            });
162
163            var response = await page.GotoAsync(Server.EmptyPage);
164            Assert.AreEqual("page", await response.TextAsync());
165        }
166
167        [PlaywrightTest("browsercontext-route.spec.ts", "should fall back to context.route")]
168        public async Task ShouldFallBackToContextRoute()
169        {
170            await using var context = await Browser.NewContextAsync();
171            await context.RouteAsync("**/empty.html", (route) =>
172            {
173                route.FulfillAsync(new() { Status = (int)HttpStatusCode.OK, Body = "context" });
174            });
175
176            var page = await context.NewPageAsync();
177            await page.RouteAsync("**/non-empty.html", (route) =>
178            {
179                route.FulfillAsync(new() { Status = (int)HttpStatusCode.OK, Body = "page" });
180            });
181
182            var response = await page.GotoAsync(Server.EmptyPage);
183            Assert.AreEqual("context", await response.TextAsync());
184        }
185
186        [PlaywrightTest]
187        public async Task ShouldThrowOnInvalidRouteUrl()
188        {
189            await using var context = await Browser.NewContextAsync();
190
191#if NETCOREAPP3_1
192            var regexParseExceptionType = typeof(System.Text.RegularExpressions.Regex).Assembly
193                .GetType("System.Text.RegularExpressions.RegexParseException", throwOnError: true);
194#else
195            var regexParseExceptionType = typeof(System.Text.RegularExpressions.RegexParseException);
196#endif
197
198            Assert.Throws(regexParseExceptionType, () =>
199                context.RouteAsync("[", route =>
200                {
201                    route.ContinueAsync();
202                })
203            );
204        }
205
206        [PlaywrightTest("browsercontext-route.spec.ts", "should support the times parameter with route matching")]
207        public async Task ShouldSupportTheTimesParameterWithRouteMatching()
208        {
209            await using var context = await Browser.NewContextAsync();
210            var page = await context.NewPageAsync();
211            List<int> intercepted = new();
212            await context.RouteAsync("**/empty.html", (route) =>
213            {
214                intercepted.Add(1);
215                route.ContinueAsync();
216            }, new() { Times = 1 });
217
218            await page.GotoAsync(Server.EmptyPage);
219            await page.GotoAsync(Server.EmptyPage);
220            await page.GotoAsync(Server.EmptyPage);
221            Assert.AreEqual(1, intercepted.Count);
222        }
223    }
224}
225
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 ShouldIntercept code on LambdaTest Cloud Grid

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