From 21bf1adcae2e20b0e2d884199f79a1149942c7f9 Mon Sep 17 00:00:00 2001 From: Liangying Wei Date: Thu, 23 Jan 2025 18:02:43 +0800 Subject: [PATCH] Fix test failure warnings --- .../AckHandlerTest.cs | 12 +++---- .../AddAzureSignalRFacts.cs | 7 ++-- .../AddAzureSignalRWithConnectionNameFacts.cs | 6 ++-- .../ClientConnectionContextFacts.cs | 14 ++++---- .../ClientConnectionManagerTests.cs | 30 +++++++++------- .../ClientInvocationManagerTests.cs | 36 ++++++++++--------- .../EndpointRouterTests.cs | 13 +++---- .../HubMessageSerializerTests.cs | 4 +-- .../DefaultClientInvocationManager.cs | 4 +-- .../DefaultHubProtocolResolver.cs | 10 +++--- .../Infrastructure/ServiceConnectionProxy.cs | 2 +- .../TestClientConnectionFactory.cs | 7 ++-- .../Infrastructure/TestHub.cs | 6 ++-- .../Infrastructure/TestOptionsMonitor.cs | 4 +-- .../TestServiceConnectionManager.cs | 4 +-- .../Logging/MessageLogTests.cs | 8 ++--- .../Microsoft.Azure.SignalR.Tests.csproj | 3 +- ...EndpointServiceConnectionContainerTests.cs | 33 ++++++++--------- .../RunSignalRTests.cs | 11 +++--- .../ServiceConnectionContainerTests.cs | 17 ++++----- .../ServiceConnectionFacts.cs | 8 ++--- .../ServiceConnectionTests.cs | 20 +++++------ .../ServiceContextFacts.cs | 10 +++--- .../ServiceEndpointProviderFacts.cs | 10 +++--- .../ServiceHubDispatcherTests.cs | 7 ++-- .../ServiceLifetimeManagerFacts.cs | 22 ++++++------ .../ServiceLifetimeManagerFactsForNet70.cs | 16 +++++---- .../ServiceMessageTests.cs | 12 +++---- .../TestServiceConnectionContainer.cs | 11 +++--- .../TestServiceConnectionForCloseAsync.cs | 9 +++-- .../TestSimpleServiceConnection.cs | 4 +-- .../TestHubs/ConnectedHub.cs | 4 +-- .../TestHubs/SimpleHub.cs | 4 +-- test/Microsoft.Azure.SignalR.Tests/Utils.cs | 8 ++--- 34 files changed, 193 insertions(+), 183 deletions(-) diff --git a/test/Microsoft.Azure.SignalR.Tests/AckHandlerTest.cs b/test/Microsoft.Azure.SignalR.Tests/AckHandlerTest.cs index e6218bd9e..01c6de137 100644 --- a/test/Microsoft.Azure.SignalR.Tests/AckHandlerTest.cs +++ b/test/Microsoft.Azure.SignalR.Tests/AckHandlerTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -11,25 +11,25 @@ namespace Microsoft.Azure.SignalR.Tests; public class AckHandlerTest { [Fact] - public void TestOnce() + public async Task TestOnce() { var handler = new AckHandler(); var task = handler.CreateSingleAck(out var ackId); handler.TriggerAck(ackId); Assert.True(task.IsCompletedSuccessfully); - Assert.Equal(AckStatus.Ok, task.Result); + Assert.Equal(AckStatus.Ok, await task); } [Fact] public async Task TestOnce_Timeout() { var handler = new AckHandler(TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(20)); - var task = handler.CreateSingleAck(out var ackId); + var task = handler.CreateSingleAck(out var _); Assert.False(task.IsCompleted); await Task.Delay(TimeSpan.FromSeconds(1.5)); Assert.True(task.IsCompleted); // This assertion is different from RT for different behaviour when timeout of AckHandler. See annotation in AckHandler.cs method CheckAcs - Assert.Equal(AckStatus.Timeout, task.Result); + Assert.Equal(AckStatus.Timeout, await task); } [Fact] @@ -68,7 +68,7 @@ public async Task TestTwice_Timeout() await Task.Delay(TimeSpan.FromSeconds(1.5)); Assert.True(task.IsCompleted); // This assertion is different from RT for different behaviour when timeout of AckHandler. See annotation in AckHandler.cs method CheckAcs - Assert.Equal(AckStatus.Timeout, task.Result); + Assert.Equal(AckStatus.Timeout, await task); } [Fact] diff --git a/test/Microsoft.Azure.SignalR.Tests/AddAzureSignalRFacts.cs b/test/Microsoft.Azure.SignalR.Tests/AddAzureSignalRFacts.cs index 66045b70e..30081ede4 100644 --- a/test/Microsoft.Azure.SignalR.Tests/AddAzureSignalRFacts.cs +++ b/test/Microsoft.Azure.SignalR.Tests/AddAzureSignalRFacts.cs @@ -224,7 +224,6 @@ public void AddAzureReadsConnectionStringFirst() } } - [Theory] [InlineData(null, ServerStickyMode.Disabled)] [InlineData("invalid", ServerStickyMode.Disabled)] @@ -403,8 +402,7 @@ public void AddAzureSignalRWithOnlySecondaryValueThrows(string customValue, stri } // Endpoints from Endpoints and ConnectionString config are merged inside the EndpointManager - Assert.Throws(() => - serviceProvider.GetRequiredService()); + Assert.Throws(serviceProvider.GetRequiredService); } } @@ -529,7 +527,6 @@ public void AddAzureSignalRWithInValidAppName(string appName) } } - [Fact(Skip = "Manual run for CI stable")] public async Task AddAzureSignalRHotReloadConfigValue() { @@ -633,4 +630,4 @@ private static async Task> GetClaims(Action(() => - serviceProvider.GetRequiredService()); + Assert.Throws(serviceProvider.GetRequiredService); } } @@ -528,4 +526,4 @@ public void AddAzureSignalRWithConnectionNameCustomizeEndpointsOverridesConfigVa } } } -} \ No newline at end of file +} diff --git a/test/Microsoft.Azure.SignalR.Tests/ClientConnectionContextFacts.cs b/test/Microsoft.Azure.SignalR.Tests/ClientConnectionContextFacts.cs index 497cf3417..ff9ef1f0e 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ClientConnectionContextFacts.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ClientConnectionContextFacts.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -47,7 +47,7 @@ public void DoNotSetUserIdFeatureWithoutUserIdClaimTest() } [Fact] - public async void TestForwardCloseMessage() + public async Task TestForwardCloseMessage() { using var serviceConnection = new TestServiceConnection(); @@ -88,7 +88,7 @@ public async void TestForwardCloseMessage() } [Fact] - public async void TestForwardInvocationMessage() + public async Task TestForwardInvocationMessage() { using var serviceConnection = new TestServiceConnection(); @@ -129,7 +129,7 @@ public async void TestForwardInvocationMessage() } [Fact] - public async void TestForwardHandshakeResponse() + public async Task TestForwardHandshakeResponse() { using var serviceConnection = new TestServiceConnection(); @@ -167,7 +167,7 @@ public async void TestForwardHandshakeResponse() } [Fact] - public async void TestSkipHandshakeResponse() + public async Task TestSkipHandshakeResponse() { using var serviceConnection = new TestServiceConnection(); @@ -204,7 +204,7 @@ public async void TestSkipHandshakeResponse() } [Fact] - public async void TestPauseResume() + public async Task TestPauseResume() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Information, logChecker: records => { @@ -262,7 +262,7 @@ public async void TestPauseResume() } [Fact] - public async void TestPauseAck() + public async Task TestPauseAck() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Information, logChecker: records => { diff --git a/test/Microsoft.Azure.SignalR.Tests/ClientConnectionManagerTests.cs b/test/Microsoft.Azure.SignalR.Tests/ClientConnectionManagerTests.cs index 7375eec3e..24b880912 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ClientConnectionManagerTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ClientConnectionManagerTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; using System.Security.Claims; using System.Threading.Tasks; using Xunit; @@ -7,19 +10,13 @@ namespace Microsoft.Azure.SignalR.Tests; public class ClientConnectionManagerTests { - private async Task RemoveConnection(IClientConnectionManager manager, ClientConnectionContext ctx) - { - await Task.Delay(100); - ctx.OnCompleted(); - } - - [Fact(Skip = "Disable high possibility failed cases until they are fixed")] - public void TestAllClientConnectionsCompleted() + [Fact] + public async Task TestAllClientConnectionsCompleted() { var manager = new ClientConnectionManager(); - var c1 = new ClientConnectionContext(new Protocol.OpenConnectionMessage("foo", new Claim[0])); - var c2 = new ClientConnectionContext(new Protocol.OpenConnectionMessage("bar", new Claim[0])); + var c1 = new ClientConnectionContext(new Protocol.OpenConnectionMessage("foo", Array.Empty())); + var c2 = new ClientConnectionContext(new Protocol.OpenConnectionMessage("bar", Array.Empty())); manager.TryAddClientConnection(c1); manager.TryAddClientConnection(c2); @@ -28,10 +25,17 @@ public void TestAllClientConnectionsCompleted() _ = RemoveConnection(manager, c2); var expected = manager.WhenAllCompleted(); - var actual = Task.WaitAny( + var actual = await Task.WhenAny( expected, Task.Delay(TimeSpan.FromSeconds(1)) ); - Assert.Equal(0, actual); + Assert.Equal(expected, actual); } + + private static async Task RemoveConnection(IClientConnectionManager _, ClientConnectionContext ctx) + { + await Task.Delay(100); + ctx.OnCompleted(); + } + } diff --git a/test/Microsoft.Azure.SignalR.Tests/ClientInvocationManagerTests.cs b/test/Microsoft.Azure.SignalR.Tests/ClientInvocationManagerTests.cs index 0dd34a126..93cb436b5 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ClientInvocationManagerTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ClientInvocationManagerTests.cs @@ -1,10 +1,13 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. + #if NET7_0_OR_GREATER using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Protocol; @@ -30,8 +33,8 @@ public class ClientInvocationManagerTests private static readonly List TestConnectionIds = new() { "conn0", "conn1" }; private static readonly List TestInstanceIds = new() { "instance0", "instance1" }; private static readonly List TestServerIds = new() { "server1", "server2" }; - private static readonly string SuccessCompleteResult = "success-result"; - private static readonly string ErrorCompleteResult = "error-result"; + private const string SuccessCompleteResult = "success-result"; + private const string ErrorCompleteResult = "error-result"; private static ClientInvocationManager GetTestClientInvocationManager(int endpointCount = 1) { @@ -65,7 +68,7 @@ private static ClientInvocationManager GetTestClientInvocationManager(int endpoi * * Note: Client 1 and Client 2 are both managed by Server A */ - public async void TestCompleteWithoutRouterServer(bool isCompletionWithResult) + public async Task TestCompleteWithoutRouterServer(bool isCompletionWithResult) { var clientInvocationManager = GetTestClientInvocationManager(); var connectionId = TestConnectionIds[0]; @@ -89,9 +92,9 @@ public async void TestCompleteWithoutRouterServer(bool isCompletionWithResult) try { - await task; + var result = await task; Assert.True(isCompletionWithResult); - Assert.Equal(SuccessCompleteResult, task.Result); + Assert.Equal(SuccessCompleteResult, result); } catch (Exception e) { @@ -111,7 +114,7 @@ public async void TestCompleteWithoutRouterServer(bool isCompletionWithResult) * * Note: Server 2 manages Client 2. */ - public async void TestCompleteWithRouterServer(string protocol, bool isCompletionWithResult) + public async Task TestCompleteWithRouterServer(string protocol, bool isCompletionWithResult) { var serverIds = new string[] { TestServerIds[0], TestServerIds[1] }; var ciManagers = new ClientInvocationManager[] { @@ -141,9 +144,9 @@ public async void TestCompleteWithRouterServer(string protocol, bool isCompletio try { - await task; + var result = await task; Assert.True(isCompletionWithResult); - Assert.Equal(SuccessCompleteResult, task.Result); + Assert.Equal(SuccessCompleteResult, result); } catch (Exception e) { @@ -171,14 +174,13 @@ public void TestCallerManagerCancellation() Assert.False(clientInvocationManager.Caller.TryGetInvocationReturnType(invocationId, out _)); } - [Theory] [InlineData(true, 2)] [InlineData(false, 2)] [InlineData(true, 3)] [InlineData(false, 3)] // isCompletionWithResult: the invocation is completed with result or error - public async void TestCompleteWithMultiEndpointAtLast(bool isCompletionWithResult, int endpointsCount) + public async Task TestCompleteWithMultiEndpointAtLast(bool isCompletionWithResult, int endpointsCount) { Assert.True(endpointsCount > 1); var clientInvocationManager = GetTestClientInvocationManager(endpointsCount); @@ -212,9 +214,9 @@ public async void TestCompleteWithMultiEndpointAtLast(bool isCompletionWithResul try { - await task; + var result = await task; Assert.True(isCompletionWithResult); - Assert.Equal(SuccessCompleteResult, task.Result); + Assert.Equal(SuccessCompleteResult, result); } catch (Exception e) { @@ -226,7 +228,7 @@ public async void TestCompleteWithMultiEndpointAtLast(bool isCompletionWithResul [Theory] [InlineData(2)] [InlineData(3)] - public async void TestCompleteWithMultiEndpointAtMiddle(int endpointsCount) + public async Task TestCompleteWithMultiEndpointAtMiddle(int endpointsCount) { Assert.True(endpointsCount > 1); var clientInvocationManager = GetTestClientInvocationManager(endpointsCount); @@ -262,8 +264,8 @@ public async void TestCompleteWithMultiEndpointAtMiddle(int endpointsCount) try { - await task; - Assert.Equal(SuccessCompleteResult, task.Result); + var result = await task; + Assert.Equal(SuccessCompleteResult, result); } catch (Exception) { @@ -278,4 +280,4 @@ internal static ReadOnlyMemory GetBytes(string proto, HubMessage message) } } -#endif \ No newline at end of file +#endif diff --git a/test/Microsoft.Azure.SignalR.Tests/EndpointRouterTests.cs b/test/Microsoft.Azure.SignalR.Tests/EndpointRouterTests.cs index 6cc899a56..fd98767f2 100644 --- a/test/Microsoft.Azure.SignalR.Tests/EndpointRouterTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/EndpointRouterTests.cs @@ -87,7 +87,7 @@ private static ServiceEndpoint GenerateServiceEndpoint(int capacity, int serverC EndpointType.Primary, name) { EndpointMetrics = endpointMetrics }; } - private class RandomContext + private sealed class RandomContext { private readonly Dictionary _counter = new(); @@ -96,18 +96,19 @@ public void BenchTest(int loops, Func func) for (var i = 0; i < loops; i++) { var name = func(); - if (!_counter.ContainsKey(name)) + if (!_counter.TryGetValue(name, out var value)) { - _counter.Add(name, 0); + value = 0; + _counter.Add(name, value); } - _counter[name]++; + _counter[name] = ++value; } } public int GetCount(string name) { - return _counter.ContainsKey(name) ? _counter[name] : 0; + return _counter.TryGetValue(name, out var value) ? value : 0; } public void Reset() @@ -115,4 +116,4 @@ public void Reset() _counter.Clear(); } } -} \ No newline at end of file +} diff --git a/test/Microsoft.Azure.SignalR.Tests/HubMessageSerializerTests.cs b/test/Microsoft.Azure.SignalR.Tests/HubMessageSerializerTests.cs index e83902e14..a73b15559 100644 --- a/test/Microsoft.Azure.SignalR.Tests/HubMessageSerializerTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/HubMessageSerializerTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -29,7 +29,7 @@ public void HubMessageSerializerFact() serializer.SerializeMessage("JsOn", message); } - private class IgnoreCaseJsonHubProtocol : IHubProtocol + private sealed class IgnoreCaseJsonHubProtocol : IHubProtocol { public string Name => "json"; diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultClientInvocationManager.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultClientInvocationManager.cs index 780576817..168085f36 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultClientInvocationManager.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultClientInvocationManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -9,7 +9,7 @@ namespace Microsoft.Azure.SignalR; -internal class DefaultClientInvocationManager : IClientInvocationManager +internal sealed class DefaultClientInvocationManager : IClientInvocationManager { public ICallerClientResultsManager Caller { get; } diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultHubProtocolResolver.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultHubProtocolResolver.cs index 45953e8a7..ead10737a 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultHubProtocolResolver.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/DefaultHubProtocolResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal { // copied from https://github.com/aspnet/AspNetCore/blob/release/3.0-preview7/src/SignalR/server/Core/src/Internal/DefaultHubProtocolResolver.cs - internal class DefaultHubProtocolResolver : IHubProtocolResolver + internal sealed class DefaultHubProtocolResolver : IHubProtocolResolver { private readonly ILogger _logger; private readonly List _hubProtocols; @@ -33,7 +33,7 @@ public DefaultHubProtocolResolver(IEnumerable availableProtocols, } } - public virtual IHubProtocol GetProtocol(string protocolName, IReadOnlyList supportedProtocols) + public IHubProtocol GetProtocol(string protocolName, IReadOnlyList supportedProtocols) { protocolName = protocolName ?? throw new ArgumentNullException(nameof(protocolName)); @@ -68,4 +68,4 @@ public static void FoundImplementationForProtocol(ILogger logger, string protoco } } } -} \ No newline at end of file +} diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/ServiceConnectionProxy.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/ServiceConnectionProxy.cs index 933dd24fb..e5d58ae97 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/ServiceConnectionProxy.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/ServiceConnectionProxy.cs @@ -21,7 +21,7 @@ namespace Microsoft.Azure.SignalR.Tests; -internal class ServiceConnectionProxy : IClientConnectionManager, IClientConnectionFactory, IServiceConnectionFactory +internal sealed class ServiceConnectionProxy : IClientConnectionManager, IClientConnectionFactory, IServiceConnectionFactory { private static readonly IServiceProtocol SharedServiceProtocol = new ServiceProtocol(); diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestClientConnectionFactory.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestClientConnectionFactory.cs index 6abc932ed..9ce70927c 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestClientConnectionFactory.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestClientConnectionFactory.cs @@ -1,11 +1,14 @@ -using System; +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.Azure.SignalR.Protocol; namespace Microsoft.Azure.SignalR.Tests; -internal class TestClientConnectionFactory : IClientConnectionFactory +internal sealed class TestClientConnectionFactory : IClientConnectionFactory { public IList Connections = new List(); diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestHub.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestHub.cs index 218c5fd28..3eabfa4fc 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestHub.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestHub.cs @@ -1,11 +1,11 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNetCore.SignalR; namespace Microsoft.Azure.SignalR.Tests { - internal class TestHub : Hub + internal sealed class TestHub : Hub { } -} \ No newline at end of file +} diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestOptionsMonitor.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestOptionsMonitor.cs index d5cf6f787..0c58cae6a 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestOptionsMonitor.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestOptionsMonitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -9,7 +9,7 @@ namespace Microsoft.Azure.SignalR.Tests { - internal class TestOptionsMonitor : IOptionsMonitor + internal sealed class TestOptionsMonitor : IOptionsMonitor { private readonly IOptionsMonitor _monitor; diff --git a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestServiceConnectionManager.cs b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestServiceConnectionManager.cs index a2ff32333..735b2bf02 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestServiceConnectionManager.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Infrastructure/TestServiceConnectionManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -10,7 +10,7 @@ namespace Microsoft.Azure.SignalR.Tests; -internal class TestServiceConnectionManager : IServiceConnectionManager where THub : Hub +internal sealed class TestServiceConnectionManager : IServiceConnectionManager where THub : Hub { private readonly ConcurrentDictionary _writeAsyncCallCount = new ConcurrentDictionary(); diff --git a/test/Microsoft.Azure.SignalR.Tests/Logging/MessageLogTests.cs b/test/Microsoft.Azure.SignalR.Tests/Logging/MessageLogTests.cs index 4b4dfbcc8..664b5b5de 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Logging/MessageLogTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Logging/MessageLogTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -36,7 +36,7 @@ public void MessageLogTest() MessageLog.StartToSendMessageToUser(logger, new UserDataMessage("user", null, tracingId: 123UL)); Assert.Equal(Format(MessageLog.StartToSendMessageToUserTemplate, 123UL, "user"), logger.LogStr); - MessageLog.FailedToSendMessage(logger, new UserDataMessage("user", null, tracingId: 123UL), new Exception()); + MessageLog.FailedToSendMessage(logger, new UserDataMessage("user", null, tracingId: 123UL), new InvalidOperationException()); Assert.Equal(Format(MessageLog.FailedToSendMessageTemplate, 123UL), logger.LogStr); MessageLog.SucceededToSendMessage(logger, new UserDataMessage("user", null, tracingId: 123UL)); @@ -92,13 +92,13 @@ public void MessageLogTest() } } - private string Format(string logTemplate, params object[] values) + private static string Format(string logTemplate, params object[] values) { var index = 0; return Regex.Replace(logTemplate, "{[^}]*}", _ => values[index++].ToString()); } - private class TestLogger : ILogger + private sealed class TestLogger : ILogger { public string LogStr { get; private set; } diff --git a/test/Microsoft.Azure.SignalR.Tests/Microsoft.Azure.SignalR.Tests.csproj b/test/Microsoft.Azure.SignalR.Tests/Microsoft.Azure.SignalR.Tests.csproj index 31fc8e861..0414baf3d 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Microsoft.Azure.SignalR.Tests.csproj +++ b/test/Microsoft.Azure.SignalR.Tests/Microsoft.Azure.SignalR.Tests.csproj @@ -1,11 +1,10 @@ - + MULTIFRAMEWORK false 11 net8.0 - false diff --git a/test/Microsoft.Azure.SignalR.Tests/MultiEndpointServiceConnectionContainerTests.cs b/test/Microsoft.Azure.SignalR.Tests/MultiEndpointServiceConnectionContainerTests.cs index b96b17404..1aea85aa5 100644 --- a/test/Microsoft.Azure.SignalR.Tests/MultiEndpointServiceConnectionContainerTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/MultiEndpointServiceConnectionContainerTests.cs @@ -5,6 +5,7 @@ using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -138,11 +139,11 @@ public class MultiEndpointServiceConnectionContainerTests : VerifiableLoggedTest private static readonly JoinGroupWithAckMessage DefaultGroupMessage = new("a", "a", -1); - private readonly string ConnectionString1 = string.Format(ConnectionStringFormatter, Url1); + private readonly string ConnectionString1 = string.Format(CultureInfo.InvariantCulture, ConnectionStringFormatter, Url1); - private readonly string ConnectionString2 = string.Format(ConnectionStringFormatter, Url2); + private readonly string ConnectionString2 = string.Format(CultureInfo.InvariantCulture, ConnectionStringFormatter, Url2); - private readonly string ConnectionString3 = string.Format(ConnectionStringFormatter, Url3); + private readonly string ConnectionString3 = string.Format(CultureInfo.InvariantCulture, ConnectionStringFormatter, Url3); public MultiEndpointServiceConnectionContainerTests(ITestOutputHelper output) : base(output) { @@ -1632,9 +1633,9 @@ public async Task ServiceConnectionContainerScopeWithPingUpdateTest() var url1 = "http://url1"; var url2 = "http://url2"; var url22 = "http://url22"; - var connectionString1 = string.Format(connectionStringFormatter, url1); - var connectionString2 = string.Format(connectionStringFormatter, url2); - var connectionString22 = string.Format(connectionStringFormatter, url22); + var connectionString1 = string.Format(CultureInfo.InvariantCulture, connectionStringFormatter, url1); + var connectionString2 = string.Format(CultureInfo.InvariantCulture, connectionStringFormatter, url2); + var connectionString22 = string.Format(CultureInfo.InvariantCulture, connectionStringFormatter, url22); var sem = new TestServiceEndpointManager(new ServiceEndpoint(connectionString1, EndpointType.Primary, "1"), new ServiceEndpoint(connectionString2, EndpointType.Primary, "2")); @@ -1824,8 +1825,8 @@ public async Task TestEndpointWithStatusPingPlusClientCount(int c1, int c2) var containers = container.GetTestOnlineContainers(); var container1 = containers.Where(x => x.Endpoint.Name == "1").FirstOrDefault(); var container2 = containers.Where(x => x.Endpoint.Name == "22").FirstOrDefault(); - await Task.WhenAll(container1.MockReceivedStatusPing(true, c1)); - await Task.WhenAll(container2.MockReceivedStatusPing(true, c2)); + await container1.MockReceivedStatusPing(true, c1); + await container2.MockReceivedStatusPing(true, c2); Assert.Equal(c1, hubEndpoints[0].EndpointMetrics.ClientConnectionCount); Assert.Equal(c2, hubEndpoints[1].EndpointMetrics.ClientConnectionCount); @@ -1856,7 +1857,7 @@ internal async Task TestMultiEndpointOffline(GracefulShutdownMode mode) await TestEndpointOfflineInner(manager, new TestEndpointRouter(), mode); } - private (PingConnectionHandler, ConnectionDelegate) GetConnectionDelegate() + private static (PingConnectionHandler, ConnectionDelegate) GetConnectionDelegate() { var services = new ServiceCollection(); var connectionHandler = new PingConnectionHandler(); @@ -1866,7 +1867,7 @@ internal async Task TestMultiEndpointOffline(GracefulShutdownMode mode) return (connectionHandler, builder.Build()); } - private async Task TestEndpointOfflineInner(IServiceEndpointManager manager, IEndpointRouter router, GracefulShutdownMode mode) + private static async Task TestEndpointOfflineInner(IServiceEndpointManager manager, IEndpointRouter router, GracefulShutdownMode mode) { var containers = new List(); @@ -1897,10 +1898,10 @@ private async Task TestEndpointOfflineInner(IServiceEndpointManager manager, IEn } } - private TestMultiEndpointServiceConnectionContainer CreateMultiEndpointConnection(EndpointStatus[] status, TaskCompletionSource writeTcs, ILoggerFactory loggerFactory) + private static TestMultiEndpointServiceConnectionContainer CreateMultiEndpointConnection(EndpointStatus[] status, TaskCompletionSource writeTcs, ILoggerFactory loggerFactory) { var i = 0; - var endpoints = status.Select(s => new ServiceEndpoint(string.Format(ConnectionStringFormatter, $"https://{s}{++i}"), name: status.ToString())).ToArray(); + var endpoints = status.Select(s => new ServiceEndpoint(string.Format(CultureInfo.InvariantCulture, ConnectionStringFormatter, $"https://{s}{++i}"), name: status.ToString())).ToArray(); var sem = new TestServiceEndpointManager(endpoints); var router = new TestEndpointRouter(); @@ -1966,7 +1967,7 @@ private async Task ReadMessagesAsync(ConnectionContext connection) } } - private class NotExistEndpointRouter : EndpointRouterDecorator + private sealed class NotExistEndpointRouter : EndpointRouterDecorator { public override IEnumerable GetEndpointsForConnection(string connectionId, IEnumerable endpoints) { @@ -1986,7 +1987,7 @@ public TestMultiEndpointServiceConnectionContainer(string hub, IServiceEndpointManager endpoint, IEndpointRouter router, ILoggerFactory loggerFactory, - TimeSpan? scaleTimeout = null + TimeSpan? _ = null ) : base(hub, generator, endpoint, router, loggerFactory) { } @@ -2005,7 +2006,7 @@ public List GetTestOnlineContainers() } } - private class TestServiceEndpointManager : ServiceEndpointManagerBase + private sealed class TestServiceEndpointManager : ServiceEndpointManagerBase { private readonly ServiceEndpoint[] _endpoints; @@ -2025,7 +2026,7 @@ public Task TestReloadServiceEndpoints(ServiceEndpoint[] serviceEndpoints, int t } } - private class TestEndpointRouter : EndpointRouterDecorator + private sealed class TestEndpointRouter : EndpointRouterDecorator { private readonly Exception _ex; diff --git a/test/Microsoft.Azure.SignalR.Tests/RunSignalRTests.cs b/test/Microsoft.Azure.SignalR.Tests/RunSignalRTests.cs index 9211428f9..c0a89616f 100644 --- a/test/Microsoft.Azure.SignalR.Tests/RunSignalRTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/RunSignalRTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -191,7 +191,6 @@ public IServiceProvider ConfigureServices(IServiceCollection services) private sealed class ControlledServiceConnectionContext : ConnectionContext { private static readonly ServiceProtocol _serviceProtocol = new ServiceProtocol(); - private static readonly JsonHubProtocol _signalRPro = new JsonHubProtocol(); public ControlledServiceConnectionContext() { var pipe = DuplexPipe.CreateConnectionPair(new PipeOptions(pauseWriterThreshold: 0), new PipeOptions(pauseWriterThreshold: 0)); @@ -201,10 +200,10 @@ public ControlledServiceConnectionContext() _ = WriteHandshakeResponseAsync(Application.Output); } - private async Task WriteHandshakeResponseAsync(PipeWriter output) + private static async Task WriteHandshakeResponseAsync(PipeWriter output) { _serviceProtocol.WriteMessage(new Protocol.HandshakeResponseMessage(), output); - var sendHandshakeResult = await output.FlushAsync(); + _ = await output.FlushAsync(); } public override IDuplexPipe Transport { get; set; } @@ -216,7 +215,7 @@ private async Task WriteHandshakeResponseAsync(PipeWriter output) public async Task OpenClientConnectionAsync(string connectionId) { - var openClientConnMsg = new OpenConnectionMessage(connectionId, new System.Security.Claims.Claim[] { }) { Protocol = "json" }; + var openClientConnMsg = new OpenConnectionMessage(connectionId, Array.Empty()) { Protocol = "json" }; _serviceProtocol.WriteMessage(openClientConnMsg, Application.Output); await Application.Output.FlushAsync(); @@ -249,7 +248,7 @@ public static ReadOnlyMemory GetMessageBytes(Microsoft.AspNetCore.SignalR. private sealed class CaptureDataConnectionFactory : IConnectionFactory { - private TaskCompletionSource _taskCompletionSource = new TaskCompletionSource(); + private readonly TaskCompletionSource _taskCompletionSource = new TaskCompletionSource(); public Task FirstConnectionTask => _taskCompletionSource.Task; public Task DisposeAsync(ConnectionContext connection) { diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionContainerTests.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionContainerTests.cs index ed9652c3f..1b8a457d9 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionContainerTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionContainerTests.cs @@ -1,8 +1,9 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; @@ -76,7 +77,7 @@ public async Task TestServiceConnectionOffline() // write 100 messages. for (var i = 0; i < 100; i++) { - var message = new ConnectionDataMessage(i.ToString(), new byte[12]); + var message = new ConnectionDataMessage(i.ToString(CultureInfo.InvariantCulture), new byte[12]); await container.WriteAsync(message); } @@ -92,7 +93,7 @@ public async Task TestServiceConnectionOffline() // write 100 more messages. for (var i = 0; i < 100; i++) { - var message = new ConnectionDataMessage(i.ToString(), new byte[12]); + var message = new ConnectionDataMessage(i.ToString(CultureInfo.InvariantCulture), new byte[12]); await container.WriteAsync(message); } @@ -130,7 +131,7 @@ public async Task TestServiceConnectionStickyWrites() // write 100000 messages. for (var i = 0; i < 100000; i++) { - var message = new ConnectionDataMessage(i.ToString(), new byte[12]); + var message = new ConnectionDataMessage(i.ToString(CultureInfo.InvariantCulture), new byte[12]); await container.WriteAsync(message); } @@ -144,7 +145,7 @@ public async Task TestServiceConnectionStickyWrites() // write 100000 messages with the same connectionIds should double the message count for each service connection for (var i = 0; i < 100000; i++) { - var message = new ConnectionDataMessage(i.ToString(), new byte[12]); + var message = new ConnectionDataMessage(i.ToString(CultureInfo.InvariantCulture), new byte[12]); await container.WriteAsync(message); } @@ -164,7 +165,7 @@ public async Task TestServiceConnectionStickyWrites() // write 100000 messages with the same connectionIds does not throw for (var i = 0; i < 100000; i++) { - var message = new ConnectionDataMessage(i.ToString(), new byte[12]); + var message = new ConnectionDataMessage(i.ToString(CultureInfo.InvariantCulture), new byte[12]); await container.WriteAsync(message); } @@ -195,11 +196,11 @@ public async Task TestServiceConnectionStickyWritesWithScope() // write 100000 messages. for (var i = 0; i < 100000; i++) { - var message = new ConnectionDataMessage(i.ToString(), new byte[12]); + var message = new ConnectionDataMessage(i.ToString(CultureInfo.InvariantCulture), new byte[12]); await container.WriteAsync(message); } - var selected = connections.Where(s => s.ReceivedMessages.Count > 0).ToArray(); + var selected = connections.Where(s => !s.ReceivedMessages.IsEmpty).ToArray(); Assert.Single(selected); Assert.Equal(100000, selected[0].ReceivedMessages.Count); diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionFacts.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionFacts.cs index 6676c520f..6c6710fe8 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionFacts.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionFacts.cs @@ -588,7 +588,7 @@ private static void AssertTimeout(params Task[] task) Assert.False(Task.WaitAll(task, DefaultTimeoutInMilliSeconds)); } - private class TestConnectionFactoryWithHandshakeError : TestConnectionFactory + private sealed class TestConnectionFactoryWithHandshakeError : TestConnectionFactory { public TestConnectionFactoryWithHandshakeError(Func callback) : base(callback) { @@ -602,7 +602,7 @@ await HandshakeUtils.SendHandshakeResponseAsync(connection.Application.Output, } } - private class TestConnectionFactoryWithConnectivityFailure : TestConnectionFactory + private sealed class TestConnectionFactoryWithConnectivityFailure : TestConnectionFactory { private const int MaxErrorCount = 3; @@ -618,14 +618,14 @@ protected override Task AfterConnectedAsync(TestConnection connection) if (_connectCount < MaxErrorCount) { _connectCount++; - throw new Exception("Connect error."); + throw new InvalidOperationException("Connect error."); } return Task.CompletedTask; } } - private class TestConnectionFactoryWithIntermittentInvalidHandshakeResponseMessage : TestConnectionFactory + private sealed class TestConnectionFactoryWithIntermittentInvalidHandshakeResponseMessage : TestConnectionFactory { private const int MaxErrorCount = 3; diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionTests.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionTests.cs index bf10f1e8c..3cdb52db3 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceConnectionTests.cs @@ -209,7 +209,7 @@ public async Task TestServiceConnectionWithNormalApplicationTask() var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[0] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); await transportConnection.Application.Output.WriteAsync( @@ -223,7 +223,7 @@ await transportConnection.Application.Output.WriteAsync( waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); clientConnection = await waitClientTask.OrTimeout(); @@ -268,7 +268,7 @@ public async Task TestServiceConnectionErrorCleansAllClients() var clientConnectionId = Guid.NewGuid().ToString(); var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); // Cancel pending read to end the server connection @@ -327,7 +327,7 @@ public async Task TestServiceConnectionWithErrorApplicationTask() var clientConnectionId = Guid.NewGuid().ToString(); var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); @@ -401,7 +401,7 @@ public async Task TestServiceConnectionWithEndlessApplicationTaskNeverEnds() Assert.Equal(ServiceConnectionStatus.Connected, connection.Status); var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); @@ -470,7 +470,7 @@ public async Task TestClientConnectionOutgoingAbortCanEndLifeTime() var clientConnectionId = Guid.NewGuid().ToString(); var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var context = await waitClientTask.OrTimeout(); @@ -540,7 +540,7 @@ public async Task TestClientConnectionContextAbortCanSendOutCloseMessage() var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); await clientConnection.LifetimeTask.OrTimeout(); @@ -851,7 +851,7 @@ public async Task TestPartialMessagesShouldFlushCorrectly() var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); @@ -949,7 +949,7 @@ public async Task TestPartialMessagesShouldBeRemovedWhenReconnected() var waitClientTask = ccm.WaitForClientConnectionAsync(clientConnectionId); await transportConnection.Application.Output.WriteAsync( - protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { }) { Protocol = hubProtocol.Name })); + protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, Array.Empty()) { Protocol = hubProtocol.Name })); var clientConnection = await waitClientTask.OrTimeout(); @@ -1065,7 +1065,7 @@ public LastWillConnectionHandler(IHubProtocol hubProtocol, string lastWill) public override async Task OnConnectedAsync(ConnectionContext connection) { HandshakeProtocol.WriteResponseMessage(SignalRProtocol.HandshakeResponseMessage.Empty, connection.Transport.Output); - _hubProtocol.WriteMessage(new InvocationMessage(_lastWill, new object[0]), connection.Transport.Output); + _hubProtocol.WriteMessage(new InvocationMessage(_lastWill, Array.Empty()), connection.Transport.Output); await connection.Transport.Output.FlushAsync(); } } diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceContextFacts.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceContextFacts.cs index 27253721e..4b3dce7aa 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceContextFacts.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceContextFacts.cs @@ -24,7 +24,7 @@ public class ServiceContextFacts [Fact] public void ServiceConnectionContextWithEmptyClaimsIsUnauthenticated() { - var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", new Claim[0])); + var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", Array.Empty())); Assert.NotNull(serviceConnectionContext.User.Identity); Assert.False(serviceConnectionContext.User.Identity.IsAuthenticated); } @@ -96,7 +96,7 @@ public void ServiceConnectionContextWithClaimsCreatesIdentityWithClaims() [Fact] public void ServiceConnectionContextWithEmptyHttpContextByDefault() { - var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", new Claim[0])); + var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", Array.Empty())); Assert.NotNull(serviceConnectionContext.User.Identity); Assert.NotNull(serviceConnectionContext.HttpContext); Assert.Equal(serviceConnectionContext.User, serviceConnectionContext.HttpContext.User); @@ -111,7 +111,7 @@ public void ServiceConnectionContextWithNonEmptyHeaders() const string key2 = "header-key-2"; const string value1 = "header-value-1"; var value2 = new[] { "header-value-2a", "header-value-2b" }; - var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", new Claim[0], + var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", Array.Empty(), new Dictionary(StringComparer.OrdinalIgnoreCase) { {key1, value1}, @@ -133,7 +133,7 @@ public void ServiceConnectionContextWithNonEmptyHeaders() public void ServiceConnectionContextWithNonEmptyQueries() { const string queryString = "?query1=value1&query2=value2&query3=value3"; - var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", new Claim[0], EmptyHeaders, queryString)); + var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", Array.Empty(), EmptyHeaders, queryString)); Assert.NotNull(serviceConnectionContext.User.Identity); Assert.NotNull(serviceConnectionContext.HttpContext); @@ -230,7 +230,7 @@ public void ServiceConnectionContextCultureTest(string cultureQuery, bool isCult var originalCulture = CultureInfo.CurrentCulture.Name; var originalUiCulture = CultureInfo.CurrentUICulture.Name; - _ = new ClientConnectionContext(new OpenConnectionMessage("1", new Claim[0], EmptyHeaders, queryString)); + _ = new ClientConnectionContext(new OpenConnectionMessage("1", Array.Empty(), EmptyHeaders, queryString)); var expectedCulture = isCultureValid ? parsedCulture : originalCulture; var expectedUiCulture = isUiCultureValid ? parsedUiCulture : originalUiCulture; diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceEndpointProviderFacts.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceEndpointProviderFacts.cs index 32aa6aba4..b3e6c7c62 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceEndpointProviderFacts.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceEndpointProviderFacts.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -16,15 +16,15 @@ public class ServiceEndpointProviderFacts private const string Endpoint = "https://myendpoint"; private const string AccessKey = "fake_key"; private static readonly string HubName = nameof(TestHub).ToLower(); - private static readonly string AppName = "testapp"; + private const string AppName = "testapp"; - private static readonly string ConnectionStringWithoutVersion = + private const string ConnectionStringWithoutVersion = $"Endpoint={Endpoint};AccessKey={AccessKey};"; - private static readonly string ConnectionStringWithPreviewVersion = + private const string ConnectionStringWithPreviewVersion = $"Endpoint={Endpoint};AccessKey={AccessKey};Version=1.0-preview"; - private static readonly string ConnectionStringWithV1Version = $"Endpoint={Endpoint};AccessKey={AccessKey};Version=1.0"; + private const string ConnectionStringWithV1Version = $"Endpoint={Endpoint};AccessKey={AccessKey};Version=1.0"; private static readonly ServiceOptions _optionsWithoutAppName = Options.Create(new ServiceOptions()).Value; private static readonly ServiceOptions _optionsWithAppName = Options.Create(new ServiceOptions { ApplicationName = AppName }).Value; diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceHubDispatcherTests.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceHubDispatcherTests.cs index 3e4ed57e1..608026cd7 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceHubDispatcherTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceHubDispatcherTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; @@ -18,7 +21,7 @@ namespace Microsoft.Azure.SignalR.Tests; public class ServiceHubDispatcherTests { [Fact] - public async void TestShutdown() + public async Task TestShutdown() { var index = new StrongBox(); var clientManager = new TestClientConnectionManager(index); diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs index c57424e81..90c519ab7 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -62,7 +62,7 @@ public ServiceLifetimeManagerFacts() [InlineData("SendGroupsAsync", typeof(MultiGroupBroadcastDataMessage))] [InlineData("SendUserAsync", typeof(UserDataMessage))] [InlineData("SendUsersAsync", typeof(MultiUserDataMessage))] - public async void ServiceLifetimeManagerTest(string functionName, Type type) + public async Task ServiceLifetimeManagerTest(string functionName, Type type) { var serviceConnectionManager = new TestServiceConnectionManager(); var blazorDetector = new DefaultBlazorDetector(); @@ -83,7 +83,7 @@ public async void ServiceLifetimeManagerTest(string functionName, Type type) [InlineData("SendGroupExceptAsync", typeof(GroupBroadcastDataMessage))] [InlineData("AddToGroupAsync", typeof(JoinGroupWithAckMessage))] [InlineData("RemoveFromGroupAsync", typeof(LeaveGroupWithAckMessage))] - public async void ServiceLifetimeManagerGroupTest(string functionName, Type type) + public async Task ServiceLifetimeManagerGroupTest(string functionName, Type type) { var serviceConnectionManager = new TestServiceConnectionManager(); var blazorDetector = new DefaultBlazorDetector(); @@ -120,7 +120,7 @@ public async void ServiceLifetimeManagerGroupTest(string functionName, Type type [InlineData("SendUsersAsync", typeof(MultiUserDataMessage))] [InlineData("AddToGroupAsync", typeof(JoinGroupWithAckMessage))] [InlineData("RemoveFromGroupAsync", typeof(LeaveGroupWithAckMessage))] - public async void ServiceLifetimeManagerIntegrationTest(string methodName, Type messageType) + public async Task ServiceLifetimeManagerIntegrationTest(string methodName, Type messageType) { var proxy = new ServiceConnectionProxy(); var blazorDetector = new DefaultBlazorDetector(); @@ -163,7 +163,7 @@ public async void ServiceLifetimeManagerIntegrationTest(string methodName, Type [InlineData("SendGroupsAsync", typeof(MultiGroupBroadcastDataMessage))] [InlineData("SendUserAsync", typeof(UserDataMessage))] [InlineData("SendUsersAsync", typeof(MultiUserDataMessage))] - public async void ServiceLifetimeManagerIgnoreBlazorHubProtocolTest(string functionName, Type type) + public async Task ServiceLifetimeManagerIgnoreBlazorHubProtocolTest(string functionName, Type type) { var blazorDetector = new DefaultBlazorDetector(); var protocolResolver = new DefaultHubProtocolResolver(new SignalRProtocol.IHubProtocol[] @@ -195,7 +195,7 @@ public async void ServiceLifetimeManagerIgnoreBlazorHubProtocolTest(string funct [InlineData("SendGroupsAsync", typeof(MultiGroupBroadcastDataMessage))] [InlineData("SendUserAsync", typeof(UserDataMessage))] [InlineData("SendUsersAsync", typeof(MultiUserDataMessage))] - public async void ServiceLifetimeManagerOnlyBlazorHubProtocolTest(string functionName, Type type) + public async Task ServiceLifetimeManagerOnlyBlazorHubProtocolTest(string functionName, Type type) { var serviceConnectionManager = new TestServiceConnectionManager(); var blazorDetector = new DefaultBlazorDetector(); @@ -205,12 +205,12 @@ public async void ServiceLifetimeManagerOnlyBlazorHubProtocolTest(string functio Assert.Equal(1, serviceConnectionManager.GetCallCount(type)); VerifyServiceMessage(functionName, serviceConnectionManager.ServiceMessage); - Assert.Equal(1, (serviceConnectionManager.ServiceMessage as MulticastDataMessage).Payloads.Count); + Assert.Single((serviceConnectionManager.ServiceMessage as MulticastDataMessage).Payloads); Assert.True(blazorDetector.IsBlazor(nameof(TestHub))); } [Fact] - public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExisted() + public async Task TestSendConnectionAsyncisOverwrittenWhenClientConnectionExisted() { var serviceConnectionManager = new TestServiceConnectionManager(); var clientConnectionManager = new ClientConnectionManager(); @@ -228,7 +228,7 @@ public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExiste if (serviceConnection.LastMessage is MultiConnectionDataMessage m) { Assert.Equal("conn1", m.ConnectionList[0]); - Assert.Equal(1, m.Payloads.Count); + Assert.Single(m.Payloads); Assert.True(m.Payloads.ContainsKey(MockProtocol)); return; } @@ -236,7 +236,7 @@ public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExiste } [Fact] - public async void SetUserIdTest() + public async Task SetUserIdTest() { var connectionContext = new TestConnectionContext(); connectionContext.Features.Set(new ServiceUserIdFeature("testUser")); @@ -249,7 +249,7 @@ public async void SetUserIdTest() } [Fact] - public async void DoNotSetUserIdWithoutFeatureTest() + public async Task DoNotSetUserIdWithoutFeatureTest() { var connectionContext = new TestConnectionContext(); diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFactsForNet70.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFactsForNet70.cs index 1815e300f..85a58e625 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFactsForNet70.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFactsForNet70.cs @@ -1,9 +1,11 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Security.Claims; +using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.Azure.SignalR.Protocol; using Microsoft.Azure.SignalR.Tests.Common; @@ -22,7 +24,7 @@ public class ServiceLifetimeManagerFactsForNet70 : ServiceLifetimeManagerFacts [InlineData("json", false)] [InlineData("messagepack", true)] [InlineData("messagepack", false)] - public async void TestClientInvocationOneService(string protocol, bool isCompletionWithResult) + public async Task TestClientInvocationOneService(string protocol, bool isCompletionWithResult) { var serviceConnection = new TestServiceConnection(); var serviceConnectionManager = new TestServiceConnectionManager(); @@ -56,9 +58,9 @@ public async void TestClientInvocationOneService(string protocol, bool isComplet // Check if the invocation result is correct try { - await task; + var result = await task; Assert.True(isCompletionWithResult); - Assert.Equal(invocationResult, task.Result); + Assert.Equal(invocationResult, result); } catch (Exception e) { @@ -72,7 +74,7 @@ public async void TestClientInvocationOneService(string protocol, bool isComplet [InlineData("json", false)] [InlineData("messagepack", true)] [InlineData("messagepack", false)] - public async void TestMultiClientInvocationsMultipleService(string protocol, bool isCompletionWithResult) + public async Task TestMultiClientInvocationsMultipleService(string protocol, bool isCompletionWithResult) { var clientConnectionContext = GetClientConnectionContextWithConnection(TestConnectionIds[1], protocol); var clientConnectionManager = new ClientConnectionManager(); @@ -115,9 +117,9 @@ public async void TestMultiClientInvocationsMultipleService(string protocol, boo try { - await task; + var result = await task; Assert.True(isCompletionWithResult); - Assert.Equal(invocationResult, task.Result); + Assert.Equal(invocationResult, result); } catch (Exception e) { diff --git a/test/Microsoft.Azure.SignalR.Tests/ServiceMessageTests.cs b/test/Microsoft.Azure.SignalR.Tests/ServiceMessageTests.cs index 3ea2478ab..efe5a5475 100644 --- a/test/Microsoft.Azure.SignalR.Tests/ServiceMessageTests.cs +++ b/test/Microsoft.Azure.SignalR.Tests/ServiceMessageTests.cs @@ -30,10 +30,6 @@ public class ServiceMessageTests : VerifiableLoggedTest { private const string SigningKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - private const string MicrosoftEntraConnectionString = "endpoint=https://localhost;authType=aad;"; - - private static readonly Uri DefaultEndpoint = new("http://localhost"); - private const string DefaultAudience = "https://localhost"; private const string LocalConnectionString = "endpoint=https://localhost;accessKey=" + SigningKey; @@ -365,7 +361,7 @@ private ServiceEndpoint MockServiceEndpoint(string keyTypeName) }; } - private class TestTokenCredential : TokenCredential + private sealed class TestTokenCredential : TokenCredential { public string Token { get; } = Guid.NewGuid().ToString(); @@ -388,7 +384,7 @@ private sealed class TestConnectionContainer private sealed class TestConnectionHandler : ConnectionHandler { - private readonly int _shutdownAfter = 0; + private readonly int _shutdownAfter; private readonly string _lastWords; @@ -460,7 +456,7 @@ private sealed class TestServiceConnection : ServiceConnection private readonly TaskCompletionSource _clientDisconnectedTcs = new(); - private ReadOnlySequence _payload = new(); + private ReadOnlySequence _payload; public TestClientConnectionManager ClientConnectionManager { get; } @@ -476,7 +472,7 @@ private sealed class TestServiceConnection : ServiceConnection public SignalRProtocol.IHubProtocol DefaultHubProtocol { get; } = new SignalRProtocol.JsonHubProtocol(); - private TestConnection Connection => _container.Instance ?? throw new Exception("connection needs to be started"); + private TestConnection Connection => _container.Instance ?? throw new InvalidOperationException("connection needs to be started"); public TestServiceConnection(TestConnectionContainer container, IServiceProtocol serviceProtocol, diff --git a/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionContainer.cs b/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionContainer.cs index 71f6ef2b7..48f16d0ef 100644 --- a/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionContainer.cs +++ b/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionContainer.cs @@ -1,8 +1,9 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; +using System.Globalization; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -14,9 +15,9 @@ namespace Microsoft.Azure.SignalR.Tests; internal sealed class TestServiceConnectionContainer : ServiceConnectionContainerBase { - public bool IsOffline { get; set; } = false; + public bool IsOffline { get; set; } - public bool MockOffline { get; set; } = false; + public bool MockOffline { get; set; } public List Connections => ServiceConnections; @@ -39,7 +40,7 @@ public override async Task OfflineAsync(GracefulShutdownMode mode, CancellationT { if (MockOffline) { - await Task.Delay(100); + await Task.Delay(100, token); IsOffline = true; } else @@ -77,7 +78,7 @@ public Task MockReceivedStatusPing(bool isActive) public Task MockReceivedStatusPing(bool isActive, int clientCount) { - var ping = new PingMessage { Messages = new[] { "status", isActive ? "1" : "0", "clientcount", clientCount.ToString() } }; + var ping = new PingMessage { Messages = new[] { "status", isActive ? "1" : "0", "clientcount", clientCount.ToString(CultureInfo.InvariantCulture) } }; return base.HandlePingAsync(ping); } diff --git a/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionForCloseAsync.cs b/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionForCloseAsync.cs index 12fb59ff0..b5d99e987 100644 --- a/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionForCloseAsync.cs +++ b/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestServiceConnectionForCloseAsync.cs @@ -1,10 +1,13 @@ -using System.Threading.Tasks; +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Threading.Tasks; using Microsoft.Azure.SignalR.Protocol; using Microsoft.Azure.SignalR.Tests.Common; namespace Microsoft.Azure.SignalR.Tests; -internal class TestServiceConnectionForCloseAsync : TestServiceConnection +internal sealed class TestServiceConnectionForCloseAsync : TestServiceConnection { public TestServiceConnectionForCloseAsync() : base(ServiceConnectionStatus.Connected, false) { @@ -14,4 +17,4 @@ protected override Task OnClientConnectedAsync(OpenConnectionMessage openConnect { return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestSimpleServiceConnection.cs b/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestSimpleServiceConnection.cs index 53192d411..7f977c64c 100644 --- a/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestSimpleServiceConnection.cs +++ b/test/Microsoft.Azure.SignalR.Tests/TestClasses/TestSimpleServiceConnection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -13,7 +13,7 @@ internal sealed class TestSimpleServiceConnection : IServiceConnection { private readonly bool _throws; - private readonly TaskCompletionSource _writeAsyncTcs = null; + private readonly TaskCompletionSource _writeAsyncTcs; public ServiceConnectionStatus Status { get; } diff --git a/test/Microsoft.Azure.SignalR.Tests/TestHubs/ConnectedHub.cs b/test/Microsoft.Azure.SignalR.Tests/TestHubs/ConnectedHub.cs index a7d1efea9..34d821448 100644 --- a/test/Microsoft.Azure.SignalR.Tests/TestHubs/ConnectedHub.cs +++ b/test/Microsoft.Azure.SignalR.Tests/TestHubs/ConnectedHub.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -8,7 +8,7 @@ namespace Microsoft.Azure.SignalR.Tests.TestHubs; -internal class ConnectedHub : Hub +internal sealed class ConnectedHub : Hub { private readonly ILogger _logger; diff --git a/test/Microsoft.Azure.SignalR.Tests/TestHubs/SimpleHub.cs b/test/Microsoft.Azure.SignalR.Tests/TestHubs/SimpleHub.cs index dcc74440e..b936f2f0c 100644 --- a/test/Microsoft.Azure.SignalR.Tests/TestHubs/SimpleHub.cs +++ b/test/Microsoft.Azure.SignalR.Tests/TestHubs/SimpleHub.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading.Tasks; @@ -8,7 +8,7 @@ namespace Microsoft.Azure.SignalR.Tests.TestHubs; -internal class SimpleHub : Hub +internal sealed class SimpleHub : Hub { private readonly ILogger _logger; diff --git a/test/Microsoft.Azure.SignalR.Tests/Utils.cs b/test/Microsoft.Azure.SignalR.Tests/Utils.cs index 1be204c0f..c2ed89f93 100644 --- a/test/Microsoft.Azure.SignalR.Tests/Utils.cs +++ b/test/Microsoft.Azure.SignalR.Tests/Utils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -7,12 +7,12 @@ namespace Microsoft.Azure.SignalR.Tests { - internal class Utils + internal sealed class Utils { public static async Task PollWait(Func pollFunc, int count = 5) { - bool result = false; - int times = 0; + var result = false; + var times = 0; while (!result) { times++;