diff --git a/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionDispatcherTests.cs b/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionDispatcherTests.cs index 7934e98df1..59617e965b 100644 --- a/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionDispatcherTests.cs +++ b/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionDispatcherTests.cs @@ -30,23 +30,18 @@ using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.Http.Connections.Tests { public class HttpConnectionDispatcherTests : VerifiableLoggedTest { - public HttpConnectionDispatcherTests(ITestOutputHelper output) : base(output) - { - } - [Fact] public async Task NegotiateReservesConnectionIdAndReturnsIt() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddSingleton(); @@ -66,10 +61,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task CheckThatThresholdValuesAreEnforced() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddSingleton(); @@ -104,10 +99,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.ServerSentEvents)] public async Task CheckThatThresholdValuesAreEnforcedWithSends(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var pipeOptions = new PipeOptions(pauseWriterThreshold: 8, resumeWriterThreshold: 4); var connection = manager.CreateConnection(pipeOptions, pipeOptions); connection.TransportType = transportType; @@ -156,10 +151,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling | HttpTransportType.WebSockets)] public async Task NegotiateReturnsAvailableTransportsAfterFilteringByOptions(HttpTransportType transports) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set(new ResponseFeature()); context.Features.Set(new TestWebSocketConnectionFeature()); @@ -190,10 +185,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling)] public async Task EndpointsThatAcceptConnectionId404WhenUnknownConnectionIdProvided(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); using (var strm = new MemoryStream()) { @@ -227,10 +222,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task EndpointsThatAcceptConnectionId404WhenUnknownConnectionIdProvidedForPost() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); using (var strm = new MemoryStream()) { @@ -262,10 +257,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task PostNotAllowedForWebSocketConnections() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.WebSockets; @@ -299,10 +294,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task PostReturns404IfConnectionDisposed() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; await connection.DisposeAsync(closeGracefully: false); @@ -337,10 +332,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.WebSockets)] public async Task TransportEndingGracefullyWaitsOnApplication(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; @@ -398,10 +393,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task TransportEndingGracefullyWaitsOnApplicationLongPolling() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; @@ -461,10 +456,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.ServerSentEvents)] public async Task PostSendsToConnection(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; @@ -510,10 +505,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.ServerSentEvents)] public async Task PostSendsToConnectionInParallel(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; @@ -595,10 +590,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task HttpContextFeatureForLongpollingWorksBetweenPolls() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; @@ -692,10 +687,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling)] public async Task EndpointsThatRequireConnectionId400WhenNoConnectionIdProvided(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); using (var strm = new MemoryStream()) { var context = new DefaultHttpContext(); @@ -726,10 +721,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.ServerSentEvents)] public async Task IOExceptionWhenReadingRequestReturns400Response(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; @@ -762,10 +757,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task EndpointsThatRequireConnectionId400WhenNoConnectionIdProvidedForPost() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); using (var strm = new MemoryStream()) { var context = new DefaultHttpContext(); @@ -794,9 +789,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.ServerSentEvents, 404)] public async Task EndPointThatOnlySupportsLongPollingRejectsOtherTransports(HttpTransportType transportType, int status) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - await CheckTransportSupported(HttpTransportType.LongPolling, transportType, status, loggerFactory); + await CheckTransportSupported(HttpTransportType.LongPolling, transportType, status, LoggerFactory); } } @@ -806,9 +801,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling, 404)] public async Task EndPointThatOnlySupportsSSERejectsOtherTransports(HttpTransportType transportType, int status) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - await CheckTransportSupported(HttpTransportType.ServerSentEvents, transportType, status, loggerFactory); + await CheckTransportSupported(HttpTransportType.ServerSentEvents, transportType, status, LoggerFactory); } } @@ -818,9 +813,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling, 404)] public async Task EndPointThatOnlySupportsWebSockesRejectsOtherTransports(HttpTransportType transportType, int status) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - await CheckTransportSupported(HttpTransportType.WebSockets, transportType, status, loggerFactory); + await CheckTransportSupported(HttpTransportType.WebSockets, transportType, status, LoggerFactory); } } @@ -828,22 +823,22 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling, 404)] public async Task EndPointThatOnlySupportsWebSocketsAndSSERejectsLongPolling(HttpTransportType transportType, int status) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - await CheckTransportSupported(HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents, transportType, status, loggerFactory); + await CheckTransportSupported(HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents, transportType, status, LoggerFactory); } } [Fact] public async Task CompletedEndPointEndsConnection() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.ServerSentEvents; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, HttpTransportType.ServerSentEvents); @@ -871,13 +866,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests writeContext.EventId.Name == "FailedDispose"; } - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.ServerSentEvents; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, HttpTransportType.ServerSentEvents); @@ -898,13 +893,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task CompletedEndPointEndsLongPollingConnection() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -929,13 +924,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task LongPollingTimeoutSets200StatusCode() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -953,15 +948,16 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task WebSocketTransportTimesOutWhenCloseFrameNotReceived() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.WebSockets; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, HttpTransportType.WebSockets); @@ -985,13 +981,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.ServerSentEvents)] public async Task RequestToActiveConnectionId409ForStreamingTransports(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context1 = MakeRequest("/foo", connection); var context2 = MakeRequest("/foo", connection); @@ -1028,13 +1024,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task RequestToActiveConnectionIdKillsPreviousConnectionLongPolling() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context1 = MakeRequest("/foo", connection); var context2 = MakeRequest("/foo", connection); @@ -1069,14 +1065,14 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.LongPolling)] public async Task RequestToDisposedConnectionIdReturns404(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; connection.Status = HttpConnectionStatus.Disposed; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, transportType); @@ -1097,13 +1093,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task ConnectionStateSetToInactiveAfterPoll() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -1132,13 +1128,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task BlockingConnectionWorksWithStreamingConnections() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.ServerSentEvents; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, HttpTransportType.ServerSentEvents); @@ -1167,13 +1163,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task BlockingConnectionWorksWithLongPollingConnection() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -1208,13 +1204,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task AttemptingToPollWhileAlreadyPollingReplacesTheCurrentPoll() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton(); @@ -1253,13 +1249,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.WebSockets, TransferFormat.Binary | TransferFormat.Text)] public async Task TransferModeSet(HttpTransportType transportType, TransferFormat? expectedTransferFormats) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, transportType); @@ -1285,12 +1281,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task UnauthorizedConnectionFailsToStartEndPoint() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddOptions(); @@ -1331,12 +1327,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task AuthenticatedUserWithoutPermissionCausesForbidden() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddOptions(); @@ -1379,12 +1375,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task AuthorizedConnectionCanConnectToEndPoint() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set(new ResponseFeature()); var services = new ServiceCollection(); @@ -1439,12 +1435,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task AllPoliciesRequiredForAuthorizedEndPoint() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set(new ResponseFeature()); var services = new ServiceCollection(); @@ -1526,12 +1522,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task AuthorizedConnectionWithAcceptedSchemesCanConnectToEndPoint() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set(new ResponseFeature()); var services = new ServiceCollection(); @@ -1589,12 +1585,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task AuthorizedConnectionWithRejectedSchemesFailsToConnectToEndPoint() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddOptions(); @@ -1643,13 +1639,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task SetsInherentKeepAliveFeatureOnFirstLongPollingRequest() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -1675,13 +1671,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(HttpTransportType.WebSockets)] public async Task DeleteEndpointRejectsRequestToTerminateNonLongPollingTransport(HttpTransportType transportType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); SetTransport(context, transportType); @@ -1716,13 +1712,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DeleteEndpointGracefullyTerminatesLongPolling() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -1767,13 +1763,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DeleteEndpointGracefullyTerminatesLongPollingEvenWhenBetweenPolls() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = MakeRequest("/foo", connection); @@ -1815,10 +1811,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task NegotiateDoesNotReturnWebSocketsWhenNotAvailable() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set(new ResponseFeature()); var services = new ServiceCollection(); @@ -1857,14 +1853,14 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task WriteThatIsDisposedBeforeCompleteReturns404() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var pipeOptions = new PipeOptions(pauseWriterThreshold: 13, resumeWriterThreshold: 10); var connection = manager.CreateConnection(pipeOptions, pipeOptions); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton(); @@ -1915,14 +1911,14 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task CanDisposeWhileWriteLockIsBlockedOnBackpressureAndResponseReturns404() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var pipeOptions = new PipeOptions(pauseWriterThreshold: 13, resumeWriterThreshold: 10); var connection = manager.CreateConnection(pipeOptions, pipeOptions); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton(); @@ -1968,14 +1964,14 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task LongPollingCanPollIfWritePipeHasBackpressure() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var pipeOptions = new PipeOptions(pauseWriterThreshold: 13, resumeWriterThreshold: 10); var connection = manager.CreateConnection(pipeOptions, pipeOptions); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton(); @@ -2028,13 +2024,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests writeContext.EventId.Name == "FailedDispose"); } - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { - var manager = CreateConnectionManager(loggerFactory); + var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; - var dispatcher = new HttpConnectionDispatcher(manager, loggerFactory); + var dispatcher = new HttpConnectionDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton(); diff --git a/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionManagerTests.cs b/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionManagerTests.cs index 62dfc89009..13f569dac7 100644 --- a/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionManagerTests.cs +++ b/test/Microsoft.AspNetCore.Http.Connections.Tests/HttpConnectionManagerTests.cs @@ -10,23 +10,17 @@ using Microsoft.AspNetCore.Http.Connections.Internal; using Microsoft.AspNetCore.SignalR.Tests; using Microsoft.Extensions.Logging; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.Http.Connections.Tests { public class HttpConnectionManagerTests : VerifiableLoggedTest { - public HttpConnectionManagerTests(ITestOutputHelper output) - : base(output) - { - } - [Fact] public void NewConnectionsHaveConnectionId() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(); Assert.NotNull(connection.ConnectionId); @@ -52,13 +46,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(ConnectionStates.CloseGracefully | ConnectionStates.ApplicationFaulted | ConnectionStates.TransportNotFaulted)] public async Task DisposingConnectionsClosesBothSidesOfThePipe(ConnectionStates states) { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var closeGracefully = (states & ConnectionStates.CloseGracefully) != 0; var applicationFaulted = (states & ConnectionStates.ApplicationFaulted) != 0; var transportFaulted = (states & ConnectionStates.TransportFaulted) != 0; - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(); if (applicationFaulted) @@ -123,9 +117,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public void NewConnectionsCanBeRetrieved() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(); Assert.NotNull(connection.ConnectionId); @@ -138,9 +132,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public void AddNewConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); var transport = connection.Transport; @@ -157,9 +151,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public void RemoveConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); var transport = connection.Transport; @@ -179,9 +173,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task CloseConnectionsEndsAllPendingConnections() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); connection.ApplicationTask = Task.Run(async () => @@ -227,9 +221,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DisposingConnectionMultipleTimesWaitsOnConnectionClose() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -250,9 +244,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DisposingConnectionMultipleGetsExceptionFromTransportOrApp() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -277,9 +271,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DisposingConnectionMultipleGetsCancellation() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -301,9 +295,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DisposeInactiveConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); Assert.NotNull(connection.ConnectionId); @@ -317,9 +311,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task DisposeInactiveConnectionWithNoPipes() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var connectionManager = CreateConnectionManager(loggerFactory); + var connectionManager = CreateConnectionManager(LoggerFactory); var connection = connectionManager.CreateConnection(); Assert.NotNull(connection.ConnectionId); @@ -334,10 +328,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task ApplicationLifetimeIsHookedUp() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var appLifetime = new TestApplicationLifetime(); - var connectionManager = CreateConnectionManager(loggerFactory, appLifetime); + var connectionManager = CreateConnectionManager(LoggerFactory, appLifetime); var tcs = new TaskCompletionSource(); appLifetime.Start(); @@ -360,12 +354,12 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task ApplicationLifetimeCanStartBeforeHttpConnectionManagerInitialized() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var appLifetime = new TestApplicationLifetime(); appLifetime.Start(); - var connectionManager = CreateConnectionManager(loggerFactory, appLifetime); + var connectionManager = CreateConnectionManager(LoggerFactory, appLifetime); var tcs = new TaskCompletionSource(); var connection = connectionManager.CreateConnection(PipeOptions.Default, PipeOptions.Default); diff --git a/test/Microsoft.AspNetCore.Http.Connections.Tests/LongPollingTests.cs b/test/Microsoft.AspNetCore.Http.Connections.Tests/LongPollingTests.cs index 69c471d72c..7796d9ba71 100644 --- a/test/Microsoft.AspNetCore.Http.Connections.Tests/LongPollingTests.cs +++ b/test/Microsoft.AspNetCore.Http.Connections.Tests/LongPollingTests.cs @@ -10,30 +10,23 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http.Connections.Internal.Transports; using Microsoft.AspNetCore.SignalR.Tests; -using Microsoft.Extensions.Logging; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.Http.Connections.Tests { public class LongPollingTests : VerifiableLoggedTest { - public LongPollingTests(ITestOutputHelper output) - : base(output) - { - } - [Fact] public async Task Set204StatusCodeWhenChannelComplete() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); - var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, loggerFactory); + var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, LoggerFactory); connection.Transport.Output.Complete(); @@ -46,14 +39,14 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task Set200StatusCodeWhenTimeoutTokenFires() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); var timeoutToken = new CancellationToken(true); - var poll = new LongPollingTransport(timeoutToken, connection.Application.Input, loggerFactory); + var poll = new LongPollingTransport(timeoutToken, connection.Application.Input, LoggerFactory); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(timeoutToken, context.RequestAborted)) { @@ -68,13 +61,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task FrameSentAsSingleResponse() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); - var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, loggerFactory); + var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, LoggerFactory); var ms = new MemoryStream(); context.Response.Body = ms; @@ -91,13 +84,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task MultipleFramesSentAsSingleResponse() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); - var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, loggerFactory); + var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, LoggerFactory); var ms = new MemoryStream(); context.Response.Body = ms; diff --git a/test/Microsoft.AspNetCore.Http.Connections.Tests/ServerSentEventsTests.cs b/test/Microsoft.AspNetCore.Http.Connections.Tests/ServerSentEventsTests.cs index 72c0ec3103..e68a74d34f 100644 --- a/test/Microsoft.AspNetCore.Http.Connections.Tests/ServerSentEventsTests.cs +++ b/test/Microsoft.AspNetCore.Http.Connections.Tests/ServerSentEventsTests.cs @@ -6,33 +6,25 @@ using System.IO.Pipelines; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Connections.Internal.Transports; -using Microsoft.Extensions.Logging; using Xunit; using Microsoft.AspNetCore.SignalR.Tests; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.Http.Connections.Tests { public class ServerSentEventsTests : VerifiableLoggedTest { - public ServerSentEventsTests(ITestOutputHelper output) - : base(output) - { - } - [Fact] public async Task SSESetsContentType() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); - var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, loggerFactory); + var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, LoggerFactory); connection.Transport.Output.Complete(); @@ -46,7 +38,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task SSETurnsResponseBufferingOff() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); @@ -54,7 +46,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests var feature = new HttpBufferingFeature(); context.Features.Set(feature); - var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: connection.ConnectionId, loggerFactory); + var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: connection.ConnectionId, LoggerFactory); connection.Transport.Output.Complete(); @@ -67,7 +59,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task SSEWritesMessages() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, new PipeOptions(readerScheduler: PipeScheduler.Inline)); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); @@ -75,7 +67,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests var ms = new MemoryStream(); context.Response.Body = ms; - var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, loggerFactory); + var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, LoggerFactory); var task = sse.ProcessRequestAsync(context, context.RequestAborted); @@ -89,7 +81,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task SSEWritesVeryLargeMessages() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, new PipeOptions(readerScheduler: PipeScheduler.Inline)); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); @@ -97,7 +89,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests var ms = new MemoryStream(); context.Response.Body = ms; - var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, loggerFactory); + var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, LoggerFactory); var task = sse.ProcessRequestAsync(context, context.RequestAborted); @@ -117,13 +109,13 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData("Hello\r\nWorld", ":\r\ndata: Hello\r\ndata: World\r\n\r\n")] public async Task SSEAddsAppropriateFraming(string message, string expected) { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); - var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, loggerFactory); + var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, LoggerFactory); var ms = new MemoryStream(); context.Response.Body = ms; diff --git a/test/Microsoft.AspNetCore.Http.Connections.Tests/WebSocketsTests.cs b/test/Microsoft.AspNetCore.Http.Connections.Tests/WebSocketsTests.cs index d965636ec9..0af2f65812 100644 --- a/test/Microsoft.AspNetCore.Http.Connections.Tests/WebSocketsTests.cs +++ b/test/Microsoft.AspNetCore.Http.Connections.Tests/WebSocketsTests.cs @@ -15,35 +15,28 @@ 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)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); - var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application, loggerFactory.CreateLogger("HttpConnectionContext1")); + var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application, LoggerFactory.CreateLogger("HttpConnectionContext1")); using (var feature = new TestWebSocketConnectionFeature()) { - var connectionContext = new HttpConnectionContext(string.Empty, null, null, loggerFactory.CreateLogger("HttpConnectionContext2")); - var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory); + var connectionContext = new HttpConnectionContext(string.Empty, null, null, LoggerFactory.CreateLogger("HttpConnectionContext2")); + 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()); @@ -83,16 +76,16 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [InlineData(TransferFormat.Binary, nameof(WebSocketMessageType.Binary))] public async Task WebSocketTransportSetsMessageTypeBasedOnTransferFormatFeature(TransferFormat transferFormat, string expectedMessageType) { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); - var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application, loggerFactory.CreateLogger("HttpConnectionContext1")); + var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application, LoggerFactory.CreateLogger("HttpConnectionContext1")); using (var feature = new TestWebSocketConnectionFeature()) { - var connectionContext = new HttpConnectionContext(string.Empty, null, null, loggerFactory.CreateLogger("HttpConnectionContext2")); + var connectionContext = new HttpConnectionContext(string.Empty, null, null, LoggerFactory.CreateLogger("HttpConnectionContext2")); connectionContext.ActiveFormat = transferFormat; - var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory); + 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()); @@ -120,10 +113,10 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task TransportCommunicatesErrorToApplicationWhenClientDisconnectsAbnormally() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); - var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application, loggerFactory.CreateLogger("HttpConnectionContext1")); + var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application, LoggerFactory.CreateLogger("HttpConnectionContext1")); using (var feature = new TestWebSocketConnectionFeature()) { @@ -146,8 +139,8 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests } } - var connectionContext = new HttpConnectionContext(string.Empty, null, null, loggerFactory.CreateLogger("HttpConnectionContext2")); - var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory); + var connectionContext = new HttpConnectionContext(string.Empty, null, null, LoggerFactory.CreateLogger("HttpConnectionContext2")); + 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()); @@ -173,7 +166,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task ClientReceivesInternalServerErrorWhenTheApplicationFails() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application); @@ -181,7 +174,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests using (var feature = new TestWebSocketConnectionFeature()) { var connectionContext = new HttpConnectionContext(string.Empty, null, null); - var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory); + 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()); @@ -205,7 +198,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task TransportClosesOnCloseTimeoutIfClientDoesNotSendCloseFrame() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application); @@ -218,7 +211,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests }; var connectionContext = new HttpConnectionContext(string.Empty, null, null); - var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); + var ws = new WebSocketsTransport(options, connection.Application, connectionContext, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it @@ -240,7 +233,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task TransportFailsOnTimeoutWithErrorWhenApplicationFailsAndClientDoesNotSendCloseFrame() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application); @@ -253,7 +246,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests }; var connectionContext = new HttpConnectionContext(string.Empty, null, null); - var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); + var ws = new WebSocketsTransport(options, connection.Application, connectionContext, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it @@ -275,7 +268,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task ServerGracefullyClosesWhenApplicationEndsThenClientSendsCloseFrame() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application); @@ -289,7 +282,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests }; var connectionContext = new HttpConnectionContext(string.Empty, null, null); - var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); + var ws = new WebSocketsTransport(options, connection.Application, connectionContext, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it @@ -315,7 +308,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests [Fact] public async Task ServerGracefullyClosesWhenClientSendsCloseFrameThenApplicationEnds() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application); @@ -329,7 +322,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests }; var connectionContext = new HttpConnectionContext(string.Empty, null, null); - var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); + var ws = new WebSocketsTransport(options, connection.Application, connectionContext, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it @@ -358,7 +351,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests const string ExpectedSubProtocol = "expected"; var providedSubProtocols = new[] {"provided1", "provided2"}; - using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug)) + using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", pair.Transport, pair.Application); @@ -376,7 +369,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Tests }; var connectionContext = new HttpConnectionContext(string.Empty, null, null); - var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); + var ws = new WebSocketsTransport(options, connection.Application, connectionContext, LoggerFactory); // Create an HttpContext var context = new DefaultHttpContext(); diff --git a/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubConnectionTests.cs b/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubConnectionTests.cs index 986b8a041f..f0a7309a9a 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubConnectionTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubConnectionTests.cs @@ -18,7 +18,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests { @@ -32,12 +31,6 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests { private const string DefaultHubDispatcherLoggerName = "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher"; - // Pass null for server fixture as tests should provide their own - // This is to prevent logs from previous tests affecting running tests - public HubConnectionTests(ITestOutputHelper output) : base(output) - { - } - private HubConnection CreateHubConnection( string url, string path = null, @@ -72,11 +65,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests public async Task CheckFixedMessage(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(CheckFixedMessage)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { var connectionBuilder = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + path, transportType); + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + path, transportType); connectionBuilder.Services.AddSingleton(protocol); var connection = connectionBuilder.Build(); @@ -91,7 +84,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -106,10 +99,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests public async Task CanSendAndReceiveMessage(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(CanSendAndReceiveMessage)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { const string originalMessage = "SignalR"; - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -120,7 +113,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -132,13 +125,14 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task CanStopAndStartConnection(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(CanStopAndStartConnection)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { const string originalMessage = "SignalR"; - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -151,7 +145,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -163,15 +157,16 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task CanStartConnectionFromClosedEvent(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(CanStartConnectionFromClosedEvent)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); const string originalMessage = "SignalR"; - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); var restartTcs = new TaskCompletionSource(); connection.Closed += async e => { @@ -213,7 +208,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -228,10 +223,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests public async Task MethodsAreCaseInsensitive(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(MethodsAreCaseInsensitive)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { const string originalMessage = "SignalR"; - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -242,7 +237,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -254,14 +249,15 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task CanInvokeClientMethodFromServer(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(CanInvokeClientMethodFromServer)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { const string originalMessage = "SignalR"; - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -275,7 +271,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -287,12 +283,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task InvokeNonExistantClientMethodFromServer(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(InvokeNonExistantClientMethodFromServer)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); var closeTcs = new TaskCompletionSource(); connection.Closed += e => { @@ -316,7 +313,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} during test: {Message}", ex.GetType().Name, ex.Message); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} during test: {Message}", ex.GetType().Name, ex.Message); throw; } finally @@ -328,12 +325,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task CanStreamClientMethodFromServer(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(CanStreamClientMethodFromServer)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -345,7 +343,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -357,6 +355,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task CanCloseStreamMethodEarly(string protocolName, HttpTransportType transportType, string path) { bool ExpectedErrors(WriteContext writeContext) @@ -368,9 +367,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(CanCloseStreamMethodEarly)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}", ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -393,7 +392,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -405,12 +404,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(HubProtocolsAndTransportsAndHubPaths))] + [LogLevel(LogLevel.Trace)] public async Task StreamDoesNotStartIfTokenAlreadyCanceled(string protocolName, HttpTransportType transportType, string path) { var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, LogLevel.Trace, $"{nameof(StreamDoesNotStartIfTokenAlreadyCanceled)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) + using (StartServer(out var server)) { - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -422,7 +422,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -443,9 +443,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var protocol = HubProtocols[protocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ExceptionFromStreamingSentToClient)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, path, transportType, protocol, loggerFactory); + var connection = CreateHubConnection(server.Url, path, transportType, protocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -456,7 +456,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -477,9 +477,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionIfHubMethodCannotBeResolved)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -489,7 +489,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -510,9 +510,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionIfHubMethodCannotBeResolvedAndArgumentsPassedIn)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -522,7 +522,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -543,9 +543,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionOnHubMethodArgumentCountMismatch)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -555,7 +555,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -576,9 +576,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionOnHubMethodArgumentTypeMismatch)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -588,7 +588,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -609,9 +609,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionIfStreamingHubMethodCannotBeResolved)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -622,7 +622,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -643,9 +643,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionOnStreamingHubMethodArgumentCountMismatch)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -656,7 +656,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -677,9 +677,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionOnStreamingHubMethodArgumentTypeMismatch)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -690,7 +690,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -711,9 +711,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionIfNonStreamMethodInvokedWithStreamAsync)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -723,7 +723,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -744,9 +744,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionIfStreamMethodInvokedWithInvoke)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -756,7 +756,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -777,9 +777,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } var hubProtocol = HubProtocols[hubProtocolName]; - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ServerThrowsHubExceptionIfBuildingAsyncEnumeratorIsNotPossible)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var connection = CreateHubConnection(fixture.Url, hubPath, transportType, hubProtocol, loggerFactory); + var connection = CreateHubConnection(server.Url, hubPath, transportType, hubProtocol, LoggerFactory); try { await connection.StartAsync().OrTimeout(); @@ -789,7 +789,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -803,18 +803,18 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [MemberData(nameof(TransportTypes))] public async Task ClientCanUseJwtBearerTokenForAuthentication(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ClientCanUseJwtBearerTokenForAuthentication)}_{transportType}")) + using (StartServer(out var server)) { async Task AccessTokenProvider() { - var httpResponse = await new HttpClient().GetAsync(fixture.Url + "/generateJwtToken"); + var httpResponse = await new HttpClient().GetAsync(server.Url + "/generateJwtToken"); httpResponse.EnsureSuccessStatusCode(); return await httpResponse.Content.ReadAsStringAsync(); }; var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/authorizedhub", transportType, options => + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/authorizedhub", transportType, options => { options.AccessTokenProvider = AccessTokenProvider; }) @@ -827,7 +827,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -841,11 +841,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [MemberData(nameof(TransportTypes))] public async Task ClientCanUseJwtBearerTokenForAuthenticationWhenRedirected(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ClientCanUseJwtBearerTokenForAuthenticationWhenRedirected)}_{transportType}")) + using (StartServer(out var server)) { var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/redirect", transportType) + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/redirect", transportType) .Build(); try { @@ -855,7 +855,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -869,11 +869,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [MemberData(nameof(TransportTypes))] public async Task ClientCanSendHeaders(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(ClientCanSendHeaders)}_{transportType}")) + using (StartServer(out var server)) { var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/default", transportType, options => + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/default", transportType, options => { options.Headers["X-test"] = "42"; options.Headers["X-42"] = "test"; @@ -887,7 +887,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -901,15 +901,15 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [WebSocketsSupportedCondition] public async Task WebSocketOptionsAreApplied() { - using (StartServer(out var loggerFactory, out var fixture, $"{nameof(WebSocketOptionsAreApplied)}")) + using (StartServer(out var server)) { // System.Net has a HttpTransportType type which means we need to fully-qualify this rather than 'use' the namespace var cookieJar = new System.Net.CookieContainer(); - cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(fixture.Url).Host)); + cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(server.Url).Host)); var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/default", HttpTransportType.WebSockets, options => + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/default", HttpTransportType.WebSockets, options => { options.WebSocketConfiguration = o => o.Cookies = cookieJar; }) @@ -922,7 +922,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -935,11 +935,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Fact] public async Task CheckHttpConnectionFeatures() { - using (StartServer(out var loggerFactory, out var fixture)) + using (StartServer(out var server)) { var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/default") + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/default") .Build(); try { @@ -958,7 +958,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -971,11 +971,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Fact] public async Task UserIdProviderCanAccessHttpContext() { - using (StartServer(out var loggerFactory, out var fixture)) + using (StartServer(out var server)) { var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/default", options => + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/default", options => { options.Headers.Add(HeaderUserIdProvider.HeaderName, "SuperAdmin"); }) @@ -989,7 +989,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -1002,12 +1002,12 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Fact] public async Task NegotiationSkipsServerSentEventsWhenUsingBinaryProtocol() { - using (StartServer(out var loggerFactory, out var fixture)) + using (StartServer(out var server)) { var hubConnectionBuilder = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) + .WithLoggerFactory(LoggerFactory) .AddMessagePackProtocol() - .WithUrl(fixture.Url + "/default-nowebsockets"); + .WithUrl(server.Url + "/default-nowebsockets"); var hubConnection = hubConnectionBuilder.Build(); try @@ -1019,7 +1019,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -1032,12 +1032,12 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Fact] public async Task StopCausesPollToReturnImmediately() { - using (StartServer(out var loggerFactory, out var fixture)) + using (StartServer(out var server)) { PollTrackingMessageHandler pollTracker = null; var hubConnection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) - .WithUrl(fixture.Url + "/default", options => + .WithLoggerFactory(LoggerFactory) + .WithUrl(server.Url + "/default", options => { options.Transports = HttpTransportType.LongPolling; options.HttpMessageHandlerFactory = handler => diff --git a/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubProtocolVersionTests.cs b/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubProtocolVersionTests.cs index 47b6ff6229..f0b5658ca2 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubProtocolVersionTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.FunctionalTests/HubProtocolVersionTests.cs @@ -19,7 +19,6 @@ using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests { @@ -31,18 +30,14 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Collection(HubProtocolVersionTestsCollection.Name)] public class HubProtocolVersionTests : FunctionalTestBase { - public HubProtocolVersionTests(ITestOutputHelper output) : base(output) - { - } - [Theory] [MemberData(nameof(TransportTypes))] public async Task ClientUsingOldCallWithOriginalProtocol(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var server, $"{nameof(ClientUsingOldCallWithOriginalProtocol)}_{transportType}")) + using (StartServer(out var server)) { var connectionBuilder = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) + .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); var connection = connectionBuilder.Build(); @@ -57,7 +52,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -71,10 +66,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [MemberData(nameof(TransportTypes))] public async Task ClientUsingOldCallWithNewProtocol(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var server, $"{nameof(ClientUsingOldCallWithNewProtocol)}_{transportType}")) + using (StartServer(out var server)) { var connectionBuilder = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) + .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); connectionBuilder.Services.AddSingleton(new VersionedJsonHubProtocol(1000)); @@ -90,7 +85,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -104,19 +99,19 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [MemberData(nameof(TransportTypes))] public async Task ClientUsingNewCallWithNewProtocol(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var server, $"{nameof(ClientUsingNewCallWithNewProtocol)}_{transportType}")) + using (StartServer(out var server)) { var httpConnectionFactory = new HttpConnectionFactory(Options.Create(new HttpConnectionOptions { Url = new Uri(server.Url + "/version"), Transports = transportType - }), loggerFactory); + }), LoggerFactory); var tcs = new TaskCompletionSource(); var proxyConnectionFactory = new ProxyConnectionFactory(httpConnectionFactory); var connectionBuilder = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory); + .WithLoggerFactory(LoggerFactory); connectionBuilder.Services.AddSingleton(new VersionedJsonHubProtocol(1000)); connectionBuilder.Services.AddSingleton(proxyConnectionFactory); @@ -147,7 +142,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally @@ -159,6 +154,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests [Theory] [MemberData(nameof(TransportTypes))] + [LogLevel(LogLevel.Trace)] public async Task ClientWithUnsupportedProtocolVersionDoesNotConnect(HttpTransportType transportType) { bool ExpectedErrors(WriteContext writeContext) @@ -166,10 +162,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests return writeContext.LoggerName == typeof(HubConnection).FullName; } - using (StartServer(out var loggerFactory, out var server, LogLevel.Trace, $"{nameof(ClientWithUnsupportedProtocolVersionDoesNotConnect)}_{transportType}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { var connectionBuilder = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) + .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); connectionBuilder.Services.AddSingleton(new VersionedJsonHubProtocol(int.MaxValue)); @@ -183,7 +179,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests } catch (Exception ex) { - loggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); + LoggerFactory.CreateLogger().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally diff --git a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.ConnectionLifecycle.cs b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.ConnectionLifecycle.cs index a688fcee4c..73278bfd3d 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.ConnectionLifecycle.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.ConnectionLifecycle.cs @@ -14,7 +14,6 @@ using Microsoft.AspNetCore.SignalR.Tests; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.Tests { @@ -22,16 +21,12 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests { public class ConnectionLifecycle : VerifiableLoggedTest { - public ConnectionLifecycle(ITestOutputHelper output) : base(output) - { - } - [Fact] public async Task CanStartStartedConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - await WithConnectionAsync(CreateConnection(loggerFactory: loggerFactory), async (connection) => + await WithConnectionAsync(CreateConnection(loggerFactory: LoggerFactory), async (connection) => { await connection.StartAsync(TransferFormat.Text).OrTimeout(); await connection.StartAsync(TransferFormat.Text).OrTimeout(); @@ -42,10 +37,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task CanStartStartingConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { await WithConnectionAsync( - CreateConnection(loggerFactory: loggerFactory, transport: new TestTransport(onTransportStart: SyncPoint.Create(out var syncPoint))), + CreateConnection(loggerFactory: LoggerFactory, transport: new TestTransport(onTransportStart: SyncPoint.Create(out var syncPoint))), async (connection) => { var firstStart = connection.StartAsync(TransferFormat.Text).OrTimeout(); @@ -62,10 +57,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task CannotStartConnectionOnceDisposed() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { await WithConnectionAsync( - CreateConnection(loggerFactory: loggerFactory), + CreateConnection(loggerFactory: LoggerFactory), async (connection) => { await connection.StartAsync(TransferFormat.Text).OrTimeout(); @@ -90,7 +85,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests writeContext.EventId.Name == "ErrorStartingTransport"; } - using (StartVerifiableLog(out var loggerFactory, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { var startCounter = 0; var expected = new Exception("Transport failed to start"); @@ -120,7 +115,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests await WithConnectionAsync( CreateConnection( - loggerFactory: loggerFactory, + loggerFactory: LoggerFactory, transportType: HttpTransports.All, transport: new TestTransport(onTransportStart: OnTransportStart)), async (connection) => @@ -141,7 +136,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests writeContext.EventId.Name == "ErrorStartingTransport"; } - using (StartVerifiableLog(out var loggerFactory, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { var startCounter = 0; var availableTransports = 3; @@ -154,7 +149,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests await WithConnectionAsync( CreateConnection( - loggerFactory: loggerFactory, + loggerFactory: LoggerFactory, transportType: HttpTransports.All, transport: new TestTransport(onTransportStart: OnTransportStart)), async (connection) => @@ -176,10 +171,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task CanDisposeUnstartedConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { await WithConnectionAsync( - CreateConnection(loggerFactory: loggerFactory), + CreateConnection(loggerFactory: LoggerFactory), async (connection) => { await connection.DisposeAsync(); @@ -191,11 +186,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task CanDisposeStartingConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { await WithConnectionAsync( CreateConnection( - loggerFactory: loggerFactory, + loggerFactory: LoggerFactory, transport: new TestTransport( onTransportStart: SyncPoint.Create(out var transportStart), onTransportStop: SyncPoint.Create(out var transportStop))), @@ -225,11 +220,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task CanDisposeDisposingConnection() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { await WithConnectionAsync( CreateConnection( - loggerFactory: loggerFactory, + loggerFactory: LoggerFactory, transport: new TestTransport(onTransportStop: SyncPoint.Create(out var transportStop))), async (connection) => { @@ -290,7 +285,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests writeContext.EventId.Name == "ErrorSending"; } - using (StartVerifiableLog(out var loggerFactory, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { var httpHandler = new TestHttpMessageHandler(); @@ -312,7 +307,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); await WithConnectionAsync( - CreateConnection(httpHandler, loggerFactory), + CreateConnection(httpHandler, LoggerFactory), async (connection) => { await connection.StartAsync(TransferFormat.Text).OrTimeout(); @@ -349,7 +344,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task SSEWaitsForResponseToStart() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var httpHandler = new TestHttpMessageHandler(); @@ -360,10 +355,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests return ResponseUtils.CreateResponse(HttpStatusCode.Accepted); }); - var sse = new ServerSentEventsTransport(new HttpClient(httpHandler), loggerFactory); + var sse = new ServerSentEventsTransport(new HttpClient(httpHandler), LoggerFactory); await WithConnectionAsync( - CreateConnection(httpHandler, loggerFactory: loggerFactory, transport: sse), + CreateConnection(httpHandler, loggerFactory: LoggerFactory, transport: sse), async (connection) => { var startTask = connection.StartAsync(TransferFormat.Text).OrTimeout(); diff --git a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.Transport.cs b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.Transport.cs index 6d46bfd4ff..54ecfa98b5 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.Transport.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.Transport.cs @@ -15,7 +15,6 @@ using Microsoft.AspNetCore.Http.Connections.Client; using Microsoft.AspNetCore.Http.Connections.Client.Internal; using Microsoft.AspNetCore.SignalR.Tests; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.Tests { @@ -23,10 +22,6 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests { public class Transport : VerifiableLoggedTest { - public Transport(ITestOutputHelper output) : base(output) - { - } - [Theory] [InlineData(HttpTransportType.LongPolling)] [InlineData(HttpTransportType.ServerSentEvents)] @@ -81,7 +76,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [InlineData(HttpTransportType.ServerSentEvents, false)] public async Task HttpConnectionSetsInherentKeepAliveFeature(HttpTransportType transportType, bool expectedValue) { - using (StartVerifiableLog(out var loggerFactory, testName: $"HttpConnectionSetsInherentKeepAliveFeature_{transportType}_{expectedValue}")) + using (StartVerifiableLog()) { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); @@ -90,7 +85,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests testHttpHandler.OnRequest((request, next, token) => Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent))); await WithConnectionAsync( - CreateConnection(testHttpHandler, transportType: transportType, loggerFactory: loggerFactory), + CreateConnection(testHttpHandler, transportType: transportType, loggerFactory: LoggerFactory), async (connection) => { await connection.StartAsync(TransferFormat.Text).OrTimeout(); diff --git a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.cs b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.cs index 45283c4a81..4de8ca1f4b 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HttpConnectionTests.cs @@ -16,16 +16,11 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Testing; using Moq; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.Tests { public partial class HttpConnectionTests : VerifiableLoggedTest { - public HttpConnectionTests(ITestOutputHelper output) : base(output) - { - } - [Fact] public void CannotCreateConnectionWithNullUrl() { diff --git a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HubConnectionTests.cs b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HubConnectionTests.cs index 550d13a879..66d711b2da 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.Tests/HubConnectionTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.Tests/HubConnectionTests.cs @@ -16,39 +16,44 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Moq; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.Tests { public partial class HubConnectionTests : VerifiableLoggedTest { - public HubConnectionTests(ITestOutputHelper output) - : base(output) - { - } - [Fact] public async Task InvokeThrowsIfSerializingMessageFails() { - var exception = new InvalidOperationException(); - var hubConnection = CreateHubConnection(new TestConnection(), protocol: MockHubProtocol.Throw(exception)); - await hubConnection.StartAsync().OrTimeout(); + bool ExpectedErrors(WriteContext writeContext) + { + return writeContext.LoggerName == typeof(HubConnection).FullName && + writeContext.EventId.Name == "FailedToSendInvocation"; + } + using (StartVerifiableLog(ExpectedErrors)) + { + var exception = new InvalidOperationException(); + var hubConnection = CreateHubConnection(new TestConnection(), protocol: MockHubProtocol.Throw(exception), LoggerFactory); + await hubConnection.StartAsync().OrTimeout(); - var actualException = - await Assert.ThrowsAsync(async () => await hubConnection.InvokeAsync("test").OrTimeout()); - Assert.Same(exception, actualException); + var actualException = + await Assert.ThrowsAsync(async () => await hubConnection.InvokeAsync("test").OrTimeout()); + Assert.Same(exception, actualException); + } } [Fact] public async Task SendAsyncThrowsIfSerializingMessageFails() { - var exception = new InvalidOperationException(); - var hubConnection = CreateHubConnection(new TestConnection(), protocol: MockHubProtocol.Throw(exception)); - await hubConnection.StartAsync().OrTimeout(); + using (StartVerifiableLog()) + { + var exception = new InvalidOperationException(); + var hubConnection = CreateHubConnection(new TestConnection(), protocol: MockHubProtocol.Throw(exception), LoggerFactory); + await hubConnection.StartAsync().OrTimeout(); - var actualException = - await Assert.ThrowsAsync(async () => await hubConnection.SendAsync("test").OrTimeout()); - Assert.Same(exception, actualException); + var actualException = + await Assert.ThrowsAsync(async () => await hubConnection.SendAsync("test").OrTimeout()); + Assert.Same(exception, actualException); + } } [Fact] @@ -77,60 +82,80 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests [Fact] public async Task PendingInvocationsAreCanceledWhenConnectionClosesCleanly() { - var hubConnection = CreateHubConnection(new TestConnection()); + using (StartVerifiableLog()) + { + var hubConnection = CreateHubConnection(new TestConnection(), loggerFactory: LoggerFactory); - await hubConnection.StartAsync().OrTimeout(); - var invokeTask = hubConnection.InvokeAsync("testMethod").OrTimeout(); - await hubConnection.StopAsync().OrTimeout(); + await hubConnection.StartAsync().OrTimeout(); + var invokeTask = hubConnection.InvokeAsync("testMethod").OrTimeout(); + await hubConnection.StopAsync().OrTimeout(); - await Assert.ThrowsAsync(async () => await invokeTask); + await Assert.ThrowsAsync(async () => await invokeTask); + } } [Fact] public async Task PendingInvocationsAreTerminatedWithExceptionWhenTransportCompletesWithError() { - var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, protocol: Mock.Of()); + bool ExpectedErrors(WriteContext writeContext) + { + return writeContext.LoggerName == typeof(HubConnection).FullName && + (writeContext.EventId.Name == "ShutdownWithError" || + writeContext.EventId.Name == "ServerDisconnectedWithError"); + } + using (StartVerifiableLog(ExpectedErrors)) + { + var connection = new TestConnection(); + var hubConnection = CreateHubConnection(connection, protocol: Mock.Of(), LoggerFactory); - await hubConnection.StartAsync().OrTimeout(); - var invokeTask = hubConnection.InvokeAsync("testMethod").OrTimeout(); + await hubConnection.StartAsync().OrTimeout(); + var invokeTask = hubConnection.InvokeAsync("testMethod").OrTimeout(); - var exception = new InvalidOperationException(); - connection.CompleteFromTransport(exception); + var exception = new InvalidOperationException(); + connection.CompleteFromTransport(exception); - var actualException = await Assert.ThrowsAsync(async () => await invokeTask); - Assert.Equal(exception, actualException); + var actualException = await Assert.ThrowsAsync(async () => await invokeTask); + Assert.Equal(exception, actualException); + } } [Fact] public async Task ConnectionTerminatedIfServerTimeoutIntervalElapsesWithNoMessages() { - var hubConnection = CreateHubConnection(new TestConnection()); - hubConnection.ServerTimeout = TimeSpan.FromMilliseconds(100); - - var closeTcs = new TaskCompletionSource(); - hubConnection.Closed += ex => + bool ExpectedErrors(WriteContext writeContext) { - closeTcs.TrySetResult(ex); - return Task.CompletedTask; - }; + return writeContext.LoggerName == typeof(HubConnection).FullName && + writeContext.EventId.Name == "ShutdownWithError"; + } + using (StartVerifiableLog(ExpectedErrors)) + { + var hubConnection = CreateHubConnection(new TestConnection(), loggerFactory: LoggerFactory); + hubConnection.ServerTimeout = TimeSpan.FromMilliseconds(100); - await hubConnection.StartAsync().OrTimeout(); + var closeTcs = new TaskCompletionSource(); + hubConnection.Closed += ex => + { + closeTcs.TrySetResult(ex); + return Task.CompletedTask; + }; - var exception = Assert.IsType(await closeTcs.Task.OrTimeout()); + await hubConnection.StartAsync().OrTimeout(); - // We use an interpolated string so the tests are accurate on non-US machines. - Assert.Equal($"Server timeout ({hubConnection.ServerTimeout.TotalMilliseconds:0.00}ms) elapsed without receiving a message from the server.", exception.Message); + var exception = Assert.IsType(await closeTcs.Task.OrTimeout()); + + // We use an interpolated string so the tests are accurate on non-US machines. + Assert.Equal($"Server timeout ({hubConnection.ServerTimeout.TotalMilliseconds:0.00}ms) elapsed without receiving a message from the server.", exception.Message); + } } [Fact] public async Task ServerTimeoutIsDisabledWhenUsingTransportWithInherentKeepAlive() { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { var testConnection = new TestConnection(); testConnection.Features.Set(new TestKeepAliveFeature() { HasInherentKeepAlive = true }); - var hubConnection = CreateHubConnection(testConnection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(testConnection, loggerFactory: LoggerFactory); hubConnection.ServerTimeout = TimeSpan.FromMilliseconds(1); await hubConnection.StartAsync().OrTimeout(); @@ -151,6 +176,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task PendingInvocationsAreTerminatedIfServerTimeoutIntervalElapsesWithNoMessages() { bool ExpectedErrors(WriteContext writeContext) @@ -159,9 +185,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests writeContext.EventId.Name == "ShutdownWithError"; } - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { - var hubConnection = CreateHubConnection(new TestConnection(), loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(new TestConnection(), loggerFactory: LoggerFactory); hubConnection.ServerTimeout = TimeSpan.FromMilliseconds(2000); await hubConnection.StartAsync().OrTimeout(); @@ -177,12 +203,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task StreamIntsToServer() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace)) + using (StartVerifiableLog()) { var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(connection, loggerFactory: LoggerFactory); await hubConnection.StartAsync().OrTimeout(); var channel = Channel.CreateUnbounded(); @@ -206,7 +233,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests channel.Writer.TryComplete(); var completion = await connection.ReadSentJsonAsync().OrTimeout(); Assert.Equal(HubProtocolConstants.StreamCompleteMessageType, completion["type"]); - + await connection.ReceiveJsonMessage( new { type = HubProtocolConstants.CompletionMessageType, invocationId = invocation["invocationId"], result = 42 } ).OrTimeout(); @@ -216,12 +243,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task StreamIntsToServerViaSend() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace)) + using (StartVerifiableLog()) { var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(connection, loggerFactory: LoggerFactory); await hubConnection.StartAsync().OrTimeout(); var channel = Channel.CreateUnbounded(); @@ -246,12 +274,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task StreamsObjectsToServer() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace)) + using (StartVerifiableLog()) { var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(connection, loggerFactory: LoggerFactory); await hubConnection.StartAsync().OrTimeout(); var channel = Channel.CreateUnbounded(); @@ -289,12 +318,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task UploadStreamCancelationSendsStreamComplete() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace)) + using (StartVerifiableLog()) { var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(connection, loggerFactory: LoggerFactory); await hubConnection.StartAsync().OrTimeout(); var cts = new CancellationTokenSource(); @@ -321,12 +351,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task InvocationCanCompleteBeforeStreamCompletes() { - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace)) + using (StartVerifiableLog()) { var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(connection, loggerFactory: LoggerFactory); await hubConnection.StartAsync().OrTimeout(); var channel = Channel.CreateUnbounded(); @@ -346,6 +377,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } [Fact] + [LogLevel(LogLevel.Trace)] public async Task WrongTypeOnServerResponse() { bool ExpectedErrors(WriteContext writeContext) @@ -354,10 +386,10 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests (writeContext.EventId.Name == "ServerDisconnectedWithError" || writeContext.EventId.Name == "ShutdownWithError"); } - using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace, expectedErrorsFilter: ExpectedErrors)) + using (StartVerifiableLog(ExpectedErrors)) { var connection = new TestConnection(); - var hubConnection = CreateHubConnection(connection, loggerFactory: loggerFactory); + var hubConnection = CreateHubConnection(connection, loggerFactory: LoggerFactory); await hubConnection.StartAsync().OrTimeout(); // we expect to get sent ints, and receive an int back diff --git a/test/Microsoft.AspNetCore.SignalR.Client.Tests/LongPollingTransportTests.cs b/test/Microsoft.AspNetCore.SignalR.Client.Tests/LongPollingTransportTests.cs index 9dfbb30b56..0d985d69c0 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.Tests/LongPollingTransportTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.Tests/LongPollingTransportTests.cs @@ -8,20 +8,15 @@ using System.IO.Pipelines; using System.Linq; using System.Net; using System.Net.Http; -using System.Net.Http.Headers; -using System.Reflection; -using System.Runtime.InteropServices.ComTypes; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; -using Microsoft.AspNetCore.Http.Connections.Client; using Microsoft.AspNetCore.Http.Connections.Client.Internal; using Microsoft.AspNetCore.SignalR.Tests; using Moq; using Moq.Protected; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.Tests { @@ -29,10 +24,6 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests { private static readonly Uri TestUri = new Uri("http://example.com/?id=1234"); - public LongPollingTransportTests(ITestOutputHelper output) : base(output) - { - } - [Fact] public async Task LongPollingTransportStopsPollAndSendLoopsWhenTransportStopped() { @@ -258,11 +249,11 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests } }); - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { using (var httpClient = new HttpClient(mockHttpHandler.Object)) { - var longPollingTransport = new LongPollingTransport(httpClient, loggerFactory); + var longPollingTransport = new LongPollingTransport(httpClient, LoggerFactory); await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary).OrTimeout(); diff --git a/test/Microsoft.AspNetCore.SignalR.Client.Tests/ServerSentEventsTransportTests.cs b/test/Microsoft.AspNetCore.SignalR.Client.Tests/ServerSentEventsTransportTests.cs index 6e1e474ca8..ab497f6ab3 100644 --- a/test/Microsoft.AspNetCore.SignalR.Client.Tests/ServerSentEventsTransportTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Client.Tests/ServerSentEventsTransportTests.cs @@ -6,29 +6,20 @@ using System.IO; using System.IO.Pipelines; using System.Net.Http; using System.Net.Http.Headers; -using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; -using Microsoft.AspNetCore.Http.Connections.Client; using Microsoft.AspNetCore.Http.Connections.Client.Internal; using Microsoft.AspNetCore.SignalR.Tests; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Testing; using Moq; using Moq.Protected; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client.Tests { public class ServerSentEventsTransportTests : VerifiableLoggedTest { - public ServerSentEventsTransportTests(ITestOutputHelper output) : base(output) - { - } - [Fact] public async Task CanStartStopSSETransport() { @@ -56,9 +47,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests try { using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); await sseTransport.StartAsync( new Uri("http://fakeuri.org"), TransferFormat.Text).OrTimeout(); @@ -99,9 +90,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); Task transportActiveTask; try @@ -147,9 +138,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); await sseTransport.StartAsync( new Uri("http://fakeuri.org"), TransferFormat.Text).OrTimeout(); @@ -237,9 +228,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); await sseTransport.StartAsync( new Uri("http://fakeuri.org"), TransferFormat.Text).OrTimeout(); @@ -264,9 +255,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); await sseTransport.StartAsync( new Uri("http://fakeuri.org"), TransferFormat.Text).OrTimeout(); @@ -318,9 +309,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); await sseTransport.StartAsync( new Uri("http://fakeuri.org"), TransferFormat.Text).OrTimeout(); @@ -353,9 +344,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); var ex = await Assert.ThrowsAsync(() => sseTransport.StartAsync(new Uri("http://fakeuri.org"), TransferFormat.Binary).OrTimeout()); @@ -380,9 +371,9 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) - using (StartVerifiableLog(out var loggerFactory, $"{nameof(SSETransportThrowsForInvalidTransferFormat)}_{transferFormat}")) + using (StartVerifiableLog()) { - var sseTransport = new ServerSentEventsTransport(httpClient, loggerFactory); + var sseTransport = new ServerSentEventsTransport(httpClient, LoggerFactory); var exception = await Assert.ThrowsAsync(() => sseTransport.StartAsync(new Uri("http://fakeuri.org"), transferFormat)); diff --git a/test/Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests/RedisEndToEnd.cs b/test/Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests/RedisEndToEnd.cs index 8e747ad4fd..b214afaeca 100644 --- a/test/Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests/RedisEndToEnd.cs +++ b/test/Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests/RedisEndToEnd.cs @@ -12,7 +12,6 @@ using Microsoft.AspNetCore.Testing.xunit; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests { @@ -28,7 +27,7 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests { private readonly RedisServerFixture _serverFixture; - public RedisEndToEndTests(RedisServerFixture serverFixture, ITestOutputHelper output) : base(output) + public RedisEndToEndTests(RedisServerFixture serverFixture) { if (serverFixture == null) { @@ -43,12 +42,11 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests [MemberData(nameof(TransportTypesAndProtocolTypes))] public async Task HubConnectionCanSendAndReceiveMessages(HttpTransportType transportType, string protocolName) { - using (StartVerifiableLog(out var loggerFactory, testName: - $"{nameof(HubConnectionCanSendAndReceiveMessages)}_{transportType.ToString()}_{protocolName}")) + using (StartVerifiableLog()) { var protocol = HubProtocolHelpers.GetHubProtocol(protocolName); - var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory); + var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, LoggerFactory); await connection.StartAsync().OrTimeout(); var str = await connection.InvokeAsync("Echo", "Hello, World!").OrTimeout(); @@ -64,13 +62,12 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests [MemberData(nameof(TransportTypesAndProtocolTypes))] public async Task HubConnectionCanSendAndReceiveGroupMessages(HttpTransportType transportType, string protocolName) { - using (StartVerifiableLog(out var loggerFactory, testName: - $"{nameof(HubConnectionCanSendAndReceiveGroupMessages)}_{transportType.ToString()}_{protocolName}")) + using (StartVerifiableLog()) { var protocol = HubProtocolHelpers.GetHubProtocol(protocolName); - var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory); - var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, loggerFactory); + var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, LoggerFactory); + var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, LoggerFactory); var tcs = new TaskCompletionSource(); connection.On("Echo", message => tcs.TrySetResult(message)); @@ -97,13 +94,12 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests [MemberData(nameof(TransportTypesAndProtocolTypes))] public async Task CanSendAndReceiveUserMessagesFromMultipleConnectionsWithSameUser(HttpTransportType transportType, string protocolName) { - using (StartVerifiableLog(out var loggerFactory, testName: - $"{nameof(CanSendAndReceiveUserMessagesFromMultipleConnectionsWithSameUser)}_{transportType.ToString()}_{protocolName}")) + using (StartVerifiableLog()) { var protocol = HubProtocolHelpers.GetHubProtocol(protocolName); - var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory, userName: "userA"); - var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, loggerFactory, userName: "userA"); + var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, LoggerFactory, userName: "userA"); + var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, LoggerFactory, userName: "userA"); var tcs = new TaskCompletionSource(); connection.On("Echo", message => tcs.TrySetResult(message)); @@ -130,13 +126,12 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Tests // Regression test: // When multiple connections from the same user were connected and one left, it used to unsubscribe from the user channel // Now we keep track of users connections and only unsubscribe when no users are listening - using (StartVerifiableLog(out var loggerFactory, testName: - $"{nameof(CanSendAndReceiveUserMessagesWhenOneConnectionWithUserDisconnects)}_{transportType.ToString()}_{protocolName}")) + using (StartVerifiableLog()) { var protocol = HubProtocolHelpers.GetHubProtocol(protocolName); - var firstConnection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory, userName: "userA"); - var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, loggerFactory, userName: "userA"); + var firstConnection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, LoggerFactory, userName: "userA"); + var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, LoggerFactory, userName: "userA"); var tcs = new TaskCompletionSource(); firstConnection.On("Echo", message => tcs.TrySetResult(message)); diff --git a/test/Microsoft.AspNetCore.SignalR.Tests.Utils/FunctionalTestBase.cs b/test/Microsoft.AspNetCore.SignalR.Tests.Utils/FunctionalTestBase.cs index 023f3b90b2..797c7a846a 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests.Utils/FunctionalTestBase.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests.Utils/FunctionalTestBase.cs @@ -3,10 +3,7 @@ using System; using System.Collections.Generic; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Tests { @@ -14,7 +11,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests { private readonly Func _globalExpectedErrorsFilter; - public FunctionalTestBase(ITestOutputHelper output) : base(output) + public FunctionalTestBase() { // Suppress errors globally here _globalExpectedErrorsFilter = (writeContext) => false; @@ -38,17 +35,10 @@ namespace Microsoft.AspNetCore.SignalR.Tests }; } - public IDisposable StartServer(out ILoggerFactory loggerFactory, out InProcessTestServer testServer, LogLevel minLogLevel, [CallerMemberName] string testName = null, Func expectedErrorsFilter = null) where T : class + public IDisposable StartServer(out InProcessTestServer testServer, Func expectedErrorsFilter = null) where T : class { - var disposable = base.StartVerifiableLog(out loggerFactory, minLogLevel, testName, ResolveExpectedErrorsFilter(expectedErrorsFilter)); - testServer = new InProcessTestServer(loggerFactory); - return new MultiDisposable(testServer, disposable); - } - - public IDisposable StartServer(out ILoggerFactory loggerFactory, out InProcessTestServer testServer, [CallerMemberName] string testName = null, Func expectedErrorsFilter = null) where T : class - { - var disposable = base.StartVerifiableLog(out loggerFactory, testName, ResolveExpectedErrorsFilter(expectedErrorsFilter)); - testServer = new InProcessTestServer(loggerFactory); + var disposable = base.StartVerifiableLog(ResolveExpectedErrorsFilter(expectedErrorsFilter)); + testServer = new InProcessTestServer(LoggerFactory); return new MultiDisposable(testServer, disposable); } diff --git a/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifiableLoggedTest.cs b/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifiableLoggedTest.cs index 3c99566817..08e924ce98 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifiableLoggedTest.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifiableLoggedTest.cs @@ -2,37 +2,20 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Tests { public class VerifiableLoggedTest : LoggedTest { - public VerifiableLoggedTest(ITestOutputHelper output) : base(output) + public virtual IDisposable StartVerifiableLog(Func expectedErrorsFilter = null) { + return CreateScope(expectedErrorsFilter); } - public virtual IDisposable StartVerifiableLog(out ILoggerFactory loggerFactory, [CallerMemberName] string testName = null, Func expectedErrorsFilter = null) + private VerifyNoErrorsScope CreateScope(Func expectedErrorsFilter = null) { - var disposable = StartLog(out loggerFactory, testName); - - return CreateScope(ref loggerFactory, disposable, expectedErrorsFilter); - } - - public virtual IDisposable StartVerifiableLog(out ILoggerFactory loggerFactory, LogLevel minLogLevel, [CallerMemberName] string testName = null, Func expectedErrorsFilter = null) - { - var disposable = StartLog(out loggerFactory, minLogLevel, testName); - - return CreateScope(ref loggerFactory, disposable, expectedErrorsFilter); - } - - private VerifyNoErrorsScope CreateScope(ref ILoggerFactory loggerFactory, IDisposable wrappedDisposable = null, Func expectedErrorsFilter = null) - { - loggerFactory = new WrappingLoggerFactory(loggerFactory ?? new LoggerFactory()); - return new VerifyNoErrorsScope(loggerFactory, wrappedDisposable, expectedErrorsFilter); + return new VerifyNoErrorsScope(LoggerFactory, wrappedDisposable: null, expectedErrorsFilter); } } } diff --git a/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifyNoErrorsScope.cs b/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifyNoErrorsScope.cs index c66862fedc..f23712c8d5 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifyNoErrorsScope.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests.Utils/VerifyNoErrorsScope.cs @@ -2,9 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; diff --git a/test/Microsoft.AspNetCore.SignalR.Tests/EndToEndTests.cs b/test/Microsoft.AspNetCore.SignalR.Tests/EndToEndTests.cs index 786608fcf7..d8f7cb754b 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests/EndToEndTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests/EndToEndTests.cs @@ -21,7 +21,6 @@ using Microsoft.Extensions.Logging.Testing; using Moq; using Moq.Protected; using Xunit; -using Xunit.Abstractions; using HttpConnectionOptions = Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionOptions; namespace Microsoft.AspNetCore.SignalR.Tests @@ -34,19 +33,15 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Collection(EndToEndTestsCollection.Name)] public class EndToEndTests : FunctionalTestBase { - public EndToEndTests(ITestOutputHelper output) : base(output) - { - } - [Fact] public async Task CanStartAndStopConnectionUsingDefaultTransport() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { var url = server.Url + "/echo"; // The test should connect to the server using WebSockets transport on Windows 8 and newer. // On Windows 7/2008R2 it should use ServerSentEvents transport to connect to the server. - var connection = new HttpConnection(new Uri(url), HttpTransports.All, loggerFactory); + var connection = new HttpConnection(new Uri(url), HttpTransports.All, LoggerFactory); await connection.StartAsync(TransferFormat.Binary).OrTimeout(); await connection.DisposeAsync().OrTimeout(); } @@ -61,14 +56,14 @@ namespace Microsoft.AspNetCore.SignalR.Tests writeContext.EventId.Name == "ErrorStartingTransport"; } - using (StartServer(out var loggerFactory, out var server, expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, expectedErrorsFilter: ExpectedErrors)) { var url = server.Url + "/echo"; // The test should connect to the server using WebSockets transport on Windows 8 and newer. // On Windows 7/2008R2 it should use ServerSentEvents transport to connect to the server. // The test logic lives in the TestTransportFactory and FakeTransport. - var connection = new HttpConnection(new HttpConnectionOptions { Url = new Uri(url) }, loggerFactory, new TestTransportFactory()); + var connection = new HttpConnection(new HttpConnectionOptions { Url = new Uri(url) }, LoggerFactory, new TestTransportFactory()); await connection.StartAsync(TransferFormat.Text).OrTimeout(); await connection.DisposeAsync().OrTimeout(); } @@ -76,12 +71,13 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Theory] [MemberData(nameof(TransportTypes))] + [LogLevel(LogLevel.Trace)] public async Task CanStartAndStopConnectionUsingGivenTransport(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var server, minLogLevel: LogLevel.Trace, testName: $"CanStartAndStopConnectionUsingGivenTransport_{transportType}")) + using (StartServer(out var server)) { var url = server.Url + "/echo"; - var connection = new HttpConnection(new Uri(url), transportType, loggerFactory); + var connection = new HttpConnection(new Uri(url), transportType, LoggerFactory); await connection.StartAsync(TransferFormat.Text).OrTimeout(); await connection.DisposeAsync().OrTimeout(); } @@ -91,9 +87,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsTest() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); const string message = "Hello, World!"; using (var ws = new ClientWebSocket()) @@ -129,9 +125,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsReceivesAndSendsPartialFramesTest() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); const string message = "Hello, World!"; using (var ws = new ClientWebSocket()) @@ -168,9 +164,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task HttpRequestsNotSentWhenWebSocketsTransportRequestedAndSkipNegotiationSet() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/echo"; var mockHttpHandler = new Mock(); @@ -187,7 +183,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests HttpMessageHandlerFactory = (httpMessageHandler) => mockHttpHandler.Object }; - var connection = new HttpConnection(httpOptions, loggerFactory); + var connection = new HttpConnection(httpOptions, LoggerFactory); try { @@ -218,9 +214,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(HttpTransportType.ServerSentEvents)] public async Task HttpConnectionThrowsIfSkipNegotiationSetAndTransportIsNotWebSockets(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/echo"; var mockHttpHandler = new Mock(); @@ -237,7 +233,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests HttpMessageHandlerFactory = (httpMessageHandler) => mockHttpHandler.Object }; - var connection = new HttpConnection(httpOptions, loggerFactory); + var connection = new HttpConnection(httpOptions, LoggerFactory); try { @@ -258,16 +254,17 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Theory] [MemberData(nameof(TransportTypesAndTransferFormats))] + [LogLevel(LogLevel.Trace)] public async Task ConnectionCanSendAndReceiveMessages(HttpTransportType transportType, TransferFormat requestedTransferFormat) { - using (StartServer(out var loggerFactory, out var server, minLogLevel: LogLevel.Trace, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}_{requestedTransferFormat.ToString()}")) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); const string message = "Major Key"; var url = server.Url + "/echo"; - var connection = new HttpConnection(new Uri(url), transportType, loggerFactory); + var connection = new HttpConnection(new Uri(url), transportType, LoggerFactory); try { logger.LogInformation("Starting connection to {url}", url); @@ -310,26 +307,20 @@ namespace Microsoft.AspNetCore.SignalR.Tests } } - public static IEnumerable MessageSizesData - { - get - { - yield return new object[] { new string('A', 5 * 4096) }; - yield return new object[] { new string('A', 1000 * 4096 + 32) }; - } - } - [ConditionalTheory] [WebSocketsSupportedCondition] - [MemberData(nameof(MessageSizesData))] - public async Task ConnectionCanSendAndReceiveDifferentMessageSizesWebSocketsTransport(string message) + [InlineData(5 * 4096)] + [InlineData(1000 * 4096 + 32)] + [LogLevel(LogLevel.Trace)] + public async Task ConnectionCanSendAndReceiveDifferentMessageSizesWebSocketsTransport(int length) { - using (StartServer(out var loggerFactory, out var server, LogLevel.Trace, testName: $"ConnectionCanSendAndReceiveDifferentMessageSizesWebSocketsTransport_{message.Length}")) + var message = new string('A', length); + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/echo"; - var connection = new HttpConnection(new Uri(url), HttpTransportType.WebSockets, loggerFactory); + var connection = new HttpConnection(new Uri(url), HttpTransportType.WebSockets, LoggerFactory); try { @@ -364,6 +355,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests [ConditionalFact] [WebSocketsSupportedCondition] + [LogLevel(LogLevel.Trace)] public async Task UnauthorizedWebSocketsConnectionDoesNotConnect() { bool ExpectedErrors(WriteContext writeContext) @@ -372,12 +364,12 @@ namespace Microsoft.AspNetCore.SignalR.Tests writeContext.EventId.Name == "ErrorWithNegotiation"; } - using (StartServer(out var loggerFactory, out var server, LogLevel.Trace, expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/auth"; - var connection = new HttpConnection(new Uri(url), HttpTransportType.WebSockets, loggerFactory); + var connection = new HttpConnection(new Uri(url), HttpTransportType.WebSockets, LoggerFactory); var exception = await Assert.ThrowsAsync(() => connection.StartAsync(TransferFormat.Binary).OrTimeout()); @@ -387,6 +379,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests [ConditionalFact] [WebSocketsSupportedCondition] + [LogLevel(LogLevel.Trace)] public async Task UnauthorizedDirectWebSocketsConnectionDoesNotConnect() { bool ExpectedErrors(WriteContext writeContext) @@ -395,9 +388,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests writeContext.EventId.Name == "ErrorStartingTransport"; } - using (StartServer(out var loggerFactory, out var server, LogLevel.Trace, expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/auth"; var options = new HttpConnectionOptions @@ -407,7 +400,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests SkipNegotiation = true }; - var connection = new HttpConnection(options, loggerFactory); + var connection = new HttpConnection(options, LoggerFactory); await Assert.ThrowsAsync(() => connection.StartAsync(TransferFormat.Binary).OrTimeout()); } @@ -416,6 +409,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Theory] [InlineData(HttpTransportType.LongPolling)] [InlineData(HttpTransportType.ServerSentEvents)] + [LogLevel(LogLevel.Trace)] public async Task UnauthorizedConnectionDoesNotConnect(HttpTransportType transportType) { bool ExpectedErrors(WriteContext writeContext) @@ -424,12 +418,12 @@ namespace Microsoft.AspNetCore.SignalR.Tests writeContext.EventId.Name == "ErrorWithNegotiation"; } - using (StartServer(out var loggerFactory, out var server, LogLevel.Trace, testName: $"{nameof(UnauthorizedConnectionDoesNotConnect)}_{transportType}", expectedErrorsFilter: ExpectedErrors)) + using (StartServer(out var server, ExpectedErrors)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/auth"; - var connection = new HttpConnection(new Uri(url), transportType, loggerFactory); + var connection = new HttpConnection(new Uri(url), transportType, LoggerFactory); try { @@ -481,13 +475,13 @@ namespace Microsoft.AspNetCore.SignalR.Tests private async Task ServerClosesConnectionWithErrorIfHubCannotBeCreated(HttpTransportType transportType) { - using (StartServer(out var loggerFactory, out var server, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}")) + using (StartServer(out var server)) { - var logger = loggerFactory.CreateLogger(); + var logger = LoggerFactory.CreateLogger(); var url = server.Url + "/uncreatable"; var connection = new HubConnectionBuilder() - .WithLoggerFactory(loggerFactory) + .WithLoggerFactory(LoggerFactory) .WithUrl(url, transportType) .Build(); try diff --git a/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTestUtils/Utils.cs b/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTestUtils/Utils.cs index 294ec7922f..fed151dd6d 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTestUtils/Utils.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTestUtils/Utils.cs @@ -4,6 +4,8 @@ using System; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Microsoft.AspNetCore.SignalR.Tests @@ -50,7 +52,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests } } - public static IServiceProvider CreateServiceProvider(Action addServices = null) + public static IServiceProvider CreateServiceProvider(Action addServices = null, ILoggerFactory loggerFactory = null) { var services = new ServiceCollection(); services.AddOptions() @@ -61,12 +63,17 @@ namespace Microsoft.AspNetCore.SignalR.Tests addServices?.Invoke(services); + if (loggerFactory != null) + { + services.AddSingleton(loggerFactory); + } + return services.BuildServiceProvider(); } - public static Connections.ConnectionHandler GetHubConnectionHandler(Type hubType, Action addServices = null) + public static Connections.ConnectionHandler GetHubConnectionHandler(Type hubType, Action addServices = null, ILoggerFactory loggerFactory = null) { - var serviceProvider = CreateServiceProvider(addServices); + var serviceProvider = CreateServiceProvider(addServices, loggerFactory); return (Connections.ConnectionHandler)serviceProvider.GetService(GetConnectionHandlerType(hubType)); } } diff --git a/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.cs b/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.cs index b27a73414b..1147b2e4e4 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.cs @@ -17,7 +17,8 @@ using Microsoft.AspNetCore.Http.Connections.Features; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Options; using Moq; using Newtonsoft.Json; @@ -27,488 +28,588 @@ using Xunit; namespace Microsoft.AspNetCore.SignalR.Tests { - public class HubConnectionHandlerTests + public class HubConnectionHandlerTests : VerifiableLoggedTest { [Fact] + [LogLevel(LogLevel.Trace)] public async Task HubsAreDisposed() { - var trackDispose = new TrackDispose(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(s => s.AddSingleton(trackDispose)); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var trackDispose = new TrackDispose(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(s => s.AddSingleton(trackDispose), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask; + // kill the connection + client.Dispose(); - Assert.Equal(2, trackDispose.DisposeCount); + await connectionHandlerTask; + + Assert.Equal(2, trackDispose.DisposeCount); + } } } [Fact] public async Task ConnectionAbortedTokenTriggers() { - var state = new ConnectionLifetimeState(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(s => s.AddSingleton(state)); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var state = new ConnectionLifetimeState(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(s => s.AddSingleton(state), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + // kill the connection + client.Dispose(); - Assert.True(state.TokenCallbackTriggered); - Assert.False(state.TokenStateInConnected); - Assert.True(state.TokenStateInDisconnected); + await connectionHandlerTask.OrTimeout(); + + Assert.True(state.TokenCallbackTriggered); + Assert.False(state.TokenStateInConnected); + Assert.True(state.TokenStateInDisconnected); + } } } [Fact] public async Task OnDisconnectedAsyncTriggersWhenAbortedTokenCallbackThrows() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + // kill the connection + client.Dispose(); - var firedOnConnected = (bool)client.Connection.Items[nameof(ErrorInAbortedTokenHub.OnConnectedAsync)]; - var firedOnDisconnected = (bool)client.Connection.Items[nameof(ErrorInAbortedTokenHub.OnDisconnectedAsync)]; + await connectionHandlerTask.OrTimeout(); - Assert.True(firedOnConnected); - Assert.True(firedOnDisconnected); + var firedOnConnected = (bool)client.Connection.Items[nameof(ErrorInAbortedTokenHub.OnConnectedAsync)]; + var firedOnDisconnected = (bool)client.Connection.Items[nameof(ErrorInAbortedTokenHub.OnDisconnectedAsync)]; + + Assert.True(firedOnConnected); + Assert.True(firedOnDisconnected); + } } } [Fact] public async Task AbortFromHubMethodForcesClientDisconnect() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.SendInvocationAsync(nameof(AbortHub.Kill)).OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + await client.SendInvocationAsync(nameof(AbortHub.Kill)).OrTimeout(); - Assert.Null(client.TryRead()); + await connectionHandlerTask.OrTimeout(); + + Assert.Null(client.TryRead()); + } } } [Fact] public async Task MissingHandshakeAndMessageSentFromHubConnectionCanBeDisposedCleanly() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler, false, false); + return writeContext.LoggerName == typeof(HubConnectionContext).FullName && + writeContext.EventId.Name == "HandshakeFailed"; + } - // kill the connection - client.Dispose(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await connectionHandlerTask; + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler, false, false); - Assert.Null(client.HandshakeResponseMessage); + // kill the connection + client.Dispose(); + + await connectionHandlerTask; + + Assert.Null(client.HandshakeResponseMessage); + } } } [Fact] public async Task HandshakeTimesOut() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + using (StartVerifiableLog()) { - services.Configure(options => + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { - options.HandshakeTimeout = TimeSpan.FromMilliseconds(5); - }); - }); - var connectionHandler = serviceProvider.GetService>(); + services.Configure(options => + { + options.HandshakeTimeout = TimeSpan.FromMilliseconds(5); + }); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler, false); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler, false); - Assert.NotNull(client.HandshakeResponseMessage); - Assert.Equal("Handshake was canceled.", client.HandshakeResponseMessage.Error); + Assert.NotNull(client.HandshakeResponseMessage); + Assert.Equal("Handshake was canceled.", client.HandshakeResponseMessage.Error); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CanLoadHubContext() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var context = serviceProvider.GetRequiredService>(); - await context.Clients.All.SendAsync("Send", "test"); + using (StartVerifiableLog()) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var context = serviceProvider.GetRequiredService>(); + await context.Clients.All.SendAsync("Send", "test"); + } } [Fact] public async Task CanLoadTypedHubContext() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var context = serviceProvider.GetRequiredService>(); - await context.Clients.All.Send("test"); + using (StartVerifiableLog()) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var context = serviceProvider.GetRequiredService>(); + await context.Clients.All.Send("test"); + } } [Fact] public void FailsToLoadInvalidTypedHubClient() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var ex = Assert.Throws(() => - serviceProvider.GetRequiredService>()); - Assert.Equal($"Cannot generate proxy implementation for '{typeof(IVoidReturningTypedHubClient).FullName}.{nameof(IVoidReturningTypedHubClient.Send)}'. All client proxy methods must return '{typeof(Task).FullName}'.", ex.Message); + using (StartVerifiableLog()) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var ex = Assert.Throws(() => + serviceProvider.GetRequiredService>()); + Assert.Equal($"Cannot generate proxy implementation for '{typeof(IVoidReturningTypedHubClient).FullName}.{nameof(IVoidReturningTypedHubClient.Send)}'. All client proxy methods must return '{typeof(Task).FullName}'.", ex.Message); + } } [Fact] public async Task HandshakeFailureFromUnknownProtocolSendsResponseWithError() { - var hubProtocolMock = new Mock(); - hubProtocolMock.Setup(m => m.Name).Returns("CustomProtocol"); - - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - - using (var client = new TestClient(protocol: hubProtocolMock.Object)) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return writeContext.LoggerName == typeof(HubConnectionContext).FullName && + writeContext.EventId.Name == "HandshakeFailed"; + } - Assert.NotNull(client.HandshakeResponseMessage); - Assert.Equal("The protocol 'CustomProtocol' is not supported.", client.HandshakeResponseMessage.Error); + using (StartVerifiableLog(ExpectedErrors)) + { + var hubProtocolMock = new Mock(); + hubProtocolMock.Setup(m => m.Name).Returns("CustomProtocol"); - client.Dispose(); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); - await connectionHandlerTask.OrTimeout(); + using (var client = new TestClient(protocol: hubProtocolMock.Object)) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + + Assert.NotNull(client.HandshakeResponseMessage); + Assert.Equal("The protocol 'CustomProtocol' is not supported.", client.HandshakeResponseMessage.Error); + + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HandshakeFailureFromUnsupportedFormatSendsResponseWithError() { - var hubProtocolMock = new Mock(); - hubProtocolMock.Setup(m => m.Name).Returns("CustomProtocol"); - - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - - using (var client = new TestClient(protocol: new MessagePackHubProtocol())) + bool ExpectedErrors(WriteContext writeContext) { - client.SupportedFormats = TransferFormat.Text; + return writeContext.LoggerName == typeof(HubConnectionContext).FullName && + writeContext.EventId.Name == "HandshakeFailed"; + } - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + using (StartVerifiableLog(ExpectedErrors)) + { + var hubProtocolMock = new Mock(); + hubProtocolMock.Setup(m => m.Name).Returns("CustomProtocol"); - Assert.NotNull(client.HandshakeResponseMessage); - Assert.Equal("Cannot use the 'messagepack' protocol on the current transport. The transport does not support 'Binary' transfer format.", client.HandshakeResponseMessage.Error); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); - client.Dispose(); + using (var client = new TestClient(protocol: new MessagePackHubProtocol())) + { + client.SupportedFormats = TransferFormat.Text; - await connectionHandlerTask.OrTimeout(); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + + Assert.NotNull(client.HandshakeResponseMessage); + Assert.Equal("Cannot use the 'messagepack' protocol on the current transport. The transport does not support 'Binary' transfer format.", client.HandshakeResponseMessage.Error); + + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task SendingHandshakeRequestInChunksWorks() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - var part1 = Encoding.UTF8.GetBytes("{\"protocol\": \"json\""); - var part2 = Encoding.UTF8.GetBytes(",\"version\": 1}"); - var part3 = Encoding.UTF8.GetBytes("\u001e"); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - client.SupportedFormats = TransferFormat.Text; + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); + var part1 = Encoding.UTF8.GetBytes("{\"protocol\": \"json\""); + var part2 = Encoding.UTF8.GetBytes(",\"version\": 1}"); + var part3 = Encoding.UTF8.GetBytes("\u001e"); - var connectionHandlerTask = await client.ConnectAsync(connectionHandler, - sendHandshakeRequestMessage: false, - expectedHandshakeResponseMessage: false); + using (var client = new TestClient()) + { + client.SupportedFormats = TransferFormat.Text; - // Wait for the handshake response - var task = client.ReadAsync(isHandshake: true); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler, + sendHandshakeRequestMessage: false, + expectedHandshakeResponseMessage: false); - await client.Connection.Application.Output.WriteAsync(part1); + // Wait for the handshake response + var task = client.ReadAsync(isHandshake: true); - Assert.False(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(part1); - await client.Connection.Application.Output.WriteAsync(part2); + Assert.False(task.IsCompleted); - Assert.False(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(part2); - await client.Connection.Application.Output.WriteAsync(part3); + Assert.False(task.IsCompleted); - Assert.True(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(part3); - var response = (await task) as HandshakeResponseMessage; - Assert.NotNull(response); + Assert.True(task.IsCompleted); - client.Dispose(); + var response = (await task) as HandshakeResponseMessage; + Assert.NotNull(response); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task SendingInvocatonInChunksWorks() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - var part1 = Encoding.UTF8.GetBytes("{\"type\":1, \"invocationId\":\"1\", "); - var part2 = Encoding.UTF8.GetBytes("\"target\": \"Echo\", \"arguments\""); - var part3 = Encoding.UTF8.GetBytes(":[\"hello\"]}\u001e"); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - client.SupportedFormats = TransferFormat.Text; + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); + var part1 = Encoding.UTF8.GetBytes("{\"type\":1, \"invocationId\":\"1\", "); + var part2 = Encoding.UTF8.GetBytes("\"target\": \"Echo\", \"arguments\""); + var part3 = Encoding.UTF8.GetBytes(":[\"hello\"]}\u001e"); - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + using (var client = new TestClient()) + { + client.SupportedFormats = TransferFormat.Text; - // Wait for the hub completion - var task = client.ReadAsync(); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connection.Application.Output.WriteAsync(part1); + // Wait for the hub completion + var task = client.ReadAsync(); - Assert.False(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(part1); - await client.Connection.Application.Output.WriteAsync(part2); + Assert.False(task.IsCompleted); - Assert.False(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(part2); - await client.Connection.Application.Output.WriteAsync(part3); + Assert.False(task.IsCompleted); - Assert.True(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(part3); - var completionMessage = await task as CompletionMessage; - Assert.NotNull(completionMessage); - Assert.Equal("hello", completionMessage.Result); - Assert.Equal("1", completionMessage.InvocationId); + Assert.True(task.IsCompleted); - client.Dispose(); + var completionMessage = await task as CompletionMessage; + Assert.NotNull(completionMessage); + Assert.Equal("hello", completionMessage.Result); + Assert.Equal("1", completionMessage.InvocationId); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task SendingHandshakeRequestAndInvocationInSamePayloadParsesHandshakeAndInvocation() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - var payload = Encoding.UTF8.GetBytes("{\"protocol\": \"json\",\"version\": 1}\u001e{\"type\":1, \"invocationId\":\"1\", \"target\": \"Echo\", \"arguments\":[\"hello\"]}\u001e"); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - client.SupportedFormats = TransferFormat.Text; + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); + var payload = Encoding.UTF8.GetBytes("{\"protocol\": \"json\",\"version\": 1}\u001e{\"type\":1, \"invocationId\":\"1\", \"target\": \"Echo\", \"arguments\":[\"hello\"]}\u001e"); - var connectionHandlerTask = await client.ConnectAsync(connectionHandler, - sendHandshakeRequestMessage: false, - expectedHandshakeResponseMessage: false); + using (var client = new TestClient()) + { + client.SupportedFormats = TransferFormat.Text; - // Wait for the handshake response - var task = client.ReadAsync(isHandshake: true); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler, + sendHandshakeRequestMessage: false, + expectedHandshakeResponseMessage: false); - await client.Connection.Application.Output.WriteAsync(payload); + // Wait for the handshake response + var task = client.ReadAsync(isHandshake: true); - Assert.True(task.IsCompleted); + await client.Connection.Application.Output.WriteAsync(payload); - var response = await task as HandshakeResponseMessage; - Assert.NotNull(response); + Assert.True(task.IsCompleted); - var completionMessage = await client.ReadAsync() as CompletionMessage; - Assert.NotNull(completionMessage); - Assert.Equal("hello", completionMessage.Result); - Assert.Equal("1", completionMessage.InvocationId); + var response = await task as HandshakeResponseMessage; + Assert.NotNull(response); - client.Dispose(); + var completionMessage = await client.ReadAsync() as CompletionMessage; + Assert.NotNull(completionMessage); + Assert.Equal("hello", completionMessage.Result); + Assert.Equal("1", completionMessage.InvocationId); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HandshakeSuccessSendsResponseWithoutError() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); - Assert.NotNull(client.HandshakeResponseMessage); - Assert.Null(client.HandshakeResponseMessage.Error); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - client.Dispose(); + Assert.NotNull(client.HandshakeResponseMessage); + Assert.Null(client.HandshakeResponseMessage.Error); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HandshakeFailureFromIncompatibleProtocolVersionSendsResponseWithError() { - var hubProtocolMock = new Mock(); - hubProtocolMock.Setup(m => m.Name).Returns("json"); - hubProtocolMock.Setup(m => m.Version).Returns(9001); - - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - - using (var client = new TestClient(protocol: hubProtocolMock.Object)) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var hubProtocolMock = new Mock(); + hubProtocolMock.Setup(m => m.Name).Returns("json"); + hubProtocolMock.Setup(m => m.Version).Returns(9001); - Assert.NotNull(client.HandshakeResponseMessage); - Assert.Equal("The server does not support version 9001 of the 'json' protocol.", client.HandshakeResponseMessage.Error); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); - client.Dispose(); + using (var client = new TestClient(protocol: hubProtocolMock.Object)) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + Assert.NotNull(client.HandshakeResponseMessage); + Assert.Equal("The server does not support version 9001 of the 'json' protocol.", client.HandshakeResponseMessage.Error); + + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task ConnectionClosesOnServerWithPartialHandshakeMessageAndCompletedPipe() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - // partial handshake - var payload = Encoding.UTF8.GetBytes("{\"protocol\": \"json\",\"ver"); - await client.Connection.Application.Output.WriteAsync(payload).OrTimeout(); + return writeContext.LoggerName == typeof(HubConnectionContext).FullName && + writeContext.EventId.Name == "HandshakeFailed"; + } - var connectionHandlerTask = await client.ConnectAsync(connectionHandler, sendHandshakeRequestMessage: false, expectedHandshakeResponseMessage: false); - // Complete the pipe to 'close' the connection - client.Connection.Application.Output.Complete(); + using (StartVerifiableLog(ExpectedErrors)) + { + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); - // This will never complete as the pipe was completed and nothing can be written to it - var handshakeReadTask = client.ReadAsync(true); + using (var client = new TestClient()) + { + // partial handshake + var payload = Encoding.UTF8.GetBytes("{\"protocol\": \"json\",\"ver"); + await client.Connection.Application.Output.WriteAsync(payload).OrTimeout(); - // Check that the connection was closed on the server - await connectionHandlerTask.OrTimeout(); - Assert.False(handshakeReadTask.IsCompleted); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler, sendHandshakeRequestMessage: false, expectedHandshakeResponseMessage: false); + // Complete the pipe to 'close' the connection + client.Connection.Application.Output.Complete(); - client.Dispose(); + // This will never complete as the pipe was completed and nothing can be written to it + var handshakeReadTask = client.ReadAsync(true); + + // Check that the connection was closed on the server + await connectionHandlerTask.OrTimeout(); + Assert.False(handshakeReadTask.IsCompleted); + + client.Dispose(); + } } } [Fact] public async Task LifetimeManagerOnDisconnectedAsyncCalledIfLifetimeManagerOnConnectedAsyncThrows() { - var mockLifetimeManager = new Mock>(); - mockLifetimeManager - .Setup(m => m.OnConnectedAsync(It.IsAny())) - .Throws(new InvalidOperationException("Lifetime manager OnConnectedAsync failed.")); - var mockHubActivator = new Mock>(); - - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + using (StartVerifiableLog()) { - services.AddSingleton(mockLifetimeManager.Object); - services.AddSingleton(mockHubActivator.Object); - }); + var mockLifetimeManager = new Mock>(); + mockLifetimeManager + .Setup(m => m.OnConnectedAsync(It.IsAny())) + .Throws(new InvalidOperationException("Lifetime manager OnConnectedAsync failed.")); + var mockHubActivator = new Mock>(); - var connectionHandler = serviceProvider.GetService>(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services.AddSingleton(mockLifetimeManager.Object); + services.AddSingleton(mockHubActivator.Object); + }, LoggerFactory); - using (var client = new TestClient()) - { - var exception = - await Assert.ThrowsAsync( - async () => - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); - }); - Assert.Equal("Lifetime manager OnConnectedAsync failed.", exception.Message); + var connectionHandler = serviceProvider.GetService>(); - client.Dispose(); + using (var client = new TestClient()) + { + var exception = + await Assert.ThrowsAsync( + async () => + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + await connectionHandlerTask.OrTimeout(); + }); + Assert.Equal("Lifetime manager OnConnectedAsync failed.", exception.Message); - mockLifetimeManager.Verify(m => m.OnConnectedAsync(It.IsAny()), Times.Once); - mockLifetimeManager.Verify(m => m.OnDisconnectedAsync(It.IsAny()), Times.Once); - // No hubs should be created since the connection is terminated - mockHubActivator.Verify(m => m.Create(), Times.Never); - mockHubActivator.Verify(m => m.Release(It.IsAny()), Times.Never); + client.Dispose(); + + mockLifetimeManager.Verify(m => m.OnConnectedAsync(It.IsAny()), Times.Once); + mockLifetimeManager.Verify(m => m.OnDisconnectedAsync(It.IsAny()), Times.Once); + // No hubs should be created since the connection is terminated + mockHubActivator.Verify(m => m.Create(), Times.Never); + mockHubActivator.Verify(m => m.Release(It.IsAny()), Times.Never); + } } } [Fact] public async Task HubOnDisconnectedAsyncCalledIfHubOnConnectedAsyncThrows() { - var mockLifetimeManager = new Mock>(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + bool ExpectedErrors(WriteContext writeContext) { - services.AddSingleton(mockLifetimeManager.Object); - }); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.HubConnectionHandler" && + writeContext.EventId.Name == "ErrorDispatchingHubEvent"; + } - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog(ExpectedErrors)) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - client.Dispose(); + var mockLifetimeManager = new Mock>(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services.AddSingleton(mockLifetimeManager.Object); + }, LoggerFactory); - await connectionHandlerTask.OrTimeout(); + var connectionHandler = serviceProvider.GetService>(); - mockLifetimeManager.Verify(m => m.OnConnectedAsync(It.IsAny()), Times.Once); - mockLifetimeManager.Verify(m => m.OnDisconnectedAsync(It.IsAny()), Times.Once); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + + mockLifetimeManager.Verify(m => m.OnConnectedAsync(It.IsAny()), Times.Once); + mockLifetimeManager.Verify(m => m.OnDisconnectedAsync(It.IsAny()), Times.Once); + } } } [Fact] public async Task LifetimeManagerOnDisconnectedAsyncCalledIfHubOnDisconnectedAsyncThrows() { - var mockLifetimeManager = new Mock>(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + bool ExpectedErrors(WriteContext writeContext) { - services.AddSingleton(mockLifetimeManager.Object); - }); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.HubConnectionHandler" && + writeContext.EventId.Name == "ErrorDispatchingHubEvent"; + } - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog(ExpectedErrors)) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - client.Dispose(); + var mockLifetimeManager = new Mock>(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services.AddSingleton(mockLifetimeManager.Object); + }, LoggerFactory); - var exception = await Assert.ThrowsAsync(async () => await connectionHandlerTask); - Assert.Equal("Hub OnDisconnected failed.", exception.Message); + var connectionHandler = serviceProvider.GetService>(); - mockLifetimeManager.Verify(m => m.OnConnectedAsync(It.IsAny()), Times.Once); - mockLifetimeManager.Verify(m => m.OnDisconnectedAsync(It.IsAny()), Times.Once); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + client.Dispose(); + + var exception = await Assert.ThrowsAsync(async () => await connectionHandlerTask); + Assert.Equal("Hub OnDisconnected failed.", exception.Message); + + mockLifetimeManager.Verify(m => m.OnConnectedAsync(It.IsAny()), Times.Once); + mockLifetimeManager.Verify(m => m.OnDisconnectedAsync(It.IsAny()), Times.Once); + } } } [Fact] public async Task HubMethodCanReturnValueFromTask() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync(nameof(MethodHub.TaskValueMethod)).OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - // json serializer makes this a long - Assert.Equal(42L, result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync(nameof(MethodHub.TaskValueMethod)).OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + // json serializer makes this a long + Assert.Equal(42L, result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -516,20 +617,23 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task HubMethodsAreCaseInsensitive(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = (Task)await client.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - var result = (await client.InvokeAsync("echo", "hello").OrTimeout()).Result; + using (var client = new TestClient()) + { + var connectionHandlerTask = (Task)await client.ConnectAsync(connectionHandler); - Assert.Equal("hello", result); + var result = (await client.InvokeAsync("echo", "hello").OrTimeout()).Result; - // kill the connection - client.Dispose(); + Assert.Equal("hello", result); - await connectionHandlerTask.OrTimeout(); + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -538,158 +642,188 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(nameof(MethodHub.MethodThatYieldsFailedTask), false)] public async Task HubMethodCanThrowOrYieldFailedTask(string methodName, bool detailedErrors) { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + bool ExpectedErrors(WriteContext writeContext) { - builder.AddSignalR(options => - { - options.EnableDetailedErrors = detailedErrors; - }); - }); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog(ExpectedErrors)) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - - var message = await client.InvokeAsync(methodName).OrTimeout(); - - if (detailedErrors) + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => { - Assert.Equal($"An unexpected error occurred invoking '{methodName}' on the server. InvalidOperationException: BOOM!", message.Error); - } - else + builder.AddSignalR(options => + { + options.EnableDetailedErrors = detailedErrors; + }); + }, LoggerFactory); + + var connectionHandler = serviceProvider.GetService>(); + + using (var client = new TestClient()) { - Assert.Equal($"An unexpected error occurred invoking '{methodName}' on the server.", message.Error); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + + var message = await client.InvokeAsync(methodName).OrTimeout(); + + if (detailedErrors) + { + Assert.Equal($"An unexpected error occurred invoking '{methodName}' on the server. InvalidOperationException: BOOM!", message.Error); + } + else + { + Assert.Equal($"An unexpected error occurred invoking '{methodName}' on the server.", message.Error); + } + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); } - - // kill the connection - client.Dispose(); - - await connectionHandlerTask.OrTimeout(); } } [Fact] public async Task DetailedExceptionEvenWhenNotExplicitlySet() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var methodName = nameof(MethodHub.ThrowHubException); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var message = await client.InvokeAsync(methodName).OrTimeout(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - Assert.Equal($"An unexpected error occurred invoking '{methodName}' on the server. HubException: This is a hub exception", message.Error); + var methodName = nameof(MethodHub.ThrowHubException); - // kill the connection - client.Dispose(); + var connectionHandler = serviceProvider.GetService>(); - await connectionHandlerTask.OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + + var message = await client.InvokeAsync(methodName).OrTimeout(); + + Assert.Equal($"An unexpected error occurred invoking '{methodName}' on the server. HubException: This is a hub exception", message.Error); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubMethodDoesNotSendResultWhenInvocationIsNonBlocking() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - await client.SendInvocationAsync(nameof(MethodHub.ValueMethod), nonBlocking: true).OrTimeout(); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); - - // Ensure the client channel is empty - var message = client.TryRead(); - switch (message) + using (var client = new TestClient()) { - case CloseMessage close: - break; - default: - Assert.Null(message); - break; - } + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + await client.SendInvocationAsync(nameof(MethodHub.ValueMethod), nonBlocking: true).OrTimeout(); + + // kill the connection + client.Dispose(); + + // Ensure the client channel is empty + var message = client.TryRead(); + switch (message) + { + case CloseMessage close: + break; + default: + Assert.Null(message); + break; + } + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubMethodCanBeVoid() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync(nameof(MethodHub.VoidMethod)).OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - Assert.Null(result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync(nameof(MethodHub.VoidMethod)).OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + Assert.Null(result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubMethodCanBeRenamedWithAttribute() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync("RenamedMethod").OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - // json serializer makes this a long - Assert.Equal(43L, result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync("RenamedMethod").OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + // json serializer makes this a long + Assert.Equal(43L, result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubMethodNameAttributeIsInherited() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync("RenamedVirtualMethod").OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - // json serializer makes this a long - Assert.Equal(34L, result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync("RenamedVirtualMethod").OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + // json serializer makes this a long + Assert.Equal(34L, result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -699,203 +833,260 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(nameof(MethodHub.ValueMethod))] public async Task NonBlockingInvocationDoesNotSendCompletion(string methodName) { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return methodName == nameof(MethodHub.MethodThatThrows) && writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - // This invocation should be completely synchronous - await client.SendInvocationAsync(methodName, nonBlocking: true).OrTimeout(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - // kill the connection - client.Dispose(); + var connectionHandler = serviceProvider.GetService>(); - // only thing written should be close message - var closeMessage = await client.ReadAsync().OrTimeout(); - Assert.IsType(closeMessage); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + // This invocation should be completely synchronous + await client.SendInvocationAsync(methodName, nonBlocking: true).OrTimeout(); + + // kill the connection + client.Dispose(); + + // only thing written should be close message + var closeMessage = await client.ReadAsync().OrTimeout(); + Assert.IsType(closeMessage); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubMethodWithMultiParam() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync(nameof(MethodHub.ConcatString), (byte)32, 42, 'm', "string").OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - Assert.Equal("32, 42, m, string", result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync(nameof(MethodHub.ConcatString), (byte)32, 42, 'm', "string").OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + Assert.Equal("32, 42, m, string", result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CanCallInheritedHubMethodFromInheritingHub() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync(nameof(InheritedHub.BaseMethod), "string").OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - Assert.Equal("string", result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync(nameof(InheritedHub.BaseMethod), "string").OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + Assert.Equal("string", result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CanCallOverridenVirtualHubMethod() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - var result = (await client.InvokeAsync(nameof(InheritedHub.VirtualMethod), 10).OrTimeout()).Result; + var connectionHandler = serviceProvider.GetService>(); - Assert.Equal(0L, result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // kill the connection - client.Dispose(); + var result = (await client.InvokeAsync(nameof(InheritedHub.VirtualMethod), 10).OrTimeout()).Result; - await connectionHandlerTask.OrTimeout(); + Assert.Equal(0L, result); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CannotCallOverriddenBaseHubMethod() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var result = await client.InvokeAsync(nameof(MethodHub.OnDisconnectedAsync)).OrTimeout(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - Assert.Equal("Failed to invoke 'OnDisconnectedAsync' due to an error on the server. HubException: Method does not exist.", result.Error); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + var result = await client.InvokeAsync(nameof(MethodHub.OnDisconnectedAsync)).OrTimeout(); + + Assert.Equal("Failed to invoke 'OnDisconnectedAsync' due to an error on the server. HubException: Method does not exist.", result.Error); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public void HubsCannotHaveOverloadedMethods() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); + using (StartVerifiableLog()) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - try - { - var connectionHandler = serviceProvider.GetService>(); - Assert.True(false); - } - catch (NotSupportedException ex) - { - Assert.Equal("Duplicate definitions of 'OverloadedMethod'. Overloading is not supported.", ex.Message); + try + { + var connectionHandler = serviceProvider.GetService>(); + Assert.True(false); + } + catch (NotSupportedException ex) + { + Assert.Equal("Duplicate definitions of 'OverloadedMethod'. Overloading is not supported.", ex.Message); + } } } [Fact] public async Task CannotCallStaticHubMethods() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var result = await client.InvokeAsync(nameof(MethodHub.StaticMethod)).OrTimeout(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - Assert.Equal("Failed to invoke 'StaticMethod' due to an error on the server. HubException: Method does not exist.", result.Error); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + var result = await client.InvokeAsync(nameof(MethodHub.StaticMethod)).OrTimeout(); + + Assert.Equal("Failed to invoke 'StaticMethod' due to an error on the server. HubException: Method does not exist.", result.Error); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CannotCallObjectMethodsOnHub() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var result = await client.InvokeAsync(nameof(MethodHub.ToString)).OrTimeout(); - Assert.Equal("Failed to invoke 'ToString' due to an error on the server. HubException: Method does not exist.", result.Error); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - result = await client.InvokeAsync(nameof(MethodHub.GetHashCode)).OrTimeout(); - Assert.Equal("Failed to invoke 'GetHashCode' due to an error on the server. HubException: Method does not exist.", result.Error); + var connectionHandler = serviceProvider.GetService>(); - result = await client.InvokeAsync(nameof(MethodHub.Equals)).OrTimeout(); - Assert.Equal("Failed to invoke 'Equals' due to an error on the server. HubException: Method does not exist.", result.Error); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - result = await client.InvokeAsync(nameof(MethodHub.ReferenceEquals)).OrTimeout(); - Assert.Equal("Failed to invoke 'ReferenceEquals' due to an error on the server. HubException: Method does not exist.", result.Error); + var result = await client.InvokeAsync(nameof(MethodHub.ToString)).OrTimeout(); + Assert.Equal("Failed to invoke 'ToString' due to an error on the server. HubException: Method does not exist.", result.Error); - // kill the connection - client.Dispose(); + result = await client.InvokeAsync(nameof(MethodHub.GetHashCode)).OrTimeout(); + Assert.Equal("Failed to invoke 'GetHashCode' due to an error on the server. HubException: Method does not exist.", result.Error); - await connectionHandlerTask.OrTimeout(); + result = await client.InvokeAsync(nameof(MethodHub.Equals)).OrTimeout(); + Assert.Equal("Failed to invoke 'Equals' due to an error on the server. HubException: Method does not exist.", result.Error); + + result = await client.InvokeAsync(nameof(MethodHub.ReferenceEquals)).OrTimeout(); + Assert.Equal("Failed to invoke 'ReferenceEquals' due to an error on the server. HubException: Method does not exist.", result.Error); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CannotCallDisposeMethodOnHub() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var result = await client.InvokeAsync(nameof(MethodHub.Dispose)).OrTimeout(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - Assert.Equal("Failed to invoke 'Dispose' due to an error on the server. HubException: Method does not exist.", result.Error); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + var result = await client.InvokeAsync(nameof(MethodHub.Dispose)).OrTimeout(); + + Assert.Equal("Failed to invoke 'Dispose' due to an error on the server. HubException: Method does not exist.", result.Error); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -903,69 +1094,75 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task BroadcastHubMethodSendsToAllClients(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - - await firstClient.SendInvocationAsync(nameof(MethodHub.BroadcastMethod), "test").OrTimeout(); - - foreach (var result in await Task.WhenAll( - firstClient.ReadAsync(), - secondClient.ReadAsync()).OrTimeout()) + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) { - var invocation = Assert.IsType(result); - Assert.Equal("Broadcast", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + + await firstClient.SendInvocationAsync(nameof(MethodHub.BroadcastMethod), "test").OrTimeout(); + + foreach (var result in await Task.WhenAll( + firstClient.ReadAsync(), + secondClient.ReadAsync()).OrTimeout()) + { + var invocation = Assert.IsType(result); + Assert.Equal("Broadcast", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); + } + + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); } - - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); - - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); } } [Fact] public async Task SendArraySendsArrayToAllClients() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + var connectionHandler = serviceProvider.GetService>(); - await firstClient.SendInvocationAsync(nameof(MethodHub.SendArray)).OrTimeout(); - - foreach (var result in await Task.WhenAll( - firstClient.ReadAsync(), - secondClient.ReadAsync()).OrTimeout()) + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) { - var invocation = Assert.IsType(result); - Assert.Equal("Array", invocation.Target); - Assert.Single(invocation.Arguments); - var values = ((JArray)invocation.Arguments[0]).Select(t => t.Value()).ToArray(); - Assert.Equal(new[] { 1, 2, 3 }, values); + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + + await firstClient.SendInvocationAsync(nameof(MethodHub.SendArray)).OrTimeout(); + + foreach (var result in await Task.WhenAll( + firstClient.ReadAsync(), + secondClient.ReadAsync()).OrTimeout()) + { + var invocation = Assert.IsType(result); + Assert.Equal("Array", invocation.Target); + Assert.Single(invocation.Arguments); + var values = ((JArray)invocation.Arguments[0]).Select(t => t.Value()).ToArray(); + Assert.Equal(new[] { 1, 2, 3 }, values); + } + + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); } - - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); - - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); } } @@ -973,39 +1170,40 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToOthers(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - await firstClient.SendInvocationAsync("SendToOthers", "To others").OrTimeout(); + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - var secondClientResult = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(secondClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("To others", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("SendToOthers", "To others").OrTimeout(); - var firstClientResult = await firstClient.ReadAsync().OrTimeout(); - var completion = Assert.IsType(firstClientResult); + var secondClientResult = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(secondClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("To others", invocation.Arguments[0]); - await secondClient.SendInvocationAsync("BroadcastMethod", "To everyone").OrTimeout(); - firstClientResult = await firstClient.ReadAsync().OrTimeout(); - invocation = Assert.IsType(firstClientResult); - Assert.Equal("Broadcast", invocation.Target); - Assert.Equal("To everyone", invocation.Arguments[0]); + var firstClientResult = await firstClient.ReadAsync().OrTimeout(); + var completion = Assert.IsType(firstClientResult); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); - - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + await secondClient.SendInvocationAsync("BroadcastMethod", "To everyone").OrTimeout(); + firstClientResult = await firstClient.ReadAsync().OrTimeout(); + invocation = Assert.IsType(firstClientResult); + Assert.Equal("Broadcast", invocation.Target); + Assert.Equal("To everyone", invocation.Arguments[0]); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } @@ -1013,50 +1211,62 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToCaller(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - await firstClient.SendInvocationAsync("SendToCaller", "To caller").OrTimeout(); + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - var firstClientResult = await firstClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(firstClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("To caller", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("SendToCaller", "To caller").OrTimeout(); - await firstClient.SendInvocationAsync("BroadcastMethod", "To everyone").OrTimeout(); - var secondClientResult = await secondClient.ReadAsync().OrTimeout(); - invocation = Assert.IsType(secondClientResult); - Assert.Equal("Broadcast", invocation.Target); - Assert.Equal("To everyone", invocation.Arguments[0]); + var firstClientResult = await firstClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(firstClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("To caller", invocation.Arguments[0]); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + await firstClient.SendInvocationAsync("BroadcastMethod", "To everyone").OrTimeout(); + var secondClientResult = await secondClient.ReadAsync().OrTimeout(); + invocation = Assert.IsType(secondClientResult); + Assert.Equal("Broadcast", invocation.Target); + Assert.Equal("To everyone", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } [Fact] public async Task FailsToInitializeInvalidTypedHub() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(SimpleVoidReturningTypedHub)); - - using (var firstClient = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - // ConnectAsync returns a Task and it's the INNER Task that will be faulted. - var connectionTask = await firstClient.ConnectAsync(connectionHandler); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.HubConnectionHandler" && + writeContext.EventId.Name == "ErrorDispatchingHubEvent"; + } - // We should get a close frame now - var close = Assert.IsType(await firstClient.ReadAsync()); - Assert.Equal("Connection closed with an error.", close.Error); + using (StartVerifiableLog(ExpectedErrors)) + { + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(SimpleVoidReturningTypedHub), loggerFactory: LoggerFactory); + + using (var firstClient = new TestClient()) + { + // ConnectAsync returns a Task and it's the INNER Task that will be faulted. + var connectionTask = await firstClient.ConnectAsync(connectionHandler); + + // We should get a close frame now + var close = Assert.IsType(await firstClient.ReadAsync()); + Assert.Equal("Connection closed with an error.", close.Error); + } } } @@ -1064,42 +1274,45 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToAllExcept(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) - using (var thirdClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - var thirdConnectionHandlerTask = await thirdClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected, thirdClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + using (var thirdClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var thirdConnectionHandlerTask = await thirdClient.ConnectAsync(connectionHandler); - var excludeSecondClientId = new HashSet(); - excludeSecondClientId.Add(secondClient.Connection.ConnectionId); - var excludeThirdClientId = new HashSet(); - excludeThirdClientId.Add(thirdClient.Connection.ConnectionId); + await Task.WhenAll(firstClient.Connected, secondClient.Connected, thirdClient.Connected).OrTimeout(); - await firstClient.SendInvocationAsync("SendToAllExcept", "To second", excludeThirdClientId).OrTimeout(); - await firstClient.SendInvocationAsync("SendToAllExcept", "To third", excludeSecondClientId).OrTimeout(); + var excludeSecondClientId = new HashSet(); + excludeSecondClientId.Add(secondClient.Connection.ConnectionId); + var excludeThirdClientId = new HashSet(); + excludeThirdClientId.Add(thirdClient.Connection.ConnectionId); - var secondClientResult = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(secondClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("To second", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("SendToAllExcept", "To second", excludeThirdClientId).OrTimeout(); + await firstClient.SendInvocationAsync("SendToAllExcept", "To third", excludeSecondClientId).OrTimeout(); - var thirdClientResult = await thirdClient.ReadAsync().OrTimeout(); - invocation = Assert.IsType(thirdClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("To third", invocation.Arguments[0]); + var secondClientResult = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(secondClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("To second", invocation.Arguments[0]); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); - thirdClient.Dispose(); + var thirdClientResult = await thirdClient.ReadAsync().OrTimeout(); + invocation = Assert.IsType(thirdClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("To third", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask, thirdConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + thirdClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask, thirdConnectionHandlerTask).OrTimeout(); + } } } @@ -1107,44 +1320,47 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToMultipleClients(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) - using (var thirdClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - var thirdConnectionHandlerTask = await thirdClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected, thirdClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + using (var thirdClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var thirdConnectionHandlerTask = await thirdClient.ConnectAsync(connectionHandler); - var secondAndThirdClients = new HashSet {secondClient.Connection.ConnectionId, + await Task.WhenAll(firstClient.Connected, secondClient.Connected, thirdClient.Connected).OrTimeout(); + + var secondAndThirdClients = new HashSet {secondClient.Connection.ConnectionId, thirdClient.Connection.ConnectionId }; - await firstClient.SendInvocationAsync("SendToMultipleClients", "Second and Third", secondAndThirdClients).OrTimeout(); + await firstClient.SendInvocationAsync("SendToMultipleClients", "Second and Third", secondAndThirdClients).OrTimeout(); - var secondClientResult = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(secondClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("Second and Third", invocation.Arguments[0]); + var secondClientResult = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(secondClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("Second and Third", invocation.Arguments[0]); - var thirdClientResult = await thirdClient.ReadAsync().OrTimeout(); - invocation = Assert.IsType(thirdClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("Second and Third", invocation.Arguments[0]); + var thirdClientResult = await thirdClient.ReadAsync().OrTimeout(); + invocation = Assert.IsType(thirdClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("Second and Third", invocation.Arguments[0]); - // Check that first client only got the completion message - var hubMessage = await firstClient.ReadAsync().OrTimeout(); - Assert.IsType(hubMessage); - Assert.Null(firstClient.TryRead()); + // Check that first client only got the completion message + var hubMessage = await firstClient.ReadAsync().OrTimeout(); + Assert.IsType(hubMessage); + Assert.Null(firstClient.TryRead()); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); - thirdClient.Dispose(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + thirdClient.Dispose(); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask, thirdConnectionHandlerTask).OrTimeout(); + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask, thirdConnectionHandlerTask).OrTimeout(); + } } } @@ -1152,41 +1368,44 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToMultipleUsers(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient(userIdentifier: "userA")) - using (var secondClient = new TestClient(userIdentifier: "userB")) - using (var thirdClient = new TestClient(userIdentifier: "userC")) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - var thirdConnectionHandlerTask = await thirdClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected, thirdClient.Connected).OrTimeout(); + using (var firstClient = new TestClient(userIdentifier: "userA")) + using (var secondClient = new TestClient(userIdentifier: "userB")) + using (var thirdClient = new TestClient(userIdentifier: "userC")) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var thirdConnectionHandlerTask = await thirdClient.ConnectAsync(connectionHandler); - await firstClient.SendInvocationAsync(nameof(MethodHub.SendToMultipleUsers), new[] { "userB", "userC" }, "Second and Third").OrTimeout(); + await Task.WhenAll(firstClient.Connected, secondClient.Connected, thirdClient.Connected).OrTimeout(); - var secondClientResult = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(secondClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("Second and Third", invocation.Arguments[0]); + await firstClient.SendInvocationAsync(nameof(MethodHub.SendToMultipleUsers), new[] { "userB", "userC" }, "Second and Third").OrTimeout(); - var thirdClientResult = await thirdClient.ReadAsync().OrTimeout(); - invocation = Assert.IsType(thirdClientResult); - Assert.Equal("Send", invocation.Target); - Assert.Equal("Second and Third", invocation.Arguments[0]); + var secondClientResult = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(secondClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("Second and Third", invocation.Arguments[0]); - // Check that first client only got the completion message - var hubMessage = await firstClient.ReadAsync().OrTimeout(); - Assert.IsType(hubMessage); - Assert.Null(firstClient.TryRead()); + var thirdClientResult = await thirdClient.ReadAsync().OrTimeout(); + invocation = Assert.IsType(thirdClientResult); + Assert.Equal("Send", invocation.Target); + Assert.Equal("Second and Third", invocation.Arguments[0]); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); - thirdClient.Dispose(); + // Check that first client only got the completion message + var hubMessage = await firstClient.ReadAsync().OrTimeout(); + Assert.IsType(hubMessage); + Assert.Null(firstClient.TryRead()); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask, thirdConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + thirdClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask, thirdConnectionHandlerTask).OrTimeout(); + } } } @@ -1194,40 +1413,43 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task HubsCanAddAndSendToGroup(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - var result = (await firstClient.InvokeAsync("GroupSendMethod", "testGroup", "test").OrTimeout()).Result; + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - // check that 'firstConnection' hasn't received the group send - Assert.Null(firstClient.TryRead()); + var result = (await firstClient.InvokeAsync("GroupSendMethod", "testGroup", "test").OrTimeout()).Result; - // check that 'secondConnection' hasn't received the group send - Assert.Null(secondClient.TryRead()); + // check that 'firstConnection' hasn't received the group send + Assert.Null(firstClient.TryRead()); - result = (await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout()).Result; + // check that 'secondConnection' hasn't received the group send + Assert.Null(secondClient.TryRead()); - await firstClient.SendInvocationAsync(nameof(MethodHub.GroupSendMethod), "testGroup", "test").OrTimeout(); + result = (await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout()).Result; - // check that 'secondConnection' has received the group send - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + await firstClient.SendInvocationAsync(nameof(MethodHub.GroupSendMethod), "testGroup", "test").OrTimeout(); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + // check that 'secondConnection' has received the group send + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } @@ -1235,49 +1457,52 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToGroupExcept(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - var result = (await firstClient.InvokeAsync("GroupSendMethod", "testGroup", "test").OrTimeout()).Result; + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - // check that 'firstConnection' hasn't received the group send - Assert.Null(firstClient.TryRead()); + var result = (await firstClient.InvokeAsync("GroupSendMethod", "testGroup", "test").OrTimeout()).Result; - // check that 'secondConnection' hasn't received the group send - Assert.Null(secondClient.TryRead()); + // check that 'firstConnection' hasn't received the group send + Assert.Null(firstClient.TryRead()); - await firstClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); - await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); + // check that 'secondConnection' hasn't received the group send + Assert.Null(secondClient.TryRead()); - var excludedConnectionIds = new List { firstClient.Connection.ConnectionId }; + await firstClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); + await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); - await firstClient.SendInvocationAsync("GroupExceptSendMethod", "testGroup", "test", excludedConnectionIds).OrTimeout(); + var excludedConnectionIds = new List { firstClient.Connection.ConnectionId }; - // check that 'secondConnection' has received the group send - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("GroupExceptSendMethod", "testGroup", "test", excludedConnectionIds).OrTimeout(); - // Check that first client only got the completion message - hubMessage = await firstClient.ReadAsync().OrTimeout(); - Assert.IsType(hubMessage); + // check that 'secondConnection' has received the group send + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - Assert.Null(firstClient.TryRead()); + // Check that first client only got the completion message + hubMessage = await firstClient.ReadAsync().OrTimeout(); + Assert.IsType(hubMessage); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + Assert.Null(firstClient.TryRead()); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } @@ -1285,47 +1510,50 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task SendToOthersInGroup(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - var result = (await firstClient.InvokeAsync("GroupSendMethod", "testGroup", "test").OrTimeout()).Result; + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - // check that 'firstConnection' hasn't received the group send - Assert.Null(firstClient.TryRead()); + var result = (await firstClient.InvokeAsync("GroupSendMethod", "testGroup", "test").OrTimeout()).Result; - // check that 'secondConnection' hasn't received the group send - Assert.Null(secondClient.TryRead()); + // check that 'firstConnection' hasn't received the group send + Assert.Null(firstClient.TryRead()); - await firstClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); - await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); + // check that 'secondConnection' hasn't received the group send + Assert.Null(secondClient.TryRead()); - await firstClient.SendInvocationAsync("SendToOthersInGroup", "testGroup", "test").OrTimeout(); + await firstClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); + await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "testGroup").OrTimeout(); - // check that 'secondConnection' has received the group send - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("SendToOthersInGroup", "testGroup", "test").OrTimeout(); - // Check that first client only got the completion message - hubMessage = await firstClient.ReadAsync().OrTimeout(); - Assert.IsType(hubMessage); + // check that 'secondConnection' has received the group send + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - Assert.Null(firstClient.TryRead()); + // Check that first client only got the completion message + hubMessage = await firstClient.ReadAsync().OrTimeout(); + Assert.IsType(hubMessage); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + Assert.Null(firstClient.TryRead()); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } @@ -1333,59 +1561,65 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task InvokeMultipleGroups(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "GroupA").OrTimeout(); - await firstClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "GroupB").OrTimeout(); ; + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - var groupNames = new List { "GroupA", "GroupB" }; - await firstClient.SendInvocationAsync(nameof(MethodHub.SendToMultipleGroups), "test", groupNames).OrTimeout(); + await secondClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "GroupA").OrTimeout(); + await firstClient.InvokeAsync(nameof(MethodHub.GroupAddMethod), "GroupB").OrTimeout(); ; - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + var groupNames = new List { "GroupA", "GroupB" }; + await firstClient.SendInvocationAsync(nameof(MethodHub.SendToMultipleGroups), "test", groupNames).OrTimeout(); - hubMessage = await firstClient.ReadAsync().OrTimeout(); - invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + hubMessage = await firstClient.ReadAsync().OrTimeout(); + invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } [Fact] public async Task RemoveFromGroupWhenNotInGroupDoesNotFail() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - await client.SendInvocationAsync(nameof(MethodHub.GroupRemoveMethod), "testGroup").OrTimeout(); + var connectionHandler = serviceProvider.GetService>(); - // kill the connection - client.Dispose(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await connectionHandlerTask.OrTimeout(); + await client.SendInvocationAsync(nameof(MethodHub.GroupRemoveMethod), "testGroup").OrTimeout(); + + // kill the connection + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -1393,30 +1627,33 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task HubsCanSendToUser(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient(userIdentifier: "userA")) - using (var secondClient = new TestClient(userIdentifier: "userB")) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient(userIdentifier: "userA")) + using (var secondClient = new TestClient(userIdentifier: "userB")) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - await firstClient.SendInvocationAsync("ClientSendMethod", "userB", "test").OrTimeout(); + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - // check that 'secondConnection' has received the group send - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("ClientSendMethod", "userB", "test").OrTimeout(); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + // check that 'secondConnection' has received the group send + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } @@ -1424,60 +1661,66 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(HubTypes))] public async Task HubsCanSendToConnection(Type hubType) { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(hubType, loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - await firstClient.SendInvocationAsync("ConnectionSendMethod", secondClient.Connection.ConnectionId, "test").OrTimeout(); + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - // check that 'secondConnection' has received the group send - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("ConnectionSendMethod", secondClient.Connection.ConnectionId, "test").OrTimeout(); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + // check that 'secondConnection' has received the group send + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } [Fact] public async Task DelayedSendTest() { - var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT)); - - using (var firstClient = new TestClient()) - using (var secondClient = new TestClient()) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); + var connectionHandler = HubConnectionHandlerTestUtils.GetHubConnectionHandler(typeof(HubT), loggerFactory: LoggerFactory); - await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); + using (var firstClient = new TestClient()) + using (var secondClient = new TestClient()) + { + var firstConnectionHandlerTask = await firstClient.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await secondClient.ConnectAsync(connectionHandler); - await firstClient.SendInvocationAsync("DelayedSend", secondClient.Connection.ConnectionId, "test").OrTimeout(); + await Task.WhenAll(firstClient.Connected, secondClient.Connected).OrTimeout(); - // check that 'secondConnection' has received the group send - var hubMessage = await secondClient.ReadAsync().OrTimeout(); - var invocation = Assert.IsType(hubMessage); - Assert.Equal("Send", invocation.Target); - Assert.Single(invocation.Arguments); - Assert.Equal("test", invocation.Arguments[0]); + await firstClient.SendInvocationAsync("DelayedSend", secondClient.Connection.ConnectionId, "test").OrTimeout(); - // kill the connections - firstClient.Dispose(); - secondClient.Dispose(); + // check that 'secondConnection' has received the group send + var hubMessage = await secondClient.ReadAsync().OrTimeout(); + var invocation = Assert.IsType(hubMessage); + Assert.Equal("Send", invocation.Target); + Assert.Single(invocation.Arguments); + Assert.Equal("test", invocation.Arguments[0]); - await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + // kill the connections + firstClient.Dispose(); + secondClient.Dispose(); + + await Task.WhenAll(firstConnectionHandlerTask, secondConnectionHandlerTask).OrTimeout(); + } } } @@ -1485,62 +1728,68 @@ namespace Microsoft.AspNetCore.SignalR.Tests [MemberData(nameof(StreamingMethodAndHubProtocols))] public async Task HubsCanStreamResponses(string method, string protocolName) { - var protocol = HubProtocolHelpers.GetHubProtocol(protocolName); + using (StartVerifiableLog()) + { + var protocol = HubProtocolHelpers.GetHubProtocol(protocolName); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); var connectionHandler = serviceProvider.GetService>(); var invocationBinder = new Mock(); invocationBinder.Setup(b => b.GetStreamItemType(It.IsAny())).Returns(typeof(string)); - using (var client = new TestClient(protocol: protocol, invocationBinder: invocationBinder.Object)) - { - client.SupportedFormats = protocol.TransferFormat; + using (var client = new TestClient(protocol: protocol, invocationBinder: invocationBinder.Object)) + { + client.SupportedFormats = protocol.TransferFormat; - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // Wait for a connection, or for the endpoint to fail. - await client.Connected.OrThrowIfOtherFails(connectionHandlerTask).OrTimeout(); + // Wait for a connection, or for the endpoint to fail. + await client.Connected.OrThrowIfOtherFails(connectionHandlerTask).OrTimeout(); - var messages = await client.StreamAsync(method, 4).OrTimeout(); + var messages = await client.StreamAsync(method, 4).OrTimeout(); - Assert.Equal(5, messages.Count); - HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "0"), messages[0]); - HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "1"), messages[1]); - HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "2"), messages[2]); - HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "3"), messages[3]); - HubConnectionHandlerTestUtils.AssertHubMessage(CompletionMessage.Empty(string.Empty), messages[4]); + Assert.Equal(5, messages.Count); + HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "0"), messages[0]); + HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "1"), messages[1]); + HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "2"), messages[2]); + HubConnectionHandlerTestUtils.AssertHubMessage(new StreamItemMessage(string.Empty, "3"), messages[3]); + HubConnectionHandlerTestUtils.AssertHubMessage(CompletionMessage.Empty(string.Empty), messages[4]); - client.Dispose(); + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task NonErrorCompletionSentWhenStreamCanceledFromClient() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.Connected.OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - var invocationId = Guid.NewGuid().ToString("N"); - await client.SendHubMessageAsync(new StreamInvocationMessage(invocationId, nameof(StreamingHub.BlockingStream), Array.Empty())); + await client.Connected.OrTimeout(); - // cancel the Streaming method - await client.SendHubMessageAsync(new CancelInvocationMessage(invocationId)).OrTimeout(); + var invocationId = Guid.NewGuid().ToString("N"); + await client.SendHubMessageAsync(new StreamInvocationMessage(invocationId, nameof(StreamingHub.BlockingStream), Array.Empty())); - var hubMessage = Assert.IsType(await client.ReadAsync().OrTimeout()); - Assert.Equal(invocationId, hubMessage.InvocationId); - Assert.Null(hubMessage.Error); + // cancel the Streaming method + await client.SendHubMessageAsync(new CancelInvocationMessage(invocationId)).OrTimeout(); - client.Dispose(); + var hubMessage = Assert.IsType(await client.ReadAsync().OrTimeout()); + Assert.Equal(invocationId, hubMessage.InvocationId); + Assert.Null(hubMessage.Error); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -1549,73 +1798,79 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(false)] public async Task ReceiveCorrectErrorFromStreamThrowing(bool detailedErrors) { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + using (StartVerifiableLog()) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => builder.AddSignalR(options => { options.EnableDetailedErrors = detailedErrors; - })); - var connectionHandler = serviceProvider.GetService>(); + }), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - - await client.Connected.OrTimeout(); - - var messages = await client.StreamAsync(nameof(StreamingHub.ThrowStream)); - - Assert.Equal(1, messages.Count); - var completion = messages[0] as CompletionMessage; - Assert.NotNull(completion); - if (detailedErrors) + using (var client = new TestClient()) { - Assert.Equal("An error occurred on the server while streaming results. Exception: Exception from channel", completion.Error); - } - else - { - Assert.Equal("An error occurred on the server while streaming results.", completion.Error); - } + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - client.Dispose(); + await client.Connected.OrTimeout(); - await connectionHandlerTask.OrTimeout(); + var messages = await client.StreamAsync(nameof(StreamingHub.ThrowStream)); + + Assert.Equal(1, messages.Count); + var completion = messages[0] as CompletionMessage; + Assert.NotNull(completion); + if (detailedErrors) + { + Assert.Equal("An error occurred on the server while streaming results. Exception: Exception from channel", completion.Error); + } + else + { + Assert.Equal("An error occurred on the server while streaming results.", completion.Error); + } + + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task CanSendToConnectionsWithDifferentProtocols() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client1 = new TestClient(protocol: new JsonHubProtocol())) - using (var client2 = new TestClient(protocol: new MessagePackHubProtocol())) + using (StartVerifiableLog()) { - var firstConnectionHandlerTask = await client1.ConnectAsync(connectionHandler); - var secondConnectionHandlerTask = await client2.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client1.Connected.OrTimeout(); - await client2.Connected.OrTimeout(); + using (var client1 = new TestClient(protocol: new JsonHubProtocol())) + using (var client2 = new TestClient(protocol: new MessagePackHubProtocol())) + { + var firstConnectionHandlerTask = await client1.ConnectAsync(connectionHandler); + var secondConnectionHandlerTask = await client2.ConnectAsync(connectionHandler); - var sentMessage = "From Json"; + await client1.Connected.OrTimeout(); + await client2.Connected.OrTimeout(); - await client1.SendInvocationAsync(nameof(MethodHub.BroadcastMethod), sentMessage); - var message1 = await client1.ReadAsync().OrTimeout(); - var message2 = await client2.ReadAsync().OrTimeout(); + var sentMessage = "From Json"; - var completion1 = message1 as InvocationMessage; - Assert.NotNull(completion1); - Assert.Equal(sentMessage, completion1.Arguments[0]); - var completion2 = message2 as InvocationMessage; - Assert.NotNull(completion2); - // Argument[0] is a 'MsgPackObject' with a string internally, ToString to compare it - Assert.Equal(sentMessage, completion2.Arguments[0].ToString()); + await client1.SendInvocationAsync(nameof(MethodHub.BroadcastMethod), sentMessage); + var message1 = await client1.ReadAsync().OrTimeout(); + var message2 = await client2.ReadAsync().OrTimeout(); - client1.Dispose(); - client2.Dispose(); + var completion1 = message1 as InvocationMessage; + Assert.NotNull(completion1); + Assert.Equal(sentMessage, completion1.Arguments[0]); + var completion2 = message2 as InvocationMessage; + Assert.NotNull(completion2); + // Argument[0] is a 'MsgPackObject' with a string internally, ToString to compare it + Assert.Equal(sentMessage, completion2.Arguments[0].ToString()); - await firstConnectionHandlerTask.OrTimeout(); - await secondConnectionHandlerTask.OrTimeout(); + client1.Dispose(); + client2.Dispose(); + + await firstConnectionHandlerTask.OrTimeout(); + await secondConnectionHandlerTask.OrTimeout(); + } } } @@ -1639,220 +1894,238 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Fact] public async Task UnauthorizedConnectionCannotInvokeHubMethodWithAuthorization() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + using (StartVerifiableLog()) { - services.AddAuthorization(options => + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { - options.AddPolicy("test", policy => + services.AddAuthorization(options => { - policy.RequireClaim(ClaimTypes.NameIdentifier); - policy.AddAuthenticationSchemes("Default"); + options.AddPolicy("test", policy => + { + policy.RequireClaim(ClaimTypes.NameIdentifier); + policy.AddAuthenticationSchemes("Default"); + }); }); - }); - }); + }, LoggerFactory); - var connectionHandler = serviceProvider.GetService>(); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + await client.Connected.OrTimeout(); - var message = await client.InvokeAsync(nameof(MethodHub.AuthMethod)).OrTimeout(); + var message = await client.InvokeAsync(nameof(MethodHub.AuthMethod)).OrTimeout(); - Assert.NotNull(message.Error); + Assert.NotNull(message.Error); - client.Dispose(); + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task AuthorizedConnectionCanInvokeHubMethodWithAuthorization() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + using (StartVerifiableLog()) { - services.AddAuthorization(options => + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { - options.AddPolicy("test", policy => + services.AddAuthorization(options => { - policy.RequireClaim(ClaimTypes.NameIdentifier); - policy.AddAuthenticationSchemes("Default"); + options.AddPolicy("test", policy => + { + policy.RequireClaim(ClaimTypes.NameIdentifier); + policy.AddAuthenticationSchemes("Default"); + }); }); - }); - }); + }, LoggerFactory); - var connectionHandler = serviceProvider.GetService>(); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - client.Connection.User.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "name") })); - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + using (var client = new TestClient()) + { + client.Connection.User.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "name") })); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + await client.Connected.OrTimeout(); - var message = await client.InvokeAsync(nameof(MethodHub.AuthMethod)).OrTimeout(); + var message = await client.InvokeAsync(nameof(MethodHub.AuthMethod)).OrTimeout(); - Assert.Null(message.Error); + Assert.Null(message.Error); - client.Dispose(); + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubOptionsCanUseCustomJsonSerializerSettings() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + using (StartVerifiableLog()) { - services - .AddSignalR() - .AddJsonProtocol(o => - { - o.PayloadSerializerSettings = new JsonSerializerSettings + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services + .AddSignalR() + .AddJsonProtocol(o => { - ContractResolver = new DefaultContractResolver() - }; - }); - }); + o.PayloadSerializerSettings = new JsonSerializerSettings + { + ContractResolver = new DefaultContractResolver() + }; + }); + }, LoggerFactory); - var connectionHandler = serviceProvider.GetService>(); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + await client.Connected.OrTimeout(); - await client.SendInvocationAsync(nameof(MethodHub.BroadcastItem)).OrTimeout(); + await client.SendInvocationAsync(nameof(MethodHub.BroadcastItem)).OrTimeout(); - var message = (InvocationMessage)await client.ReadAsync().OrTimeout(); + var message = (InvocationMessage)await client.ReadAsync().OrTimeout(); - var customItem = message.Arguments[0].ToString(); - // by default properties serialized by JsonHubProtocol are using camelCasing - Assert.Contains("Message", customItem); - Assert.Contains("paramName", customItem); + var customItem = message.Arguments[0].ToString(); + // by default properties serialized by JsonHubProtocol are using camelCasing + Assert.Contains("Message", customItem); + Assert.Contains("paramName", customItem); - client.Dispose(); + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task JsonHubProtocolUsesCamelCasingByDefault() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.Connected.OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.SendInvocationAsync(nameof(MethodHub.BroadcastItem)).OrTimeout(); + await client.Connected.OrTimeout(); - var message = (InvocationMessage)await client.ReadAsync().OrTimeout(); + await client.SendInvocationAsync(nameof(MethodHub.BroadcastItem)).OrTimeout(); - var customItem = message.Arguments[0].ToString(); - // originally Message, paramName - Assert.Contains("message", customItem); - Assert.Contains("paramName", customItem); + var message = (InvocationMessage)await client.ReadAsync().OrTimeout(); - client.Dispose(); + var customItem = message.Arguments[0].ToString(); + // originally Message, paramName + Assert.Contains("message", customItem); + Assert.Contains("paramName", customItem); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task HubOptionsCanUseCustomMessagePackSettings() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + using (StartVerifiableLog()) { - services.AddSignalR() - .AddMessagePackProtocol(options => - { - options.FormatterResolvers.Insert(0, new CustomFormatter()); - }); - }); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services.AddSignalR() + .AddMessagePackProtocol(options => + { + options.FormatterResolvers.Insert(0, new CustomFormatter()); + }); + }, LoggerFactory); - var connectionHandler = serviceProvider.GetService>(); + var connectionHandler = serviceProvider.GetService>(); - var msgPackOptions = serviceProvider.GetRequiredService>(); - using (var client = new TestClient(protocol: new MessagePackHubProtocol(msgPackOptions))) - { - client.SupportedFormats = TransferFormat.Binary; - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var msgPackOptions = serviceProvider.GetRequiredService>(); + using (var client = new TestClient(protocol: new MessagePackHubProtocol(msgPackOptions))) + { + client.SupportedFormats = TransferFormat.Binary; + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + await client.Connected.OrTimeout(); - await client.SendInvocationAsync(nameof(MethodHub.BroadcastItem)).OrTimeout(); + await client.SendInvocationAsync(nameof(MethodHub.BroadcastItem)).OrTimeout(); - var message = Assert.IsType(await client.ReadAsync().OrTimeout()); + var message = Assert.IsType(await client.ReadAsync().OrTimeout()); - var result = message.Arguments[0] as Dictionary; - Assert.Equal("formattedString", result["Message"]); - Assert.Equal("formattedString", result["paramName"]); + var result = message.Arguments[0] as Dictionary; + Assert.Equal("formattedString", result["Message"]); + Assert.Equal("formattedString", result["paramName"]); - client.Dispose(); + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task ConnectionUserIdIsAssignedByUserIdProvider() { - var firstRequest = true; - var userIdProvider = new TestUserIdProvider(c => + using (StartVerifiableLog()) { - if (firstRequest) + var firstRequest = true; + var userIdProvider = new TestUserIdProvider(c => { - firstRequest = false; - return "client1"; - } - else + if (firstRequest) + { + firstRequest = false; + return "client1"; + } + else + { + return "client2"; + } + }); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { - return "client2"; + services.AddSingleton(userIdProvider); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); + + using (var client1 = new TestClient()) + using (var client2 = new TestClient()) + { + var connectionHandlerTask1 = await client1.ConnectAsync(connectionHandler); + var connectionHandlerTask2 = await client2.ConnectAsync(connectionHandler); + + await client1.Connected.OrTimeout(); + await client2.Connected.OrTimeout(); + + await client2.SendInvocationAsync(nameof(MethodHub.SendToMultipleUsers), new[] { "client1" }, "Hi!").OrTimeout(); + + var message = (InvocationMessage)await client1.ReadAsync().OrTimeout(); + + Assert.Equal("Send", message.Target); + Assert.Collection(message.Arguments, arg => Assert.Equal("Hi!", arg)); + + client1.Dispose(); + client2.Dispose(); + + await connectionHandlerTask1.OrTimeout(); + await connectionHandlerTask2.OrTimeout(); + + // Read the completion, then we should have nothing left in client2's queue + Assert.IsType(client2.TryRead()); + Assert.IsType(client2.TryRead()); + Assert.Null(client2.TryRead()); } - }); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => - { - services.AddSingleton(userIdProvider); - }); - var connectionHandler = serviceProvider.GetService>(); - - using (var client1 = new TestClient()) - using (var client2 = new TestClient()) - { - var connectionHandlerTask1 = await client1.ConnectAsync(connectionHandler); - var connectionHandlerTask2 = await client2.ConnectAsync(connectionHandler); - - await client1.Connected.OrTimeout(); - await client2.Connected.OrTimeout(); - - await client2.SendInvocationAsync(nameof(MethodHub.SendToMultipleUsers), new[] { "client1" }, "Hi!").OrTimeout(); - - var message = (InvocationMessage)await client1.ReadAsync().OrTimeout(); - - Assert.Equal("Send", message.Target); - Assert.Collection(message.Arguments, arg => Assert.Equal("Hi!", arg)); - - client1.Dispose(); - client2.Dispose(); - - await connectionHandlerTask1.OrTimeout(); - await connectionHandlerTask2.OrTimeout(); - - // Read the completion, then we should have nothing left in client2's queue - Assert.IsType(client2.TryRead()); - Assert.IsType(client2.TryRead()); - Assert.Null(client2.TryRead()); } } @@ -1903,271 +2176,298 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Fact] public async Task CanGetHttpContextFromHubConnectionContext() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var httpContext = new DefaultHttpContext(); - var feature = new TestHttpContextFeature + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + + var connectionHandler = serviceProvider.GetService>(); + + using (var client = new TestClient()) { - HttpContext = httpContext - }; - client.Connection.Features.Set(feature); - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var httpContext = new DefaultHttpContext(); + var feature = new TestHttpContextFeature + { + HttpContext = httpContext + }; + client.Connection.Features.Set(feature); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + await client.Connected.OrTimeout(); - var result = (await client.InvokeAsync(nameof(MethodHub.HasHttpContext)).OrTimeout()).Result; - Assert.True((bool)result); + var result = (await client.InvokeAsync(nameof(MethodHub.HasHttpContext)).OrTimeout()).Result; + Assert.True((bool)result); - client.Dispose(); + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task GetHttpContextFromHubConnectionContextHandlesNull() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); - await client.Connected.OrTimeout(); + var connectionHandler = serviceProvider.GetService>(); - var result = (await client.InvokeAsync(nameof(MethodHub.HasHttpContext)).OrTimeout()).Result; - Assert.False((bool)result); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - client.Dispose(); + await client.Connected.OrTimeout(); - await connectionHandlerTask.OrTimeout(); + var result = (await client.InvokeAsync(nameof(MethodHub.HasHttpContext)).OrTimeout()).Result; + Assert.False((bool)result); + + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task AcceptsPingMessages() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // Send a ping - await client.SendHubMessageAsync(PingMessage.Instance).OrTimeout(); + using (var client = new TestClient(new JsonHubProtocol())) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + await client.Connected.OrTimeout(); - // Now do an invocation to make sure we processed the ping message - var completion = await client.InvokeAsync(nameof(MethodHub.ValueMethod)).OrTimeout(); - Assert.NotNull(completion); + // Send a ping + await client.SendHubMessageAsync(PingMessage.Instance).OrTimeout(); - client.Dispose(); + // Now do an invocation to make sure we processed the ping message + var completion = await client.InvokeAsync(nameof(MethodHub.ValueMethod)).OrTimeout(); + Assert.NotNull(completion); - await connectionHandlerTask.OrTimeout(); + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task DoesNotWritePingMessagesIfSufficientOtherMessagesAreSent() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => - services.Configure(options => - options.KeepAliveInterval = TimeSpan.FromMilliseconds(100))); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + services.Configure(options => + options.KeepAliveInterval = TimeSpan.FromMilliseconds(100)), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.Connected.OrTimeout(); - - // Echo a bunch of stuff, waiting 10ms between each, until 500ms have elapsed - var start = DateTime.UtcNow; - while ((DateTime.UtcNow - start).TotalMilliseconds <= 500.0) + using (var client = new TestClient(new JsonHubProtocol())) { - await client.SendInvocationAsync("Echo", "foo").OrTimeout(); - await Task.Delay(10); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + + await client.Connected.OrTimeout(); + + // Echo a bunch of stuff, waiting 10ms between each, until 500ms have elapsed + var start = DateTime.UtcNow; + while ((DateTime.UtcNow - start).TotalMilliseconds <= 500.0) + { + await client.SendInvocationAsync("Echo", "foo").OrTimeout(); + await Task.Delay(10); + } + + // Shut down + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + + client.Connection.Transport.Output.Complete(); + + // We shouldn't have any ping messages + HubMessage message; + var counter = 0; + while ((message = await client.ReadAsync()) != null) + { + counter += 1; + Assert.IsNotType(message); + } + Assert.InRange(counter, 1, 50); } - - // Shut down - client.Dispose(); - - await connectionHandlerTask.OrTimeout(); - - client.Connection.Transport.Output.Complete(); - - // We shouldn't have any ping messages - HubMessage message; - var counter = 0; - while ((message = await client.ReadAsync()) != null) - { - counter += 1; - Assert.IsNotType(message); - } - Assert.InRange(counter, 1, 50); } } [Fact] public async Task WritesPingMessageIfNothingWrittenWhenKeepAliveIntervalElapses() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => - services.Configure(options => - options.KeepAliveInterval = TimeSpan.FromMilliseconds(100))); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + services.Configure(options => + options.KeepAliveInterval = TimeSpan.FromMilliseconds(100)), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // Wait 500 ms, but make sure to yield some time up to unblock concurrent threads - // This is useful on AppVeyor because it's slow enough to end up with no time - // being available for the endpoint to run. - for (var i = 0; i < 50; i += 1) + using (var client = new TestClient(new JsonHubProtocol())) { - client.TickHeartbeat(); - await Task.Yield(); - await Task.Delay(10); - } + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + await client.Connected.OrTimeout(); - // Shut down - client.Dispose(); - - await connectionHandlerTask.OrTimeout(); - - client.Connection.Transport.Output.Complete(); - - // We should have all pings (and close message) - HubMessage message; - var pingCounter = 0; - var hasCloseMessage = false; - while ((message = await client.ReadAsync().OrTimeout()) != null) - { - if (hasCloseMessage) + // Wait 500 ms, but make sure to yield some time up to unblock concurrent threads + // This is useful on AppVeyor because it's slow enough to end up with no time + // being available for the endpoint to run. + for (var i = 0; i < 50; i += 1) { - Assert.True(false, "Received message after close"); + client.TickHeartbeat(); + await Task.Yield(); + await Task.Delay(10); } - switch (message) + // Shut down + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + + client.Connection.Transport.Output.Complete(); + + // We should have all pings (and close message) + HubMessage message; + var pingCounter = 0; + var hasCloseMessage = false; + while ((message = await client.ReadAsync().OrTimeout()) != null) { - case PingMessage _: - pingCounter += 1; - break; - case CloseMessage _: - hasCloseMessage = true; - break; - default: - Assert.True(false, "Unexpected message type: " + message.GetType().Name); - break; + if (hasCloseMessage) + { + Assert.True(false, "Received message after close"); + } + + switch (message) + { + case PingMessage _: + pingCounter += 1; + break; + case CloseMessage _: + hasCloseMessage = true; + break; + default: + Assert.True(false, "Unexpected message type: " + message.GetType().Name); + break; + } } + Assert.InRange(pingCounter, 1, Int32.MaxValue); } - Assert.InRange(pingCounter, 1, Int32.MaxValue); } } [Fact] public async Task ConnectionNotTimedOutIfClientNeverPings() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => - services.Configure(options => - options.ClientTimeoutInterval = TimeSpan.FromMilliseconds(100))); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); - // This is a fake client -- it doesn't auto-ping to signal + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + services.Configure(options => + options.ClientTimeoutInterval = TimeSpan.FromMilliseconds(100)), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // We go over the 100 ms timeout interval... - await Task.Delay(120); - client.TickHeartbeat(); + using (var client = new TestClient(new JsonHubProtocol())) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + await client.Connected.OrTimeout(); + // This is a fake client -- it doesn't auto-ping to signal - // but client should still be open, since it never pinged to activate the timeout checking - Assert.False(connectionHandlerTask.IsCompleted); + // We go over the 100 ms timeout interval... + await Task.Delay(120); + client.TickHeartbeat(); + + // but client should still be open, since it never pinged to activate the timeout checking + Assert.False(connectionHandlerTask.IsCompleted); + } } } [Fact] public async Task ConnectionTimesOutIfInitialPingAndThenNoMessages() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => - services.Configure(options => - options.ClientTimeoutInterval = TimeSpan.FromMilliseconds(100))); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); - await client.SendHubMessageAsync(PingMessage.Instance); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + services.Configure(options => + options.ClientTimeoutInterval = TimeSpan.FromMilliseconds(100)), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await Task.Delay(300); - client.TickHeartbeat(); + using (var client = new TestClient(new JsonHubProtocol())) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + await client.Connected.OrTimeout(); + await client.SendHubMessageAsync(PingMessage.Instance); - await Task.Delay(300); - client.TickHeartbeat(); + await Task.Delay(300); + client.TickHeartbeat(); - await connectionHandlerTask.OrTimeout(); + await Task.Delay(300); + client.TickHeartbeat(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task ReceivingMessagesPreventsConnectionTimeoutFromOccuring() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => - services.Configure(options => - options.ClientTimeoutInterval = TimeSpan.FromMilliseconds(300))); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - await client.Connected.OrTimeout(); - await client.SendHubMessageAsync(PingMessage.Instance); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + services.Configure(options => + options.ClientTimeoutInterval = TimeSpan.FromMilliseconds(300)), LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - for (int i = 0; i < 10; i++) + using (var client = new TestClient(new JsonHubProtocol())) { - await Task.Delay(100); - client.TickHeartbeat(); + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + await client.Connected.OrTimeout(); await client.SendHubMessageAsync(PingMessage.Instance); - } - Assert.False(connectionHandlerTask.IsCompleted); + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); + client.TickHeartbeat(); + await client.SendHubMessageAsync(PingMessage.Instance); + } + + Assert.False(connectionHandlerTask.IsCompleted); + } } } [Fact] public async Task EndingConnectionSendsCloseMessageWithNoError() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.Connected.OrTimeout(); + using (var client = new TestClient(new JsonHubProtocol())) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - // Shut down - client.Dispose(); + await client.Connected.OrTimeout(); - await connectionHandlerTask.OrTimeout(); + // Shut down + client.Dispose(); - client.Connection.Transport.Output.Complete(); + await connectionHandlerTask.OrTimeout(); - var message = await client.ReadAsync().OrTimeout(); + client.Connection.Transport.Output.Complete(); - var closeMessage = Assert.IsType(message); - Assert.Null(closeMessage.Error); + var message = await client.ReadAsync().OrTimeout(); + + var closeMessage = Assert.IsType(message); + Assert.Null(closeMessage.Error); + } } } @@ -2176,189 +2476,216 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(false)] public async Task ErrorInHubOnConnectSendsCloseMessageWithError(bool detailedErrors) { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + bool ExpectedErrors(WriteContext writeContext) { - builder.AddSignalR(options => - { - options.EnableDetailedErrors = detailedErrors; - }); - }); - var connectionHandler = serviceProvider.GetService>(); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.HubConnectionHandler" && + writeContext.EventId.Name == "ErrorDispatchingHubEvent"; + } - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog(ExpectedErrors)) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler); - - var message = await client.ReadAsync().OrTimeout(); - - var closeMessage = Assert.IsType(message); - if (detailedErrors) + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => { - Assert.Equal("Connection closed with an error. InvalidOperationException: Hub OnConnected failed.", closeMessage.Error); - } - else - { - Assert.Equal("Connection closed with an error.", closeMessage.Error); - } + builder.AddSignalR(options => + { + options.EnableDetailedErrors = detailedErrors; + }); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await connectionHandlerTask.OrTimeout(); + using (var client = new TestClient(new JsonHubProtocol())) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler); + + var message = await client.ReadAsync().OrTimeout(); + + var closeMessage = Assert.IsType(message); + if (detailedErrors) + { + Assert.Equal("Connection closed with an error. InvalidOperationException: Hub OnConnected failed.", closeMessage.Error); + } + else + { + Assert.Equal("Connection closed with an error.", closeMessage.Error); + } + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task StreamingInvocationsDoNotBlockOtherInvocations() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient(new JsonHubProtocol())) + using (StartVerifiableLog()) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // Blocking streaming invocation to test that other invocations can still run - await client.SendHubMessageAsync(new StreamInvocationMessage("1", nameof(StreamingHub.BlockingStream), Array.Empty())).OrTimeout(); + using (var client = new TestClient(new JsonHubProtocol())) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - var completion = await client.InvokeAsync(nameof(StreamingHub.NonStream)).OrTimeout(); - Assert.Equal(42L, completion.Result); + // Blocking streaming invocation to test that other invocations can still run + await client.SendHubMessageAsync(new StreamInvocationMessage("1", nameof(StreamingHub.BlockingStream), Array.Empty())).OrTimeout(); - // Shut down - client.Dispose(); + var completion = await client.InvokeAsync(nameof(StreamingHub.NonStream)).OrTimeout(); + Assert.Equal(42L, completion.Result); - await connectionHandlerTask.OrTimeout(); + // Shut down + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task InvocationsRunInOrder() { - var tcsService = new TcsService(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + using (StartVerifiableLog()) { - builder.AddSingleton(tcsService); - }); - var connectionHandler = serviceProvider.GetService>(); + var tcsService = new TcsService(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + { + builder.AddSingleton(tcsService); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // Because we use PipeScheduler.Inline the hub invocations will run inline until they wait, which happens inside the LongRunningMethod call - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + // Because we use PipeScheduler.Inline the hub invocations will run inline until they wait, which happens inside the LongRunningMethod call + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - // Long running hub invocation to test that other invocations will not run until it is completed - await client.SendInvocationAsync(nameof(LongRunningHub.LongRunningMethod), nonBlocking: false).OrTimeout(); - // Wait for the long running method to start - await tcsService.StartedMethod.Task.OrTimeout(); + // Long running hub invocation to test that other invocations will not run until it is completed + await client.SendInvocationAsync(nameof(LongRunningHub.LongRunningMethod), nonBlocking: false).OrTimeout(); + // Wait for the long running method to start + await tcsService.StartedMethod.Task.OrTimeout(); - // Invoke another hub method which will wait for the first method to finish - await client.SendInvocationAsync(nameof(LongRunningHub.SimpleMethod), nonBlocking: false).OrTimeout(); - // Both invocations should be waiting now - Assert.Null(client.TryRead()); + // Invoke another hub method which will wait for the first method to finish + await client.SendInvocationAsync(nameof(LongRunningHub.SimpleMethod), nonBlocking: false).OrTimeout(); + // Both invocations should be waiting now + Assert.Null(client.TryRead()); - // Release the long running hub method - tcsService.EndMethod.TrySetResult(null); + // Release the long running hub method + tcsService.EndMethod.TrySetResult(null); - // Long running hub method result - var firstResult = await client.ReadAsync().OrTimeout(); + // Long running hub method result + var firstResult = await client.ReadAsync().OrTimeout(); - var longRunningCompletion = Assert.IsType(firstResult); - Assert.Equal(12L, longRunningCompletion.Result); + var longRunningCompletion = Assert.IsType(firstResult); + Assert.Equal(12L, longRunningCompletion.Result); - // simple hub method result - var secondResult = await client.ReadAsync().OrTimeout(); + // simple hub method result + var secondResult = await client.ReadAsync().OrTimeout(); - var simpleCompletion = Assert.IsType(secondResult); - Assert.Equal(21L, simpleCompletion.Result); + var simpleCompletion = Assert.IsType(secondResult); + Assert.Equal(21L, simpleCompletion.Result); - // Shut down - client.Dispose(); + // Shut down + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task StreamInvocationsBlockOtherInvocationsUntilTheyStartStreaming() { - var tcsService = new TcsService(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + using (StartVerifiableLog()) { - builder.AddSingleton(tcsService); - builder.AddSingleton(typeof(IHubActivator<>), typeof(CustomHubActivator<>)); - }); - var connectionHandler = serviceProvider.GetService>(); + var tcsService = new TcsService(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + { + builder.AddSingleton(tcsService); + builder.AddSingleton(typeof(IHubActivator<>), typeof(CustomHubActivator<>)); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - // Because we use PipeScheduler.Inline the hub invocations will run inline until they wait, which happens inside the LongRunningMethod call - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + // Because we use PipeScheduler.Inline the hub invocations will run inline until they wait, which happens inside the LongRunningMethod call + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - // Long running hub invocation to test that other invocations will not run until it is completed - var streamInvocationId = await client.SendStreamInvocationAsync(nameof(LongRunningHub.LongRunningStream)).OrTimeout(); - // Wait for the long running method to start - await tcsService.StartedMethod.Task.OrTimeout(); + // Long running hub invocation to test that other invocations will not run until it is completed + var streamInvocationId = await client.SendStreamInvocationAsync(nameof(LongRunningHub.LongRunningStream)).OrTimeout(); + // Wait for the long running method to start + await tcsService.StartedMethod.Task.OrTimeout(); - // Invoke another hub method which will wait for the first method to finish - await client.SendInvocationAsync(nameof(LongRunningHub.SimpleMethod), nonBlocking: false).OrTimeout(); - // Both invocations should be waiting now - Assert.Null(client.TryRead()); + // Invoke another hub method which will wait for the first method to finish + await client.SendInvocationAsync(nameof(LongRunningHub.SimpleMethod), nonBlocking: false).OrTimeout(); + // Both invocations should be waiting now + Assert.Null(client.TryRead()); - // Release the long running hub method - tcsService.EndMethod.TrySetResult(null); + // Release the long running hub method + tcsService.EndMethod.TrySetResult(null); - // simple hub method result - var result = await client.ReadAsync().OrTimeout(); + // simple hub method result + var result = await client.ReadAsync().OrTimeout(); - var simpleCompletion = Assert.IsType(result); - Assert.Equal(21L, simpleCompletion.Result); + var simpleCompletion = Assert.IsType(result); + Assert.Equal(21L, simpleCompletion.Result); - var hubActivator = serviceProvider.GetService>() as CustomHubActivator; + var hubActivator = serviceProvider.GetService>() as CustomHubActivator; - // OnConnectedAsync and SimpleMethod hubs have been disposed at this point - Assert.Equal(2, hubActivator.ReleaseCount); + // OnConnectedAsync and SimpleMethod hubs have been disposed at this point + Assert.Equal(2, hubActivator.ReleaseCount); - await client.SendHubMessageAsync(new CancelInvocationMessage(streamInvocationId)).OrTimeout(); + await client.SendHubMessageAsync(new CancelInvocationMessage(streamInvocationId)).OrTimeout(); - // Completion message for canceled Stream - await client.ReadAsync().OrTimeout(); + // Completion message for canceled Stream + await client.ReadAsync().OrTimeout(); - // Stream method is now disposed - Assert.Equal(3, hubActivator.ReleaseCount); + // Stream method is now disposed + Assert.Equal(3, hubActivator.ReleaseCount); - // Shut down - client.Dispose(); + // Shut down + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task ServerSendsCloseWithErrorWhenConnectionClosedWithPartialMessage() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + bool ExpectedErrors(WriteContext writeContext) { - services.AddSignalR(options => options.EnableDetailedErrors = true); - }); - var connectionHandler = serviceProvider.GetService>(); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.HubConnectionHandler" && + writeContext.EventId.Name == "ErrorProcessingRequest"; + } - using (var client = new TestClient()) + using (StartVerifiableLog(ExpectedErrors)) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services.AddSignalR(options => options.EnableDetailedErrors = true); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.Connection.Application.Output.WriteAsync(Encoding.UTF8.GetBytes(new[] { '{' })).OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - // Close connection - client.Connection.Application.Output.Complete(); + await client.Connection.Application.Output.WriteAsync(Encoding.UTF8.GetBytes(new[] { '{' })).OrTimeout(); - // Ignore message from OnConnectedAsync - await client.ReadAsync().OrTimeout(); + // Close connection + client.Connection.Application.Output.Complete(); - var closeMessage = Assert.IsType(await client.ReadAsync().OrTimeout()); + // Ignore message from OnConnectedAsync + await client.ReadAsync().OrTimeout(); - Assert.Equal("Connection closed with an error. InvalidDataException: Connection terminated while reading a message.", closeMessage.Error); + var closeMessage = Assert.IsType(await client.ReadAsync().OrTimeout()); - // Shut down - client.Dispose(); + Assert.Equal("Connection closed with an error. InvalidDataException: Connection terminated while reading a message.", closeMessage.Error); - await connectionHandlerTask.OrTimeout(); + // Shut down + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } @@ -2452,20 +2779,30 @@ namespace Microsoft.AspNetCore.SignalR.Tests [Fact] public async Task ConnectionAbortedIfSendFailsWithProtocolError() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + bool ExpectedErrors(WriteContext writeContext) { - services.AddSignalR(options => options.EnableDetailedErrors = true); - }); - var connectionHandler = serviceProvider.GetService>(); + // Self referencing class will cause write failure + return writeContext.LoggerName == typeof(HubConnectionContext).FullName && + writeContext.EventId.Name == "FailedWritingMessage"; + } - using (var client = new TestClient()) + using (StartVerifiableLog(ExpectedErrors)) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => + { + services.AddSignalR(options => options.EnableDetailedErrors = true); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - await client.SendInvocationAsync(nameof(MethodHub.ProtocolError)).OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - await client.Connected.OrTimeout(); - await connectionHandlerTask.OrTimeout(); + await client.SendInvocationAsync(nameof(MethodHub.ProtocolError)).OrTimeout(); + + await client.Connected.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } @@ -2606,86 +2943,101 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(nameof(LongRunningHub.CancelableStreamMiddle), 1, 2)] public async Task StreamHubMethodCanAcceptCancellationTokenAsArgumentAndBeTriggeredOnCancellation(string methodName, params object[] args) { - var tcsService = new TcsService(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + using (StartVerifiableLog()) { - builder.AddSingleton(tcsService); - }); - var connectionHandler = serviceProvider.GetService>(); + var tcsService = new TcsService(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + { + builder.AddSingleton(tcsService); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - var streamInvocationId = await client.SendStreamInvocationAsync(methodName, args).OrTimeout(); - // Wait for the stream method to start - await tcsService.StartedMethod.Task.OrTimeout(); + var streamInvocationId = await client.SendStreamInvocationAsync(methodName, args).OrTimeout(); + // Wait for the stream method to start + await tcsService.StartedMethod.Task.OrTimeout(); - // Cancel the stream which should trigger the CancellationToken in the hub method - await client.SendHubMessageAsync(new CancelInvocationMessage(streamInvocationId)).OrTimeout(); + // Cancel the stream which should trigger the CancellationToken in the hub method + await client.SendHubMessageAsync(new CancelInvocationMessage(streamInvocationId)).OrTimeout(); - var result = await client.ReadAsync().OrTimeout(); + var result = await client.ReadAsync().OrTimeout(); - var simpleCompletion = Assert.IsType(result); - Assert.Null(simpleCompletion.Result); + var simpleCompletion = Assert.IsType(result); + Assert.Null(simpleCompletion.Result); - // CancellationToken passed to hub method will allow EndMethod to be triggered if it is canceled. - await tcsService.EndMethod.Task.OrTimeout(); + // CancellationToken passed to hub method will allow EndMethod to be triggered if it is canceled. + await tcsService.EndMethod.Task.OrTimeout(); - // Shut down - client.Dispose(); + // Shut down + client.Dispose(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task StreamHubMethodCanAcceptCancellationTokenAsArgumentAndBeTriggeredOnConnectionAborted() { - var tcsService = new TcsService(); - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + using (StartVerifiableLog()) { - builder.AddSingleton(tcsService); - }); - var connectionHandler = serviceProvider.GetService>(); + var tcsService = new TcsService(); + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(builder => + { + builder.AddSingleton(tcsService); + }, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - using (var client = new TestClient()) - { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - var streamInvocationId = await client.SendStreamInvocationAsync(nameof(LongRunningHub.CancelableStream)).OrTimeout(); - // Wait for the stream method to start - await tcsService.StartedMethod.Task.OrTimeout(); + var streamInvocationId = await client.SendStreamInvocationAsync(nameof(LongRunningHub.CancelableStream)).OrTimeout(); + // Wait for the stream method to start + await tcsService.StartedMethod.Task.OrTimeout(); - // Shut down the client which should trigger the CancellationToken in the hub method - client.Dispose(); + // Shut down the client which should trigger the CancellationToken in the hub method + client.Dispose(); - // CancellationToken passed to hub method will allow EndMethod to be triggered if it is canceled. - await tcsService.EndMethod.Task.OrTimeout(); + // CancellationToken passed to hub method will allow EndMethod to be triggered if it is canceled. + await tcsService.EndMethod.Task.OrTimeout(); - await connectionHandlerTask.OrTimeout(); + await connectionHandlerTask.OrTimeout(); + } } } [Fact] public async Task InvokeHubMethodCannotAcceptCancellationTokenAsArgument() { - var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(); - var connectionHandler = serviceProvider.GetService>(); - - using (var client = new TestClient()) + bool ExpectedErrors(WriteContext writeContext) { - var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); + return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && + writeContext.EventId.Name == "FailedInvokingHubMethod"; + } - var invocationId = await client.SendInvocationAsync(nameof(MethodHub.InvalidArgument)).OrTimeout(); + using (StartVerifiableLog(ExpectedErrors)) + { + var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(null, LoggerFactory); + var connectionHandler = serviceProvider.GetService>(); - var completion = Assert.IsType(await client.ReadAsync().OrTimeout()); + using (var client = new TestClient()) + { + var connectionHandlerTask = await client.ConnectAsync(connectionHandler).OrTimeout(); - Assert.Equal("Failed to invoke 'InvalidArgument' due to an error on the server.", completion.Error); + var invocationId = await client.SendInvocationAsync(nameof(MethodHub.InvalidArgument)).OrTimeout(); - client.Dispose(); + var completion = Assert.IsType(await client.ReadAsync().OrTimeout()); - await connectionHandlerTask.OrTimeout(); + Assert.Equal("Failed to invoke 'InvalidArgument' due to an error on the server.", completion.Error); + + client.Dispose(); + + await connectionHandlerTask.OrTimeout(); + } } } diff --git a/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs b/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs index b8337cabf7..3d3cc1da9b 100644 --- a/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs +++ b/test/Microsoft.AspNetCore.SignalR.Tests/WebSocketsTransportTests.cs @@ -15,17 +15,12 @@ using Microsoft.AspNetCore.Http.Connections.Client.Internal; using Microsoft.AspNetCore.Testing.xunit; using Moq; using Xunit; -using Xunit.Abstractions; namespace Microsoft.AspNetCore.SignalR.Tests { [Collection(EndToEndTestsCollection.Name)] public class WebSocketsTransportTests : FunctionalTestBase { - public WebSocketsTransportTests(ITestOutputHelper output) : base(output) - { - } - [ConditionalFact] [WebSocketsSupportedCondition] public void HttpOptionsSetOntoWebSocketOptions() @@ -57,9 +52,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsTransportStopsSendAndReceiveLoopsWhenTransportIsStopped() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: LoggerFactory, accessTokenProvider: null); await webSocketsTransport.StartAsync(new Uri(server.WebSocketsUrl + "/echo"), TransferFormat.Binary).OrTimeout(); await webSocketsTransport.StopAsync().OrTimeout(); @@ -71,9 +66,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsTransportSendsUserAgent() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: LoggerFactory, accessTokenProvider: null); await webSocketsTransport.StartAsync(new Uri(server.WebSocketsUrl + "/httpheader"), TransferFormat.Binary).OrTimeout(); @@ -99,9 +94,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsTransportSendsXRequestedWithHeader() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: LoggerFactory, accessTokenProvider: null); await webSocketsTransport.StartAsync(new Uri(server.WebSocketsUrl + "/httpheader"), TransferFormat.Binary).OrTimeout(); @@ -122,9 +117,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsTransportStopsWhenConnectionChannelClosed() { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: LoggerFactory, accessTokenProvider: null); await webSocketsTransport.StartAsync(new Uri(server.WebSocketsUrl + "/echo"), TransferFormat.Binary); webSocketsTransport.Output.Complete(); @@ -138,9 +133,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(TransferFormat.Binary)] public async Task WebSocketsTransportStopsWhenConnectionClosedByTheServer(TransferFormat transferFormat) { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: LoggerFactory, accessTokenProvider: null); await webSocketsTransport.StartAsync(new Uri(server.WebSocketsUrl + "/echoAndClose"), transferFormat); await webSocketsTransport.Output.WriteAsync(new byte[] { 0x42 }); @@ -160,9 +155,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [InlineData(TransferFormat.Binary)] public async Task WebSocketsTransportSetsTransferFormat(TransferFormat transferFormat) { - using (StartServer(out var loggerFactory, out var server)) + using (StartServer(out var server)) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: LoggerFactory, accessTokenProvider: null); await webSocketsTransport.StartAsync(new Uri(server.WebSocketsUrl + "/echo"), transferFormat).OrTimeout(); @@ -178,9 +173,9 @@ namespace Microsoft.AspNetCore.SignalR.Tests [WebSocketsSupportedCondition] public async Task WebSocketsTransportThrowsForInvalidTransferFormat(TransferFormat transferFormat) { - using (StartVerifiableLog(out var loggerFactory)) + using (StartVerifiableLog()) { - var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, loggerFactory: loggerFactory, accessTokenProvider: null); + var webSocketsTransport = new WebSocketsTransport(httpConnectionOptions: null, LoggerFactory, accessTokenProvider: null); var exception = await Assert.ThrowsAsync(() => webSocketsTransport.StartAsync(new Uri("http://fakeuri.org"), transferFormat));