forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHttpClientHandlerTest.RemoteServer.cs
1391 lines (1262 loc) · 67.3 KB
/
HttpClientHandlerTest.RemoteServer.cs
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
#if WINHTTPHANDLER_TEST
using HttpClientHandler = System.Net.Http.WinHttpClientHandler;
#endif
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsBrowserDomSupportedOrNotBrowser))]
public sealed class HttpClientHandler_RemoteServerTest : HttpClientHandlerTestBase
{
private const string ExpectedContent = "Test content";
private const string Username = "testuser";
private const string Password = "password";
private readonly NetworkCredential _credential = new NetworkCredential(Username, Password);
public static readonly object[][] Http2Servers = Configuration.Http.Http2Servers;
public static readonly object[][] Http2NoPushServers = Configuration.Http.Http2NoPushServers;
// Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3
// "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"
public static readonly IEnumerable<object[]> HttpMethods =
GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1");
public static readonly IEnumerable<object[]> HttpMethodsThatAllowContent =
GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1");
public static readonly IEnumerable<object[]> HttpMethodsThatDontAllowContent =
GetMethods("HEAD", "TRACE");
private static bool IsWindows10Version1607OrGreater => PlatformDetection.IsWindows10Version1607OrGreater;
private static IEnumerable<object[]> GetMethods(params string[] methods)
{
foreach (string method in methods)
{
foreach (Uri serverUri in Configuration.Http.GetEchoServerList())
{
yield return new object[] { method, serverUri };
}
}
}
public HttpClientHandler_RemoteServerTest(ITestOutputHelper output) : base(output)
{
}
[OuterLoop("Uses external servers")]
[Theory]
[InlineData(false)]
[InlineData(true)]
[SkipOnPlatform(TestPlatforms.Browser, "UseProxy not supported on Browser")]
public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.UseProxy = useProxy;
handler.UseDefaultCredentials = false;
using (HttpClient client = CreateHttpClient(handler))
{
Uri uri = Configuration.Http.RemoteSecureHttp11Server.NegotiateAuthUriForDefaultCreds;
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
public async Task SendAsync_SimpleGet_Success(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (HttpResponseMessage response = await client.GetAsync(remoteServer.EchoUri))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
for (int i = 0; i < 3; i++)
{
using (HttpResponseMessage response = await client.GetAsync(remoteServer.EchoUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (HttpResponseMessage response = await client.GetAsync(remoteServer.EchoUri))
{
client.Dispose();
Assert.NotNull(response);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(responseContent, response.Content.Headers.ContentMD5, false, null);
}
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(RemoteServersMemberData))]
[SkipOnPlatform(TestPlatforms.Browser, "Credentials is not supported on Browser")]
public async Task GetAsync_ServerNeedsBasicAuthAndSetDefaultCredentials_StatusCodeUnauthorized(Configuration.Http.RemoteServer remoteServer)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = CredentialCache.DefaultCredentials;
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
{
Uri uri = remoteServer.BasicAuthUriForCreds(Username, Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(RemoteServersMemberData))]
[SkipOnPlatform(TestPlatforms.Browser, "Credentials is not supported on Browser")]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK(Configuration.Http.RemoteServer remoteServer)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = _credential;
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
{
Uri uri = remoteServer.BasicAuthUriForCreds(Username, Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/101115", typeof(PlatformDetection), nameof(PlatformDetection.IsFirefox))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/108019", TestPlatforms.Browser)]
public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
Uri uri = remoteServer.BasicAuthUriForCreds(Username, Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory]
[MemberData(nameof(RemoteServersAndHeaderEchoUrisMemberData))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndEmptyValueSent(Configuration.Http.RemoteServer remoteServer, Uri uri)
{
if (IsWinHttpHandler && !PlatformDetection.IsWindows10Version1709OrGreater)
{
return;
}
string name = "X-Cust-Header-NoValue";
string value = "";
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
_output.WriteLine($"name={name}, value={value}");
client.DefaultRequestHeaders.Add(name, value);
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersHeaderValuesAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(Configuration.Http.RemoteServer remoteServer, string name, string value, Uri uri)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
_output.WriteLine($"name={name}, value={value}");
client.DefaultRequestHeaders.Add(name, value);
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersAndHeaderEchoUrisMemberData))]
public async Task GetAsync_LargeRequestHeader_HeadersAndValuesSent(Configuration.Http.RemoteServer remoteServer, Uri uri)
{
// Unfortunately, our remote servers seem to have pretty strict limits (around 16K?)
// on the total size of the request header.
// TODO: Figure out how to reconfigure remote endpoints to allow larger request headers,
// and then increase the limits in this test.
string headerValue = new string('a', 2048);
const int headerCount = 6;
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
for (int i = 0; i < headerCount; i++)
{
client.DefaultRequestHeaders.Add($"Header-{i}", headerValue);
}
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
for (int i = 0; i < headerCount; i++)
{
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, $"Header-{i}", headerValue));
}
}
}
}
public static IEnumerable<object[]> RemoteServersHeaderValuesAndUris()
{
foreach ((Configuration.Http.RemoteServer remoteServer, Uri uri) in RemoteServersAndHeaderEchoUris())
{
yield return new object[] { remoteServer, "X-CustomHeader", "x-value", uri };
yield return new object[] { remoteServer, "MyHeader", "1, 2, 3", uri };
// Construct a header value with every valid character (except space)
string allchars = "";
for (int i = 0x21; i <= 0x7E; i++)
{
allchars = allchars + (char)i;
}
// Put a space in the middle so it's not interpreted as insignificant leading/trailing whitespace
allchars = allchars + " " + allchars;
yield return new object[] { remoteServer, "All-Valid-Chars-Header", allchars, uri };
}
}
public static IEnumerable<(Configuration.Http.RemoteServer remoteServer, Uri uri)> RemoteServersAndHeaderEchoUris()
{
foreach (Configuration.Http.RemoteServer remoteServer in Configuration.Http.GetRemoteServers())
{
yield return (remoteServer, remoteServer.EchoUri);
yield return (remoteServer, remoteServer.RedirectUriForDestinationUri(
statusCode: 302,
destinationUri: remoteServer.EchoUri,
hops: 1));
}
}
public static IEnumerable<object[]> RemoteServersAndHeaderEchoUrisMemberData() => RemoteServersAndHeaderEchoUris().Select(x => new object[] { x.remoteServer, x.uri });
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
const int NumGets = 5;
Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets)
select client.GetAsync(remoteServer.EchoUri, HttpCompletionOption.ResponseHeadersRead)).ToArray();
for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available
{
using (HttpResponseMessage response = await responseTasks[i])
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK(Configuration.Http.RemoteServer remoteServer)
{
// Sync API supported only up to HTTP/1.1
if (!TestAsync && remoteServer.HttpVersion.Major >= 2)
{
return;
}
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, remoteServer.EchoUri) { Version = remoteServer.HttpVersion };
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
using (HttpResponseMessage response = await client.SendAsync(TestAsync, request, HttpCompletionOption.ResponseHeadersRead))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_CallMethodTwice_StringContent(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
string data = "Test String";
var content = new StringContent(data, Encoding.UTF8);
if (PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
content.Headers.Add("Content-MD5-Skip", "browser");
}
else
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
}
HttpResponseMessage response;
using (response = await client.PostAsync(remoteServer.VerifyUploadUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Repeat call.
content = new StringContent(data, Encoding.UTF8);
if (PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
content.Headers.Add("Content-MD5-Skip", "browser");
}
else
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
}
using (response = await client.PostAsync(remoteServer.VerifyUploadUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_CallMethod_UnicodeStringContent(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb";
var content = new StringContent(data, Encoding.UTF8);
if (PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
content.Headers.Add("Content-MD5-Skip", "browser");
}
else
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
}
using (HttpResponseMessage response = await client.PostAsync(remoteServer.VerifyUploadUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))]
public async Task PostAsync_CallMethod_StreamContent(Configuration.Http.RemoteServer remoteServer, HttpContent content, byte[] expectedData)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
if (PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
content.Headers.Add("Content-MD5-Skip", "browser");
}
else
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
}
using (HttpResponseMessage response = await client.PostAsync(remoteServer.VerifyUploadUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
private sealed class StreamContentWithSyncAsyncCopy : StreamContent
{
private readonly Stream _stream;
private readonly bool _syncCopy;
public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream)
{
_stream = stream;
_syncCopy = syncCopy;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
if (_syncCopy)
{
try
{
_stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes
return Task.CompletedTask;
}
catch (Exception exc)
{
return Task.FromException(exc);
}
}
return base.SerializeToStreamAsync(stream, context);
}
}
public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData
{
get
{
foreach (Configuration.Http.RemoteServer remoteServer in Configuration.Http.GetRemoteServers()) // target server
foreach (bool syncCopy in BoolValues) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync
{
byte[] data = new byte[1234];
new Random(42).NextBytes(data);
// A MemoryStream
{
var memStream = new MemoryStream(data, writable: false);
yield return new object[] { remoteServer, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data };
}
// A multipart content that provides its own stream from CreateContentReadStreamAsync
{
var mc = new MultipartContent();
mc.Add(new ByteArrayContent(data));
var memStream = new MemoryStream();
mc.CopyToAsync(memStream).GetAwaiter().GetResult();
yield return new object[] { remoteServer, mc, memStream.ToArray() };
}
// A stream that provides the data synchronously and has a known length
{
var wrappedMemStream = new MemoryStream(data, writable: false);
var syncKnownLengthStream = new DelegateStream(
canReadFunc: () => wrappedMemStream.CanRead,
canSeekFunc: () => wrappedMemStream.CanSeek,
lengthFunc: () => wrappedMemStream.Length,
positionGetFunc: () => wrappedMemStream.Position,
positionSetFunc: p => wrappedMemStream.Position = p,
readFunc: (buffer, offset, count) => wrappedMemStream.Read(buffer, offset, count),
readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token));
yield return new object[] { remoteServer, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data };
}
// A stream that provides the data synchronously and has an unknown length
{
int syncUnknownLengthStreamOffset = 0;
Func<byte[], int, int, int> readFunc = (buffer, offset, count) =>
{
int bytesRemaining = data.Length - syncUnknownLengthStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, count);
Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy);
syncUnknownLengthStreamOffset += bytesToCopy;
return bytesToCopy;
};
var syncUnknownLengthStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readFunc: readFunc,
readAsyncFunc: (buffer, offset, count, token) => Task.FromResult(readFunc(buffer, offset, count)));
yield return new object[] { remoteServer, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data };
}
// A stream that provides the data asynchronously
{
int asyncStreamOffset = 0, maxDataPerRead = 100;
Func<byte[], int, int, int> readFunc = (buffer, offset, count) =>
{
int bytesRemaining = data.Length - asyncStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count));
Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy);
asyncStreamOffset += bytesToCopy;
return bytesToCopy;
};
var asyncStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readFunc: readFunc,
readAsyncFunc: async (buffer, offset, count, token) =>
{
await Task.Delay(1).ConfigureAwait(false);
return readFunc(buffer, offset, count);
});
yield return new object[] { remoteServer, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data };
}
// Providing data from a FormUrlEncodedContent's stream
{
var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("key", "val") });
yield return new object[] { remoteServer, formContent, Encoding.GetEncoding("iso-8859-1").GetBytes("key=val") };
}
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_CallMethod_NullContent(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
using (HttpResponseMessage response = await client.PostAsync(remoteServer.EchoUri, null))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_CallMethod_EmptyContent(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
var content = new StringContent(string.Empty);
using (HttpResponseMessage response = await client.PostAsync(remoteServer.EchoUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
public static IEnumerable<object[]> ExpectContinueVersion()
{
return
from expect in new bool?[] { true, false, null }
from version in new Version[] { new Version(1, 0), new Version(1, 1), new Version(2, 0) }
select new object[] { expect, version };
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory]
[MemberData(nameof(ExpectContinueVersion))]
[SkipOnPlatform(TestPlatforms.Browser, "ExpectContinue not supported on Browser")]
public async Task PostAsync_ExpectContinue_Success(bool? expectContinue, Version version)
{
// Sync API supported only up to HTTP/1.1
if (!TestAsync && version.Major >= 2)
{
return;
}
using (HttpClient client = CreateHttpClient())
{
var req = new HttpRequestMessage(HttpMethod.Post, version.Major == 2 ? Configuration.Http.Http2RemoteEchoServer : Configuration.Http.RemoteEchoServer)
{
Content = new StringContent("Test String", Encoding.UTF8),
Version = version
};
req.Headers.ExpectContinue = expectContinue;
using (HttpResponseMessage response = await client.SendAsync(TestAsync, req))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
if (!IsWinHttpHandler)
{
const string ExpectedReqHeader = "\"Expect\": \"100-continue\"";
if (expectContinue == true && (version >= new Version(1, 1)))
{
Assert.Contains(ExpectedReqHeader, await response.Content.ReadAsStringAsync());
}
else
{
Assert.DoesNotContain(ExpectedReqHeader, await response.Content.ReadAsStringAsync());
}
}
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(Configuration.Http.RemoteServer remoteServer)
{
const string ContentString = "This is the content string.";
var content = new StringContent(ContentString);
Uri redirectUri = remoteServer.RedirectUriForDestinationUri(
302,
remoteServer.EchoUri,
1);
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (HttpResponseMessage response = await client.PostAsync(redirectUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain(ContentString, responseContent);
Assert.DoesNotContain("Content-Length", responseContent);
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_RedirectWith307_LargePayload(Configuration.Http.RemoteServer remoteServer)
{
await PostAsync_Redirect_LargePayload_Helper(remoteServer, 307, true);
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_RedirectWith302_LargePayload(Configuration.Http.RemoteServer remoteServer)
{
await PostAsync_Redirect_LargePayload_Helper(remoteServer, 302, false);
}
private async Task PostAsync_Redirect_LargePayload_Helper(Configuration.Http.RemoteServer remoteServer, int statusCode, bool expectRedirectToPost)
{
using (var fs = new FileStream(
Path.Combine(Path.GetTempPath(), Path.GetTempFileName()),
FileMode.Create,
FileAccess.ReadWrite,
FileShare.None,
0x1000,
FileOptions.DeleteOnClose))
{
string contentString = string.Join("", Enumerable.Repeat("Content", 100000));
byte[] contentBytes = Encoding.UTF32.GetBytes(contentString);
fs.Write(contentBytes, 0, contentBytes.Length);
fs.Flush(flushToDisk: true);
fs.Position = 0;
Uri redirectUri = remoteServer.RedirectUriForDestinationUri(
statusCode: statusCode,
destinationUri: remoteServer.VerifyUploadUri,
hops: 1);
var content = new StreamContent(fs);
// Compute MD5 of request body data. This will be verified by the server when it receives the request.
if (PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
content.Headers.Add("Content-MD5-Skip", "browser");
}
else
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(contentBytes);
}
using HttpClient client = CreateHttpClientForRemoteServer(remoteServer);
client.Timeout = TimeSpan.FromMinutes(10);
using (HttpResponseMessage response = await client.PostAsync(redirectUri, content))
{
try
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
catch
{
_output.WriteLine($"{(int)response.StatusCode} {response.ReasonPhrase}");
throw;
}
if (expectRedirectToPost)
{
IEnumerable<string> headerValue = response.Headers.GetValues("X-HttpRequest-Method");
Assert.Equal("POST", headerValue.First());
}
}
}
}
#if !NETFRAMEWORK
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task PostAsync_ReuseRequestContent_Success(Configuration.Http.RemoteServer remoteServer)
{
const string ContentString = "This is the content string.";
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
var content = new StringContent(ContentString);
for (int i = 0; i < 2; i++)
{
using (HttpResponseMessage response = await client.PostAsync(remoteServer.EchoUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(ContentString, await response.Content.ReadAsStringAsync());
}
}
}
}
#endif
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(HttpMethods))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent(
string method,
Uri serverUri)
{
if (method == "TRACE" && PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/53592", TestPlatforms.Browser)]
return;
}
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
serverUri)
{ Version = UseVersion };
using (HttpResponseMessage response = await client.SendAsync(TestAsync, request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(HttpMethodsThatAllowContent))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success(
string method,
Uri serverUri)
{
if (method == "GET" && PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/53591", TestPlatforms.Browser)]
return;
}
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
serverUri)
{ Version = UseVersion };
request.Content = new StringContent(ExpectedContent);
using (HttpResponseMessage response = await client.SendAsync(TestAsync, request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
ExpectedContent);
}
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))]
public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent(
string method,
Uri serverUri)
{
if (method == "TRACE" && PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/53592", TestPlatforms.Browser)]
return;
}
if (method == "HEAD" && PlatformDetection.IsBrowser)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/53591", TestPlatforms.Browser)]
return;
}
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
serverUri)
{
Content = new StringContent(ExpectedContent),
Version = UseVersion
};
using (HttpResponseMessage response = await client.SendAsync(TestAsync, request))
{
if (method == "TRACE")
{
// .NET Framework also allows the HttpWebRequest and HttpClient APIs to send a request using 'TRACE'
// verb and a request body. The usual response from a server is "400 Bad Request".
// See here for more info: https://github.com/dotnet/runtime/issues/17475
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
else
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain(ExpectedContent, responseContent);
}
}
}
}
public static IEnumerable<object[]> SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success_MemberData()
{
foreach (var server in Configuration.Http.GetRemoteServers())
{
yield return new object[] { server, "12345678910", 0 };
yield return new object[] { server, "12345678910", 5 };
}
}
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[Theory, MemberData(nameof(SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success_MemberData))]
public async Task SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success(Configuration.Http.RemoteServer remoteServer, string stringContent, int startingPosition)
{
using (var handler = new HttpMessageInvoker(CreateHttpClientHandler()))
{
byte[] byteContent = Encoding.ASCII.GetBytes(stringContent);
var content = new MemoryStream();
content.Write(byteContent, 0, byteContent.Length);
content.Position = startingPosition;
var request = new HttpRequestMessage(HttpMethod.Post, remoteServer.EchoUri) { Content = new StreamContent(content), Version = UseVersion };
for (int iter = 0; iter < 2; iter++)
{
using (HttpResponseMessage response = await handler.SendAsync(TestAsync, request, CancellationToken.None))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent);
string bodyContent = System.Text.Json.JsonDocument.Parse(responseContent).RootElement.GetProperty("BodyContent").GetString();
Assert.Contains(stringContent.Substring(startingPosition), bodyContent);
if (startingPosition != 0)
{
Assert.DoesNotContain(stringContent.Substring(0, startingPosition), bodyContent);
}
}
}
}
}
public static IEnumerable<object[]> RemoteServersAndRedirectStatusCodes()
{
foreach (Configuration.Http.RemoteServer remoteServer in Configuration.Http.GetRemoteServers())
{
yield return new object[] { remoteServer, 300 };
yield return new object[] { remoteServer, 301 };
yield return new object[] { remoteServer, 302 };
yield return new object[] { remoteServer, 303 };
yield return new object[] { remoteServer, 307 };
yield return new object[] { remoteServer, 308 };
}
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(RemoteServersAndRedirectStatusCodes))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/55083", TestPlatforms.Browser)]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(Configuration.Http.RemoteServer remoteServer, int statusCode)
{
if (statusCode == 308 && (IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = false;
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
{
Uri uri = remoteServer.RedirectUriForDestinationUri(
statusCode: statusCode,
destinationUri: remoteServer.EchoUri,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(RemoteServersAndRedirectStatusCodes))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/55083", TestPlatforms.Browser)]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(Configuration.Http.RemoteServer remoteServer, int statusCode)
{
if (statusCode == 308 && (IsWinHttpHandler && PlatformDetection.WindowsVersion < 10))
{
// 308 redirects are not supported on old versions of WinHttp, or on .NET Framework.
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
{
Uri uri = remoteServer.RedirectUriForDestinationUri(
statusCode: statusCode,
destinationUri: remoteServer.EchoUri,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(remoteServer.EchoUri, response.RequestMessage.RequestUri);
}
}
}
[OuterLoop("Uses external servers")]
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/55083", TestPlatforms.Browser)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/110578")]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (HttpClient client = CreateHttpClient(handler))
{
Uri uri = Configuration.Http.RemoteHttp11Server.RedirectUriForDestinationUri(
statusCode: 302,
destinationUri: Configuration.Http.RemoteSecureHttp11Server.EchoUri,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);