This repository has been archived by the owner on Dec 18, 2018. It is now read-only.
/
WebSocketsTests.cs
407 lines (324 loc) · 18.6 KB
/
WebSocketsTests.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Connections.Internal;
using Microsoft.AspNetCore.Http.Connections.Internal.Transports;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR.Tests;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Http.Connections.Tests
{
public class WebSocketsTests : VerifiableLoggedTest
{
public WebSocketsTests(ITestOutputHelper output)
: base(output)
{
}
// Using nameof with WebSocketMessageType because it is a GACed type and xunit can't serialize it
[Theory]
[InlineData(nameof(WebSocketMessageType.Text))]
[InlineData(nameof(WebSocketMessageType.Binary))]
public async Task ReceivedFramesAreWrittenToChannel(string webSocketMessageType)
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory);
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(await feature.AcceptAsync());
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
// Send a frame, then close
await feature.Client.SendAsync(
buffer: new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")),
messageType: (WebSocketMessageType)Enum.Parse(typeof(WebSocketMessageType), webSocketMessageType),
endOfMessage: true,
cancellationToken: CancellationToken.None);
await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
var result = await connection.Transport.Input.ReadAsync();
var buffer = result.Buffer;
Assert.Equal("Hello", Encoding.UTF8.GetString(buffer.ToArray()));
connection.Transport.Input.AdvanceTo(buffer.End);
connection.Transport.Output.Complete();
// The transport should finish now
await transport;
// The connection should close after this, which means the client will get a close frame.
var clientSummary = await client;
Assert.Equal(WebSocketCloseStatus.NormalClosure, clientSummary.CloseResult.CloseStatus);
}
}
}
// Using nameof with WebSocketMessageType because it is a GACed type and xunit can't serialize it
[Theory]
[InlineData(TransferFormat.Text, nameof(WebSocketMessageType.Text))]
[InlineData(TransferFormat.Binary, nameof(WebSocketMessageType.Binary))]
public async Task WebSocketTransportSetsMessageTypeBasedOnTransferFormatFeature(TransferFormat transferFormat, string expectedMessageType)
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
connectionContext.ActiveFormat = transferFormat;
var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory);
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(await feature.AcceptAsync());
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
// Write to the output channel, and then complete it
await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello"));
connection.Transport.Output.Complete();
// The client should finish now, as should the server
var clientSummary = await client;
await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
await transport;
Assert.Equal(1, clientSummary.Received.Count);
Assert.True(clientSummary.Received[0].EndOfMessage);
Assert.Equal((WebSocketMessageType)Enum.Parse(typeof(WebSocketMessageType), expectedMessageType), clientSummary.Received[0].MessageType);
Assert.Equal("Hello", Encoding.UTF8.GetString(clientSummary.Received[0].Buffer));
}
}
}
[Fact]
public async Task TransportCommunicatesErrorToApplicationWhenClientDisconnectsAbnormally()
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
async Task CompleteApplicationAfterTransportCompletes()
{
try
{
// Wait until the transport completes so that we can end the application
var result = await connection.Transport.Input.ReadAsync();
connection.Transport.Input.AdvanceTo(result.Buffer.End);
}
catch (Exception ex)
{
Assert.IsType<WebSocketError>(ex);
}
finally
{
// Complete the application so that the connection unwinds without aborting
connection.Transport.Output.Complete();
}
}
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory);
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(await feature.AcceptAsync());
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
// When the close frame is received, we complete the application so the send
// loop unwinds
_ = CompleteApplicationAfterTransportCompletes();
// Terminate the client to server channel with an exception
feature.Client.SendAbort();
// Wait for the transport
await transport.OrTimeout();
await client.OrTimeout();
}
}
}
[Fact]
public async Task ClientReceivesInternalServerErrorWhenTheApplicationFails()
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory);
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(await feature.AcceptAsync());
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
// Fail in the app
connection.Transport.Output.Complete(new InvalidOperationException("Catastrophic failure."));
var clientSummary = await client.OrTimeout();
Assert.Equal(WebSocketCloseStatus.InternalServerError, clientSummary.CloseResult.CloseStatus);
// Close from the client
await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
await transport.OrTimeout();
}
}
}
[Fact]
public async Task TransportClosesOnCloseTimeoutIfClientDoesNotSendCloseFrame()
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var options = new WebSocketOptions()
{
CloseTimeout = TimeSpan.FromSeconds(1)
};
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory);
var serverSocket = await feature.AcceptAsync();
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(serverSocket);
// End the app
connection.Transport.Output.Complete();
await transport.OrTimeout(TimeSpan.FromSeconds(10));
// Now we're closed
Assert.Equal(WebSocketState.Aborted, serverSocket.State);
serverSocket.Dispose();
}
}
}
[Fact]
public async Task TransportFailsOnTimeoutWithErrorWhenApplicationFailsAndClientDoesNotSendCloseFrame()
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var options = new WebSocketOptions
{
CloseTimeout = TimeSpan.FromSeconds(1)
};
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory);
var serverSocket = await feature.AcceptAsync();
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(serverSocket);
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
// fail the client to server channel
connection.Transport.Output.Complete(new Exception());
await transport.OrTimeout();
Assert.Equal(WebSocketState.Aborted, serverSocket.State);
}
}
}
[Fact]
public async Task ServerGracefullyClosesWhenApplicationEndsThenClientSendsCloseFrame()
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var options = new WebSocketOptions
{
// We want to verify behavior without timeout affecting it
CloseTimeout = TimeSpan.FromSeconds(20)
};
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory);
var serverSocket = await feature.AcceptAsync();
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(serverSocket);
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
// close the client to server channel
connection.Transport.Output.Complete();
_ = await client.OrTimeout();
await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).OrTimeout();
await transport.OrTimeout();
Assert.Equal(WebSocketCloseStatus.NormalClosure, serverSocket.CloseStatus);
}
}
}
[Fact]
public async Task ServerGracefullyClosesWhenClientSendsCloseFrameThenApplicationEnds()
{
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var options = new WebSocketOptions
{
// We want to verify behavior without timeout affecting it
CloseTimeout = TimeSpan.FromSeconds(20)
};
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory);
var serverSocket = await feature.AcceptAsync();
// Give the server socket to the transport and run it
var transport = ws.ProcessSocketAsync(serverSocket);
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).OrTimeout();
// close the client to server channel
connection.Transport.Output.Complete();
_ = await client.OrTimeout();
await transport.OrTimeout();
Assert.Equal(WebSocketCloseStatus.NormalClosure, serverSocket.CloseStatus);
}
}
}
[Fact]
public async Task SubProtocolSelectorIsUsedToSelectSubProtocol()
{
const string ExpectedSubProtocol = "expected";
var providedSubProtocols = new[] {"provided1", "provided2"};
using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
{
var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);
var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application);
using (var feature = new TestWebSocketConnectionFeature())
{
var options = new WebSocketOptions
{
// We want to verify behavior without timeout affecting it
CloseTimeout = TimeSpan.FromSeconds(20),
SubProtocolSelector = protocols => {
Assert.Equal(providedSubProtocols, protocols.ToArray());
return ExpectedSubProtocol;
},
};
var connectionContext = new HttpConnectionContext(string.Empty, null, null);
var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory);
// Create an HttpContext
var context = new DefaultHttpContext();
context.Request.Headers.Add(HeaderNames.WebSocketSubProtocols, providedSubProtocols.ToArray());
context.Features.Set<IHttpWebSocketFeature>(feature);
var transport = ws.ProcessRequestAsync(context, CancellationToken.None);
await feature.Accepted.OrThrowIfOtherFails(transport);
// Assert the feature got the right subprotocol
Assert.Equal(ExpectedSubProtocol, feature.SubProtocol);
// Run the client socket
var client = feature.Client.ExecuteAndCaptureFramesAsync();
await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).OrTimeout();
// close the client to server channel
connection.Transport.Output.Complete();
_ = await client.OrTimeout();
await transport.OrTimeout();
}
}
}
}
}