forked from microsoft/playwright-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobalFetchTests.cs
More file actions
564 lines (517 loc) · 27.9 KB
/
Copy pathGlobalFetchTests.cs
File metadata and controls
564 lines (517 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/*
* MIT License
*
* Copyright (c) Microsoft Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System.Globalization;
using System.Text;
using System.Text.Json;
namespace Microsoft.Playwright.Tests;
public class GlobalFetchTests : PlaywrightTestEx
{
[PlaywrightTest("global-fetch.spec.ts", "should work")]
public async Task ShouldWork()
{
var request = await Playwright.APIRequest.NewContextAsync();
var methodsToTest = new[] { "fetch", "delete", "get", "head", "patch", "post", "put" };
var url = Server.Prefix + "/simple.json";
foreach (var method in methodsToTest)
{
var response = await request.NameToMethod(method)(url, null);
Assert.AreEqual(url, response.Url);
Assert.AreEqual(200, response.Status);
Assert.AreEqual("OK", response.StatusText);
Assert.AreEqual(true, response.Ok);
Assert.AreEqual("application/json; charset=utf-8", response.Headers.ToDictionary(x => x.Key, x => x.Value)["content-type"]);
Assert.AreEqual(1, response.HeadersArray.Where(x => x.Name == "Content-Type" && x.Value == "application/json; charset=utf-8").Count());
Assert.AreEqual(method == "head" ? "" : "{\"foo\": \"bar\"}\n", await response.TextAsync());
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should dispose global request")]
public async Task ShouldDisposeGlobalRequest()
{
var request = await Playwright.APIRequest.NewContextAsync();
var response = await request.GetAsync(Server.Prefix + "/simple.json");
var parsedJSON = await response.JsonAsync();
Assert.AreEqual("bar", parsedJSON?.GetProperty("foo").GetString());
await request.DisposeAsync();
var exception = Assert.ThrowsAsync<PlaywrightException>(() => response.BodyAsync());
Assert.AreEqual("Response has been disposed", exception.Message);
}
[PlaywrightTest("global-fetch.spec.ts", "support global userAgent option")]
public async Task ShouldSupportGlobalUserAgentOption()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { UserAgent = "My Agent" });
var (receivedUserAgent, response) = await TaskUtils.WhenAll(
Server.WaitForRequest("/empty.html", request => request.Headers.ToDictionary(x => x.Key, x => x.Value)["User-Agent"]),
request.GetAsync(Server.EmptyPage)
);
Assert.AreEqual(true, response.Ok);
Assert.AreEqual(Server.EmptyPage, response.Url);
Assert.AreEqual("My Agent", receivedUserAgent);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should support global timeout option")]
public async Task ShouldSupportGlobalTimeoutOption()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { Timeout = 100 });
Server.SetRoute("/empty.html", async request => await Task.Delay(5_000));
var exception = Assert.ThrowsAsync<TimeoutException>(() => request.GetAsync(Server.EmptyPage));
StringAssert.Contains("Timeout 100ms exceeded", exception.Message);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should propagate extra http headers with redirects")]
public async Task ShouldPropagateExtraHttpHeadersWithRedirects()
{
Server.SetRedirect("/a/redirect1", "/b/c/redirect2");
Server.SetRedirect("/b/c/redirect2", "/simple.json");
var request = await Playwright.APIRequest.NewContextAsync(new() { ExtraHTTPHeaders = new Dictionary<string, string>() { { "My-Secret", "Value" } } });
var (req1MySecret, req2MySecret, req3MySecret, _) = await TaskUtils.WhenAll(
Server.WaitForRequest("/a/redirect1", r => r.Headers["My-Secret"]),
Server.WaitForRequest("/b/c/redirect2", r => r.Headers["My-Secret"]),
Server.WaitForRequest("/simple.json", r => r.Headers["My-Secret"]),
request.GetAsync(Server.Prefix + "/a/redirect1"));
Assert.AreEqual("Value", req1MySecret);
Assert.AreEqual("Value", req2MySecret);
Assert.AreEqual("Value", req3MySecret);
}
[PlaywrightTest("global-fetch.spec.ts", "should support global httpCredentials option")]
public async Task ShouldSupportGlobalHttpCredentialsOption()
{
Server.SetAuth("/empty.html", "user", "pass");
var request1 = await Playwright.APIRequest.NewContextAsync();
var response1 = await request1.GetAsync(Server.EmptyPage);
Assert.AreEqual(401, response1.Status);
await request1.DisposeAsync();
var request2 = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass" } });
var response2 = await request2.GetAsync(Server.EmptyPage);
Assert.AreEqual(200, response2.Status);
await request2.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return error with wrong credentials")]
public async Task ShouldReturnErrorWithWrongCredentials()
{
Server.SetAuth("/empty.html", "user", "pass");
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "wrong" } });
var response = await request.GetAsync(Server.EmptyPage);
Assert.AreEqual(401, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should work with correct credentials and matching origin")]
public async Task ShouldWorkWithCorrectCredentialsAndMatchingOrigin()
{
Server.SetAuth("/empty.html", "user", "pass");
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass", Origin = Server.Prefix } });
var response = await request.GetAsync(Server.EmptyPage);
Assert.AreEqual(200, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should work with correct credentials and matching origin case insensitive")]
public async Task ShouldWorkWithCorrectCredentialsAndMatchingOriginCaseInsensitive()
{
Server.SetAuth("/empty.html", "user", "pass");
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass", Origin = Server.Prefix.ToUpperInvariant() } });
var response = await request.GetAsync(Server.EmptyPage);
Assert.AreEqual(200, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return error with correct credentials and mismatching scheme")]
public async Task ShouldReturnErrorWithCorrectCredentialsAndMismatchingScheme()
{
Server.SetAuth("/empty.html", "user", "pass");
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass", Origin = Server.Prefix.Replace("http://", "https://") } });
var response = await request.GetAsync(Server.EmptyPage);
Assert.AreEqual(401, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return error with correct credentials and mismatching hostname")]
public async Task ShouldReturnErrorWithCorrectCredentialsandMismatchingHostname()
{
Server.SetAuth("/empty.html", "user", "pass");
var hostname = new Uri(Server.Prefix).Host;
var origin = Server.Prefix.Replace(hostname, "mismatching-hostname");
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass", Origin = origin } });
var response = await request.GetAsync(Server.EmptyPage);
Assert.AreEqual(401, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return error with correct credentials and mismatching port")]
public async Task ShouldReturnErrorWithCorrectCredentialsAndMismatchingPort()
{
Server.SetAuth("/empty.html", "user", "pass");
var origin = Server.Prefix.Replace(Server.Port.ToString(CultureInfo.InvariantCulture), (Server.Port + 1).ToString(CultureInfo.InvariantCulture));
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass", Origin = origin } });
var response = await request.GetAsync(Server.EmptyPage);
Assert.AreEqual(401, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should use proxy")]
[Ignore("Fetch API is using the CONNECT Http proxy server method all the time")]
public async Task ShouldUseProxy()
{
Server.SetRoute("/target.html", ctx => ctx.Response.WriteAsync("<html><title>Served by the proxy</title></html>"));
var request = await Playwright.APIRequest.NewContextAsync(new() { Proxy = new() { Server = $"127.0.0.1:{Server.Port}" } });
var response = await request.GetAsync(Server.Prefix + "/target.html");
StringAssert.Contains("Served by the proxy", await response.TextAsync());
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should support HTTPCredentials.send")]
public async Task ShouldSupportHTTPCredentialsSend()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { HttpCredentials = new() { Username = "user", Password = "pass", Origin = Server.Prefix.ToUpperInvariant(), Send = HttpCredentialsSend.Always } });
{
var (requestHeaders, response) = await TaskUtils.WhenAll(
Server.WaitForRequest("/empty.html", request => request.Headers.ToDictionary(header => header.Key, header => header.Value)),
request.GetAsync(Server.EmptyPage)
);
Assert.AreEqual(requestHeaders["Authorization"], "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:pass")));
Assert.AreEqual(200, response.Status);
}
{
var (requestHeaders, response) = await TaskUtils.WhenAll(
Server.WaitForRequest("/empty.html", request => request.Headers.ToDictionary(header => header.Key, header => header.Value)),
request.GetAsync(Server.CrossProcessPrefix + "/empty.html")
);
Assert.AreEqual(200, response.Status);
// Not sent to another origin.
Assert.AreEqual(false, requestHeaders.ContainsKey("Authorization"));
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should support global ignoreHTTPSErrors option")]
public async Task ShouldSupportGlobalIgnoreHTTPSErrorsOption()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { IgnoreHTTPSErrors = true });
var response = await request.GetAsync(HttpsServer.EmptyPage);
Assert.AreEqual(200, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should propagate ignoreHTTPSErrors on redirects")]
public async Task ShouldPropagateIgnoreHTTPSErrorsOnRedirect()
{
HttpsServer.SetRedirect("/redir", "/empty.html");
var request = await Playwright.APIRequest.NewContextAsync();
var response = await request.GetAsync(HttpsServer.Prefix + "/redir", new() { IgnoreHTTPSErrors = true });
Assert.AreEqual(200, response.Status);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return server address from response")]
public async Task ShouldReturnServerAddressFromResponse()
{
var request = await Playwright.APIRequest.NewContextAsync();
// The second request reuses the keep-alive socket and should report the address as well.
for (int i = 0; i < 2; i++)
{
var response = await request.GetAsync(Server.EmptyPage);
var addr = await response.ServerAddrAsync();
Assert.IsNotNull(addr);
StringAssert.IsMatch("^(127\\.0\\.0\\.1|::1)$", addr.IpAddress);
Assert.AreEqual(Server.Port, addr.Port);
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return security details from response")]
public async Task ShouldReturnSecurityDetailsFromResponse()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { IgnoreHTTPSErrors = true });
// The second request reuses the keep-alive socket and should report the details as well.
for (int i = 0; i < 2; i++)
{
var response = await request.GetAsync(HttpsServer.EmptyPage);
var details = await response.SecurityDetailsAsync();
Assert.IsNotNull(details);
Assert.AreEqual("puppeteer-tests", details.SubjectName);
Assert.AreEqual("puppeteer-tests", details.Issuer);
StringAssert.Contains("TLS", details.Protocol);
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return null security details for http response")]
public async Task ShouldReturnNullSecurityDetailsForHttpResponse()
{
var request = await Playwright.APIRequest.NewContextAsync();
var response = await request.GetAsync(Server.EmptyPage);
Assert.IsNull(await response.SecurityDetailsAsync());
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should resolve url relative to global baseURL option")]
public async Task ShouldResolveUrlRelativeToGlobalBaseURLOption()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { BaseURL = Server.Prefix });
var response = await request.GetAsync("/empty.html");
Assert.AreEqual(Server.EmptyPage, response.Url);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return empty body")]
public async Task ShouldReturnEmptyBody()
{
var request = await Playwright.APIRequest.NewContextAsync();
var response = await request.GetAsync(Server.EmptyPage);
var body = await response.BodyAsync();
Assert.AreEqual(0, body.Length);
Assert.AreEqual("", await response.TextAsync());
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "serialize corectly")]
public async Task ShouldSerializeCorrectly()
{
var testCases = new List<(string, (string, object), string)>(){
("object", (null, new {Foo="Bar" }), "{\u0022foo\u0022:\u0022Bar\u0022}"),
("array", (null, new object[]{"foo", "bar", 2021 }), "[\"foo\",\"bar\",2021]"),
("string", ("foo", null), "foo"),
("string (falsey)", (string.Empty, null), string.Empty),
("number", (null, 2021), "2021"),
("number (falsey)", (null, 0), "0"),
("boolean", (null, true), "true"),
("bool (false)", (null, false), "false"),
("null", (null, null), string.Empty),
("literal string undefined", ("undefined", null), "undefined"),
};
IAPIRequestContext request;
IAPIResponse response;
Server.SetRoute("/in-is-out", ctx => ctx.Request.Body.CopyToAsync(ctx.Response.Body));
foreach (var (name, (valueString, valueObject), expected) in testCases)
{
request = await Playwright.APIRequest.NewContextAsync();
response = await request.PostAsync(Server.Prefix + "/in-is-out", new() { DataObject = valueObject, DataString = valueString });
Assert.AreEqual(expected, await response.TextAsync());
var stringifiedValue = JsonSerializer.Serialize(string.IsNullOrEmpty(valueString) ? valueString : valueObject);
var (serverRequestBody, _) = await TaskUtils.WhenAll(
Server.WaitForRequest("/in-is-out", request =>
{
using StreamReader reader = new(request.Body, Encoding.UTF8);
return reader.ReadToEndAsync().GetAwaiter().GetResult();
}),
request.PostAsync(Server.Prefix + "/in-is-out", new() { DataString = stringifiedValue, Headers = new Dictionary<string, string>() { ["Content-Type"] = "application/json" } })
);
Assert.AreEqual(stringifiedValue, serverRequestBody);
await request.DisposeAsync();
}
}
[PlaywrightTest("global-fetch.spec.ts", "should accept already serialized data as Buffer when content-type is application/json")]
public async Task ShouldAcceptAlreadySerializedDataAsBufferWhenContentTypeIsJSON()
{
var request = await Playwright.APIRequest.NewContextAsync();
var value = Encoding.UTF8.GetBytes("{\"foo\":\"Bar\"}");
var (serverPostBody, _) = await TaskUtils.WhenAll(
Server.WaitForRequest("/empty.html", request =>
{
using StreamReader reader = new(request.Body);
return reader.ReadToEndAsync().GetAwaiter().GetResult();
}),
request.PostAsync(Server.EmptyPage, new() { DataByte = value, Headers = new Dictionary<string, string>() { ["Content-Type"] = "application/json" } })
);
Assert.AreEqual(value, serverPostBody);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should have nice toString")]
public async Task ShouldHaveANiceToString()
{
var request = await Playwright.APIRequest.NewContextAsync();
var response = await request.PostAsync(Server.EmptyPage, new() { Data = "My post data", Headers = new Dictionary<string, string>() { ["Content-Type"] = "application/json" } });
var str = response.ToString();
StringAssert.Contains("APIResponse: 200 OK", str);
foreach (var header in response.HeadersArray)
{
StringAssert.Contains($" {header.Name}: {header.Value}", str);
}
await response.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should not fail on empty body with encoding")]
public async Task ShouldNotFailOnEmptyBodyWithEncoding()
{
var request = await Playwright.APIRequest.NewContextAsync();
foreach (var method in new[] { "head", "put" })
{
foreach (var encoding in new[] { "br", "gzip", "deflate" })
{
Server.SetRoute("/empty.html", (ctx) =>
{
ctx.Response.StatusCode = 200;
ctx.Response.Headers.Append("Content-Encoding", encoding);
ctx.Response.Headers.Append("Content-Type", "text/plain");
return Task.CompletedTask;
});
var response = await request.NameToMethod(method)(Server.EmptyPage, null);
Assert.AreEqual(200, response.Status);
Assert.AreEqual(0, (await response.BodyAsync()).Length);
}
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should return body for failing requests")]
public async Task ShouldReturnBodyForFailingRequests()
{
var request = await Playwright.APIRequest.NewContextAsync();
foreach (var method in new[] { "head", "put", "trace" })
{
Server.SetRoute("/empty.html", async (ctx) =>
{
ctx.Response.StatusCode = 404;
ctx.Response.Headers.Append("Content-Length", "10");
ctx.Response.Headers.Append("Content-Type", "text/plain");
await ctx.Response.WriteAsync("Not found.");
});
var response = await request.FetchAsync(Server.EmptyPage, new() { Method = method });
Assert.AreEqual(404, response.Status);
// HEAD response returns empty body in node http module.
Assert.AreEqual(method == "head" ? "" : "Not found.", await response.TextAsync());
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should throw an error when maxRedirects is exceeded")]
public async Task ShouldThrowAnErrorWhenMaxRedirectsIsExceeded()
{
Server.SetRedirect("/a/redirect1", "/b/c/redirect2");
Server.SetRedirect("/b/c/redirect2", "/b/c/redirect3");
Server.SetRedirect("/b/c/redirect3", "/b/c/redirect4");
Server.SetRedirect("/b/c/redirect4", "/simple.json");
var request = await Playwright.APIRequest.NewContextAsync();
foreach (var method in new[] { "GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH" })
{
foreach (var maxRedirects in new[] { 1, 2, 3 })
{
var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => request.FetchAsync($"{Server.Prefix}/a/redirect1", new() { Method = method, MaxRedirects = maxRedirects }));
StringAssert.Contains("Max redirect count exceeded", exception.Message);
}
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should not follow redirects when maxRedirects is set to 0")]
public async Task ShouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0()
{
Server.SetRedirect("/a/redirect1", "/b/c/redirect2");
Server.SetRedirect("/b/c/redirect2", "/simple.json");
var request = await Playwright.APIRequest.NewContextAsync();
foreach (var method in new[] { "GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH" })
{
var response = await request.FetchAsync($"{Server.Prefix}/a/redirect1", new() { Method = method, MaxRedirects = 0 });
Assert.AreEqual("/b/c/redirect2", response.Headers["location"]);
Assert.AreEqual(302, response.Status);
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should not follow redirects when maxRedirects is set to 0 in newContext")]
public async Task ShouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0InNewContext()
{
Server.SetRedirect("/a/redirect1", "/b/c/redirect2");
Server.SetRedirect("/b/c/redirect2", "/simple.json");
var request = await Playwright.APIRequest.NewContextAsync(new() { MaxRedirects = 0 });
foreach (var method in new[] { "GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH" })
{
var response = await request.FetchAsync($"{Server.Prefix}/a/redirect1", new() { Method = method });
Assert.AreEqual("/b/c/redirect2", response.Headers["location"]);
Assert.AreEqual(302, response.Status);
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should throw an error when maxRedirects is less than 0")]
public async Task ShouldThrowAnErrorWhenMaxRedirectsIsLessThan0()
{
Server.SetRedirect("/a/redirect1", "/b/c/redirect2");
Server.SetRedirect("/b/c/redirect2", "/simple.json");
var request = await Playwright.APIRequest.NewContextAsync();
foreach (var method in new[] { "GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH" })
{
var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => request.FetchAsync($"{Server.Prefix}/a/redirect1", new() { Method = method, MaxRedirects = -1 }));
StringAssert.Contains("'MaxRedirects' must be greater than or equal to '0'", exception.Message);
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should not modify request method in options")]
public async Task ShouldNotModifyRequestMethodInOptions()
{
var request = await Playwright.APIRequest.NewContextAsync();
Server.SetRoute("/echo", (ctx) =>
{
ctx.Response.StatusCode = 200;
return ctx.Response.WriteAsync(ctx.Request.Method);
});
var options = new APIRequestContextOptions();
{
var response = await request.FetchAsync(Server.Prefix + "/echo", options);
await Expect(response).ToBeOKAsync();
Assert.AreEqual("GET", await response.TextAsync());
Assert.IsNull(options.Method);
}
{
var response = await request.DeleteAsync(Server.Prefix + "/echo", options);
await Expect(response).ToBeOKAsync();
Assert.AreEqual("DELETE", await response.TextAsync());
Assert.IsNull(options.Method);
}
{
var response = await request.PutAsync(Server.Prefix + "/echo", options);
await Expect(response).ToBeOKAsync();
Assert.AreEqual("PUT", await response.TextAsync());
Assert.IsNull(options.Method);
}
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should serialize null values in JSON")]
public async Task ShouldSerializeNullValuesInJSON()
{
var request = await Playwright.APIRequest.NewContextAsync();
Server.SetRoute("/echo", ctx => ctx.Request.Body.CopyToAsync(ctx.Response.Body));
var response = await request.PostAsync(Server.Prefix + "/echo", new() { DataObject = new { foo = (object)null } });
await Expect(response).ToBeOKAsync();
Assert.AreEqual("{\"foo\":null}", await response.TextAsync());
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should throw when failOnStatusCode is set to true inside APIRequest context options")]
public async Task ShouldThrowWhenFailOnStatusCodeIsSet()
{
var request = await Playwright.APIRequest.NewContextAsync(new() { FailOnStatusCode = true });
Server.SetRoute("/empty.html", async (ctx) =>
{
ctx.Response.StatusCode = 404;
ctx.Response.Headers.Append("Content-Length", "10");
ctx.Response.Headers.Append("Content-Type", "text/plain");
await ctx.Response.WriteAsync("Not found.");
});
var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await request.PostAsync(Server.Prefix + "/empty.html"));
StringAssert.Contains("404 Not Found", exception.Message);
await request.DisposeAsync();
}
[PlaywrightTest("global-fetch.spec.ts", "should retry ECONNRESET")]
public async Task ShouldRetryECONNRESET()
{
var request = await Playwright.APIRequest.NewContextAsync();
int requestCount = 0;
Server.SetRoute("/test", (context) =>
{
if (requestCount++ < 3)
{
context.Abort();
return Task.CompletedTask;
}
context.Response.Headers.ContentType = "text/plain";
context.Response.StatusCode = 200;
return context.Response.WriteAsync("Hello!");
});
var response = await request.GetAsync(Server.Prefix + "/test", new() { MaxRetries = 3 });
Assert.AreEqual(200, response.Status);
Assert.AreEqual("Hello!", await response.TextAsync());
Assert.AreEqual(4, requestCount);
await request.DisposeAsync();
}
}