From a7d529a1d5df50b358e807be7ec68451306341f2 Mon Sep 17 00:00:00 2001 From: Tomasz Maruszak Date: Thu, 23 Jan 2025 23:11:34 +0100 Subject: [PATCH] Cleanup Signed-off-by: Tomasz Maruszak --- src/.editorconfig | 3 + .../CircuitBreakerConsumerInterceptor.cs | 36 ++++++++- .../Services/OutboxLockRenewalTimerFactory.cs | 2 +- ...mMessageBus.Host.Serialization.Avro.csproj | 2 +- .../GoogleProtobufMessageSerializer.cs | 8 +- ...s.Host.Serialization.GoogleProtobuf.csproj | 2 +- ...essageBus.Host.Serialization.Hybrid.csproj | 2 +- .../JsonMessageSerializer.cs | 74 ++++++++++++++++--- ...mMessageBus.Host.Serialization.Json.csproj | 2 +- ...s.Host.Serialization.SystemTextJson.csproj | 2 +- .../SqlHelper.cs | 35 ++++++++- .../MessageProcessors/MessageHandler.cs | 4 +- .../ResponseMessageProcessor.cs | 1 - src/SlimMessageBus.Host/MessageBusBase.cs | 1 + .../ConsumerBuilderTest.cs | 50 ++++++------- .../HandlerBuilderTest.cs | 12 +-- .../TypeCollectionTests.cs | 6 +- .../HybridTests.cs | 4 +- .../JsonMessageSerializerTests.cs | 22 +++--- .../JsonMessageSerializerTests.cs | 22 +++--- .../Collections/RuntimeTypeCacheTests.cs | 13 +--- 21 files changed, 202 insertions(+), 101 deletions(-) diff --git a/src/.editorconfig b/src/.editorconfig index 53489ab9..2cc329eb 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -103,6 +103,8 @@ csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent csharp_style_prefer_primary_constructors = true:suggestion +csharp_prefer_system_threading_lock = true:suggestion +dotnet_diagnostic.xUnit1045.severity = silent [*.{cs,vb}] #### Naming styles #### @@ -186,6 +188,7 @@ dotnet_style_qualification_for_event = false:suggestion dotnet_diagnostic.VSTHRD200.severity = none # not supported by .netstandard2.0 dotnet_diagnostic.CA1510.severity = none +dotnet_diagnostic.CA1512.severity = none [*.{csproj,xml}] indent_style = space diff --git a/src/SlimMessageBus.Host.CircuitBreaker/Implementation/CircuitBreakerConsumerInterceptor.cs b/src/SlimMessageBus.Host.CircuitBreaker/Implementation/CircuitBreakerConsumerInterceptor.cs index 1a059661..40ad3ec4 100644 --- a/src/SlimMessageBus.Host.CircuitBreaker/Implementation/CircuitBreakerConsumerInterceptor.cs +++ b/src/SlimMessageBus.Host.CircuitBreaker/Implementation/CircuitBreakerConsumerInterceptor.cs @@ -3,8 +3,10 @@ /// /// Circuit breaker to toggle consumer status on an external events. /// -internal sealed class CircuitBreakerConsumerInterceptor(ILogger logger) : IAbstractConsumerInterceptor +internal sealed partial class CircuitBreakerConsumerInterceptor(ILogger logger) : IAbstractConsumerInterceptor { + private readonly ILogger _logger = logger; + public int Order => 100; public async Task CanStart(AbstractConsumer consumer) @@ -33,12 +35,12 @@ async Task BreakerChanged(Circuit state) var bus = consumer.Settings[0].MessageBusSettings.Name ?? "default"; if (shouldPause) { - logger.LogWarning("Circuit breaker tripped for '{Path}' on '{Bus}' bus. Consumer paused.", path, bus); + LogCircuitTripped(path, bus); await consumer.DoStop().ConfigureAwait(false); } else { - logger.LogInformation("Circuit breaker restored for '{Path}' on '{Bus}' bus. Consumer resumed.", path, bus); + LogCircuitRestored(path, bus); await consumer.DoStart().ConfigureAwait(false); } consumer.SetIsPaused(shouldPause); @@ -89,4 +91,32 @@ public async Task CanStop(AbstractConsumer consumer) public Task Started(AbstractConsumer consumer) => Task.CompletedTask; public Task Stopped(AbstractConsumer consumer) => Task.CompletedTask; + + #region Logging + + [LoggerMessage( + EventId = 0, + Level = LogLevel.Warning, + Message = "Circuit breaker tripped for '{Path}' on '{Bus}' bus. Consumer paused.")] + private partial void LogCircuitTripped(string path, string bus); + + [LoggerMessage( + EventId = 1, + Level = LogLevel.Information, + Message = "Circuit breaker restored for '{Path}' on '{Bus}' bus. Consumer resumed.")] + private partial void LogCircuitRestored(string path, string bus); + + #endregion +} + +#if NETSTANDARD2_0 + +partial class CircuitBreakerConsumerInterceptor +{ + private partial void LogCircuitTripped(string path, string bus) + => _logger.LogWarning("Circuit breaker tripped for '{Path}' on '{Bus}' bus. Consumer paused.", path, bus); + + private partial void LogCircuitRestored(string path, string bus) + => _logger.LogInformation("Circuit breaker restored for '{Path}' on '{Bus}' bus. Consumer resumed.", path, bus); } +#endif \ No newline at end of file diff --git a/src/SlimMessageBus.Host.Outbox/Services/OutboxLockRenewalTimerFactory.cs b/src/SlimMessageBus.Host.Outbox/Services/OutboxLockRenewalTimerFactory.cs index 56254736..4bef2a4d 100644 --- a/src/SlimMessageBus.Host.Outbox/Services/OutboxLockRenewalTimerFactory.cs +++ b/src/SlimMessageBus.Host.Outbox/Services/OutboxLockRenewalTimerFactory.cs @@ -9,7 +9,7 @@ public class OutboxLockRenewalTimerFactory(IS private bool _isDisposed = false; public IOutboxLockRenewalTimer CreateRenewalTimer(TimeSpan lockDuration, TimeSpan interval, Action lockLost, CancellationToken cancellationToken) - => (OutboxLockRenewalTimer)ActivatorUtilities.CreateInstance(_scope.ServiceProvider, typeof(OutboxLockRenewalTimer), lockDuration, interval, lockLost, cancellationToken); + => ActivatorUtilities.CreateInstance>(_scope.ServiceProvider); public async ValueTask DisposeAsync() { diff --git a/src/SlimMessageBus.Host.Serialization.Avro/SlimMessageBus.Host.Serialization.Avro.csproj b/src/SlimMessageBus.Host.Serialization.Avro/SlimMessageBus.Host.Serialization.Avro.csproj index bcf8a4b3..0986f359 100644 --- a/src/SlimMessageBus.Host.Serialization.Avro/SlimMessageBus.Host.Serialization.Avro.csproj +++ b/src/SlimMessageBus.Host.Serialization.Avro/SlimMessageBus.Host.Serialization.Avro.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/GoogleProtobufMessageSerializer.cs b/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/GoogleProtobufMessageSerializer.cs index 997c8386..1d48bd9e 100644 --- a/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/GoogleProtobufMessageSerializer.cs +++ b/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/GoogleProtobufMessageSerializer.cs @@ -15,10 +15,8 @@ public GoogleProtobufMessageSerializer(ILoggerFactory loggerFactory, IMessagePar _messageParserFactory = messageParserFactory ?? new MessageParserFactory(); } - public byte[] Serialize(Type t, object message) - { - return ((IMessage)message).ToByteArray(); - } + public byte[] Serialize(Type t, object message) + => ((IMessage)message).ToByteArray(); public object Deserialize(Type t, byte[] payload) { @@ -31,7 +29,7 @@ public object Deserialize(Type t, byte[] payload) BindingFlags.Instance, null, messageParser, - new object[] { payload }); + [payload]); return message; } diff --git a/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/SlimMessageBus.Host.Serialization.GoogleProtobuf.csproj b/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/SlimMessageBus.Host.Serialization.GoogleProtobuf.csproj index 897a3c2e..822fc28c 100644 --- a/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/SlimMessageBus.Host.Serialization.GoogleProtobuf.csproj +++ b/src/SlimMessageBus.Host.Serialization.GoogleProtobuf/SlimMessageBus.Host.Serialization.GoogleProtobuf.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/SlimMessageBus.Host.Serialization.Hybrid/SlimMessageBus.Host.Serialization.Hybrid.csproj b/src/SlimMessageBus.Host.Serialization.Hybrid/SlimMessageBus.Host.Serialization.Hybrid.csproj index df179d57..c769784c 100644 --- a/src/SlimMessageBus.Host.Serialization.Hybrid/SlimMessageBus.Host.Serialization.Hybrid.csproj +++ b/src/SlimMessageBus.Host.Serialization.Hybrid/SlimMessageBus.Host.Serialization.Hybrid.csproj @@ -16,7 +16,7 @@ - + diff --git a/src/SlimMessageBus.Host.Serialization.Json/JsonMessageSerializer.cs b/src/SlimMessageBus.Host.Serialization.Json/JsonMessageSerializer.cs index c3998f70..de4d9930 100644 --- a/src/SlimMessageBus.Host.Serialization.Json/JsonMessageSerializer.cs +++ b/src/SlimMessageBus.Host.Serialization.Json/JsonMessageSerializer.cs @@ -7,7 +7,7 @@ namespace SlimMessageBus.Host.Serialization.Json; using Newtonsoft.Json; -public class JsonMessageSerializer : IMessageSerializer, IMessageSerializer +public partial class JsonMessageSerializer : IMessageSerializer, IMessageSerializer { private readonly ILogger _logger; private readonly Encoding _encoding; @@ -30,10 +30,10 @@ public JsonMessageSerializer() public byte[] Serialize(Type t, object message) { var jsonPayload = JsonConvert.SerializeObject(message, t, _serializerSettings); - _logger.LogDebug("Type {MessageType} serialized from {Message} to JSON {MessageJson}", t, message, jsonPayload); + LogSerialized(t, message, jsonPayload); return _encoding.GetBytes(jsonPayload); - } - + } + public object Deserialize(Type t, byte[] payload) { var jsonPayload = string.Empty; @@ -44,7 +44,11 @@ public object Deserialize(Type t, byte[] payload) } catch (Exception e) { - _logger.LogError(e, "Type {MessageType} could not been deserialized, payload: {MessagePayload}, JSON: {MessageJson}", t, _logger.IsEnabled(LogLevel.Debug) ? Convert.ToBase64String(payload) : "(...)", jsonPayload); + var base64Payload = _logger.IsEnabled(LogLevel.Debug) + ? Convert.ToBase64String(payload) + : "(...)"; + + LogDeserializationFailed(t, jsonPayload, base64Payload, e); throw; } } @@ -56,16 +60,66 @@ public object Deserialize(Type t, byte[] payload) string IMessageSerializer.Serialize(Type t, object message) { var payload = JsonConvert.SerializeObject(message, t, _serializerSettings); - _logger.LogDebug("Type {MessageType} serialized from {Message} to JSON {MessageJson}", t, message, payload); + LogSerialized(t, message, payload); return payload; } public object Deserialize(Type t, string payload) { - var message = JsonConvert.DeserializeObject(payload, t, _serializerSettings); - _logger.LogDebug("Type {MessageType} deserialized from JSON {MessageJson} to {Message}", t, payload, message); - return message; + try + { + var message = JsonConvert.DeserializeObject(payload, t, _serializerSettings); + LogDeserializedFromString(t, payload, message); + return message; + } + catch (Exception e) + { + LogDeserializationFailed(t, payload, string.Empty, e); + throw; + } } + #endregion + + #region Logging + +#if !NETSTANDARD2_0 + + [LoggerMessage( + EventId = 0, + Level = LogLevel.Debug, + Message = "Type {MessageType} serialized from {Message} to JSON {MessageJson}")] + private partial void LogSerialized(Type messageType, object message, string messageJson); + + [LoggerMessage( + EventId = 1, + Level = LogLevel.Debug, + Message = "Type {MessageType} deserialized from JSON {MessageJson} to {Message}")] + private partial void LogDeserializedFromString(Type messageType, string messageJson, object message); + + [LoggerMessage( + EventId = 2, + Level = LogLevel.Error, + Message = "Type {MessageType} could not been deserialized, payload: {MessagePayload}, JSON: {MessageJson}")] + private partial void LogDeserializationFailed(Type messageType, string messageJson, string messagePayload, Exception e); + +#endif + #endregion -} \ No newline at end of file +} + +#if NETSTANDARD2_0 + +public partial class JsonMessageSerializer +{ + private void LogSerialized(Type messageType, object message, string messageJson) + => _logger.LogDebug("Type {MessageType} serialized from {Message} to JSON {MessageJson}", messageType, message, messageJson); + + private void LogDeserializedFromString(Type messageType, string messageJson, object message) + => _logger.LogDebug("Type {MessageType} deserialized from JSON {MessageJson} to {Message}", messageType, messageJson, message); + + private void LogDeserializationFailed(Type messageType, string messageJson, string messagePayload, Exception e) + => _logger.LogError(e, "Type {MessageType} could not been deserialized, payload: {MessagePayload}, JSON: {MessageJson}", messageType, messagePayload, messageJson); +} + +#endif \ No newline at end of file diff --git a/src/SlimMessageBus.Host.Serialization.Json/SlimMessageBus.Host.Serialization.Json.csproj b/src/SlimMessageBus.Host.Serialization.Json/SlimMessageBus.Host.Serialization.Json.csproj index 4f91f6b7..d0d77129 100644 --- a/src/SlimMessageBus.Host.Serialization.Json/SlimMessageBus.Host.Serialization.Json.csproj +++ b/src/SlimMessageBus.Host.Serialization.Json/SlimMessageBus.Host.Serialization.Json.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/SlimMessageBus.Host.Serialization.SystemTextJson/SlimMessageBus.Host.Serialization.SystemTextJson.csproj b/src/SlimMessageBus.Host.Serialization.SystemTextJson/SlimMessageBus.Host.Serialization.SystemTextJson.csproj index fb72242a..1287d0c1 100644 --- a/src/SlimMessageBus.Host.Serialization.SystemTextJson/SlimMessageBus.Host.Serialization.SystemTextJson.csproj +++ b/src/SlimMessageBus.Host.Serialization.SystemTextJson/SlimMessageBus.Host.Serialization.SystemTextJson.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/SlimMessageBus.Host.Sql.Common/SqlHelper.cs b/src/SlimMessageBus.Host.Sql.Common/SqlHelper.cs index bcd7d1cb..47865ebd 100644 --- a/src/SlimMessageBus.Host.Sql.Common/SqlHelper.cs +++ b/src/SlimMessageBus.Host.Sql.Common/SqlHelper.cs @@ -3,7 +3,7 @@ using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; -public static class SqlHelper +public static partial class SqlHelper { private static readonly HashSet TransientErrorNumbers = [ @@ -20,7 +20,7 @@ public static async Task RetryIfError(ILogger logger, SqlRetry { if (tries > 1) { - logger.LogInformation("SQL error encountered. Will begin attempt number {SqlRetryNumber} of {SqlRetryCount} max...", tries, retrySettings.RetryCount); + LogSqlError(logger, retrySettings.RetryCount, tries); await Task.Delay(nextRetryInterval, token); nextRetryInterval = nextRetryInterval.Multiply(retrySettings.RetryIntervalFactor); } @@ -36,7 +36,7 @@ public static async Task RetryIfError(ILogger logger, SqlRetry } // transient SQL error - continue trying lastTransientException = sqlEx; - logger.LogDebug(sqlEx, "SQL error occurred {SqlErrorCode}. Will retry operation", sqlEx.Number); + LogWillRetry(logger, sqlEx.Number, sqlEx); } } throw lastTransientException; @@ -47,4 +47,33 @@ public static Task RetryIfTransientError(ILogger logger, SqlRe public static Task RetryIfTransientError(ILogger logger, SqlRetrySettings retrySettings, Func operation, CancellationToken token) => RetryIfTransientError(logger, retrySettings, async () => { await operation(); return null; }, token); + + #region Logging + + [LoggerMessage( + EventId = 0, + Level = LogLevel.Information, + Message = "SQL error encountered. Will begin attempt number {SqlRetryNumber} of {SqlRetryCount} max...")] + private static partial void LogSqlError(ILogger logger, int sqlRetryCount, int sqlRetryNumber); + + [LoggerMessage( + EventId = 1, + Level = LogLevel.Debug, + Message = "SQL error occurred {SqlErrorCode}. Will retry operation")] + private static partial void LogWillRetry(ILogger logger, int sqlErrorCode, SqlException e); + + #endregion +} + +#if NETSTANDARD2_0 + +partial class SqlHelper +{ + private static partial void LogSqlError(ILogger logger, int sqlRetryCount, int sqlRetryNumber) + => logger.LogInformation("SQL error encountered. Will begin attempt number {SqlRetryNumber} of {SqlRetryCount} max...", sqlRetryNumber, sqlRetryCount); + + private static partial void LogWillRetry(ILogger logger, int sqlErrorCode, SqlException e) + => logger.LogDebug(e, "SQL error occurred {SqlErrorCode}. Will retry operation", sqlErrorCode); } + +#endif \ No newline at end of file diff --git a/src/SlimMessageBus.Host/Consumer/MessageProcessors/MessageHandler.cs b/src/SlimMessageBus.Host/Consumer/MessageProcessors/MessageHandler.cs index e785d199..393ddcac 100644 --- a/src/SlimMessageBus.Host/Consumer/MessageProcessors/MessageHandler.cs +++ b/src/SlimMessageBus.Host/Consumer/MessageProcessors/MessageHandler.cs @@ -104,7 +104,7 @@ public MessageHandler( catch (Exception ex) { attempts++; - var handleErrorResult = await DoHandleError(message, messageType, messageScope, consumerContext, ex, attempts, cancellationToken).ConfigureAwait(false); + var handleErrorResult = await DoHandleError(message, messageType, messageScope, consumerContext, ex, attempts).ConfigureAwait(false); if (handleErrorResult is ProcessResult.RetryState) { continue; @@ -144,7 +144,7 @@ private async Task DoHandleInternal(object message, IMessageTypeConsumer return await ExecuteConsumer(message, consumerContext, consumerInvoker, responseType).ConfigureAwait(false); } - private async Task DoHandleError(object message, Type messageType, IMessageScope messageScope, IConsumerContext consumerContext, Exception ex, int attempts, CancellationToken cancellationToken) + private async Task DoHandleError(object message, Type messageType, IMessageScope messageScope, IConsumerContext consumerContext, Exception ex, int attempts) { var errorHandlerResult = ProcessResult.Failure; diff --git a/src/SlimMessageBus.Host/Consumer/MessageProcessors/ResponseMessageProcessor.cs b/src/SlimMessageBus.Host/Consumer/MessageProcessors/ResponseMessageProcessor.cs index b1f02b40..6f68faa1 100644 --- a/src/SlimMessageBus.Host/Consumer/MessageProcessors/ResponseMessageProcessor.cs +++ b/src/SlimMessageBus.Host/Consumer/MessageProcessors/ResponseMessageProcessor.cs @@ -69,7 +69,6 @@ private Exception OnResponseArrived(TTransportMessage transportMessage, string p if (requestState == null) { LogResponseWillBeDiscarded(path, requestId); - // ToDo: add and API hook to these kind of situation return null; } diff --git a/src/SlimMessageBus.Host/MessageBusBase.cs b/src/SlimMessageBus.Host/MessageBusBase.cs index 827bf499..3199a90d 100644 --- a/src/SlimMessageBus.Host/MessageBusBase.cs +++ b/src/SlimMessageBus.Host/MessageBusBase.cs @@ -760,6 +760,7 @@ public virtual IMessageScope CreateMessageScope(ConsumerSettings consumerSetting } #if NETSTANDARD2_0 + public abstract partial class MessageBusBase { private partial void LogCouldNotStartConsumers(Exception ex) diff --git a/src/Tests/SlimMessageBus.Host.Configuration.Test/ConsumerBuilderTest.cs b/src/Tests/SlimMessageBus.Host.Configuration.Test/ConsumerBuilderTest.cs index 19d8c1fe..378d28f6 100644 --- a/src/Tests/SlimMessageBus.Host.Configuration.Test/ConsumerBuilderTest.cs +++ b/src/Tests/SlimMessageBus.Host.Configuration.Test/ConsumerBuilderTest.cs @@ -22,7 +22,7 @@ public void Given_MessageType_When_Configured_Then_MessageType_ProperlySet_And_C // assert subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.Consumer); subject.ConsumerSettings.ConsumerType.Should().BeNull(); - subject.ConsumerSettings.MessageType.Should().Be(typeof(SomeMessage)); + subject.ConsumerSettings.MessageType.Should().Be(); } [Theory] @@ -95,36 +95,36 @@ public void Given_BaseMessageType_And_ItsHierarchy_When_WithConsumer_ForTheBaseT subject.ConsumerSettings.ResponseType.Should().BeNull(); subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.Consumer); - subject.ConsumerSettings.ConsumerType.Should().Be(typeof(BaseMessageConsumer)); + subject.ConsumerSettings.ConsumerType.Should().Be(); Func call = () => subject.ConsumerSettings.ConsumerMethod(new BaseMessageConsumer(), new BaseMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(BaseMessage)); subject.ConsumerSettings.Invokers.Count.Should().Be(4); var consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(BaseMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(BaseMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(BaseMessageConsumer)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new BaseMessageConsumer(), new BaseMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(BaseMessage)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(DerivedAMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(DerivedAMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(DerivedAMessageConsumer)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new DerivedAMessageConsumer(), new DerivedAMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(DerivedAMessage)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(DerivedBMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(DerivedBMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(DerivedBMessageConsumer)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new DerivedBMessageConsumer(), new DerivedBMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(DerivedBMessage)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(Derived2AMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(Derived2AMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(Derived2AMessageConsumer)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new Derived2AMessageConsumer(), new Derived2AMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(Derived2AMessage)); @@ -149,36 +149,36 @@ public void Given_BaseMessageType_And_ItsHierarchy_And_ConsumerOfContext_When_Wi subject.ConsumerSettings.ResponseType.Should().BeNull(); subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.Consumer); - subject.ConsumerSettings.ConsumerType.Should().Be(typeof(BaseMessageConsumerOfContext)); + subject.ConsumerSettings.ConsumerType.Should().Be(); Func call = () => subject.ConsumerSettings.ConsumerMethod(new BaseMessageConsumerOfContext(), new BaseMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(BaseMessage)); subject.ConsumerSettings.Invokers.Count.Should().Be(4); var consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(BaseMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(BaseMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(BaseMessageConsumerOfContext)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new BaseMessageConsumerOfContext(), new BaseMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(BaseMessage)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(DerivedAMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(DerivedAMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(DerivedAMessageConsumerOfContext)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new DerivedAMessageConsumerOfContext(), new DerivedAMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(DerivedAMessage)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(DerivedBMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(DerivedBMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(DerivedBMessageConsumerOfContext)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new DerivedBMessageConsumerOfContext(), new DerivedBMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(DerivedBMessage)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(Derived2AMessage)); - consumerInvokerSettings.MessageType.Should().Be(typeof(Derived2AMessage)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(Derived2AMessageConsumerOfContext)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new Derived2AMessageConsumerOfContext(), new Derived2AMessage(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(Derived2AMessage)); @@ -198,25 +198,25 @@ public void Given_BaseRequestType_And_ItsHierarchy_When_WithConsumer_ForTheBaseT .WithConsumer(); // assert - subject.ConsumerSettings.ResponseType.Should().Be(typeof(BaseResponse)); + subject.ConsumerSettings.ResponseType.Should().Be(); subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.Consumer); - subject.ConsumerSettings.ConsumerType.Should().Be(typeof(BaseRequestConsumer)); + subject.ConsumerSettings.ConsumerType.Should().Be(); Func call = () => subject.ConsumerSettings.ConsumerMethod(new BaseRequestConsumer(), new BaseRequest(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(BaseRequest)); subject.ConsumerSettings.Invokers.Count.Should().Be(2); var consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(BaseRequest)); - consumerInvokerSettings.MessageType.Should().Be(typeof(BaseRequest)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(BaseRequestConsumer)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new BaseRequestConsumer(), new BaseRequest(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(BaseRequest)); consumerInvokerSettings = subject.ConsumerSettings.Invokers.Single(x => x.MessageType == typeof(DerivedRequest)); - consumerInvokerSettings.MessageType.Should().Be(typeof(DerivedRequest)); - consumerInvokerSettings.ConsumerType.Should().Be(typeof(DerivedRequestConsumer)); + consumerInvokerSettings.MessageType.Should().Be(); + consumerInvokerSettings.ConsumerType.Should().Be(); consumerInvokerSettings.ParentSettings.Should().BeSameAs(subject.ConsumerSettings); call = () => consumerInvokerSettings.ConsumerMethod(new DerivedRequestConsumer(), new DerivedRequest(), consumerContextMock.Object, consumerContextMock.Object.CancellationToken); call.Should().ThrowAsync().WithMessage(nameof(DerivedRequest)); diff --git a/src/Tests/SlimMessageBus.Host.Configuration.Test/HandlerBuilderTest.cs b/src/Tests/SlimMessageBus.Host.Configuration.Test/HandlerBuilderTest.cs index 82e95fed..4e305534 100644 --- a/src/Tests/SlimMessageBus.Host.Configuration.Test/HandlerBuilderTest.cs +++ b/src/Tests/SlimMessageBus.Host.Configuration.Test/HandlerBuilderTest.cs @@ -20,8 +20,8 @@ public void When_Created_Given_RequestAndResposeType_Then_MessageType_And_Respon var subject = new HandlerBuilder(_messageBusSettings); // assert - subject.ConsumerSettings.MessageType.Should().Be(typeof(SomeRequest)); - subject.ConsumerSettings.ResponseType.Should().Be(typeof(SomeResponse)); + subject.ConsumerSettings.MessageType.Should().Be(); + subject.ConsumerSettings.ResponseType.Should().Be(); subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.RequestResponse); subject.ConsumerSettings.ConsumerType.Should().BeNull(); subject.ConsumerSettings.Invokers.Should().BeEmpty(); @@ -34,7 +34,7 @@ public void When_Created_Given_RequestWithoutResposeType_Then_MessageType_And_De var subject = new HandlerBuilder(_messageBusSettings); // assert - subject.ConsumerSettings.MessageType.Should().Be(typeof(SomeRequestWithoutResponse)); + subject.ConsumerSettings.MessageType.Should().Be(); subject.ConsumerSettings.ResponseType.Should().BeNull(); subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.RequestResponse); subject.ConsumerSettings.ConsumerType.Should().BeNull(); @@ -101,14 +101,14 @@ public void When_Configured_Given_RequestResponse_Then_ProperSettings(bool ofCon } // assert - subject.ConsumerSettings.MessageType.Should().Be(typeof(SomeRequest)); + subject.ConsumerSettings.MessageType.Should().Be(); subject.ConsumerSettings.Path.Should().Be(_path); subject.ConsumerSettings.Instances.Should().Be(3); subject.ConsumerSettings.ConsumerType.Should().Be(consumerType); subject.ConsumerSettings.ConsumerMode.Should().Be(ConsumerMode.RequestResponse); - subject.ConsumerSettings.ResponseType.Should().Be(typeof(SomeResponse)); + subject.ConsumerSettings.ResponseType.Should().Be(); subject.ConsumerSettings.Invokers.Count.Should().Be(2); @@ -153,7 +153,7 @@ public void When_Configured_Given_RequestWithoutResponse_And_HandlersWithDerived } // assert - subject.ConsumerSettings.MessageType.Should().Be(typeof(SomeRequestWithoutResponse)); + subject.ConsumerSettings.MessageType.Should().Be(); subject.ConsumerSettings.Path.Should().Be(_path); subject.ConsumerSettings.Instances.Should().Be(3); diff --git a/src/Tests/SlimMessageBus.Host.Configuration.Test/TypeCollectionTests.cs b/src/Tests/SlimMessageBus.Host.Configuration.Test/TypeCollectionTests.cs index 0a8ff343..ca296748 100644 --- a/src/Tests/SlimMessageBus.Host.Configuration.Test/TypeCollectionTests.cs +++ b/src/Tests/SlimMessageBus.Host.Configuration.Test/TypeCollectionTests.cs @@ -9,7 +9,7 @@ public void Add_Should_AddTypeToCollection_IfAssignableToGeneric() var collection = new TypeCollection(); // Act - collection.Add(typeof(SampleClass)); + collection.Add(); // Assert collection.Count.Should().Be(1); @@ -37,7 +37,7 @@ public void Add_Should_ThrowException_WhenTypeIsAssignableToGenericButAlreadyExi collection.Add(); // Act - Action act = () => collection.Add(typeof(SampleClass)); + Action act = () => collection.Add(); // Assert act.Should().Throw().WithMessage("Type already exists in the collection. (Parameter 'type')"); @@ -169,7 +169,7 @@ public void Remove_Should_RemoveTypeFromCollection_WhenSuppliedAsType() collection.Add(); // Act - var removed = collection.Remove(typeof(SampleClass)); + var removed = collection.Remove(); // Assert removed.Should().BeTrue(); diff --git a/src/Tests/SlimMessageBus.Host.Integration.Test/HybridTests.cs b/src/Tests/SlimMessageBus.Host.Integration.Test/HybridTests.cs index cc0cd751..a44c1198 100644 --- a/src/Tests/SlimMessageBus.Host.Integration.Test/HybridTests.cs +++ b/src/Tests/SlimMessageBus.Host.Integration.Test/HybridTests.cs @@ -115,12 +115,12 @@ public async Task When_PublishToMemoryBus_Given_InsideConsumerWithMessageScope_T // all the internal messages should be processed by Memory bus store .Where(x => x.Name == nameof(InternalMessageConsumer) || x.Name == nameof(InternalMessageConsumerInterceptor) || x.Name == nameof(InternalMessageProducerInterceptor) || x.Name == nameof(InternalMessagePublishInterceptor)) - .Should().AllSatisfy(x => x.ContextMessageBusType.Should().Be(typeof(MemoryMessageBus))); + .Should().AllSatisfy(x => x.ContextMessageBusType.Should().Be()); // all the external messages should be processed by Azure Service Bus store .Where(x => x.Name == nameof(ExternalMessageConsumer) || x.Name == nameof(ExternalMessageConsumerInterceptor)) - .Should().AllSatisfy(x => x.ContextMessageBusType.Should().Be(typeof(ServiceBusMessageBus))); + .Should().AllSatisfy(x => x.ContextMessageBusType.Should().Be()); // in this order var eventsThatHappenedWhenExternalWasPublished = grouping.Values.SingleOrDefault(x => x.Count == 2); diff --git a/src/Tests/SlimMessageBus.Host.Serialization.Json.Test/JsonMessageSerializerTests.cs b/src/Tests/SlimMessageBus.Host.Serialization.Json.Test/JsonMessageSerializerTests.cs index 0a237e38..41098586 100644 --- a/src/Tests/SlimMessageBus.Host.Serialization.Json.Test/JsonMessageSerializerTests.cs +++ b/src/Tests/SlimMessageBus.Host.Serialization.Json.Test/JsonMessageSerializerTests.cs @@ -4,20 +4,16 @@ namespace SlimMessageBus.Host.Serialization.Json.Test; public class JsonMessageSerializerTests { - public static IEnumerable Data => - [ - [null, null], - [10, 10], - [false, false], - [true, true], - ["string", "string"], - [DateTime.Now.Date, DateTime.Now.Date], - [Guid.Empty, "00000000-0000-0000-0000-000000000000"], - ]; - - public JsonMessageSerializerTests() + public static TheoryData Data => new() { - } + { null, null }, + { 10, 10 }, + { false, false }, + { true, true}, + { "string", "string"}, + { DateTime.Now.Date, DateTime.Now.Date}, + { Guid.Empty, "00000000-0000-0000-0000-000000000000"}, + }; [Theory] [MemberData(nameof(Data))] diff --git a/src/Tests/SlimMessageBus.Host.Serialization.SystemTextJson.Test/JsonMessageSerializerTests.cs b/src/Tests/SlimMessageBus.Host.Serialization.SystemTextJson.Test/JsonMessageSerializerTests.cs index b4af80c1..0423ef30 100644 --- a/src/Tests/SlimMessageBus.Host.Serialization.SystemTextJson.Test/JsonMessageSerializerTests.cs +++ b/src/Tests/SlimMessageBus.Host.Serialization.SystemTextJson.Test/JsonMessageSerializerTests.cs @@ -2,16 +2,16 @@ namespace SlimMessageBus.Host.Serialization.SystemTextJson.Test; public class JsonMessageSerializerTests { - public static IEnumerable Data => - [ - [null, null], - [10, 10], - [false, false], - [true, true], - ["string", "string"], - [DateTime.Now.Date, DateTime.Now.Date], - [Guid.Empty, "00000000-0000-0000-0000-000000000000"], - ]; + public static TheoryData Data => new() + { + { null, null}, + { 10, 10}, + { false, false}, + { true, true}, + { "string", "string"}, + { DateTime.Now.Date, DateTime.Now.Date}, + { Guid.Empty, "00000000-0000-0000-0000-000000000000"}, + }; [Theory] [MemberData(nameof(Data))] @@ -58,7 +58,7 @@ public void When_RegisterSerializer_Then_UsesOptionsFromContainerIfAvailable(boo // Simulate the options have been used in an serializer already (see https://github.com/zarusz/SlimMessageBus/issues/252) // Modifying options (adding converters) when the options are already in use by a serializer will throw an exception: System.InvalidOperationException : This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization. - JsonSerializer.SerializeToUtf8Bytes(new Dictionary(), typeof(Dictionary), jsonOptions); + JsonSerializer.SerializeToUtf8Bytes(new Dictionary(), jsonOptions); if (jsonOptionComeFromContainer) { diff --git a/src/Tests/SlimMessageBus.Host.Test/Collections/RuntimeTypeCacheTests.cs b/src/Tests/SlimMessageBus.Host.Test/Collections/RuntimeTypeCacheTests.cs index d412d632..3ac15e98 100644 --- a/src/Tests/SlimMessageBus.Host.Test/Collections/RuntimeTypeCacheTests.cs +++ b/src/Tests/SlimMessageBus.Host.Test/Collections/RuntimeTypeCacheTests.cs @@ -5,13 +5,8 @@ public class RuntimeTypeCacheTests { - private readonly RuntimeTypeCache _subject; + private readonly RuntimeTypeCache _subject = new(); - public RuntimeTypeCacheTests() - { - _subject = new RuntimeTypeCache(); - } - [Theory] [InlineData(typeof(bool), typeof(int), false)] [InlineData(typeof(SomeMessageConsumer), typeof(IConsumer), true)] @@ -86,13 +81,9 @@ public void When_GetClosedGenericType(Type openGenericType, Type genericParamete public static TheoryData Data => new() { { (new SomeMessage[] { new() }).Concat([new SomeMessage()]), true }, - { new List { new(), new() }, true }, - { new SomeMessage[] { new(), new() }, true}, - { new HashSet { new(), new() }, true }, - { new object(), false }, }; @@ -109,7 +100,7 @@ public void Given_ObjectThatIsCollection_When_Then(object collection, bool isCol if (isCollection) { collectionInfo.Should().NotBeNull(); - collectionInfo.ItemType.Should().Be(typeof(SomeMessage)); + collectionInfo.ItemType.Should().Be(); var col = collectionInfo.ToCollection(collection); col.Should().NotBeNull(); col.Should().BeSameAs((IEnumerable)collection);