How to use ShouldAllowMockingSvgWithCharset method of Microsoft.Playwright.Tests.RequestFulfillTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.RequestFulfillTests.ShouldAllowMockingSvgWithCharset

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageRequestFulfillTests.cs

Source: PageRequestFulfillTests.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.IO;
27using System.Linq;
28using System.Net;
29using System.Threading.Tasks;
30using Microsoft.AspNetCore.Http;
31using NUnit.Framework;
32
33namespace Microsoft.Playwright.Tests
34{
35    public class RequestFulfillTests : PageTestEx
36    {
37        [PlaywrightTest("page-request-fulfill.spec.ts", "should work")]
38        public async Task ShouldWork()
39        {
40            await Page.RouteAsync("**/*", (route) =>
41            {
42                route.FulfillAsync(new()
43                {
44                    Status = (int)HttpStatusCode.Created,
45                    Headers = new Dictionary<string, string>
46                    {
47                        ["foo"] = "bar"
48                    },
49                    ContentType = "text/html",
50                    Body = "Yo, page!",
51                });
52            });
53            var response = await Page.GotoAsync(Server.EmptyPage);
54            Assert.AreEqual((int)HttpStatusCode.Created, response.Status);
55#pragma warning disable 0612
56            Assert.AreEqual("bar", response.Headers["foo"]);
57#pragma warning restore 0612
58            Assert.AreEqual("Yo, page!", await Page.EvaluateAsync<string>("() => document.body.textContent"));
59        }
60
61        /// <summary>
62        /// In Playwright this method is called ShouldWorkWithStatusCode422.
63        /// I found that status 422 is not available in all .NET runtime versions (see https://github.com/dotnet/core/blob/4c4642d548074b3fbfd425541a968aadd75fea99/release-notes/2.1/Preview/api-diff/preview2/2.1-preview2_System.Net.md)
64        /// As the goal here is testing HTTP codes that are not in Chromium (see https://cs.chromium.org/chromium/src/net/http/http_status_code_list.h?sq=package:chromium) we will use code 426: Upgrade Required
65        /// </summary>
66        [PlaywrightTest("page-request-fulfill.spec.ts", "should work with status code 422")]
67        public async Task ShouldWorkWithStatusCode422()
68        {
69            await Page.RouteAsync("**/*", (route) =>
70            {
71                route.FulfillAsync(new() { Status = (int)HttpStatusCode.UpgradeRequired, Body = "Yo, page!" });
72            });
73            var response = await Page.GotoAsync(Server.EmptyPage);
74            Assert.AreEqual((int)HttpStatusCode.UpgradeRequired, response.Status);
75            Assert.AreEqual("Upgrade Required", response.StatusText);
76            Assert.AreEqual("Yo, page!", await Page.EvaluateAsync<string>("() => document.body.textContent"));
77        }
78
79        [PlaywrightTest("page-request-fulfill.spec.ts", "should allow mocking binary responses")]
80        [Ignore("We need screenshots for this")]
81        public async Task ShouldAllowMockingBinaryResponses()
82        {
83            await Page.RouteAsync("**/*", (route) =>
84            {
85                byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetAsset("pptr.png"));
86                route.FulfillAsync(new()
87                {
88                    ContentType = "image/png",
89                    BodyBytes = imageBuffer,
90                });
91            });
92            await Page.EvaluateAsync(@"PREFIX => {
93                const img = document.createElement('img');
94                img.src = PREFIX + '/does-not-exist.png';
95                document.body.appendChild(img);
96                return new Promise(fulfill => img.onload = fulfill);
97            }", Server.Prefix);
98            var img = await Page.QuerySelectorAsync("img");
99            Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()));
100        }
101
102        [PlaywrightTest("page-request-fulfill.spec.ts", "should allow mocking svg with charset")]
103        [Ignore("We need screenshots for this")]
104        public void ShouldAllowMockingSvgWithCharset()
105        {
106        }
107
108        [PlaywrightTest("page-request-fulfill.spec.ts", "should work with file path")]
109        [Ignore("We need screenshots for this")]
110        public async Task ShouldWorkWithFilePath()
111        {
112            await Page.RouteAsync("**/*", (route) =>
113            {
114                route.FulfillAsync(new()
115                {
116                    ContentType = "shouldBeIgnored",
117                    Path = TestUtils.GetAsset("pptr.png"),
118                });
119            });
120
121            await Page.EvaluateAsync(@"PREFIX => {
122                const img = document.createElement('img');
123                img.src = PREFIX + '/does-not-exist.png';
124                document.body.appendChild(img);
125                return new Promise(fulfill => img.onload = fulfill);
126            }", Server.Prefix);
127            var img = await Page.QuerySelectorAsync("img");
128            Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()));
129        }
130
131        [PlaywrightTest("page-request-fulfill.spec.ts", "should stringify intercepted request response headers")]
132        public async Task ShouldStringifyInterceptedRequestResponseHeaders()
133        {
134            await Page.RouteAsync("**/*", (route) =>
135            {
136                route.FulfillAsync(new()
137                {
138                    Status = (int)HttpStatusCode.OK,
139                    Headers = new Dictionary<string, string>
140                    {
141                        ["foo"] = "true"
142                    },
143                    Body = "Yo, page!",
144                });
145            });
146
147            var response = await Page.GotoAsync(Server.EmptyPage);
148            Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
149#pragma warning disable 0612
150            Assert.AreEqual("true", response.Headers["foo"]);
151#pragma warning restore 0612
152            Assert.AreEqual("Yo, page!", await Page.EvaluateAsync<string>("() => document.body.textContent"));
153        }
154
155        [PlaywrightTest("page-request-fulfill.spec.ts", "should not modify the headers sent to the server")]
156        [Ignore("Flacky with the ASP.NET server")]
157        public async Task ShouldNotModifyTheHeadersSentToTheServer()
158        {
159            await Page.GotoAsync(Server.EmptyPage);
160            var interceptedRequests = new List<Dictionary<string, string>>();
161
162            await Page.GotoAsync(Server.Prefix + "/unused");
163
164            Server.SetRoute("/something", ctx =>
165            {
166                var hh = new Dictionary<string, string>();
167                foreach (var h in ctx.Request.Headers)
168                {
169                    hh[h.Key] = h.Value;
170                }
171                interceptedRequests.Add(hh);
172                ctx.Response.Headers["Access-Control-Allow-Origin"] = "*";
173                return ctx.Response.WriteAsync("done");
174            });
175
176            string text = await Page.EvaluateAsync<string>(@"async url => {
177                const data = await fetch(url);
178                return data.text();
179            }", Server.CrossProcessPrefix + "/something");
180
181            Assert.AreEqual("done", text);
182
183            IRequest playwrightRequest = null;
184
185            await Page.RouteAsync(Server.CrossProcessPrefix + "/something", (route) =>
186            {
187                playwrightRequest = route.Request;
188#pragma warning disable 0612
189                route.ContinueAsync(new() { Headers = route.Request.Headers.ToDictionary(x => x.Key, x => x.Value) });
190#pragma warning restore 0612
191            });
192
193            string textAfterRoute = await Page.EvaluateAsync<string>(@"async url => {
194                const data = await fetch(url);
195                return data.text();
196            }", Server.CrossProcessPrefix + "/something");
197
198            Assert.AreEqual("done", textAfterRoute);
199
200            Assert.AreEqual(2, interceptedRequests.Count);
201            Assert.AreEqual(interceptedRequests[1].OrderBy(kv => kv.Key), interceptedRequests[0].OrderBy(kv => kv.Key));
202        }
203
204        [PlaywrightTest("page-request-fulfill.spec.ts", "should include the origin header")]
205        public async Task ShouldIncludeTheOriginHeader()
206        {
207            await Page.GotoAsync(Server.EmptyPage);
208            IRequest interceptedRequest = null;
209
210            await Page.RouteAsync(Server.CrossProcessPrefix + "/something", (route) =>
211            {
212                interceptedRequest = route.Request;
213                route.FulfillAsync(new()
214                {
215                    Headers = new Dictionary<string, string> { ["Access-Control-Allow-Origin"] = "*" },
216                    ContentType = "text/plain",
217                    Body = "done",
218                });
219            });
220
221            string text = await Page.EvaluateAsync<string>(@"async url => {
222                const data = await fetch(url);
223                return data.text();
224            }", Server.CrossProcessPrefix + "/something");
225
226            Assert.AreEqual("done", text);
227#pragma warning disable 0612
228            Assert.AreEqual(Server.Prefix, interceptedRequest.Headers["origin"]);
229#pragma warning restore 0612
230        }
231    }
232}
233
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 ShouldAllowMockingSvgWithCharset code on LambdaTest Cloud Grid

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