forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWinHttpHandlerTest.cs
284 lines (248 loc) · 13.1 KB
/
WinHttpHandlerTest.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
// 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.Functional.Tests;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
// Can't use "WinHttpHandler.Functional.Tests" in namespace as it won't compile.
// WinHttpHandler is a class and not a namespace and can't be part of namespace paths.
namespace System.Net.Http.WinHttpHandlerFunctional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
public class WinHttpHandlerTest
{
private const string SlowServer = "http://httpbin.org/drip?numbytes=1&duration=1&delay=40&code=200";
private readonly ITestOutputHelper _output;
public WinHttpHandlerTest(ITestOutputHelper output)
{
_output = output;
}
[OuterLoop]
[Fact]
public void SendAsync_SimpleGet_Success()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
var response = client.GetAsync(System.Net.Test.Common.Configuration.Http.RemoteEchoServer).Result;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
_output.WriteLine(responseContent);
}
}
[OuterLoop]
[Theory]
[InlineData(CookieUsePolicy.UseInternalCookieStoreOnly, "cookieName1", "cookieValue1")]
[InlineData(CookieUsePolicy.UseSpecifiedCookieContainer, "cookieName2", "cookieValue2")]
public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(
CookieUsePolicy cookieUsePolicy,
string cookieName,
string cookieValue)
{
Uri uri = System.Net.Test.Common.Configuration.Http.RemoteSecureHttp11Server.RedirectUriForDestinationUri(302, System.Net.Test.Common.Configuration.Http.SecureRemoteEchoServer, 1);
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
handler.CookieUsePolicy = cookieUsePolicy;
if (cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
handler.CookieContainer = new CookieContainer();
}
using (HttpClient client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Add(
"X-SetCookie",
string.Format("{0}={1};Path=/", cookieName, cookieValue));
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[OuterLoop]
[Fact]
[OuterLoop]
public async Task SendAsync_SlowServerAndCancel_ThrowsTaskCanceledException()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
var cts = new CancellationTokenSource();
Task<HttpResponseMessage> t = client.GetAsync(SlowServer, cts.Token);
await Task.Delay(500);
cts.Cancel();
AggregateException ag = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<TaskCanceledException>(ag.InnerException);
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/20675")]
[OuterLoop]
[Fact]
[OuterLoop]
public void SendAsync_SlowServerRespondsAfterDefaultReceiveTimeout_ThrowsHttpRequestException()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> t = client.GetAsync(SlowServer);
AggregateException ag = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<HttpRequestException>(ag.InnerException);
}
}
[Fact]
public async Task SendAsync_GetUsingChunkedEncoding_ThrowsHttpRequestException()
{
// WinHTTP doesn't support GET requests with a request body that uses
// chunked encoding. This test pins this behavior and verifies that the
// error handling is working correctly.
var server = new Uri("http://www.microsoft.com"); // No network I/O actually happens.
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Content = new StringContent("Request body");
request.Headers.TransferEncodingChunked = true;
var handler = new WinHttpHandler();
using (HttpClient client = new HttpClient(handler))
{
HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request));
_output.WriteLine($"Ignored exception:{Environment.NewLine}{ex}");
}
}
[OuterLoop]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version1607OrGreater))]
public async Task GetAsync_SetCookieContainerMultipleCookies_CookiesSent()
{
var cookies = new Cookie[]
{
new Cookie("hello", "world"),
new Cookie("foo", "bar"),
new Cookie("ABC", "123")
};
WinHttpHandler handler = new WinHttpHandler();
var cookieContainer = new CookieContainer();
foreach (Cookie c in cookies)
{
cookieContainer.Add(Configuration.Http.Http2RemoteEchoServer, c);
}
handler.CookieContainer = cookieContainer;
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
handler.ServerCertificateValidationCallback = (m, cert, chain, err) => true;
string payload = "Cookie Test";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.Http2RemoteEchoServer) { Version = HttpVersion20.Value };
request.Content = new StringContent(payload);
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(HttpVersion20.Value, response.Version);
string responsePayload = await response.Content.ReadAsStringAsync();
var responseContent = Newtonsoft.Json.JsonConvert
.DeserializeAnonymousType(responsePayload, new { Method = "_", BodyContent = "_", Cookies = new Dictionary<string, string>() });
Assert.Equal("POST", responseContent.Method);
Assert.Equal(payload, responseContent.BodyContent);
Assert.Equal(cookies.ToDictionary(c => c.Name, c => c.Value), responseContent.Cookies);
};
}
[OuterLoop("Uses delays")]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version1607OrGreater))]
public async Task SendAsync_MultipleHttp2ConnectionsEnabled_CreateAdditionalConnections()
{
// Warm up thread pool because the full .NET Framework calls synchronous Stream.Read() and we need to delay those calls thus threads will get blocked.
ThreadPool.GetMinThreads(out _, out int completionPortThreads);
ThreadPool.SetMinThreads(401, completionPortThreads);
using var handler = new WinHttpHandler();
handler.EnableMultipleHttp2Connections = true;
handler.ServerCertificateValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
const int maxActiveStreamsLimit = 100 * 3;
const string payloadText = "Multiple HTTP/2 connections test.";
TaskCompletionSource<bool> delaySource = new TaskCompletionSource<bool>();
using var client = new HttpClient(handler);
List<(Task<HttpResponseMessage> task, DelayedStream stream)> requests = new List<(Task<HttpResponseMessage> task, DelayedStream stream)>();
for (int i = 0; i < maxActiveStreamsLimit; i++)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.Http2RemoteEchoServer) { Version = HttpVersion20.Value };
byte[] payloadBytes = Encoding.UTF8.GetBytes(payloadText);
DelayedStream content = new DelayedStream(payloadBytes, delaySource.Task);
request.Content = new StreamContent(content);
requests.Add((client.SendAsync(request, HttpCompletionOption.ResponseContentRead), content));
}
HttpRequestMessage aboveLimitRequest = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.Http2RemoteEchoServer) { Version = HttpVersion20.Value };
aboveLimitRequest.Content = new StringContent($"{payloadText}-{maxActiveStreamsLimit + 1}");
Task<HttpResponseMessage> aboveLimitResponseTask = client.SendAsync(aboveLimitRequest, HttpCompletionOption.ResponseContentRead);
await aboveLimitResponseTask.WaitAsync(TestHelper.PassingTestTimeout);
await VerifyResponse(aboveLimitResponseTask, $"{payloadText}-{maxActiveStreamsLimit + 1}");
delaySource.SetResult(true);
await Task.WhenAll(requests.Select(r => r.task).ToArray()).WaitAsync(TimeSpan.FromSeconds(15));
foreach ((Task<HttpResponseMessage> task, DelayedStream stream) in requests)
{
Assert.True(task.IsCompleted);
HttpResponseMessage response = task.Result;
Assert.True(response.IsSuccessStatusCode);
Assert.Equal(HttpVersion20.Value, response.Version);
string responsePayload = await response.Content.ReadAsStringAsync().WaitAsync(TestHelper.PassingTestTimeout);
Assert.Contains(payloadText, responsePayload);
}
}
[OuterLoop("Uses external service")]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version2004OrGreater))]
public async Task SendAsync_UseTcpKeepAliveOptions()
{
using var handler = new WinHttpHandler()
{
TcpKeepAliveEnabled = true,
TcpKeepAliveTime = TimeSpan.FromSeconds(1),
TcpKeepAliveInterval = TimeSpan.FromMilliseconds(500)
};
using var client = new HttpClient(handler);
var response = client.GetAsync(System.Net.Test.Common.Configuration.Http.RemoteEchoServer).Result;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
// Uncomment this to observe an exchange of "TCP Keep-Alive" and "TCP Keep-Alive ACK" packets:
// await Task.Delay(5000);
}
private async Task VerifyResponse(Task<HttpResponseMessage> task, string payloadText)
{
Assert.True(task.IsCompleted);
HttpResponseMessage response = task.Result;
Assert.True(response.IsSuccessStatusCode);
Assert.Equal(HttpVersion20.Value, response.Version);
string responsePayload = await response.Content.ReadAsStringAsync().WaitAsync(TestHelper.PassingTestTimeout);
Assert.Contains(payloadText, responsePayload);
}
public static bool JsonMessageContainsKeyValue(string message, string key, string value)
{
string pattern = string.Format(@"""{0}"": ""{1}""", key, value);
return message.Contains(pattern);
}
private sealed class DelayedStream : MemoryStream
{
private readonly Task _delayTask;
private readonly TaskCompletionSource<bool> _waitReadSource = new TaskCompletionSource<bool>();
private bool _delayed;
public Task WaitRead => _waitReadSource.Task;
public DelayedStream(byte[] buffer, Task delayTask)
: base(buffer)
{
_delayTask = delayTask;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (!_delayed)
{
_waitReadSource.SetResult(true);
_delayTask.Wait();
_delayed = true;
}
return base.Read(buffer, offset, count);
}
}
}
}