This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
HttpResponseStreamTests.cs
580 lines (495 loc) · 26.1 KB
/
HttpResponseStreamTests.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class HttpResponseStreamTests : IDisposable
{
private HttpListenerFactory _factory;
private HttpListener _listener;
private GetContextHelper _helper;
public HttpResponseStreamTests()
{
_factory = new HttpListenerFactory();
_listener = _factory.GetListener();
_helper = new GetContextHelper(_listener, _factory.ListeningUrl);
}
public void Dispose()
{
_factory.Dispose();
_helper.Dispose();
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task SimpleRequest_WriteAsynchronously_Succeeds(bool sendChunked)
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
response.SendChunked = sendChunked;
Stream outputStream = response.OutputStream;
try
{
await outputStream.WriteAsync(responseBuffer, 0, responseBuffer.Length);
}
finally
{
outputStream.Close();
}
byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent.");
await outputStream.WriteAsync(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length);
}
string clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task SimpleRequest_WriteSynchronouslyNonEmpty_Succeeds(bool sendChunked)
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
response.SendChunked = sendChunked;
Stream outputStream = response.OutputStream;
try
{
outputStream.Write(responseBuffer, 0, responseBuffer.Length);
}
finally
{
outputStream.Close();
}
byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent.");
outputStream.Write(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length);
}
string clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteAsynchronouslyInParts_Succeeds()
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
using (Stream outputStream = response.OutputStream)
{
await outputStream.WriteAsync(responseBuffer, 0, 5);
await outputStream.WriteAsync(responseBuffer, 5, responseBuffer.Length - 5);
}
}
var clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteSynchronouslyInParts_Succeeds()
{
const string expectedResponse = "hello from HttpListener";
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
response.ContentLength64 = responseBuffer.Length;
using (Stream outputStream = response.OutputStream)
{
outputStream.Write(responseBuffer, 0, 5);
outputStream.Write(responseBuffer, 5, responseBuffer.Length - 5);
}
}
var clientString = await clientTask;
Assert.Equal(expectedResponse, clientString);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteAynchronouslyEmpty_Succeeds()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
response.ContentLength64 = 0;
using (Stream outputStream = response.OutputStream)
{
await outputStream.WriteAsync(new byte[0], 0, 0);
}
}
Assert.Empty(await clientTask);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task SimpleRequest_WriteSynchronouslyEmpty_Succeeds()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await serverContextTask;
using (HttpListenerResponse response = serverContext.Response)
{
response.ContentLength64 = 0;
using (Stream outputStream = response.OutputStream)
{
outputStream.Write(new byte[0], 0, 0);
}
}
Assert.Empty(await clientTask);
}
}
[Fact]
public async Task CanSeek_Get_ReturnsFalse()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
Assert.False(outputStream.CanSeek);
Assert.Throws<NotSupportedException>(() => outputStream.Length);
Assert.Throws<NotSupportedException>(() => outputStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => outputStream.Position);
Assert.Throws<NotSupportedException>(() => outputStream.Position = 1);
Assert.Throws<NotSupportedException>(() => outputStream.Seek(0, SeekOrigin.Begin));
}
}
[Fact]
public async Task CanRead_Get_ReturnsFalse()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
Assert.False(outputStream.CanRead);
Assert.Throws<InvalidOperationException>(() => outputStream.Read(new byte[0], 0, 0));
await Assert.ThrowsAsync<InvalidOperationException>(() => outputStream.ReadAsync(new byte[0], 0, 0));
Assert.Throws<InvalidOperationException>(() => outputStream.EndRead(null));
}
}
[Fact]
public async Task CanWrite_Get_ReturnsTrue()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
Assert.True(outputStream.CanWrite);
// Flushing the output stream is a no-op.
outputStream.Flush();
Assert.Equal(Task.CompletedTask, outputStream.FlushAsync(CancellationToken.None));
}
}
[Fact]
public async Task Write_NullBuffer_ThrowsArgumentNullException()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => outputStream.Write(null, 0, 0));
await Assert.ThrowsAsync<ArgumentNullException>("buffer", () => outputStream.WriteAsync(null, 0, 0));
}
}
[Theory]
[InlineData(-1)]
[InlineData(3)]
public async Task Write_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset)
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => outputStream.Write(new byte[2], offset, 0));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => outputStream.WriteAsync(new byte[2], offset, 0));
}
}
[Theory]
[InlineData(0, 3)]
[InlineData(1, 2)]
[InlineData(2, 1)]
public async Task Write_InvalidOffsetSize_ThrowsArgumentOutOfRangeException(int offset, int size)
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => outputStream.Write(new byte[2], offset, size));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("size", () => outputStream.WriteAsync(new byte[2], offset, size));
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_TooMuch_ThrowsProtocolViolationException()
{
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await _listener.GetContextAsync();
using (HttpListenerResponse response = serverContext.Response)
{
Stream output = response.OutputStream;
byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
response.ContentLength64 = responseBuffer.Length - 1;
try
{
Assert.Throws<ProtocolViolationException>(() => output.Write(responseBuffer, 0, responseBuffer.Length));
await Assert.ThrowsAsync<ProtocolViolationException>(() => output.WriteAsync(responseBuffer, 0, responseBuffer.Length));
}
finally
{
// Write the remaining bytes to guarantee a successful shutdown.
output.Write(responseBuffer, 0, (int)response.ContentLength64);
output.Close();
}
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_TooLittleAsynchronouslyAndClose_ThrowsInvalidOperationException()
{
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await _listener.GetContextAsync();
using (HttpListenerResponse response = serverContext.Response)
{
Stream output = response.OutputStream;
byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
response.ContentLength64 = responseBuffer.Length + 1;
// Throws when there are bytes left to write
await output.WriteAsync(responseBuffer, 0, responseBuffer.Length);
Assert.Throws<InvalidOperationException>(() => output.Close());
// Write the final byte and make sure we can close.
await output.WriteAsync(new byte[1], 0, 1);
output.Close();
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[ActiveIssue(18128, platforms: TestPlatforms.AnyUnix)] // No exception thrown
public async Task Write_TooLittleSynchronouslyAndClose_ThrowsInvalidOperationException()
{
using (HttpClient client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext serverContext = await _listener.GetContextAsync();
using (HttpListenerResponse response = serverContext.Response)
{
Stream output = response.OutputStream;
byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
response.ContentLength64 = responseBuffer.Length + 1;
// Throws when there are bytes left to write
output.Write(responseBuffer, 0, responseBuffer.Length);
Assert.Throws<InvalidOperationException>(() => output.Close());
// Write the final byte and make sure we can close.
output.Write(new byte[1], 0, 1);
output.Close();
}
}
}
[ActiveIssue(19534, TestPlatforms.OSX)]
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Write_HeadersToClosedConnectionAsynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Writing to a disconnected client should fail.
if (!PlatformDetection.IsWindows && ignoreWriteExceptions)
{
// Windows sends headers first, followed by content. If headers fail to send, then an exception is always thrown.
// However, the managed implementation has already sent the headers by the time we run this test.
// This means that if the content fails to send, an exception is only thrown if ignoreWriteExceptions == false.
await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
}
else
{
await Assert.ThrowsAsync<HttpListenerException>(() => context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length));
}
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[ActiveIssue(19534, TestPlatforms.OSX)]
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Write_HeadersToClosedConnectionSynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Writing to a disconnected client should fail.
if (!PlatformDetection.IsWindows && ignoreWriteExceptions)
{
// Windows sends headers first, followed by content. If headers fail to send, then an exception is always thrown.
// However, the managed implementation has already sent the headers by the time we run this test.
// This means that if the content fails to send, an exception is only thrown if ignoreWriteExceptions == false.
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
else
{
Assert.Throws<HttpListenerException>(() => context.Response.OutputStream.Write(buffer, 0, buffer.Length));
}
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[ActiveIssue(19534, TestPlatforms.OSX)]
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18188, platforms: TestPlatforms.Windows)] // Indeterminate failure - socket not always fully disconnected.
public async Task Write_ContentToClosedConnectionAsynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Write the headers to the Socket.
await context.Response.OutputStream.WriteAsync(buffer, 0, 1);
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Writing non-header content to a disconnected client should fail, only if IgnoreWriteExceptions is false.
if (ignoreWriteExceptions)
{
await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
}
else
{
await Assert.ThrowsAsync<HttpListenerException>(() => context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length));
}
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[ActiveIssue(19534, TestPlatforms.OSX)]
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18188, platforms: TestPlatforms.Windows)] // Indeterminate failure - socket not always fully disconnected.
public async Task Write_ContentToClosedConnectionSynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
{
const string Text = "Some-String";
byte[] buffer = Encoding.UTF8.GetBytes(Text);
using (HttpListenerFactory factory = new HttpListenerFactory())
using (Socket client = factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
client.Send(factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListener listener = factory.GetListener();
listener.IgnoreWriteExceptions = ignoreWriteExceptions;
HttpListenerContext context = await listener.GetContextAsync();
// Write the headers to the Socket.
context.Response.OutputStream.Write(buffer, 0, 1);
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Writing non-header content to a disconnected client should fail, only if IgnoreWriteExceptions is false.
if (ignoreWriteExceptions)
{
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
else
{
Assert.Throws<HttpListenerException>(() => context.Response.OutputStream.Write(buffer, 0, buffer.Length));
}
// Closing a response from a closed client if a writing has already failed should not fail.
context.Response.Close();
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EndWrite_NullAsyncResult_ThrowsArgumentNullException(bool ignoreWriteExceptions)
{
_listener.IgnoreWriteExceptions = ignoreWriteExceptions;
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => outputStream.EndWrite(null));
}
}
[Fact]
public async Task EndWrite_InvalidAsyncResult_ThrowsArgumentException()
{
using (HttpListenerResponse response1 = await _helper.GetResponse())
using (Stream outputStream1 = response1.OutputStream)
using (HttpListenerResponse response2 = await _helper.GetResponse())
using (Stream outputStream2 = response2.OutputStream)
{
IAsyncResult beginWriteResult = outputStream1.BeginWrite(new byte[0], 0, 0, null, null);
AssertExtensions.Throws<ArgumentException>("asyncResult", () => outputStream2.EndWrite(new CustomAsyncResult()));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => outputStream2.EndWrite(beginWriteResult));
}
}
[Fact]
public async Task EndWrite_CalledTwice_ThrowsInvalidOperationException()
{
using (HttpListenerResponse response1 = await _helper.GetResponse())
using (Stream outputStream = response1.OutputStream)
{
IAsyncResult beginWriteResult = outputStream.BeginWrite(new byte[0], 0, 0, null, null);
outputStream.EndWrite(beginWriteResult);
Assert.Throws<InvalidOperationException>(() => outputStream.EndWrite(beginWriteResult));
}
}
}
}