How to use JsonAsync method of Microsoft.Playwright.Core.Response class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Response.JsonAsync

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageNetworkResponseTests.cs

Source: PageNetworkResponseTests.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.Runtime.InteropServices;
30using System.Threading.Tasks;
31using Microsoft.AspNetCore.Http;
32using Microsoft.AspNetCore.Http.Features;
33using Microsoft.Playwright.NUnit;
34using NUnit.Framework;
35
36namespace Microsoft.Playwright.Tests
37{
38    public class PageNetworkResponseTests : PageTestEx
39    {
40        [PlaywrightTest("page-network-response.spec.ts", "should return body")]
41        public async Task ShouldReturnBody()
42        {
43            var response = await Page.GotoAsync(Server.Prefix + "/pptr.png");
44            byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetAsset("pptr.png"));
45            Assert.AreEqual(imageBuffer, await response.BodyAsync());
46        }
47
48        [PlaywrightTest("page-network-response.spec.ts", "should return body with compression")]
49        public async Task ShouldReturnBodyWithCompression()
50        {
51            Server.EnableGzip("/pptr.png");
52            var response = await Page.GotoAsync(Server.Prefix + "/pptr.png");
53            byte[] imageBuffer = File.ReadAllBytes(TestUtils.GetAsset("pptr.png"));
54            Assert.AreEqual(imageBuffer, await response.BodyAsync());
55        }
56
57        [PlaywrightTest("page-network-response.spec.ts", "should work")]
58        public async Task ShouldWork()
59        {
60            Server.SetRoute("/empty.html", (context) =>
61            {
62                context.Response.Headers["foo"] = "bar";
63                return Task.CompletedTask;
64            });
65
66            var response = await Page.GotoAsync(Server.EmptyPage);
67#pragma warning disable 0612
68            StringAssert.Contains("bar", response.Headers["foo"]);
69#pragma warning restore 0612
70        }
71
72        [PlaywrightTest("page-network-response.spec.ts", "should return json")]
73        public async Task ShouldReturnJson()
74        {
75            var response = await Page.GotoAsync(Server.Prefix + "/simple.json");
76            Assert.AreEqual("{\"foo\": \"bar\"}", (await response.JsonAsync())?.GetRawText());
77        }
78
79        public async Task ShouldWorkWithGenerics()
80        {
81            var response = await Page.GotoAsync(Server.Prefix + "/simple.json");
82            var root = await response.JsonAsync();
83            Assert.AreEqual("bar", root?.GetProperty("foo").GetString());
84        }
85
86        [PlaywrightTest("page-network-response.spec.ts", "should return status text")]
87        public async Task ShouldReturnStatusText()
88        {
89            Server.SetRoute("/cool", (context) =>
90            {
91                context.Response.StatusCode = 200;
92                //There are some debates about this on these issues
93                //https://github.com/aspnet/HttpAbstractions/issues/395
94                //https://github.com/aspnet/HttpAbstractions/issues/486
95                //https://github.com/aspnet/HttpAbstractions/issues/794
96                context.Features.Get<IHttpResponseFeature>().ReasonPhrase = "cool!";
97                return Task.CompletedTask;
98            });
99            var response = await Page.GotoAsync(Server.Prefix + "/cool");
100            Assert.AreEqual("cool!", response.StatusText);
101        }
102
103        [PlaywrightTest("page-network-response.spec.ts", "should return text")]
104        public async Task ShouldReturnText()
105        {
106            var response = await Page.GotoAsync(Server.Prefix + "/simple.json");
107            Assert.AreEqual("{\"foo\": \"bar\"}", (await response.TextAsync()).Trim());
108        }
109
110        [PlaywrightTest("page-network-response.spec.ts", "should return uncompressed text")]
111        public async Task ShouldReturnUncompressedText()
112        {
113            Server.EnableGzip("/simple.json");
114            var response = await Page.GotoAsync(Server.Prefix + "/simple.json");
115#pragma warning disable 0612
116            Assert.AreEqual("gzip", response.Headers["content-encoding"]);
117#pragma warning restore 0612
118            Assert.AreEqual("{\"foo\": \"bar\"}", (await response.TextAsync()).Trim());
119        }
120
121        [PlaywrightTest("page-network-response.spec.ts", "should throw when requesting body of redirected response")]
122        public async Task ShouldThrowWhenRequestingBodyOfRedirectedResponse()
123        {
124            Server.SetRedirect("/foo.html", "/empty.html");
125            var response = await Page.GotoAsync(Server.Prefix + "/foo.html");
126            var redirectedFrom = response.Request.RedirectedFrom;
127            Assert.NotNull(redirectedFrom);
128            var redirected = await redirectedFrom.ResponseAsync();
129            Assert.AreEqual((int)HttpStatusCode.Redirect, redirected.Status);
130
131            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => redirected.TextAsync());
132            StringAssert.Contains("Response body is unavailable for redirect responses", exception.Message);
133        }
134
135        [PlaywrightTest("page-network-response.spec.ts", "should wait until response completes")]
136        public async Task ShouldWaitUntilResponseCompletes()
137        {
138            await Page.GotoAsync(Server.EmptyPage);
139            // Setup server to trap request.
140            var serverResponseCompletion = new TaskCompletionSource<bool>();
141            HttpResponse serverResponse = null;
142            Server.SetRoute("/get", context =>
143            {
144                serverResponse = context.Response;
145                context.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";
146                context.Response.WriteAsync("hello ");
147                return serverResponseCompletion.Task;
148            });
149
150            // Setup page to trap response.
151            bool requestFinished = false;
152            Page.RequestFinished += (_, e) => requestFinished = requestFinished || e.Url.Contains("/get");
153            // send request and wait for server response
154            var (pageResponse, _) = await TaskUtils.WhenAll(
155                Page.WaitForResponseAsync("**/*"),
156                Page.EvaluateAsync("fetch('./get', { method: 'GET'})"),
157                Server.WaitForRequest("/get")
158            );
159
160            Assert.NotNull(serverResponse);
161            Assert.NotNull(pageResponse);
162            Assert.AreEqual((int)HttpStatusCode.OK, pageResponse.Status);
163            Assert.False(requestFinished);
164
165            var responseText = pageResponse.TextAsync();
166            // Write part of the response and wait for it to be flushed.
167            await serverResponse.WriteAsync("wor");
168            // Finish response.
169            await serverResponse.WriteAsync("ld!");
170            serverResponseCompletion.SetResult(true);
171            Assert.AreEqual("hello world!", await responseText);
172        }
173
174        [PlaywrightTest("har.spec.ts", "should return security details directly from response")]
175        [Skip(SkipAttribute.Targets.Webkit | SkipAttribute.Targets.Linux)]
176        public async Task ShouldReturnSecurityDetails()
177        {
178            var response = await Page.GotoAsync(HttpsServer.EmptyPage);
179            var details = await response.SecurityDetailsAsync();
180
181            var name = "puppeteer-tests";
182            Assert.AreEqual(name, details.SubjectName);
183            if (TestConstants.IsWebKit)
184            {
185                Assert.AreEqual(1550084863f, details.ValidFrom);
186            }
187            else
188            {
189                Assert.AreEqual(name, details.Issuer);
190                StringAssert.Contains("TLS 1.", details.Protocol);
191            }
192        }
193
194        [PlaywrightTest("har.spec.ts", "should return server address directly from response")]
195        public async Task ShouldReturnServerAddressFromResponse()
196        {
197            var response = await Page.GotoAsync(HttpsServer.EmptyPage);
198            var details = await response.ServerAddrAsync();
199            Assert.IsNotEmpty(details.IpAddress);
200            Assert.Greater(details.Port, 0);
201        }
202
203        public override BrowserNewContextOptions ContextOptions() => new() { IgnoreHTTPSErrors = true };
204
205        [PlaywrightTest("har.spec.ts", "should report multiple set-cookie headers")]
206        public async Task ShouldReportMultipleSetCookieHeaders()
207        {
208            Server.SetRoute("/headers", async ctx =>
209            {
210                ctx.Response.Headers.Append("Set-Cookie", "a=b");
211                ctx.Response.Headers.Append("Set-Cookie", "c=d");
212                await Task.CompletedTask;
213            });
214
215            await Page.GotoAsync(Server.EmptyPage);
216            var responseTask = Page.WaitForResponseAsync("**/*");
217            await Task.WhenAll(responseTask, Page.EvaluateAsync("() => fetch('/headers')"));
218
219            var response = responseTask.Result;
220            var resultedHeaders = (await response.HeadersArrayAsync()).Where(x => x.Name.ToLower() == "set-cookie");
221            var values = resultedHeaders.Select(x => x.Value).ToArray();
222            CollectionAssert.AreEqual(new string[] { "a=b", "c=d" }, values);
223
224            Assert.IsNull(await response.HeaderValueAsync("not-there"));
225            Assert.AreEqual("a=b\nc=d", await response.HeaderValueAsync("set-cookie"));
226            Assert.AreEqual(new string[] { "a=b", "c=d" }, (await response.HeaderValuesAsync("set-cookie")).ToArray());
227        }
228
229        [PlaywrightTest("page-network-response.spec.ts", "should behave the same way for headers and allHeaders")]
230        [Skip(SkipAttribute.Targets.Webkit | SkipAttribute.Targets.Windows)] // libcurl does not support non-set-cookie multivalue headers
231        public async Task ShouldBehaveTheSameWayForHeadersAndAllHeaders()
232        {
233            Server.SetRoute("/headers", async ctx =>
234            {
235                if (!TestConstants.IsChromium)
236                {
237                    ctx.Response.Headers.Append("Set-Cookie", "a=b");
238                    ctx.Response.Headers.Append("Set-Cookie", "c=d");
239                }
240                ctx.Response.Headers.Append("Name-A", "v1");
241                ctx.Response.Headers.Append("name-B", "v4");
242                ctx.Response.Headers.Append("Name-a", "v2");
243                ctx.Response.Headers.Append("name-A", "v3");
244
245                await ctx.Response.WriteAsync("\r\n");
246                await ctx.Response.CompleteAsync();
247            });
248
249            await Page.GotoAsync(Server.EmptyPage);
250            var responseTask = Page.WaitForResponseAsync("**/*");
251            await Task.WhenAll(responseTask, Page.EvaluateAsync("() => fetch('/headers')"));
252            var response = responseTask.Result;
253            var allHeaders = await response.AllHeadersAsync();
254#pragma warning disable 0612
255            Assert.AreEqual(response.Headers, allHeaders);
256#pragma warning restore 0612
257        }
258    }
259}
260
Full Screen

Response.cs

Source: Response.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.Collections.Specialized;
28using System.Linq;
29using System.Text;
30using System.Text.Json;
31using System.Threading.Tasks;
32using Microsoft.Playwright.Transport;
33using Microsoft.Playwright.Transport.Channels;
34using Microsoft.Playwright.Transport.Protocol;
35
36namespace Microsoft.Playwright.Core
37{
38    internal class Response : ChannelOwnerBase, IChannelOwner<Response>, IResponse
39    {
40        private readonly ResponseChannel _channel;
41        private readonly ResponseInitializer _initializer;
42        private readonly TaskCompletionSource<string> _finishedTask;
43        private readonly RawHeaders _headers;
44        private Task<RawHeaders> _rawHeadersTask;
45
46        internal Response(IChannelOwner parent, string guid, ResponseInitializer initializer) : base(parent, guid)
47        {
48            _channel = new(guid, parent.Connection, this);
49            _initializer = initializer;
50            _initializer.Request.Timing = _initializer.Timing;
51            _finishedTask = new();
52
53            _headers = new RawHeaders(_initializer.Headers.ConvertAll(x => new NameValueEntry(x.Name, x.Value)).ToArray());
54        }
55
56        public IFrame Frame => _initializer.Request.Frame;
57
58        public Dictionary<string, string> Headers => _headers.Headers;
59
60        public bool Ok => Status is 0 or >= 200 and <= 299;
61
62        public IRequest Request => _initializer.Request;
63
64        public int Status => _initializer.Status;
65
66        public string StatusText => _initializer.StatusText;
67
68        public string Url => _initializer.Url;
69
70        ChannelBase IChannelOwner.Channel => _channel;
71
72        IChannel<Response> IChannelOwner<Response>.Channel => _channel;
73
74        public async Task<Dictionary<string, string>> AllHeadersAsync()
75            => (await GetRawHeadersAsync().ConfigureAwait(false)).Headers;
76
77        public Task<byte[]> BodyAsync() => _channel.GetBodyAsync();
78
79        public Task<string> FinishedAsync() => _finishedTask.Task;
80
81        public async Task<IReadOnlyList<Header>> HeadersArrayAsync()
82            => (await GetRawHeadersAsync().ConfigureAwait(false)).HeadersArray;
83
84        public async Task<string> HeaderValueAsync(string name)
85            => (await GetRawHeadersAsync().ConfigureAwait(false)).Get(name);
86
87        public async Task<IReadOnlyList<string>> HeaderValuesAsync(string name)
88            => (await GetRawHeadersAsync().ConfigureAwait(false)).GetAll(name);
89
90        public async Task<JsonElement?> JsonAsync()
91        {
92            byte[] content = await BodyAsync().ConfigureAwait(false);
93            return JsonDocument.Parse(content).RootElement;
94        }
95
96        public Task<ResponseSecurityDetailsResult> SecurityDetailsAsync() => _channel.SecurityDetailsAsync();
97
98        public Task<ResponseServerAddrResult> ServerAddrAsync() => _channel.ServerAddrAsync();
99
100        public async Task<string> TextAsync()
101        {
102            byte[] content = await BodyAsync().ConfigureAwait(false);
103            return Encoding.UTF8.GetString(content);
104        }
105
106        internal void ReportFinished(string erroMessage = null)
107        {
108            _finishedTask.SetResult(erroMessage);
109        }
110
111        private Task<RawHeaders> GetRawHeadersAsync()
112        {
113            if (_rawHeadersTask == null)
114            {
115                _rawHeadersTask = GetRawHeadersTaskAsync();
116            }
117
118            return _rawHeadersTask;
119        }
120
121        private async Task<RawHeaders> GetRawHeadersTaskAsync()
122        {
123            var headers = await _channel.GetRawHeadersAsync().ConfigureAwait(false);
124            return new(headers);
125        }
126    }
127}
128
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 JsonAsync code on LambdaTest Cloud Grid

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