How to use ShouldReturnNavigationBitWhenNavigatingToImage method of Microsoft.Playwright.Tests.PageNetworkRequestTest class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageNetworkRequestTest.ShouldReturnNavigationBitWhenNavigatingToImage

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageNetworkRequestTest.cs

Source: PageNetworkRequestTest.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.Collections.Generic;
26using System.Linq;
27using System.Threading.Tasks;
28using Microsoft.AspNetCore.Http;
29using Microsoft.Playwright.NUnit;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    ///<playwright-file>network-request.spec.ts</playwright-file>
35    public class PageNetworkRequestTest : PageTestEx
36    {
37        [PlaywrightTest("page-network-request.spec.ts", "should work for main frame navigation request")]
38        public async Task ShouldWorkForMainFrameNavigationRequests()
39        {
40            var requests = new List<IRequest>();
41            Page.Request += (_, e) => requests.Add(e);
42            await Page.GotoAsync(Server.EmptyPage);
43            Assert.That(requests, Has.Count.EqualTo(1));
44            Assert.AreEqual(Page.MainFrame, requests[0].Frame);
45        }
46
47        [PlaywrightTest("page-network-request.spec.ts", "should work for subframe navigation request")]
48        public async Task ShouldWorkForSubframeNavigationRequest()
49        {
50            var requests = new List<IRequest>();
51            Page.Request += (_, e) => requests.Add(e);
52
53            await Page.GotoAsync(Server.EmptyPage);
54
55            await FrameUtils.AttachFrameAsync(Page, "frame1", Server.EmptyPage);
56            Assert.AreEqual(2, requests.Count);
57            Assert.AreEqual(Page.FirstChildFrame(), requests[1].Frame);
58        }
59
60        [PlaywrightTest("page-network-request.spec.ts", "should work for fetch requests")]
61        public async Task ShouldWorkForFetchRequests()
62        {
63            await Page.GotoAsync(Server.EmptyPage);
64            var requests = new List<IRequest>();
65            Page.Request += (_, e) => requests.Add(e);
66            await Page.EvaluateAsync("fetch('/digits/1.png')");
67            Assert.AreEqual(1, requests.Where(r => !r.Url.Contains("favicon")).Count());
68            Assert.AreEqual(Page.MainFrame, requests[0].Frame);
69        }
70
71        [PlaywrightTest("page-network-request.spec.ts", "should return headers")]
72        public async Task ShouldReturnHeaders()
73        {
74            var response = await Page.GotoAsync(Server.EmptyPage);
75
76            string expected = TestConstants.BrowserName switch
77            {
78                "chromium" => "Chrome",
79                "firefox" => "Firefox",
80                "webkit" => "WebKit",
81                _ => "None"
82            };
83
84#pragma warning disable 0612
85            StringAssert.Contains(expected, response.Request.Headers["user-agent"]);
86#pragma warning restore 0612
87        }
88
89        [PlaywrightTest("page-network-request.spec.ts", "should return postData")]
90        public async Task ShouldReturnPostData()
91        {
92            await Page.GotoAsync(Server.EmptyPage);
93            Server.SetRoute("/post", _ => Task.CompletedTask);
94            IRequest request = null;
95            Page.Request += (_, e) => request = e;
96            await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})");
97            Assert.NotNull(request);
98            Assert.AreEqual("{\"foo\":\"bar\"}", request.PostData);
99        }
100
101        [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data")]
102        public async Task ShouldWorkWithBinaryPostData()
103        {
104            await Page.GotoAsync(Server.EmptyPage);
105            Server.SetRoute("/post", _ => Task.CompletedTask);
106            IRequest request = null;
107            Page.Request += (_, e) => request = e;
108            await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })");
109            Assert.NotNull(request);
110            byte[] data = request.PostDataBuffer;
111            Assert.AreEqual(256, data.Length);
112
113            for (int index = 0; index < data.Length; index++)
114            {
115                Assert.AreEqual(index, data[index]);
116            }
117        }
118
119        [PlaywrightTest("page-network-request.spec.ts", "should work with binary post data and interception")]
120        public async Task ShouldWorkWithBinaryPostDataAndInterception()
121        {
122            await Page.GotoAsync(Server.EmptyPage);
123            Server.SetRoute("/post", _ => Task.CompletedTask);
124            await Page.RouteAsync("/post", (route) => route.ContinueAsync());
125            IRequest request = null;
126            Page.Request += (_, e) => request = e;
127            await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })");
128            Assert.NotNull(request);
129            byte[] data = request.PostDataBuffer;
130            Assert.AreEqual(256, data.Length);
131
132            for (int index = 0; index < data.Length; index++)
133            {
134                Assert.AreEqual(index, data[index]);
135            }
136        }
137
138        [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")]
139        public async Task ShouldBeUndefinedWhenThereIsNoPostData()
140        {
141            var response = await Page.GotoAsync(Server.EmptyPage);
142            Assert.Null(response.Request.PostData);
143        }
144
145
146        [PlaywrightTest("page-network-request.spec.ts", "should parse the json post data")]
147        public async Task ShouldParseTheJsonPostData()
148        {
149            await Page.GotoAsync(Server.EmptyPage);
150            Server.SetRoute("/post", _ => Task.CompletedTask);
151            IRequest request = null;
152            Page.Request += (_, e) => request = e;
153            await Page.EvaluateHandleAsync("fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar'})})");
154            Assert.NotNull(request);
155            Assert.AreEqual("bar", request.PostDataJSON()?.GetProperty("foo").ToString());
156        }
157
158        [PlaywrightTest("page-network-request.spec.ts", "should parse the data if content-type is application/x-www-form-urlencoded")]
159        public async Task ShouldParseTheDataIfContentTypeIsApplicationXWwwFormUrlencoded()
160        {
161            await Page.GotoAsync(Server.EmptyPage);
162            Server.SetRoute("/post", _ => Task.CompletedTask);
163            IRequest request = null;
164            Page.Request += (_, e) => request = e;
165            await Page.SetContentAsync("<form method='POST' action='/post'><input type='text' name='foo' value='bar'><input type='number' name='baz' value='123'><input type='submit'></form>");
166            await Page.ClickAsync("input[type=submit]");
167
168            Assert.NotNull(request);
169            var element = request.PostDataJSON();
170            Assert.AreEqual("bar", element?.GetProperty("foo").ToString());
171            Assert.AreEqual("123", element?.GetProperty("baz").ToString());
172        }
173
174        [PlaywrightTest("page-network-request.spec.ts", "should be |undefined| when there is no post data")]
175        public async Task ShouldBeUndefinedWhenThereIsNoPostData2()
176        {
177            var response = await Page.GotoAsync(Server.EmptyPage);
178            Assert.Null(response.Request.PostDataJSON());
179        }
180
181        [PlaywrightTest("page-network-request.spec.ts", "should return event source")]
182        public async Task ShouldReturnEventSource()
183        {
184            const string sseMessage = "{\"foo\": \"bar\"}";
185
186            Server.SetRoute("/sse", async ctx =>
187            {
188                ctx.Response.Headers["content-type"] = "text/event-stream";
189                ctx.Response.Headers["connection"] = "keep-alive";
190                ctx.Response.Headers["cache-control"] = "no-cache";
191
192                await ctx.Response.Body.FlushAsync();
193                await ctx.Response.WriteAsync($"data: {sseMessage}\r\r");
194                await ctx.Response.Body.FlushAsync();
195            });
196
197            await Page.GotoAsync(Server.EmptyPage);
198            var requests = new List<IRequest>();
199            Page.Request += (_, e) => requests.Add(e);
200
201            Assert.AreEqual(sseMessage, await Page.EvaluateAsync<string>(@"() => {
202                const eventSource = new EventSource('/sse');
203                return new Promise(resolve => {
204                    eventSource.onmessage = e => resolve(e.data);
205                });
206            }"));
207
208            Assert.AreEqual("eventsource", requests[0].ResourceType);
209        }
210
211        [PlaywrightTest("page-network-request.spec.ts", "should return navigation bit")]
212        public async Task ShouldReturnNavigationBit()
213        {
214            var requests = new Dictionary<string, IRequest>();
215            Page.Request += (_, e) => requests[e.Url.Split('/').Last()] = e;
216            Server.SetRedirect("/rrredirect", "/frames/one-frame.html");
217            await Page.GotoAsync(Server.Prefix + "/rrredirect");
218            Assert.True(requests["rrredirect"].IsNavigationRequest);
219            Assert.True(requests["one-frame.html"].IsNavigationRequest);
220            Assert.True(requests["frame.html"].IsNavigationRequest);
221            Assert.False(requests["script.js"].IsNavigationRequest);
222            Assert.False(requests["style.css"].IsNavigationRequest);
223        }
224
225        [PlaywrightTest("page-network-request.spec.ts", "Request.isNavigationRequest", "should return navigation bit when navigating to image")]
226        public async Task ShouldReturnNavigationBitWhenNavigatingToImage()
227        {
228            var requests = new List<IRequest>();
229            Page.Request += (_, e) => requests.Add(e);
230            await Page.GotoAsync(Server.Prefix + "/pptr.png");
231            Assert.True(requests[0].IsNavigationRequest);
232        }
233
234        [PlaywrightTest("page-network-request.spec.ts", "should set bodySize and headersSize")]
235        public async Task ShouldSetBodySizeAndHeaderSize()
236        {
237            await Page.GotoAsync(Server.EmptyPage);
238            var tsc = new TaskCompletionSource<RequestSizesResult>();
239            Page.Request += async (sender, r) =>
240            {
241                await (await r.ResponseAsync()).FinishedAsync();
242                tsc.SetResult(await r.SizesAsync());
243            };
244            await Page.EvaluateAsync("() => fetch('./get', { method: 'POST', body: '12345'}).then(r => r.text())");
245
246            var sizes = await tsc.Task;
247            Assert.AreEqual(5, sizes.RequestBodySize);
248            Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);
249        }
250
251        [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 if there was no body")]
252        public async Task ShouldSetBodysizeTo0IfThereWasNoBody()
253        {
254            await Page.GotoAsync(Server.EmptyPage);
255            var tsc = new TaskCompletionSource<RequestSizesResult>();
256            Page.Request += async (sender, r) =>
257            {
258                await (await r.ResponseAsync()).FinishedAsync();
259                tsc.SetResult(await r.SizesAsync());
260            };
261            await Page.EvaluateAsync("() => fetch('./get').then(r => r.text())");
262
263            var sizes = await tsc.Task;
264            Assert.AreEqual(0, sizes.RequestBodySize);
265            Assert.GreaterOrEqual(sizes.RequestHeadersSize, 200);
266        }
267
268        [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize, headersSize, and transferSize")]
269        [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Chromium, SkipAttribute.Targets.Webkit)]
270        public async Task ShouldSetAllTheResponseSizes()
271        {
272            Server.SetRoute("/get", async ctx =>
273            {
274                ctx.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";
275                await ctx.Response.WriteAsync("abc134");
276                await ctx.Response.CompleteAsync();
277            });
278
279            await Page.GotoAsync(Server.EmptyPage);
280            var tsc = new TaskCompletionSource<RequestSizesResult>();
281            Page.Request += async (sender, r) =>
282            {
283                await (await r.ResponseAsync()).FinishedAsync();
284                tsc.SetResult(await r.SizesAsync());
285            };
286            var message = await Page.EvaluateAsync<string>("() => fetch('./get').then(r => r.arrayBuffer()).then(b => b.bufferLength)");
287            var sizes = await tsc.Task;
288
289            Assert.AreEqual(6, sizes.ResponseBodySize);
290            Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);
291        }
292
293        [PlaywrightTest("page-network-request.spec.ts", "should should set bodySize to 0 when there was no response body")]
294        public async Task ShouldSetBodySizeTo0WhenNoResponseBody()
295        {
296            var response = await Page.GotoAsync(Server.EmptyPage);
297            await response.FinishedAsync();
298
299            var sizes = await response.Request.SizesAsync();
300
301            Assert.AreEqual(0, sizes.ResponseBodySize);
302            Assert.GreaterOrEqual(sizes.ResponseHeadersSize, 142);
303        }
304
305
306        [PlaywrightTest("page-network-request.spec.ts", "should report raw headers")]
307        public async Task ShouldReportRawHeaders()
308        {
309            var expectedHeaders = new Dictionary<string, string>();
310            Server.SetRoute("/headers", async ctx =>
311            {
312                expectedHeaders.Clear();
313                foreach (var header in ctx.Request.Headers)
314                {
315                    expectedHeaders.Add(header.Key.ToLower(), header.Value);
316                }
317
318                await ctx.Response.CompleteAsync();
319            });
320
321            await Page.GotoAsync(Server.EmptyPage);
322            //Page.RunAndWaitForRequestFinishedAsync(
323            //    async () => await Page.EvaluateAsync("**/*")
324            var requestTask = Page.WaitForRequestAsync("**/*");
325            var evalTask = Page.EvaluateAsync(@"() =>
326fetch('/headers', {
327      headers: [
328        ['header-a', 'value-a'],
329        ['header-b', 'value-b'],
330        ['header-a', 'value-a-1'],
331        ['header-a', 'value-a-2'],
332      ]
333    })
334");
335            await Task.WhenAll(requestTask, evalTask);
336            var req = requestTask.Result;
337            Assert.AreEqual("value-a, value-a-1, value-a-2", await req.HeaderValueAsync("header-a"));
338            Assert.IsNull(await req.HeaderValueAsync("not-there"));
339        }
340    }
341}
342
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)