How to use ShouldWorkWithRedirects method of PuppeteerSharp.Tests.RequestInterceptionTests.SetRequestInterceptionTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.RequestInterceptionTests.SetRequestInterceptionTests.ShouldWorkWithRedirects

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

SetRequestInterceptionTests.cs

Source: SetRequestInterceptionTests.cs Github

copy
1using Microsoft.AspNetCore.Http;
2using System;
3using System.Collections.Generic;
4using System.IO;
5using System.Linq;
6using System.Net;
7using System.Net.Http;
8using System.Text;
9using System.Threading.Tasks;
10using Xunit;
11using Xunit.Abstractions;
12using PuppeteerSharp.Helpers;
13using PuppeteerSharp.Tests.Attributes;
14using PuppeteerSharp.Xunit;
15
16namespace PuppeteerSharp.Tests.RequestInterceptionTests
17{
18    [Collection(TestConstants.TestFixtureCollectionName)]
19    public class SetRequestInterceptionTests : PuppeteerPageBaseTest
20    {
21        public SetRequestInterceptionTests(ITestOutputHelper output) : base(output)
22        {
23        }
24
25        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should intercept")]
26        [SkipBrowserFact(skipFirefox: true)]
27        public async Task ShouldIntercept()
28        {
29            await Page.SetRequestInterceptionAsync(true);
30            Page.Request += async (_, e) =>
31            {
32                if (TestUtils.IsFavicon(e.Request))
33                {
34                    await e.Request.ContinueAsync();
35                    return;
36                }
37                Assert.Contains("empty.html", e.Request.Url);
38                Assert.NotNull(e.Request.Headers);
39                Assert.Equal(HttpMethod.Get, e.Request.Method);
40                Assert.Null(e.Request.PostData);
41                Assert.True(e.Request.IsNavigationRequest);
42                Assert.Equal(ResourceType.Document, e.Request.ResourceType);
43                Assert.Equal(Page.MainFrame, e.Request.Frame);
44                Assert.Equal(TestConstants.AboutBlank, e.Request.Frame.Url);
45                await e.Request.ContinueAsync();
46            };
47            var response = await Page.GoToAsync(TestConstants.EmptyPage);
48            Assert.True(response.Ok);
49
50            Assert.Equal(TestConstants.Port, response.RemoteAddress.Port);
51        }
52
53        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work when POST is redirected with 302")]
54        [SkipBrowserFact(skipFirefox: true)]
55        public async Task ShouldWorkWhenPostIsEedirectedWith302()
56        {
57            Server.SetRedirect("/rredirect", "/empty.html");
58            await Page.GoToAsync(TestConstants.EmptyPage);
59            await Page.SetRequestInterceptionAsync(true);
60            Page.Request += async (_, e) => await e.Request.ContinueAsync();
61
62            await Page.SetContentAsync(@"
63                <form action='/rredirect' method='post'>
64                    <input type='hidden' id='foo' name='foo' value='FOOBAR'>
65                </form>
66            ");
67            await Task.WhenAll(
68                Page.QuerySelectorAsync("form").EvaluateFunctionAsync("form => form.submit()"),
69                Page.WaitForNavigationAsync()
70            );
71        }
72
73        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work when header manipulation headers with redirect")]
74        [SkipBrowserFact(skipFirefox: true)]
75        public async Task ShouldWorkWhenHeaderManipulationHeadersWithRedirect()
76        {
77            Server.SetRedirect("/rredirect", "/empty.html");
78            await Page.SetRequestInterceptionAsync(true);
79
80            Page.Request += async (_, e) =>
81            {
82                var headers = e.Request.Headers.Clone();
83                headers["foo"] = "bar";
84                await e.Request.ContinueAsync(new Payload { Headers = headers });
85            };
86
87            await Page.GoToAsync(TestConstants.ServerUrl + "/rrredirect");
88        }
89
90        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should be able to remove headers")]
91        [SkipBrowserFact(skipFirefox: true)]
92        public async Task ShouldBeAbleToRemoveHeaders()
93        {
94            await Page.SetRequestInterceptionAsync(true);
95            Page.Request += async (_, e) =>
96            {
97                var headers = e.Request.Headers.Clone();
98                headers["foo"] = "bar";
99                headers.Remove("origin");
100                await e.Request.ContinueAsync(new Payload { Headers = headers });
101            };
102
103            var requestTask = Server.WaitForRequest("/empty.html", request => request.Headers["origin"]);
104            await Task.WhenAll(
105                requestTask,
106                Page.GoToAsync(TestConstants.ServerUrl + "/empty.html")
107            );
108            Assert.True(string.IsNullOrEmpty(requestTask.Result));
109        }
110
111        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should contain referer header")]
112        [SkipBrowserFact(skipFirefox: true)]
113        public async Task ShouldContainRefererHeader()
114        {
115            await Page.SetRequestInterceptionAsync(true);
116            var requests = new List<Request>();
117            var requestsReadyTcs = new TaskCompletionSource<bool>();
118
119            Page.Request += async (_, e) =>
120            {
121                if (!TestUtils.IsFavicon(e.Request))
122                {
123                    requests.Add(e.Request);
124
125                    if (requests.Count > 1)
126                    {
127                        requestsReadyTcs.TrySetResult(true);
128                    }
129                }
130                await e.Request.ContinueAsync();
131            };
132
133            await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
134            await requestsReadyTcs.Task.WithTimeout();
135            Assert.Contains("/one-style.css", requests[1].Url);
136            Assert.Contains("/one-style.html", requests[1].Headers["Referer"]);
137        }
138
139        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should properly return navigation response when URL has cookies")]
140        [SkipBrowserFact(skipFirefox: true)]
141        public async Task ShouldProperlyReturnNavigationResponseWhenURLHasCookies()
142        {
143            // Setup cookie.
144            await Page.GoToAsync(TestConstants.EmptyPage);
145            await Page.SetCookieAsync(new CookieParam
146            {
147                Name = "foo",
148                Value = "bar"
149            });
150
151            // Setup request interception.
152            await Page.SetRequestInterceptionAsync(true);
153            Page.Request += (sender, e) => _ = e.Request.ContinueAsync();
154            var response = await Page.ReloadAsync();
155            Assert.Equal(HttpStatusCode.OK, response.Status);
156        }
157
158        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should stop intercepting")]
159        [SkipBrowserFact(skipFirefox: true)]
160        public async Task ShouldStopIntercepting()
161        {
162            await Page.SetRequestInterceptionAsync(true);
163            async void EventHandler(object sender, RequestEventArgs e)
164            {
165                await e.Request.ContinueAsync();
166                Page.Request -= EventHandler;
167            }
168            Page.Request += EventHandler;
169            await Page.GoToAsync(TestConstants.EmptyPage);
170            await Page.SetRequestInterceptionAsync(false);
171            await Page.GoToAsync(TestConstants.EmptyPage);
172        }
173
174        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should show custom HTTP headers")]
175        [SkipBrowserFact(skipFirefox: true)]
176        public async Task ShouldShowCustomHTTPHeaders()
177        {
178            await Page.SetExtraHttpHeadersAsync(new Dictionary<string, string>
179            {
180                ["foo"] = "bar"
181            });
182            await Page.SetRequestInterceptionAsync(true);
183            Page.Request += async (_, e) =>
184            {
185                Assert.Equal("bar", e.Request.Headers["foo"]);
186                await e.Request.ContinueAsync();
187            };
188            var response = await Page.GoToAsync(TestConstants.EmptyPage);
189            Assert.True(response.Ok);
190        }
191
192        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with redirect inside sync XHR")]
193        [SkipBrowserFact(skipFirefox: true)]
194        public async Task ShouldWorkWithRedirectInsideSyncXHR()
195        {
196            await Page.GoToAsync(TestConstants.EmptyPage);
197            Server.SetRedirect("/logo.png", "/pptr.png");
198            await Page.SetRequestInterceptionAsync(true);
199            Page.Request += async (_, e) => await e.Request.ContinueAsync();
200
201            var status = await Page.EvaluateFunctionAsync<int>(@"async () =>
202            {
203                const request = new XMLHttpRequest();
204                request.open('GET', '/logo.png', false);  // `false` makes the request synchronous
205                request.send(null);
206                return request.status;
207            }");
208            Assert.Equal(200, status);
209        }
210
211        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with custom referer headers")]
212        [SkipBrowserFact(skipFirefox: true)]
213        public async Task ShouldWorkWithCustomRefererHeaders()
214        {
215            await Page.SetExtraHttpHeadersAsync(new Dictionary<string, string>
216            {
217                ["referer"] = TestConstants.EmptyPage
218            });
219            await Page.SetRequestInterceptionAsync(true);
220            Page.Request += async (_, e) =>
221            {
222                Assert.Equal(TestConstants.EmptyPage, e.Request.Headers["referer"]);
223                await e.Request.ContinueAsync();
224            };
225            var response = await Page.GoToAsync(TestConstants.EmptyPage);
226            Assert.True(response.Ok);
227        }
228
229        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should be abortable")]
230        [SkipBrowserFact(skipFirefox: true)]
231        public async Task ShouldBeAbortable()
232        {
233            await Page.SetRequestInterceptionAsync(true);
234            Page.Request += async (_, e) =>
235            {
236                if (e.Request.Url.EndsWith(".css"))
237                {
238                    await e.Request.AbortAsync();
239                }
240                else
241                {
242                    await e.Request.ContinueAsync();
243                }
244            };
245            var failedRequests = 0;
246            Page.RequestFailed += (_, _) => failedRequests++;
247            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
248            Assert.True(response.Ok);
249            Assert.Null(response.Request.Failure);
250            Assert.Equal(1, failedRequests);
251        }
252
253        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should be abortable with custom error codes")]
254        [SkipBrowserFact(skipFirefox: true)]
255        public async Task ShouldBeAbortableWithCustomErrorCodes()
256        {
257            await Page.SetRequestInterceptionAsync(true);
258            Page.Request += async (_, e) =>
259            {
260                await e.Request.AbortAsync(RequestAbortErrorCode.InternetDisconnected);
261            };
262            Request failedRequest = null;
263            Page.RequestFailed += (_, e) => failedRequest = e.Request;
264            await Page.GoToAsync(TestConstants.EmptyPage).ContinueWith(_ => { });
265            Assert.NotNull(failedRequest);
266            Assert.Equal("net::ERR_INTERNET_DISCONNECTED", failedRequest.Failure);
267        }
268
269        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should send referer")]
270        [SkipBrowserFact(skipFirefox: true)]
271        public async Task ShouldSendReferer()
272        {
273            await Page.SetExtraHttpHeadersAsync(new Dictionary<string, string>
274            {
275                ["referer"] = "http://google.com/"
276            });
277            await Page.SetRequestInterceptionAsync(true);
278            Page.Request += async (_, e) => await e.Request.ContinueAsync();
279            var requestTask = Server.WaitForRequest("/grid.html", request => request.Headers["referer"].ToString());
280            await Task.WhenAll(
281                requestTask,
282                Page.GoToAsync(TestConstants.ServerUrl + "/grid.html")
283            );
284            Assert.Equal("http://google.com/", requestTask.Result);
285        }
286
287        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should fail navigation when aborting main resource")]
288        [SkipBrowserFact(skipFirefox: true)]
289        public async Task ShouldFailNavigationWhenAbortingMainResource()
290        {
291            await Page.SetRequestInterceptionAsync(true);
292            Page.Request += async (_, e) => await e.Request.AbortAsync();
293            var exception = await Assert.ThrowsAsync<NavigationException>(
294                () => Page.GoToAsync(TestConstants.EmptyPage));
295
296            if (TestConstants.IsChrome)
297            {
298                Assert.Contains("net::ERR_FAILED", exception.Message);
299            }
300            else
301            {
302                Assert.Contains("NS_ERROR_FAILURE", exception.Message);
303            }
304        }
305
306        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with redirects")]
307        [SkipBrowserFact(skipFirefox: true)]
308        public async Task ShouldWorkWithRedirects()
309        {
310            await Page.SetRequestInterceptionAsync(true);
311            var requests = new List<Request>();
312            Page.Request += async (_, e) =>
313            {
314                await e.Request.ContinueAsync();
315                requests.Add(e.Request);
316            };
317
318            Server.SetRedirect("/non-existing-page.html", "/non-existing-page-2.html");
319            Server.SetRedirect("/non-existing-page-2.html", "/non-existing-page-3.html");
320            Server.SetRedirect("/non-existing-page-3.html", "/non-existing-page-4.html");
321            Server.SetRedirect("/non-existing-page-4.html", "/empty.html");
322            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/non-existing-page.html");
323            Assert.Equal(HttpStatusCode.OK, response.Status);
324            Assert.Contains("empty.html", response.Url);
325            Assert.Equal(5, requests.Count);
326            Assert.Equal(ResourceType.Document, requests[2].ResourceType);
327
328            // Check redirect chain
329            var redirectChain = response.Request.RedirectChain;
330            Assert.Equal(4, redirectChain.Length);
331            Assert.Contains("/non-existing-page.html", redirectChain[0].Url);
332            Assert.Contains("/non-existing-page-3.html", redirectChain[2].Url);
333
334            for (var i = 0; i < redirectChain.Length; ++i)
335            {
336                var request = redirectChain[i];
337                Assert.True(request.IsNavigationRequest);
338                Assert.Equal(request, request.RedirectChain.ElementAt(i));
339            }
340        }
341
342        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with redirects for subresources")]
343        [SkipBrowserFact(skipFirefox: true)]
344        public async Task ShouldWorkWithRedirectsForSubresources()
345        {
346            await Page.SetRequestInterceptionAsync(true);
347            var requests = new List<Request>();
348            Page.Request += async (_, e) =>
349            {
350                if (!TestUtils.IsFavicon(e.Request))
351                {
352                    requests.Add(e.Request);
353                }
354
355                await e.Request.ContinueAsync();
356            };
357
358            Server.SetRedirect("/one-style.css", "/two-style.css");
359            Server.SetRedirect("/two-style.css", "/three-style.css");
360            Server.SetRedirect("/three-style.css", "/four-style.css");
361            Server.SetRoute("/four-style.css", async context =>
362            {
363                await context.Response.WriteAsync("body {box-sizing: border-box; }");
364            });
365
366            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
367            Assert.Equal(HttpStatusCode.OK, response.Status);
368            Assert.Contains("one-style.html", response.Url);
369            Assert.Equal(5, requests.Count);
370            Assert.Equal(ResourceType.Document, requests[0].ResourceType);
371            Assert.Equal(ResourceType.StyleSheet, requests[1].ResourceType);
372
373            // Check redirect chain
374            var redirectChain = requests[1].RedirectChain;
375            Assert.Equal(3, redirectChain.Length);
376            Assert.Contains("one-style.css", redirectChain[0].Url);
377            Assert.Contains("three-style.css", redirectChain[2].Url);
378        }
379
380        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should be able to abort redirects")]
381        [SkipBrowserFact(skipFirefox: true)]
382        public async Task ShouldBeAbleToAbortRedirects()
383        {
384            await Page.SetRequestInterceptionAsync(true);
385            Server.SetRedirect("/non-existing.json", "/non-existing-2.json");
386            Server.SetRedirect("/non-existing-2.json", "/simple.html");
387            Page.Request += async (_, e) =>
388            {
389                if (e.Request.Url.Contains("non-existing-2"))
390                {
391                    await e.Request.AbortAsync();
392                }
393                else
394                {
395                    await e.Request.ContinueAsync();
396                }
397            };
398            await Page.GoToAsync(TestConstants.EmptyPage);
399            var result = await Page.EvaluateFunctionAsync<string>(@"async () => {
400                try
401                {
402                    await fetch('/non-existing.json');
403                }
404                catch (e)
405                {
406                    return e.message;
407                }
408            }");
409
410            if (TestConstants.IsChrome)
411            {
412                Assert.Contains("Failed to fetch", result);
413            }
414            else
415            {
416                Assert.Contains("NetworkError", result);
417            }
418        }
419
420        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with equal requests")]
421        [SkipBrowserFact(skipFirefox: true)]
422        public async Task ShouldWorkWithEqualRequests()
423        {
424            await Page.GoToAsync(TestConstants.EmptyPage);
425            var responseCount = 1;
426            Server.SetRoute("/zzz", context => context.Response.WriteAsync(((responseCount++) * 11) + string.Empty));
427            await Page.SetRequestInterceptionAsync(true);
428
429            var spinner = false;
430            // Cancel 2nd request.
431            Page.Request += async (_, e) =>
432            {
433                if (TestUtils.IsFavicon(e.Request))
434                {
435                    await e.Request.ContinueAsync();
436                    return;
437                }
438
439                if (spinner)
440                {
441                    spinner = !spinner;
442                    await e.Request.AbortAsync();
443                }
444                else
445                {
446                    spinner = !spinner;
447                    await e.Request.ContinueAsync();
448                }
449            };
450            var results = await Page.EvaluateExpressionAsync<string[]>(@"Promise.all([
451              fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),
452              fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),
453              fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),
454            ])");
455            Assert.Equal(new[] { "11", "FAILED", "22" }, results);
456        }
457
458        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should navigate to dataURL and fire dataURL requests")]
459        [SkipBrowserFact(skipFirefox: true)]
460        public async Task ShouldNavigateToDataURLAndFireDataURLRequests()
461        {
462            await Page.SetRequestInterceptionAsync(true);
463            var requests = new List<Request>();
464            Page.Request += async (_, e) =>
465            {
466                requests.Add(e.Request);
467                await e.Request.ContinueAsync();
468            };
469            var dataURL = "data:text/html,<div>yo</div>";
470            var response = await Page.GoToAsync(dataURL);
471            Assert.Equal(HttpStatusCode.OK, response.Status);
472            Assert.Single(requests);
473            Assert.Equal(dataURL, requests[0].Url);
474        }
475
476        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should be able to fetch dataURL and fire dataURL requests")]
477        [SkipBrowserFact(skipFirefox: true)]
478        public async Task ShouldBeAbleToFetchDataURLAndFireDataURLRequests()
479        {
480            await Page.GoToAsync(TestConstants.EmptyPage);
481            await Page.SetRequestInterceptionAsync(true);
482            var requests = new List<Request>();
483            Page.Request += async (_, e) =>
484            {
485                requests.Add(e.Request);
486                await e.Request.ContinueAsync();
487            };
488            var dataURL = "data:text/html,<div>yo</div>";
489            var text = await Page.EvaluateFunctionAsync<string>("url => fetch(url).then(r => r.text())", dataURL);
490
491            Assert.Equal("<div>yo</div>", text);
492            Assert.Single(requests);
493            Assert.Equal(dataURL, requests[0].Url);
494        }
495
496        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should navigate to URL with hash and fire requests without hash")]
497        [SkipBrowserFact(skipFirefox: true)]
498        public async Task ShouldNavigateToURLWithHashAndAndFireRequestsWithoutHash()
499        {
500            await Page.SetRequestInterceptionAsync(true);
501            var requests = new List<Request>();
502            Page.Request += async (_, e) =>
503            {
504                requests.Add(e.Request);
505                await e.Request.ContinueAsync();
506            };
507            var response = await Page.GoToAsync(TestConstants.EmptyPage + "#hash");
508            Assert.Equal(HttpStatusCode.OK, response.Status);
509            Assert.Equal(TestConstants.EmptyPage, response.Url);
510            Assert.Single(requests);
511            Assert.Equal(TestConstants.EmptyPage, requests[0].Url);
512        }
513
514        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with encoded server")]
515        [SkipBrowserFact(skipFirefox: true)]
516        public async Task ShouldWorkWithEncodedServer()
517        {
518            // The requestWillBeSent will report encoded URL, whereas interception will
519            // report URL as-is. @see crbug.com/759388
520            await Page.SetRequestInterceptionAsync(true);
521            Page.Request += async (_, e) => await e.Request.ContinueAsync();
522            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/some nonexisting page");
523            Assert.Equal(HttpStatusCode.NotFound, response.Status);
524        }
525
526        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with badly encoded server")]
527        [SkipBrowserFact(skipFirefox: true)]
528        public async Task ShouldWorkWithBadlyEncodedServer()
529        {
530            await Page.SetRequestInterceptionAsync(true);
531            Server.SetRoute("/malformed?rnd=%911", _ => Task.CompletedTask);
532            Page.Request += async (_, e) => await e.Request.ContinueAsync();
533            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/malformed?rnd=%911");
534            Assert.Equal(HttpStatusCode.OK, response.Status);
535        }
536
537        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with encoded server - 2")]
538        [SkipBrowserFact(skipFirefox: true)]
539        public async Task ShouldWorkWithEncodedServerNegative2()
540        {
541            // The requestWillBeSent will report URL as-is, whereas interception will
542            // report encoded URL for stylesheet. @see crbug.com/759388
543            await Page.SetRequestInterceptionAsync(true);
544            var requests = new List<Request>();
545            Page.Request += async (_, e) =>
546            {
547                requests.Add(e.Request);
548                await e.Request.ContinueAsync();
549            };
550            var response = await Page.GoToAsync($"data:text/html,<link rel=\"stylesheet\" href=\"{TestConstants.ServerUrl}/fonts?helvetica|arial\"/>");
551            Assert.Equal(HttpStatusCode.OK, response.Status);
552            Assert.Equal(2, requests.Count);
553            Assert.Equal(HttpStatusCode.NotFound, requests[1].Response.Status);
554        }
555
556        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should not throw \"Invalid Interception Id\" if the request was cancelled")]
557        [SkipBrowserFact(skipFirefox: true)]
558        public async Task ShouldNotThrowInvalidInterceptionIdIfTheRequestWasCancelled()
559        {
560            await Page.SetContentAsync("<iframe></iframe>");
561            await Page.SetRequestInterceptionAsync(true);
562            Request request = null;
563            var requestIntercepted = new TaskCompletionSource<bool>();
564            Page.Request += (_, e) =>
565            {
566                request = e.Request;
567                requestIntercepted.SetResult(true);
568            };
569
570            var _ = Page.QuerySelectorAsync("iframe").EvaluateFunctionAsync<object>("(frame, url) => frame.src = url", TestConstants.ServerUrl);
571            // Wait for request interception.
572            await requestIntercepted.Task;
573            // Delete frame to cause request to be canceled.
574            _ = Page.QuerySelectorAsync("iframe").EvaluateFunctionAsync<object>("frame => frame.remove()");
575            await request.ContinueAsync();
576        }
577
578        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should throw if interception is not enabled")]
579        [SkipBrowserFact(skipFirefox: true)]
580        public async Task ShouldThrowIfInterceptionIsNotEnabled()
581        {
582            Exception exception = null;
583            Page.Request += async (_, e) =>
584            {
585                try
586                {
587                    await e.Request.ContinueAsync();
588                }
589                catch (Exception ex)
590                {
591                    exception = ex;
592                }
593            };
594            await Page.GoToAsync(TestConstants.EmptyPage);
595            Assert.Contains("Request Interception is not enabled", exception.Message);
596        }
597
598        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should work with file URLs")]
599        [SkipBrowserFact(skipFirefox: true)]
600        public async Task ShouldWorkWithFileURLs()
601        {
602            await Page.SetRequestInterceptionAsync(true);
603            var urls = new List<string>();
604            Page.Request += async (_, e) =>
605            {
606                urls.Add(e.Request.Url.Split('/').Last());
607                await e.Request.ContinueAsync();
608            };
609
610            var uri = new Uri(Path.Combine(Directory.GetCurrentDirectory(), "Assets", "one-style.html")).AbsoluteUri;
611            await Page.GoToAsync(uri);
612            Assert.Equal(2, urls.Count);
613            Assert.Contains("one-style.html", urls);
614            Assert.Contains("one-style.css", urls);
615        }
616
617        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should not cache if cache disabled")]
618        [SkipBrowserFact(skipFirefox: true)]
619        public async Task ShouldNotCacheIfCacheDisabled()
620        {
621            await Page.GoToAsync(TestConstants.ServerUrl + "/cached/one-style.html");
622            await Page.SetRequestInterceptionAsync(true);
623            await Page.SetCacheEnabledAsync(false);
624            var urls = new List<string>();
625            Page.Request += (_, e) => _ = e.Request.ContinueAsync();
626
627            var cached = new List<Request>();
628            Page.RequestServedFromCache += (_, e) => cached.Add(e.Request);
629
630            await Page.ReloadAsync();
631            Assert.Empty(cached);
632        }
633
634        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should cache if cache enabled")]
635        [SkipBrowserFact(skipFirefox: true)]
636        public async Task ShouldNotCacheIfCacheEnabled()
637        {
638            await Page.GoToAsync(TestConstants.ServerUrl + "/cached/one-style.html");
639            await Page.SetRequestInterceptionAsync(true);
640            await Page.SetCacheEnabledAsync(true);
641            var urls = new List<string>();
642            Page.Request += (_, e) => _ = e.Request.ContinueAsync();
643
644            var cached = new List<Request>();
645            Page.RequestServedFromCache += (_, e) => cached.Add(e.Request);
646
647            await Page.ReloadAsync();
648            Assert.Single(cached);
649        }
650
651        [PuppeteerTest("requestinterception.spec.ts", "Page.setRequestInterception", "should load fonts if cache enabled")]
652        [SkipBrowserFact(skipFirefox: true)]
653        public async Task ShouldLoadFontsIfCacheEnabled()
654        {
655            await Page.SetRequestInterceptionAsync(true);
656            await Page.SetCacheEnabledAsync(true);
657            var urls = new List<string>();
658            Page.Request += (_, e) => _ = e.Request.ContinueAsync();
659
660            var waitTask = Page.WaitForResponseAsync(response => response.Url.EndsWith("/one-style.woff"));
661            await Page.GoToAsync(TestConstants.ServerUrl + "/cached/one-style-font.html");
662            await waitTask;
663        }
664    }
665}
666
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