diff --git a/.editorconfig b/.editorconfig index 1fa8e4eda..a4ab039e2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -33,7 +33,6 @@ csharp_new_line_before_open_brace=all csharp_preferred_modifier_order=public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion csharp_space_after_keywords_in_control_flow_statements=true csharp_style_namespace_declarations = file_scoped:warning -csharp_style_var_elsewhere=false:suggestion csharp_style_var_for_built_in_types=false:suggestion csharp_style_var_when_type_is_apparent=true:suggestion dotnet_naming_rule.private_constants_rule.severity=warning diff --git a/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs b/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs index 09d5b74d2..50d2bcca1 100644 --- a/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs +++ b/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs @@ -7,25 +7,14 @@ namespace JustSaying.Sample.Middleware; /// /// A background service responsible for starting the JustSaying message bus and publisher. /// -public class JustSayingService : IHostedService +public class JustSayingService(IMessagingBus bus, IMessagePublisher publisher, ILogger logger) : IHostedService { - private readonly IMessagingBus _bus; - private readonly IMessagePublisher _publisher; - private readonly ILogger _logger; - - public JustSayingService(IMessagingBus bus, IMessagePublisher publisher, ILogger logger) - { - _bus = bus; - _publisher = publisher; - _logger = logger; - } - public async Task StartAsync(CancellationToken cancellationToken) { - await _bus.StartAsync(cancellationToken); - await _publisher.StartAsync(cancellationToken); + await bus.StartAsync(cancellationToken); + await publisher.StartAsync(cancellationToken); - _logger.LogInformation("Message bus and publisher have started successfully"); + logger.LogInformation("Message bus and publisher have started successfully"); } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs b/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs index 3a214dec6..3c70a3f3e 100644 --- a/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs +++ b/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs @@ -1,4 +1,4 @@ -using JustSaying.Messaging.Middleware; +using JustSaying.Messaging.Middleware; using Serilog; namespace JustSaying.Sample.Middleware.Middlewares; @@ -6,18 +6,11 @@ namespace JustSaying.Sample.Middleware.Middlewares; /// /// A middleware that will output a log message before and after a message has passed through it. /// -public class EchoJustSayingMiddleware : MiddlewareBase +public class EchoJustSayingMiddleware(string name) : MiddlewareBase { - private readonly string _name; - - public EchoJustSayingMiddleware(string name) - { - _name = name; - } - protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { - Log.Information("[{MiddlewareName}] Starting {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), _name, context.Message.GetType().Name); + Log.Information("[{MiddlewareName}] Starting {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), name, context.Message.GetType().Name); try { @@ -25,7 +18,7 @@ protected override async Task RunInnerAsync(HandleMessageContext context, } finally { - Log.Information("[{MiddlewareName}] Ending {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), _name, context.Message.GetType().Name); + Log.Information("[{MiddlewareName}] Ending {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), name, context.Message.GetType().Name); } } } diff --git a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs index 2736a9c30..4054d5e99 100644 --- a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs +++ b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs @@ -8,24 +8,13 @@ namespace JustSaying.Sample.Restaurant.KitchenConsole; /// A background service responsible for starting the bus which listens for /// messages on the configured queues /// -public class Subscriber : BackgroundService +public class Subscriber(IMessagingBus bus, ILogger logger, IMessagePublisher publisher) : BackgroundService { - private readonly IMessagingBus _bus; - private readonly ILogger _logger; - private readonly IMessagePublisher _publisher; - - public Subscriber(IMessagingBus bus, ILogger logger, IMessagePublisher publisher) - { - _bus = bus; - _logger = logger; - _publisher = publisher; - } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - _logger.LogInformation("Kitchen subscriber running"); + logger.LogInformation("Kitchen subscriber running"); - await _bus.StartAsync(stoppingToken); - await _publisher.StartAsync(stoppingToken); + await bus.StartAsync(stoppingToken); + await publisher.StartAsync(stoppingToken); } } diff --git a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs index a64465179..1c8101647 100644 --- a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs +++ b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs @@ -6,17 +6,8 @@ namespace JustSaying.Sample.Restaurant.KitchenConsole.Handlers; -public class OrderOnItsWayEventHandler : IHandlerAsync +public class OrderOnItsWayEventHandler(IMessagePublisher publisher, ILogger logger) : IHandlerAsync { - private readonly IMessagePublisher _publisher; - private readonly ILogger _logger; - - public OrderOnItsWayEventHandler(IMessagePublisher publisher, ILogger logger) - { - _publisher = publisher; - _logger = logger; - } - public async Task Handle(OrderOnItsWayEvent message) { await Task.Delay(RandomNumberGenerator.GetInt32(50, 100)); @@ -26,10 +17,10 @@ public async Task Handle(OrderOnItsWayEvent message) OrderId = message.OrderId }; - _logger.LogInformation("Order {OrderId} is on its way!", message.OrderId); + logger.LogInformation("Order {OrderId} is on its way!", message.OrderId); - await _publisher.PublishAsync(orderDeliveredEvent); + await publisher.PublishAsync(orderDeliveredEvent); return true; } -} \ No newline at end of file +} diff --git a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs index 18fd28cbc..717c4e36e 100644 --- a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs +++ b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs @@ -6,21 +6,12 @@ namespace JustSaying.Sample.Restaurant.KitchenConsole.Handlers; -public class OrderPlacedEventHandler : IHandlerAsync +/// +/// Handles messages of type OrderPlacedEvent +/// Takes a dependency on IMessagePublisher so that further messages can be published +/// +public class OrderPlacedEventHandler(IMessagePublisher publisher, ILogger logger) : IHandlerAsync { - private readonly IMessagePublisher _publisher; - private readonly ILogger _logger; - - /// - /// Handles messages of type OrderPlacedEvent - /// Takes a dependency on IMessagePublisher so that further messages can be published - /// - public OrderPlacedEventHandler(IMessagePublisher publisher, ILogger log) - { - _publisher = publisher; - _logger = log; - } - public async Task Handle(OrderPlacedEvent message) { // Returning true would indicate: @@ -33,12 +24,12 @@ public async Task Handle(OrderPlacedEvent message) try { - _logger.LogInformation("Order {orderId} for {description} received", message.OrderId, message.Description); + logger.LogInformation("Order {orderId} for {description} received", message.OrderId, message.Description); // This is where you would actually handle the order placement // Intentionally left empty for the sake of this being a sample application - _logger.LogInformation("Order {OrderId} ready", message.OrderId); + logger.LogInformation("Order {OrderId} ready", message.OrderId); await Task.Delay(RandomNumberGenerator.GetInt32(50, 100)); @@ -47,13 +38,13 @@ public async Task Handle(OrderPlacedEvent message) OrderId = message.OrderId }; - await _publisher.PublishAsync(orderReadyEvent).ConfigureAwait(false); + await publisher.PublishAsync(orderReadyEvent).ConfigureAwait(false); return true; } catch (Exception ex) { - _logger.LogError(ex, "Failed to handle message for {orderId}", message.OrderId); + logger.LogError(ex, "Failed to handle message for {orderId}", message.OrderId); return false; } } -} \ No newline at end of file +} diff --git a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs index 80c59618b..1c85277d4 100644 --- a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs +++ b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs @@ -6,24 +6,13 @@ namespace JustSaying.Sample.Restaurant.OrderingApi; /// A background service responsible for starting the bus which listens for /// messages on the configured queues /// -public class BusService : BackgroundService +public class BusService(IMessagingBus bus, ILogger logger, IMessagePublisher publisher) : BackgroundService { - private readonly IMessagingBus _bus; - private readonly ILogger _logger; - private readonly IMessagePublisher _publisher; - - public BusService(IMessagingBus bus, ILogger logger, IMessagePublisher publisher) - { - _bus = bus; - _logger = logger; - _publisher = publisher; - } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - _logger.LogInformation("Ordering API subscriber running"); + logger.LogInformation("Ordering API subscriber running"); - await _publisher.StartAsync(stoppingToken); - await _bus.StartAsync(stoppingToken); + await publisher.StartAsync(stoppingToken); + await bus.StartAsync(stoppingToken); } } diff --git a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs index 692c90de3..aaf17cf80 100644 --- a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs +++ b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs @@ -4,20 +4,13 @@ namespace JustSaying.Sample.Restaurant.OrderingApi.Handlers; -public class OrderDeliveredEventHandler : IHandlerAsync +public class OrderDeliveredEventHandler(ILogger logger) : IHandlerAsync { - private readonly ILogger _logger; - - public OrderDeliveredEventHandler(ILogger logger) - { - _logger = logger; - } - public async Task Handle(OrderDeliveredEvent message) { await Task.Delay(RandomNumberGenerator.GetInt32(50, 100)); - _logger.LogInformation("Order {OrderId} has been delivered", message.OrderId); + logger.LogInformation("Order {OrderId} has been delivered", message.OrderId); return true; } -} \ No newline at end of file +} diff --git a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs index 1503b4c62..d42dbb851 100644 --- a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs +++ b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs @@ -5,20 +5,11 @@ namespace JustSaying.Sample.Restaurant.OrderingApi.Handlers; -public class OrderReadyEventHandler : IHandlerAsync +public class OrderReadyEventHandler(ILogger logger, IMessagePublisher publisher) : IHandlerAsync { - private readonly ILogger _logger; - private readonly IMessagePublisher _publisher; - - public OrderReadyEventHandler(ILogger logger, IMessagePublisher publisher) - { - _logger = logger; - _publisher = publisher; - } - public async Task Handle(OrderReadyEvent message) { - _logger.LogInformation("Order {orderId} ready", message.OrderId); + logger.LogInformation("Order {orderId} ready", message.OrderId); // This is where you would actually handle the order placement // Intentionally left empty for the sake of this being a sample application @@ -30,7 +21,7 @@ public async Task Handle(OrderReadyEvent message) OrderId = message.OrderId }; - await _publisher.PublishAsync(orderOnItsWayEvent); + await publisher.PublishAsync(orderOnItsWayEvent); // Returning true would indicate: // The message was handled successfully @@ -41,4 +32,4 @@ public async Task Handle(OrderReadyEvent message) // The message should be moved to the error queue if all retries fail return true; } -} \ No newline at end of file +} diff --git a/src/JustSaying/AwsTools/ErrorQueue.cs b/src/JustSaying/AwsTools/ErrorQueue.cs index cffdacc4d..64259c31b 100644 --- a/src/JustSaying/AwsTools/ErrorQueue.cs +++ b/src/JustSaying/AwsTools/ErrorQueue.cs @@ -11,13 +11,12 @@ namespace JustSaying.AwsTools; [Obsolete("SqsQueueBase and related classes are not intended for general usage and may be removed in a future major release")] -public class ErrorQueue : SqsQueueByNameBase +public class ErrorQueue( + RegionEndpoint region, + string sourceQueueName, + IAmazonSQS client, + ILoggerFactory loggerFactory) : SqsQueueByNameBase(region, sourceQueueName + "_error", client, loggerFactory) { - public ErrorQueue(RegionEndpoint region, string sourceQueueName, IAmazonSQS client, ILoggerFactory loggerFactory) - : base(region, sourceQueueName + "_error", client, loggerFactory) - { - } - protected override Dictionary GetCreateQueueAttributes(SqsBasicConfiguration queueConfig) { return new Dictionary @@ -55,4 +54,4 @@ public override async Task UpdateQueueAttributeAsync(SqsBasicConfiguration queue protected override bool QueueNeedsUpdating(SqsBasicConfiguration queueConfig) => MessageRetentionPeriod != queueConfig.ErrorQueueRetentionPeriod; -} \ No newline at end of file +} diff --git a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs index 97b56c383..83b6f5c27 100644 --- a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs +++ b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs @@ -93,9 +93,7 @@ await middleware.RunAsync(handleContext, null, cancellationToken) return (false, null, null); } -#pragma warning disable CA1031 catch (Exception ex) -#pragma warning restore CA1031 { _logger.LogError( ex, diff --git a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs index a412172d1..2b0ee602a 100644 --- a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs +++ b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs @@ -11,8 +11,7 @@ namespace JustSaying.AwsTools.MessageHandling.Dispatch; /// public sealed class MiddlewareMap : IInterrogable { - private readonly Dictionary<(string queueName, Type type), HandleMessageMiddleware> _middlewares - = new Dictionary<(string, Type), HandleMessageMiddleware>(); + private readonly Dictionary<(string queueName, Type type), HandleMessageMiddleware> _middlewares = new(); /// /// Checks if a middleware has been added for a given queue and message type. @@ -91,4 +90,4 @@ public InterrogationResult Interrogate() Middlewares = middlewares }); } -} \ No newline at end of file +} diff --git a/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs b/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs index 41fce0588..40afe039d 100644 --- a/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs +++ b/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs @@ -2,15 +2,10 @@ namespace JustSaying.AwsTools.MessageHandling; -internal class ForeignTopicArnProvider : ITopicArnProvider +internal class ForeignTopicArnProvider(RegionEndpoint regionEndpoint, string accountId, string topicName) : ITopicArnProvider { - private readonly string _arn; - - public ForeignTopicArnProvider(RegionEndpoint regionEndpoint, string accountId, string topicName) - { - _arn = $"arn:aws:sns:{regionEndpoint.SystemName}:{accountId}:{topicName}"; - } + private readonly string _arn = $"arn:aws:sns:{regionEndpoint.SystemName}:{accountId}:{topicName}"; public Task ArnExistsAsync() { @@ -22,4 +17,4 @@ public Task GetArnAsync() { return Task.FromResult(_arn); } -} \ No newline at end of file +} diff --git a/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs b/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs index cd04b20bb..ffe5a49e5 100644 --- a/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs +++ b/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs @@ -24,9 +24,7 @@ private async Task GetArnInternalAsync(string topicName) _exists = true; return topic.TopicArn; } -#pragma warning disable CA1031 - catch -#pragma warning restore CA1031 + catch (Exception) { // ignored } @@ -43,4 +41,4 @@ public async Task ArnExistsAsync() _ = await _lazyGetArnAsync.Value.ConfigureAwait(false); return _exists; } -} \ No newline at end of file +} diff --git a/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs b/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs index 9953aac06..835773bcf 100644 --- a/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs +++ b/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs @@ -10,15 +10,20 @@ namespace JustSaying.AwsTools.MessageHandling; -public class SnsMessagePublisher : IMessagePublisher, IInterrogable +public class SnsMessagePublisher( + IAmazonSimpleNotificationService client, + IMessageSerializationRegister serializationRegister, + ILoggerFactory loggerFactory, + IMessageSubjectProvider messageSubjectProvider, + Func handleException = null) : IMessagePublisher, IInterrogable { - private readonly IMessageSerializationRegister _serializationRegister; - private readonly IMessageSubjectProvider _messageSubjectProvider; - private readonly Func _handleException; + private readonly IMessageSerializationRegister _serializationRegister = serializationRegister; + private readonly IMessageSubjectProvider _messageSubjectProvider = messageSubjectProvider; + private readonly Func _handleException = handleException; public Action MessageResponseLogger { get; set; } public string Arn { get; internal set; } - protected IAmazonSimpleNotificationService Client { get; } - private readonly ILogger _logger; + protected IAmazonSimpleNotificationService Client { get; } = client; + private readonly ILogger _logger = loggerFactory.CreateLogger("JustSaying.Publish"); public SnsMessagePublisher( string topicArn, @@ -32,20 +37,6 @@ public SnsMessagePublisher( Arn = topicArn; } - public SnsMessagePublisher( - IAmazonSimpleNotificationService client, - IMessageSerializationRegister serializationRegister, - ILoggerFactory loggerFactory, - IMessageSubjectProvider messageSubjectProvider, - Func handleException = null) - { - Client = client; - _serializationRegister = serializationRegister; - _logger = loggerFactory.CreateLogger("JustSaying.Publish"); - _handleException = handleException; - _messageSubjectProvider = messageSubjectProvider; - } - public Task StartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; @@ -132,7 +123,7 @@ private static MessageAttributeValue BuildMessageAttributeValue(Messaging.Messag } var binaryValueStream = value.BinaryValue != null - ? new MemoryStream(value.BinaryValue.ToArray(), false) + ? new MemoryStream([.. value.BinaryValue], false) : null; return new MessageAttributeValue diff --git a/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs b/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs index bc6de96dd..ddb200e57 100644 --- a/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs +++ b/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs @@ -1,5 +1,4 @@ -using System.Text.Json; -using System.Text.RegularExpressions; +using System.Text.Json; using Amazon; namespace JustSaying.AwsTools.MessageHandling; diff --git a/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs b/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs index 4f8e9ab0a..d0cd0dcfa 100644 --- a/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs +++ b/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs @@ -8,47 +8,39 @@ namespace JustSaying.AwsTools.MessageHandling; [Obsolete("SnsTopicByName is not intended for general usage and may be removed in a future major release")] -public sealed class SnsTopicByName : IInterrogable +public sealed class SnsTopicByName( + string topicName, + IAmazonSimpleNotificationService client, + ILoggerFactory loggerFactory) : IInterrogable { - private readonly IAmazonSimpleNotificationService _client; - private readonly ILogger _logger; + private readonly ILogger _logger = loggerFactory.CreateLogger("JustSaying"); - public string TopicName { get; } + public string TopicName { get; } = topicName; public string Arn { get; private set; } internal ServerSideEncryption ServerSideEncryption { get; set; } public IDictionary Tags { get; set; } - public SnsTopicByName( - string topicName, - IAmazonSimpleNotificationService client, - ILoggerFactory loggerFactory) - { - _client = client; - TopicName = topicName; - _logger = loggerFactory.CreateLogger("JustSaying"); - } - public async Task EnsurePolicyIsUpdatedAsync(IReadOnlyCollection additionalSubscriberAccounts) { - if (additionalSubscriberAccounts.Any()) + if (additionalSubscriberAccounts.Count != 0) { var policyDetails = new SnsPolicyDetails { AccountIds = additionalSubscriberAccounts, SourceArn = Arn }; - await SnsPolicy.SaveAsync(policyDetails, _client).ConfigureAwait(false); + await SnsPolicy.SaveAsync(policyDetails, client).ConfigureAwait(false); } } public async Task ApplyTagsAsync(CancellationToken cancellationToken) { - if (!Tags.Any()) + if (Tags.Count < 1) { return; } - Tag CreateTag(KeyValuePair tag) => new() { Key = tag.Key, Value = tag.Value }; + static Tag CreateTag(KeyValuePair tag) => new() { Key = tag.Key, Value = tag.Value }; var tagRequest = new TagResourceRequest { @@ -56,7 +48,7 @@ public async Task ApplyTagsAsync(CancellationToken cancellationToken) Tags = Tags.Select(CreateTag).ToList() }; - await _client.TagResourceAsync(tagRequest, cancellationToken).ConfigureAwait(false); + await client.TagResourceAsync(tagRequest, cancellationToken).ConfigureAwait(false); _logger.LogInformation("Added {TagCount} tags to topic {TopicName}", tagRequest.Tags.Count, TopicName); } @@ -69,7 +61,7 @@ public async Task ExistsAsync(CancellationToken cancellationToken) } _logger.LogInformation("Checking for existence of the topic '{TopicName}'.", TopicName); - var topic = await _client.FindTopicAsync(TopicName).ConfigureAwait(false); + var topic = await client.FindTopicAsync(TopicName).ConfigureAwait(false); if (topic != null) { @@ -84,7 +76,7 @@ public async Task CreateAsync(CancellationToken cancellationToken) { try { - var response = await _client.CreateTopicAsync(new CreateTopicRequest(TopicName), cancellationToken) + var response = await client.CreateTopicAsync(new CreateTopicRequest(TopicName), cancellationToken) .ConfigureAwait(false); if (string.IsNullOrEmpty(response.TopicArn)) @@ -121,7 +113,7 @@ public async Task CreateWithEncryptionAsync(ServerSideEncryption config, Cancell private async Task ExtractServerSideEncryptionFromTopicAttributes() { - var attributesResponse = await _client.GetTopicAttributesAsync(Arn).ConfigureAwait(false); + var attributesResponse = await client.GetTopicAttributesAsync(Arn).ConfigureAwait(false); if (!attributesResponse.Attributes.TryGetValue( JustSayingConstants.AttributeEncryptionKeyId, @@ -147,7 +139,7 @@ private async Task EnsureServerSideEncryptionIsUpdatedAsync(ServerSideEncryption AttributeValue = config?.KmsMasterKeyId ?? string.Empty }; - var response = await _client.SetTopicAttributesAsync(request).ConfigureAwait(false); + var response = await client.SetTopicAttributesAsync(request).ConfigureAwait(false); if (response.HttpStatusCode == HttpStatusCode.OK) { @@ -190,4 +182,4 @@ public InterrogationResult Interrogate() }); } -} \ No newline at end of file +} diff --git a/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs b/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs index 1fee4ed9c..dc6a77337 100644 --- a/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs +++ b/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs @@ -9,11 +9,12 @@ namespace JustSaying.AwsTools.MessageHandling; -public class SqsMessagePublisher : IMessagePublisher +public class SqsMessagePublisher( + IAmazonSQS client, + IMessageSerializationRegister serializationRegister, + ILoggerFactory loggerFactory) : IMessagePublisher { - private readonly IAmazonSQS _client; - private readonly IMessageSerializationRegister _serializationRegister; - private readonly ILogger _logger; + private readonly ILogger _logger = loggerFactory.CreateLogger("JustSaying.Publish"); public Action MessageResponseLogger { get; set; } public Uri QueueUrl { get; internal set; } @@ -27,16 +28,6 @@ public SqsMessagePublisher( QueueUrl = queueUrl; } - public SqsMessagePublisher( - IAmazonSQS client, - IMessageSerializationRegister serializationRegister, - ILoggerFactory loggerFactory) - { - _client = client; - _serializationRegister = serializationRegister; - _logger = loggerFactory.CreateLogger("JustSaying.Publish"); - } - public Task StartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; @@ -53,7 +44,7 @@ public async Task PublishAsync(Message message, PublishMetadata metadata, Cancel SendMessageResponse response; try { - response = await _client.SendMessageAsync(request, cancellationToken).ConfigureAwait(false); + response = await client.SendMessageAsync(request, cancellationToken).ConfigureAwait(false); } catch (AmazonServiceException ex) { @@ -103,7 +94,7 @@ private SendMessageRequest BuildSendMessageRequest(Message message, PublishMetad return request; } - public string GetMessageInContext(Message message) => _serializationRegister.Serialize(message, serializeForSnsPublishing: false); + public string GetMessageInContext(Message message) => serializationRegister.Serialize(message, serializeForSnsPublishing: false); public InterrogationResult Interrogate() { diff --git a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs index 8a6dc6e1b..d73ab35ad 100644 --- a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs +++ b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs @@ -10,18 +10,14 @@ namespace JustSaying.AwsTools.MessageHandling; [Obsolete("SqsQueueBase and related classes are not intended for general usage and may be removed in a future major release")] -public class SqsQueueByName : SqsQueueByNameBase +public class SqsQueueByName( + RegionEndpoint region, + string queueName, + IAmazonSQS client, + int retryCountBeforeSendingToErrorQueue, + ILoggerFactory loggerFactory) : SqsQueueByNameBase(region, queueName, client, loggerFactory) { - private readonly int _retryCountBeforeSendingToErrorQueue; - - internal ErrorQueue ErrorQueue { get; } - - public SqsQueueByName(RegionEndpoint region, string queueName, IAmazonSQS client, int retryCountBeforeSendingToErrorQueue, ILoggerFactory loggerFactory) - : base(region, queueName, client, loggerFactory) - { - _retryCountBeforeSendingToErrorQueue = retryCountBeforeSendingToErrorQueue; - ErrorQueue = new ErrorQueue(region, queueName, client, loggerFactory); - } + internal ErrorQueue ErrorQueue { get; } = new ErrorQueue(region, queueName, client, loggerFactory); public override async Task CreateAsync(SqsBasicConfiguration queueConfig, int attempt = 0, CancellationToken cancellationToken = default) { @@ -135,7 +131,7 @@ await UpdateRedrivePolicyAsync( private async Task ApplyTagsAsync(ISqsQueue queue, Dictionary tags, CancellationToken cancellationToken) { - if (tags == null || !tags.Any()) + if (tags == null || tags.Count == 0) { return; } @@ -157,7 +153,7 @@ protected override Dictionary GetCreateQueueAttributes(SqsBasicC if (NeedErrorQueue(queueConfig)) { - policy.Add(JustSayingConstants.AttributeRedrivePolicy, new RedrivePolicy(_retryCountBeforeSendingToErrorQueue, ErrorQueue.Arn).ToString()); + policy.Add(JustSayingConstants.AttributeRedrivePolicy, new RedrivePolicy(retryCountBeforeSendingToErrorQueue, ErrorQueue.Arn).ToString()); } if (queueConfig.ServerSideEncryption != null) diff --git a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs index e6ea17489..664c96d0c 100644 --- a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs +++ b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs @@ -77,7 +77,7 @@ public virtual async Task ExistsAsync(CancellationToken cancellationToken) Uri = new Uri(result.QueueUrl); - await SetQueuePropertiesAsync(cancellationToken).ConfigureAwait(false); + await SetQueuePropertiesAsync().ConfigureAwait(false); return true; } @@ -96,7 +96,7 @@ public virtual async Task CreateAsync(SqsBasicConfiguration queueConfig, i { Uri = new Uri(queueResponse.QueueUrl); await Client.SetQueueAttributesAsync(queueResponse.QueueUrl, GetCreateQueueAttributes(queueConfig), cancellationToken).ConfigureAwait(false); - await SetQueuePropertiesAsync(cancellationToken).ConfigureAwait(false); + await SetQueuePropertiesAsync().ConfigureAwait(false); Logger.LogInformation("Created queue '{QueueName}' with ARN '{Arn}'.", QueueName, Arn); return true; @@ -126,7 +126,7 @@ public virtual async Task CreateAsync(SqsBasicConfiguration queueConfig, i maxAttempts); await Task.Delay(CreateRetryDelay, cancellationToken).ConfigureAwait(false); - await CreateAsync(queueConfig, attempt + 1).ConfigureAwait(false); + _ = await CreateAsync(queueConfig, attempt + 1).ConfigureAwait(false); } else { @@ -155,10 +155,10 @@ public virtual async Task DeleteAsync(CancellationToken cancellationToken) } } - private async Task SetQueuePropertiesAsync(CancellationToken cancellationToken) + private async Task SetQueuePropertiesAsync() { - var keys = new[] - { + string[] keys = + [ JustSayingConstants.AttributeArn, JustSayingConstants.AttributeRedrivePolicy, JustSayingConstants.AttributePolicy, @@ -167,8 +167,8 @@ private async Task SetQueuePropertiesAsync(CancellationToken cancellationToken) JustSayingConstants.AttributeDeliveryDelay, JustSayingConstants.AttributeEncryptionKeyId, JustSayingConstants.AttributeEncryptionKeyReusePeriodSecondId - }; - var attributes = await GetAttrsAsync(keys).ConfigureAwait(false); + ]; + var attributes = await GetAttributesAsync(keys).ConfigureAwait(false); Arn = attributes.QueueARN; MessageRetentionPeriod = TimeSpan.FromSeconds(attributes.MessageRetentionPeriod); _visibilityTimeout = TimeSpan.FromSeconds(attributes.VisibilityTimeout); @@ -178,7 +178,7 @@ private async Task SetQueuePropertiesAsync(CancellationToken cancellationToken) ServerSideEncryption = ExtractServerSideEncryptionFromQueueAttributes(attributes.Attributes); } - private async Task GetAttrsAsync(IEnumerable attrKeys) + private async Task GetAttributesAsync(IEnumerable attrKeys) { var request = new GetQueueAttributesRequest { diff --git a/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs b/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs index 3b09ec4d2..69c773c55 100644 --- a/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs +++ b/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs @@ -6,26 +6,15 @@ namespace JustSaying.AwsTools.QueueCreation; -public class AmazonQueueCreator : IVerifyAmazonQueues +public class AmazonQueueCreator(IAwsClientFactoryProxy awsClientFactory, ILoggerFactory loggerFactory) : IVerifyAmazonQueues { - private readonly IAwsClientFactoryProxy _awsClientFactory; - private readonly ILoggerFactory _loggerFactory; - - private const string EmptyFilterPolicy = "{}"; - - public AmazonQueueCreator(IAwsClientFactoryProxy awsClientFactory, ILoggerFactory loggerFactory) - { - _awsClientFactory = awsClientFactory; - _loggerFactory = loggerFactory; - } - public QueueWithAsyncStartup EnsureTopicExistsWithQueueSubscribed( string region, SqsReadConfiguration queueConfig) { var regionEndpoint = RegionEndpoint.GetBySystemName(region); - var sqsClient = _awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint); - var snsClient = _awsClientFactory.GetAwsClientFactory().GetSnsClient(regionEndpoint); + var sqsClient = awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint); + var snsClient = awsClientFactory.GetAwsClientFactory().GetSnsClient(regionEndpoint); var queueWithStartup = EnsureQueueExists(region, queueConfig); @@ -49,7 +38,7 @@ await SubscribeQueueAndApplyFilterPolicyAsync(snsClient, else { #pragma warning disable 618 - var eventTopic = new SnsTopicByName(queueConfig.PublishEndpoint, snsClient, _loggerFactory); + var eventTopic = new SnsTopicByName(queueConfig.PublishEndpoint, snsClient, loggerFactory); #pragma warning restore 618 await eventTopic.CreateAsync(cancellationToken).ConfigureAwait(false); @@ -84,14 +73,14 @@ public QueueWithAsyncStartup EnsureQueueExists( SqsReadConfiguration queueConfig) { var regionEndpoint = RegionEndpoint.GetBySystemName(region); - var sqsClient = _awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint); + var sqsClient = awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint); #pragma warning disable 618 var queue = new SqsQueueByName(regionEndpoint, queueConfig.QueueName, sqsClient, queueConfig.RetryCountBeforeSendingToErrorQueue, - _loggerFactory); + loggerFactory); #pragma warning restore 618 var startupTask = new Func(ct => queue.EnsureQueueAndErrorQueueExistAndAllAttributesAreUpdatedAsync( @@ -117,9 +106,9 @@ private static async Task SubscribeQueueAndApplyFilterPolicyAsync( .ConfigureAwait(false); var actualFilterPolicy = - string.IsNullOrWhiteSpace(filterPolicy) ? EmptyFilterPolicy : filterPolicy; + string.IsNullOrWhiteSpace(filterPolicy) ? "{}" : filterPolicy; await amazonSimpleNotificationService .SetSubscriptionAttributesAsync(subscriptionArn, "FilterPolicy", actualFilterPolicy) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs b/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs index 780579090..c9a086227 100644 --- a/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs +++ b/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs @@ -23,7 +23,7 @@ public static async Task> ReceiveMessagesAsync(this IAmazonSQS cl var result = await client.ReceiveMessageAsync(new ReceiveMessageRequest(queueUrl) { - AttributeNames = attributesToLoad.ToList(), + AttributeNames = [.. attributesToLoad], WaitTimeSeconds = secondsWaitTime, MaxNumberOfMessages = maxNumOfMessages }, @@ -32,4 +32,4 @@ public static async Task> ReceiveMessagesAsync(this IAmazonSQS cl if (result?.Messages != null) return result.Messages; return Array.Empty(); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Extensions/TypeExtensions.cs b/src/JustSaying/Extensions/TypeExtensions.cs index 0927fc3ed..aa298e139 100644 --- a/src/JustSaying/Extensions/TypeExtensions.cs +++ b/src/JustSaying/Extensions/TypeExtensions.cs @@ -1,6 +1,6 @@ namespace JustSaying.Extensions; -static class TypeExtensions +internal static class TypeExtensions { public static string ToSimpleName(this Type type) => type.ToString().Replace($"{type.Namespace}.", ""); diff --git a/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs b/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs index 7a5c85615..cb39a0568 100644 --- a/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs +++ b/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs @@ -146,9 +146,7 @@ public AwsClientFactoryBuilder WithSessionCredentials(string accessKeyId, string /// /// is not an absolute URI. /// -#pragma warning disable CA1054 // Uri parameters should not be strings public AwsClientFactoryBuilder WithServiceUrl(string url) -#pragma warning restore CA1054 // Uri parameters should not be strings { if (url == null) { @@ -187,4 +185,4 @@ public AwsClientFactoryBuilder WithServiceUri(Uri uri) return this; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs b/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs index 4374cc2ae..317261de3 100644 --- a/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs +++ b/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs @@ -114,10 +114,7 @@ public MessagingConfigurationBuilder WithAdditionalSubscriberAccount(string acco throw new ArgumentNullException(nameof(accountId)); } - if (AdditionalSubscriberAccounts == null) - { - AdditionalSubscriberAccounts = new List(); - } + AdditionalSubscriberAccounts ??= new List(); AdditionalSubscriberAccounts.Add(accountId); return this; @@ -334,4 +331,4 @@ public IMessagingConfig Build() return config; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/PublicationsBuilder.cs b/src/JustSaying/Fluent/PublicationsBuilder.cs index 39a4e363e..83139211d 100644 --- a/src/JustSaying/Fluent/PublicationsBuilder.cs +++ b/src/JustSaying/Fluent/PublicationsBuilder.cs @@ -26,7 +26,7 @@ internal PublicationsBuilder(MessagingBusBuilder parent) /// /// Gets the configured publication builders. /// - private IList> Publications { get; } = new List>(); + private List> Publications { get; } = []; /// /// Configures a publisher for a queue. @@ -204,4 +204,4 @@ internal void Configure(JustSayingBus bus, IAwsClientFactoryProxy proxy, ILogger builder.Configure(bus, proxy, loggerFactory); } } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs b/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs index efdfdf39e..c37616e04 100644 --- a/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs +++ b/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs @@ -6,21 +6,14 @@ namespace JustSaying.Fluent; -internal sealed class DynamicMessagePublisher : IMessagePublisher +internal sealed class DynamicMessagePublisher( + Func topicNameCustomizer, + Func staticConfigBuilder, + ILoggerFactory loggerFactory) : IMessagePublisher { private readonly ConcurrentDictionary _publisherCache = new(); - private readonly Func _topicNameCustomizer; - private readonly Func _staticConfigBuilder; - private readonly ConcurrentDictionary _topicCreationLocks = new(); - private readonly ILogger _logger; - - public DynamicMessagePublisher(Func topicNameCustomizer, Func staticConfigBuilder, ILoggerFactory loggerFactory) - { - _topicNameCustomizer = topicNameCustomizer; - _staticConfigBuilder = staticConfigBuilder; - _logger = loggerFactory.CreateLogger(); - } + private readonly ILogger _logger = loggerFactory.CreateLogger(); public InterrogationResult Interrogate() { @@ -40,7 +33,7 @@ public Task StartAsync(CancellationToken stoppingToken) public async Task PublishAsync(Message message, PublishMetadata metadata, CancellationToken cancellationToken) { - var topicName = _topicNameCustomizer(message); + var topicName = topicNameCustomizer(message); if (_publisherCache.TryGetValue(topicName, out var publisher)) { await publisher.PublishAsync(message, metadata, cancellationToken).ConfigureAwait(false); @@ -59,7 +52,7 @@ public async Task PublishAsync(Message message, PublishMetadata metadata, Cancel } _logger.LogDebug("Lock acquired to initialize topic {TopicName}", topicName); - var config = _staticConfigBuilder(topicName); + var config = staticConfigBuilder(topicName); _logger.LogDebug("Executing startup task for topic {TopicName}", topicName); await config.StartupTask(cancellationToken).ConfigureAwait(false); diff --git a/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs b/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs index b41d1cc43..e55c6bf41 100644 --- a/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs +++ b/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs @@ -4,15 +4,10 @@ namespace JustSaying.Fluent; -internal sealed class DynamicPublicationConfiguration : ITopicPublisher +internal sealed class DynamicPublicationConfiguration(IMessagePublisher publisher) : ITopicPublisher { - public DynamicPublicationConfiguration(IMessagePublisher publisher) - { - Publisher = publisher; - } - public Func StartupTask => _ => Task.CompletedTask; - public IMessagePublisher Publisher { get; } + public IMessagePublisher Publisher { get; } = publisher; public static DynamicPublicationConfiguration Build( Func topicNameCustomizer, diff --git a/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs b/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs index 29e12dab2..f7b8410fb 100644 --- a/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs +++ b/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs @@ -8,18 +8,12 @@ namespace JustSaying.Fluent; -internal sealed class StaticPublicationConfiguration : ITopicPublisher +internal sealed class StaticPublicationConfiguration( + Func startupTask, + IMessagePublisher publisher) : ITopicPublisher { - public Func StartupTask { get; } - public IMessagePublisher Publisher { get; } - - public StaticPublicationConfiguration( - Func startupTask, - IMessagePublisher publisher) - { - StartupTask = startupTask; - Publisher = publisher; - } + public Func StartupTask { get; } = startupTask; + public IMessagePublisher Publisher { get; } = publisher; public static StaticPublicationConfiguration Build( string topicName, diff --git a/src/JustSaying/Fluent/QueueAddressConfiguration.cs b/src/JustSaying/Fluent/QueueAddressConfiguration.cs index 9f20fc7e9..b0a4d28d7 100644 --- a/src/JustSaying/Fluent/QueueAddressConfiguration.cs +++ b/src/JustSaying/Fluent/QueueAddressConfiguration.cs @@ -9,5 +9,6 @@ public sealed class QueueAddressConfiguration public void Validate() { + // TODO } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs b/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs index eb1687113..2e266accc 100644 --- a/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs +++ b/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs @@ -87,13 +87,8 @@ void ISubscriptionBuilder.Configure( typeof(T), queue.QueueName); var resolutionContext = new HandlerResolutionContext(queue.QueueName); - var proposedHandler = handlerResolver.ResolveHandler(resolutionContext); - if (proposedHandler == null) - { - throw new HandlerNotRegisteredWithContainerException( + var proposedHandler = handlerResolver.ResolveHandler(resolutionContext) ?? throw new HandlerNotRegisteredWithContainerException( $"There is no handler for '{typeof(T)}' messages."); - } - var middlewareBuilder = new HandlerMiddlewareBuilder(handlerResolver, serviceResolver); var handlerMiddleware = middlewareBuilder .Configure(MiddlewareConfiguration ?? (b => b.UseDefaults(proposedHandler.GetType()))) @@ -105,4 +100,4 @@ void ISubscriptionBuilder.Configure( "Added a message handler for message type for '{MessageType}' on queue '{QueueName}'", typeof(T), queue.QueueName); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs b/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs index 9d05f81f8..8bc4eacab 100644 --- a/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs +++ b/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs @@ -78,7 +78,7 @@ public QueuePublicationBuilder WithWriteConfiguration(Action public QueuePublicationBuilder WithName(string queueName) { - return this.WithWriteConfiguration(r => r.WithQueueName(queueName)); + return WithWriteConfiguration(r => r.WithQueueName(queueName)); } /// @@ -140,4 +140,4 @@ async Task StartupTask(CancellationToken cancellationToken) typeof(T), writeConfiguration.QueueName); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs b/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs index 01e42f823..84cb978e6 100644 --- a/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs +++ b/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs @@ -192,13 +192,8 @@ void ISubscriptionBuilder.Configure( subscriptionConfig.QueueName); var resolutionContext = new HandlerResolutionContext(subscriptionConfig.QueueName); - var proposedHandler = handlerResolver.ResolveHandler(resolutionContext); - if (proposedHandler == null) - { - throw new HandlerNotRegisteredWithContainerException( + var proposedHandler = handlerResolver.ResolveHandler(resolutionContext) ?? throw new HandlerNotRegisteredWithContainerException( $"There is no handler for '{typeof(T)}' messages."); - } - var middlewareBuilder = new HandlerMiddlewareBuilder(handlerResolver, serviceResolver); var handlerMiddleware = middlewareBuilder .Configure(MiddlewareConfiguration ?? (b => b.UseDefaults(proposedHandler.GetType()))) diff --git a/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs b/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs index 28ed6d53f..279b09bdc 100644 --- a/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs +++ b/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs @@ -1,25 +1,16 @@ namespace JustSaying.Fluent.ServiceResolver; -internal class CompoundServiceResolver : IServiceResolver +internal class CompoundServiceResolver(ServiceBuilderServiceResolver serviceBuilderResolver, IServiceResolver serviceResolver) : IServiceResolver { - private readonly ServiceBuilderServiceResolver _serviceBuilderResolver; - private readonly IServiceResolver _serviceResolver; - - public CompoundServiceResolver(ServiceBuilderServiceResolver serviceBuilderResolver, IServiceResolver serviceResolver) - { - _serviceBuilderResolver = serviceBuilderResolver; - _serviceResolver = serviceResolver; - } - public T ResolveService() where T : class { - return _serviceBuilderResolver.ResolveOptionalService() ?? - _serviceResolver.ResolveService(); + return serviceBuilderResolver.ResolveOptionalService() ?? + serviceResolver.ResolveService(); } public T ResolveOptionalService() where T : class { - return _serviceBuilderResolver.ResolveOptionalService() ?? - _serviceResolver.ResolveOptionalService(); + return serviceBuilderResolver.ResolveOptionalService() ?? + serviceResolver.ResolveOptionalService(); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs b/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs index 840759ff1..df06550f2 100644 --- a/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs +++ b/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs @@ -7,19 +7,12 @@ namespace JustSaying.Fluent; -internal class ServiceBuilderServiceResolver : IServiceResolver +internal class ServiceBuilderServiceResolver(ServicesBuilder builder) : IServiceResolver { - private readonly ServicesBuilder _builder; - private readonly ConcurrentDictionary _serviceLookup = new(); private bool _built = false; - public ServiceBuilderServiceResolver(ServicesBuilder builder) - { - _builder = builder; - } - public T ResolveService() where T : class { return ResolveOptionalService() ?? @@ -29,34 +22,34 @@ public T ResolveService() where T : class private void Build() { - if (_builder.HandlerResolver != null) + if (builder.HandlerResolver != null) { - _serviceLookup[typeof(IHandlerResolver)] = _builder.HandlerResolver(); + _serviceLookup[typeof(IHandlerResolver)] = builder.HandlerResolver(); } - if (_builder.LoggerFactory != null) + if (builder.LoggerFactory != null) { - _serviceLookup[typeof(ILoggerFactory)] = _builder.LoggerFactory(); + _serviceLookup[typeof(ILoggerFactory)] = builder.LoggerFactory(); } - if (_builder.BusBuilder.ClientFactoryBuilder != null) + if (builder.BusBuilder.ClientFactoryBuilder != null) { - _serviceLookup[typeof(IAwsClientFactory)] = _builder.BusBuilder.ClientFactoryBuilder.Build(); + _serviceLookup[typeof(IAwsClientFactory)] = builder.BusBuilder.ClientFactoryBuilder.Build(); } - if (_builder.MessageMonitoring != null) + if (builder.MessageMonitoring != null) { - _serviceLookup[typeof(IMessageMonitor)] = _builder.MessageMonitoring(); + _serviceLookup[typeof(IMessageMonitor)] = builder.MessageMonitoring(); } - if (_builder.SerializationRegister != null) + if (builder.SerializationRegister != null) { - _serviceLookup[typeof(IMessageSerializationRegister)] = _builder.SerializationRegister(); + _serviceLookup[typeof(IMessageSerializationRegister)] = builder.SerializationRegister(); } - if (_builder.MessageContextAccessor != null) + if (builder.MessageContextAccessor != null) { - _serviceLookup[typeof(IMessageContextAccessor)] = _builder.MessageContextAccessor(); + _serviceLookup[typeof(IMessageContextAccessor)] = builder.MessageContextAccessor(); } _built = true; @@ -74,4 +67,4 @@ public T ResolveOptionalService() where T : class return null; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/SqsConfigurationBuilder.cs b/src/JustSaying/Fluent/SqsConfigurationBuilder.cs index 2afc57cd8..6d2653df8 100644 --- a/src/JustSaying/Fluent/SqsConfigurationBuilder.cs +++ b/src/JustSaying/Fluent/SqsConfigurationBuilder.cs @@ -55,17 +55,8 @@ internal SqsConfigurationBuilder() /// public TBuilder WithEncryption(string masterKeyId) { - if (masterKeyId == null) - { - throw new ArgumentNullException(nameof(masterKeyId)); - } - - if (Encryption == null) - { - Encryption = new ServerSideEncryption(); - } - - Encryption.KmsMasterKeyId = masterKeyId; + Encryption ??= new ServerSideEncryption(); + Encryption.KmsMasterKeyId = masterKeyId ?? throw new ArgumentNullException(nameof(masterKeyId)); return Self; } diff --git a/src/JustSaying/Fluent/SubscriptionsBuilder.cs b/src/JustSaying/Fluent/SubscriptionsBuilder.cs index c180347b6..8cb0df0e1 100644 --- a/src/JustSaying/Fluent/SubscriptionsBuilder.cs +++ b/src/JustSaying/Fluent/SubscriptionsBuilder.cs @@ -26,15 +26,14 @@ internal SubscriptionsBuilder(MessagingBusBuilder parent) /// internal MessagingBusBuilder Parent { get; } - internal SubscriptionGroupSettingsBuilder Defaults = new SubscriptionGroupSettingsBuilder(); + internal SubscriptionGroupSettingsBuilder Defaults = new(); /// /// Gets the configured subscription builders. /// - private IList> Subscriptions { get; } = new List>(); + private List> Subscriptions { get; } = []; - private IDictionary SubscriptionGroupSettings { get; } = - new Dictionary(); + private Dictionary SubscriptionGroupSettings { get; } = new(); /// /// Configure the default settings for all subscription groups. @@ -242,14 +241,8 @@ internal void Configure( IAwsClientFactoryProxy awsClientFactoryProxy, ILoggerFactory loggerFactory) { - var resolver = Parent.ServicesBuilder?.HandlerResolver?.Invoke() ?? - Parent.ServiceResolver.ResolveService(); - - if (resolver == null) - { - throw new InvalidOperationException($"No {nameof(IHandlerResolver)} is registered."); - } - + var resolver = (Parent.ServicesBuilder?.HandlerResolver?.Invoke() ?? + Parent.ServiceResolver.ResolveService()) ?? throw new InvalidOperationException($"No {nameof(IHandlerResolver)} is registered."); Defaults.Validate(); bus.SetGroupSettings(Defaults, SubscriptionGroupSettings); diff --git a/src/JustSaying/Fluent/TopicAddressPublisher.cs b/src/JustSaying/Fluent/TopicAddressPublisher.cs index a9c745d7d..f7b393dbe 100644 --- a/src/JustSaying/Fluent/TopicAddressPublisher.cs +++ b/src/JustSaying/Fluent/TopicAddressPublisher.cs @@ -9,9 +9,12 @@ namespace JustSaying.Fluent; /// /// An SNS message publisher for a . /// -internal sealed class TopicAddressPublisher : SnsMessagePublisher +internal sealed class TopicAddressPublisher( + IAmazonSimpleNotificationService snsClient, + ILoggerFactory loggerFactory, + IMessageSubjectProvider subjectProvider, + IMessageSerializationRegister serializationRegister, + Func handleException, + TopicAddress topicAddress) : SnsMessagePublisher(topicAddress.TopicArn, snsClient, serializationRegister, loggerFactory, subjectProvider, handleException) { - public TopicAddressPublisher(IAmazonSimpleNotificationService snsClient, ILoggerFactory loggerFactory, IMessageSubjectProvider subjectProvider, IMessageSerializationRegister serializationRegister, Func handleException, TopicAddress topicAddress) - : base(topicAddress.TopicArn, snsClient, serializationRegister, loggerFactory, subjectProvider, handleException) - { } -} \ No newline at end of file +} diff --git a/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs b/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs index c26fbff1d..977828070 100644 --- a/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs +++ b/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs @@ -211,13 +211,7 @@ void ISubscriptionBuilder.Configure( subscriptionConfig.QueueName); var resolutionContext = new HandlerResolutionContext(subscriptionConfig.QueueName); - var proposedHandler = handlerResolver.ResolveHandler(resolutionContext); - if (proposedHandler == null) - { - throw new HandlerNotRegisteredWithContainerException( - $"There is no handler for '{typeof(T)}' messages."); - } - + var proposedHandler = handlerResolver.ResolveHandler(resolutionContext) ?? throw new HandlerNotRegisteredWithContainerException($"There is no handler for '{typeof(T)}' messages."); var middlewareBuilder = new HandlerMiddlewareBuilder(handlerResolver, serviceResolver); var handlerMiddleware = middlewareBuilder .Configure(MiddlewareConfiguration ?? (builder => builder.UseDefaults(proposedHandler.GetType())) ) diff --git a/src/JustSaying/HandlerResolutionContext.cs b/src/JustSaying/HandlerResolutionContext.cs index b534220ce..49d464f0a 100644 --- a/src/JustSaying/HandlerResolutionContext.cs +++ b/src/JustSaying/HandlerResolutionContext.cs @@ -1,11 +1,6 @@ namespace JustSaying; -public class HandlerResolutionContext +public class HandlerResolutionContext(string queueName) { - public HandlerResolutionContext(string queueName) - { - QueueName = queueName; - } - - public string QueueName { get; private set; } -} \ No newline at end of file + public string QueueName { get; private set; } = queueName; +} diff --git a/src/JustSaying/IMessagingConfig.cs b/src/JustSaying/IMessagingConfig.cs index 92fa88b7d..ea029a05f 100644 --- a/src/JustSaying/IMessagingConfig.cs +++ b/src/JustSaying/IMessagingConfig.cs @@ -10,4 +10,4 @@ public interface IMessagingConfig : IPublishConfiguration ITopicNamingConvention TopicNamingConvention { get; set; } IQueueNamingConvention QueueNamingConvention { get; set; } void Validate(); -} \ No newline at end of file +} diff --git a/src/JustSaying/IPublishConfiguration.cs b/src/JustSaying/IPublishConfiguration.cs index c544c695c..b1206a423 100644 --- a/src/JustSaying/IPublishConfiguration.cs +++ b/src/JustSaying/IPublishConfiguration.cs @@ -9,4 +9,4 @@ public interface IPublishConfiguration TimeSpan PublishFailureBackoff { get; set; } Action MessageResponseLogger { get; set; } IReadOnlyCollection AdditionalSubscriberAccounts { get; set; } -} \ No newline at end of file +} diff --git a/src/JustSaying/JustSayingBus.cs b/src/JustSaying/JustSayingBus.cs index a0bd7b8cb..c5fbc347e 100644 --- a/src/JustSaying/JustSayingBus.cs +++ b/src/JustSaying/JustSayingBus.cs @@ -19,7 +19,7 @@ public sealed class JustSayingBus : IMessagingBus, IMessagePublisher, IDisposabl private readonly ILogger _log; private readonly ILoggerFactory _loggerFactory; - private readonly SemaphoreSlim _startLock = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _startLock = new(1, 1); private bool _busStarted; private readonly List> _startupTasks; @@ -49,14 +49,14 @@ public JustSayingBus( _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); - _startupTasks = new List>(); + _startupTasks = []; _log = _loggerFactory.CreateLogger("JustSaying"); Config = config; SerializationRegister = serializationRegister; MiddlewareMap = new MiddlewareMap(); - _publishersByType = new Dictionary(); + _publishersByType = []; _subscriptionGroupSettings = new ConcurrentDictionary(StringComparer.Ordinal); _defaultSubscriptionGroupSettings = new SubscriptionGroupSettingsBuilder(); @@ -212,10 +212,8 @@ private IMessagePublisher GetPublisherForMessage(Message message) { if (_publishersByType.Count == 0) { - var errorMessage = - "Error publishing message, no publishers registered. Has the bus been started?"; - _log.LogError(errorMessage); - throw new InvalidOperationException(errorMessage); + _log.LogError("Error publishing message, no publishers registered. Has the bus been started?"); + throw new InvalidOperationException("Error publishing message, no publishers registered. Has the bus been started?"); } var messageType = message.GetType(); diff --git a/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs b/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs index a3a8a4491..791fa6de3 100644 --- a/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs +++ b/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs @@ -4,22 +4,12 @@ namespace JustSaying.Messaging.Channels.Dispatch; -internal class MultiplexerSubscriber : IMultiplexerSubscriber +internal class MultiplexerSubscriber( + IMessageDispatcher dispatcher, + string subscriberId, + ILogger logger) : IMultiplexerSubscriber { private IAsyncEnumerable _messageSource; - private readonly IMessageDispatcher _dispatcher; - private readonly string _subscriberId; - private readonly ILogger _logger; - - public MultiplexerSubscriber( - IMessageDispatcher dispatcher, - string subscriberId, - ILogger logger) - { - _dispatcher = dispatcher; - _subscriberId = subscriberId; - _logger = logger; - } public void Subscribe(IAsyncEnumerable messageSource) { @@ -30,17 +20,17 @@ public async Task RunAsync(CancellationToken stoppingToken) { await Task.Yield(); - _logger.LogTrace("Starting up {StartupType} with Id {SubscriberId}", + logger.LogTrace("Starting up {StartupType} with Id {SubscriberId}", nameof(MultiplexerSubscriber), - _subscriberId); + subscriberId); await foreach (IQueueMessageContext messageContext in _messageSource.WithCancellation( stoppingToken)) { stoppingToken.ThrowIfCancellationRequested(); - await _dispatcher.DispatchMessageAsync(messageContext, stoppingToken) + await dispatcher.DispatchMessageAsync(messageContext, stoppingToken) .ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs b/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs index a98a1365c..1dc192243 100644 --- a/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs +++ b/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs @@ -14,18 +14,18 @@ internal sealed class MergingMultiplexer : IMultiplexer, IDisposable private CancellationToken _stoppingToken; private Task _completion; - private readonly IList> _readers; + private readonly List> _readers; private readonly Channel _targetChannel; private readonly int _channelCapacity; - private readonly SemaphoreSlim _readersLock = new SemaphoreSlim(1, 1); - private readonly object _startLock = new object(); + private readonly SemaphoreSlim _readersLock = new(1, 1); + private readonly object _startLock = new(); public MergingMultiplexer( int channelCapacity, ILogger logger) { - _readers = new List>(); + _readers = []; _logger = logger; _channelCapacity = channelCapacity; @@ -125,4 +125,4 @@ public void Dispose() _completion = null; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs b/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs index b9fc79d07..5d53c24ea 100644 --- a/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs +++ b/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs @@ -26,7 +26,7 @@ internal class MessageReceiveBuffer : IMessageReceiveBuffer private readonly IMessageMonitor _monitor; private readonly ILogger _logger; - private readonly HashSet _requestMessageAttributeNames = new HashSet(); + private readonly HashSet _requestMessageAttributeNames = new(); public ChannelReader Reader => _channel.Reader; diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs index ae8ede65a..d7a3d0835 100644 --- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs +++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs @@ -7,54 +7,40 @@ namespace JustSaying.Messaging.Channels.SubscriptionGroups; /// -internal class SubscriptionGroup : ISubscriptionGroup +/// +/// Coordinates reading messages from a collection of +/// and dispatching using a collection of . +/// +/// The to use. +/// The collection of to read from. +/// The to aggregate all messages into one stream. +/// The collection of that will dispatch the messages +/// The to be used. +internal class SubscriptionGroup( + SubscriptionGroupSettings settings, + ICollection receiveBuffers, + IMultiplexer multiplexer, + ICollection subscribers, + ILogger logger) : ISubscriptionGroup { - private readonly ICollection _receiveBuffers; - private readonly SubscriptionGroupSettings _settings; - private readonly IMultiplexer _multiplexer; - private readonly ICollection _subscribers; - private readonly ILogger _logger; - - /// - /// Coordinates reading messages from a collection of - /// and dispatching using a collection of . - /// - /// The to use. - /// The collection of to read from. - /// The to aggregate all messages into one stream. - /// The collection of that will dispatch the messages - /// The to be used. - public SubscriptionGroup( - SubscriptionGroupSettings settings, - ICollection receiveBuffers, - IMultiplexer multiplexer, - ICollection subscribers, - ILogger logger) - { - _receiveBuffers = receiveBuffers; - _settings = settings; - _multiplexer = multiplexer; - _subscribers = subscribers; - _logger = logger; - } - /// public Task RunAsync(CancellationToken stoppingToken) { - var receiveBufferQueueNames = string.Join(",", _receiveBuffers.Select(rb => rb.QueueName)); + var receiveBufferQueueNames = string.Join(",", receiveBuffers.Select(rb => rb.QueueName)); - _logger.LogInformation( - "Starting up SubscriptionGroup {SubscriptionGroupName} for queues [{Queues}] with {ReceiveBuffferCount} receive buffers and {SubscriberCount} subscribers.", - _settings.Name, + logger.LogInformation( + "Starting up SubscriptionGroup {SubscriptionGroupName} for queues [{Queues}] with {ReceiveBufferCount} receive buffers and {SubscriberCount} subscribers.", + settings.Name, receiveBufferQueueNames, - _receiveBuffers.Count, - _subscribers.Count); - - var completionTasks = new List(); + receiveBuffers.Count, + subscribers.Count); - completionTasks.Add(_multiplexer.RunAsync(stoppingToken)); - completionTasks.AddRange(_subscribers.Select(subscriber => subscriber.RunAsync(stoppingToken))); - completionTasks.AddRange(_receiveBuffers.Select(buffer => buffer.RunAsync(stoppingToken))); + var completionTasks = new List + { + multiplexer.RunAsync(stoppingToken) + }; + completionTasks.AddRange(subscribers.Select(subscriber => subscriber.RunAsync(stoppingToken))); + completionTasks.AddRange(receiveBuffers.Select(buffer => buffer.RunAsync(stoppingToken))); return Task.WhenAll(completionTasks); } @@ -64,10 +50,10 @@ public InterrogationResult Interrogate() { return new InterrogationResult(new { - _settings.Name, - ConcurrencyLimit = _subscribers.Count, - Multiplexer = _multiplexer.Interrogate(), - ReceiveBuffers = _receiveBuffers.Select(rb => rb.Interrogate()).ToArray(), + settings.Name, + ConcurrencyLimit = subscribers.Count, + Multiplexer = multiplexer.Interrogate(), + ReceiveBuffers = receiveBuffers.Select(rb => rb.Interrogate()).ToArray(), }); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs index 092919c0e..84627afb4 100644 --- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs +++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs @@ -4,27 +4,20 @@ namespace JustSaying.Messaging.Channels.SubscriptionGroups; /// -public class SubscriptionGroupCollection : ISubscriptionGroup +/// +/// Runs multiple instances of . +/// +/// The collection of instances to run. +/// The to use. +public class SubscriptionGroupCollection( + IList subscriptionGroups, + ILogger logger) : ISubscriptionGroup { - private readonly ILogger _logger; - private readonly IList _subscriptionGroups; - - /// - /// Runs multiple instances of . - /// - /// The collection of instances to run. - /// The to use. - public SubscriptionGroupCollection( - IList subscriptionGroups, - ILogger logger) - { - _subscriptionGroups = subscriptionGroups ?? throw new System.ArgumentNullException(nameof(subscriptionGroups)); - _logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); - } - + private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + private readonly IList _subscriptionGroups = subscriptionGroups ?? throw new ArgumentNullException(nameof(subscriptionGroups)); private Task _completion; private bool _started; - private readonly object _startLock = new object(); + private readonly object _startLock = new(); /// public Task RunAsync(CancellationToken stoppingToken) @@ -66,4 +59,4 @@ private Task RunImplAsync(CancellationToken stoppingToken) return Task.WhenAll(completionTasks); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs index a55bfd748..0107620c4 100644 --- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs +++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs @@ -9,9 +9,14 @@ namespace JustSaying.Messaging.Channels.SubscriptionGroups; /// are combined with overrides set here to create a final configuration /// that can be inspected via . /// -public class SubscriptionGroupConfigBuilder +/// +/// Creates an instance of . +/// +/// The name of the subscription group. +public class SubscriptionGroupConfigBuilder(string groupName) { - private readonly List _sqsQueues; + private readonly List _sqsQueues = []; + private readonly string _groupName = groupName ?? throw new ArgumentNullException(nameof(groupName)); private int? _bufferSize; private TimeSpan? _receiveBufferReadTimeout; @@ -20,18 +25,6 @@ public class SubscriptionGroupConfigBuilder private int? _multiplexerCapacity; private int? _prefetch; - private readonly string _groupName; - - /// - /// Creates an instance of . - /// - /// The name of the subscription group. - public SubscriptionGroupConfigBuilder(string groupName) - { - _groupName = groupName ?? throw new ArgumentNullException(nameof(groupName)); - _sqsQueues = new List(); - } - /// /// Adds an to be consumed by this . /// diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs index 63b144a13..bb3dcc5c3 100644 --- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs +++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs @@ -69,7 +69,7 @@ public ISubscriptionGroup Create( { ReceiveMiddleware receiveMiddleware = defaults.SqsMiddleware ?? _defaultSqsMiddleware; - List groups = subscriptionGroupSettings + var groups = subscriptionGroupSettings .Values .Select(builder => Create(receiveMiddleware, builder.Build(defaults))) .ToList(); @@ -81,7 +81,7 @@ public ISubscriptionGroup Create( private ISubscriptionGroup Create(ReceiveMiddleware receiveMiddleware, SubscriptionGroupSettings settings) { - IMultiplexer multiplexer = CreateMultiplexer(settings.MultiplexerCapacity); + var multiplexer = CreateMultiplexer(settings.MultiplexerCapacity); ICollection receiveBuffers = CreateBuffers(receiveMiddleware, settings); ICollection subscribers = CreateSubscribers(settings); @@ -103,11 +103,11 @@ private ISubscriptionGroup Create(ReceiveMiddleware receiveMiddleware, Subscript _loggerFactory.CreateLogger()); } - private ICollection CreateBuffers( + private List CreateBuffers( ReceiveMiddleware receiveMiddleware, SubscriptionGroupSettings subscriptionGroupSettings) { - var buffers = new List(); + List buffers = []; var logger = _loggerFactory.CreateLogger(); @@ -130,14 +130,14 @@ private ICollection CreateBuffers( return buffers; } - private IMultiplexer CreateMultiplexer(int channelCapacity) + private MergingMultiplexer CreateMultiplexer(int channelCapacity) { return new MergingMultiplexer( channelCapacity, _loggerFactory.CreateLogger()); } - private ICollection CreateSubscribers(SubscriptionGroupSettings settings) + private List CreateSubscribers(SubscriptionGroupSettings settings) { var logger = _loggerFactory.CreateLogger(); diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs index cce25349f..7e7bfc5cc 100644 --- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs +++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs @@ -55,7 +55,7 @@ internal SubscriptionGroupSettings( public int MultiplexerCapacity { get; } /// - /// Gets the maxiumum number of messages to fetch from SQS in each request. + /// Gets the maximum number of messages to fetch from SQS in each request. /// public int Prefetch { get; } diff --git a/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs b/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs index 498b939ff..1423679d9 100644 --- a/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs +++ b/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs @@ -6,20 +6,15 @@ namespace JustSaying.Messaging.Interrogation; /// This type represents the result of interrogating a bus component. /// [JsonConverter(typeof(InterrogationResultJsonConverter))] -public sealed class InterrogationResult +public sealed class InterrogationResult(object data) { - public InterrogationResult(object data) - { - Data = data; - } - /// /// Serialize this to JSON and log it on startup to gain some valuable insights into what's /// going on inside JustSaying. /// /// This property is intentionally untyped, because it is unstructured and subject to change. /// It should only be used for diagnostic purposes. - public object Data { get; } + public object Data { get; } = data; internal static InterrogationResult Empty { get; } = new InterrogationResult(new {}); -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageHandling/ListHandler.cs b/src/JustSaying/Messaging/MessageHandling/ListHandler.cs index b153aada7..147e7f714 100644 --- a/src/JustSaying/Messaging/MessageHandling/ListHandler.cs +++ b/src/JustSaying/Messaging/MessageHandling/ListHandler.cs @@ -1,20 +1,13 @@ namespace JustSaying.Messaging.MessageHandling; -public class ListHandler : IHandlerAsync +public class ListHandler(IEnumerable> handlers) : IHandlerAsync { - private readonly IEnumerable> _handlers; - - public ListHandler(IEnumerable> handlers) - { - _handlers = handlers; - } - public async Task Handle(T message) { - var handlerTasks = _handlers.Select(h => h.Handle(message)); + var handlerTasks = handlers.Select(h => h.Handle(message)); var handlerResults = await Task.WhenAll(handlerTasks) .ConfigureAwait(false); return handlerResults.All(x => x); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs b/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs index 43bc0951f..aea001e35 100644 --- a/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs +++ b/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs @@ -5,14 +5,9 @@ namespace JustSaying.Messaging.MessageHandling; /// /// A collection of values returned by . /// -public class MessageAttributes +public class MessageAttributes(Dictionary attributes) { - private readonly IDictionary _attributes; - - public MessageAttributes(Dictionary attributes) - { - _attributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); - } + private readonly Dictionary _attributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); public MessageAttributes() : this(new Dictionary()) @@ -21,4 +16,4 @@ public MessageAttributes() public MessageAttributeValue Get(string value) => _attributes.TryGetValue(value, out MessageAttributeValue result) ? result : null; -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageHandling/MessageContext.cs b/src/JustSaying/Messaging/MessageHandling/MessageContext.cs index 77d45456c..d200d17a5 100644 --- a/src/JustSaying/Messaging/MessageHandling/MessageContext.cs +++ b/src/JustSaying/Messaging/MessageHandling/MessageContext.cs @@ -5,33 +5,27 @@ namespace JustSaying.Messaging.MessageHandling; /// /// Context metadata about the SQS message currently being processed. /// -public class MessageContext +/// +/// Creates an instance of . +/// +/// The currently being processed. +/// The URI of the SQS queue the message is from. +/// The from the message. +public class MessageContext(SQSMessage message, Uri queueUri, MessageAttributes messageAttributes) { - /// - /// Creates an instance of . - /// - /// The currently being processed. - /// The URI of the SQS queue the message is from. - /// The from the message. - public MessageContext(SQSMessage message, Uri queueUri, MessageAttributes messageAttributes) - { - Message = message ?? throw new ArgumentNullException(nameof(message)); - QueueUri = queueUri ?? throw new ArgumentNullException(nameof(queueUri)); - MessageAttributes = messageAttributes ?? throw new ArgumentNullException(nameof(messageAttributes)); - } /// /// Gets the AWS SQS Message that is currently being processed. /// - public SQSMessage Message { get; } + public SQSMessage Message { get; } = message ?? throw new ArgumentNullException(nameof(message)); /// /// Gets the SQS Queue that the message was received on. /// - public Uri QueueUri { get; } + public Uri QueueUri { get; } = queueUri ?? throw new ArgumentNullException(nameof(queueUri)); /// /// Gets a collection of 's that were sent with this message. /// - public MessageAttributes MessageAttributes { get; } + public MessageAttributes MessageAttributes { get; } = messageAttributes ?? throw new ArgumentNullException(nameof(messageAttributes)); } \ No newline at end of file diff --git a/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs b/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs index 3d609911e..b054f385c 100644 --- a/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs +++ b/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs @@ -2,11 +2,11 @@ namespace JustSaying.Messaging.MessageHandling; public class MessageContextAccessor : IMessageContextReader, IMessageContextAccessor { - private static readonly AsyncLocal Context = new AsyncLocal(); + private static readonly AsyncLocal Context = new(); public MessageContext MessageContext { get => Context.Value; set => Context.Value = value; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs b/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs index fa8c290a3..0be4d9174 100644 --- a/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs +++ b/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs @@ -25,4 +25,4 @@ public string GetSubjectForType(Type messageType) => .Join("_", Flatten(messageType).Select(t => Regex.Replace(t.Name + "_" + t.Namespace, "\\W", "_"))) .TruncateTo(MAX_SNS_SUBJECT_LENGTH); -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs b/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs index 5c56b24ab..3fa3fb4b9 100644 --- a/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs +++ b/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs @@ -3,19 +3,15 @@ namespace JustSaying.Messaging.MessageSerialization; -public class MessageSerializationRegister : IMessageSerializationRegister +public class MessageSerializationRegister( + IMessageSubjectProvider messageSubjectProvider, + IMessageSerializationFactory serializationFactory) : IMessageSerializationRegister { - private readonly IMessageSubjectProvider _messageSubjectProvider; - private readonly IMessageSerializationFactory _serializationFactory; + private readonly IMessageSubjectProvider _messageSubjectProvider = messageSubjectProvider ?? throw new ArgumentNullException(nameof(messageSubjectProvider)); + private readonly IMessageSerializationFactory _serializationFactory = serializationFactory; private readonly ConcurrentDictionary> _typeSerializersBySubject = new(StringComparer.OrdinalIgnoreCase); private readonly HashSet _messageSerializers = new(); - public MessageSerializationRegister(IMessageSubjectProvider messageSubjectProvider, IMessageSerializationFactory serializationFactory) - { - _messageSubjectProvider = messageSubjectProvider ?? throw new ArgumentNullException(nameof(messageSubjectProvider)); - _serializationFactory = serializationFactory; - } - public void AddSerializer() where T : Message { string key = _messageSubjectProvider.GetSubjectForType(typeof(T)); diff --git a/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs b/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs index d4abfdedd..d57fdaac1 100644 --- a/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs +++ b/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs @@ -6,21 +6,15 @@ namespace JustSaying.Messaging.MessageSerialization; /// /// Represents a deserialized message with attributes. /// -public class MessageWithAttributes +public class MessageWithAttributes(Message message, MessageAttributes messageAttributes) { - public MessageWithAttributes(Message message, MessageAttributes messageAttributes) - { - Message = message; - MessageAttributes = messageAttributes; - } - /// /// Gets the message that was extracted from a message body. /// - public Message Message { get; } + public Message Message { get; } = message; /// /// Gets the attributes that were extracted from a message body. /// - public MessageAttributes MessageAttributes { get; } -} \ No newline at end of file + public MessageAttributes MessageAttributes { get; } = messageAttributes; +} diff --git a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs index cef08b5ec..da7ebbe97 100644 --- a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs +++ b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs @@ -3,19 +3,14 @@ namespace JustSaying.Messaging.MessageSerialization; -public class NewtonsoftSerializationFactory : IMessageSerializationFactory +public class NewtonsoftSerializationFactory(JsonSerializerSettings settings) : IMessageSerializationFactory { - private readonly NewtonsoftSerializer _serializer; + private readonly NewtonsoftSerializer _serializer = new(settings); public NewtonsoftSerializationFactory() : this(null) { } - public NewtonsoftSerializationFactory(JsonSerializerSettings settings) - { - _serializer = new NewtonsoftSerializer(settings); - } - public IMessageSerializer GetSerializer() where T : Message => _serializer; -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs index 6a546423f..68c5b5d25 100644 --- a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs +++ b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs @@ -16,14 +16,11 @@ public NewtonsoftSerializer() public NewtonsoftSerializer(JsonSerializerSettings settings) { - if (settings == null) - { - settings = new JsonSerializerSettings + settings ??= new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Converters = new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter() } }; - } _settings = settings; } @@ -91,4 +88,4 @@ public string GetMessageSubject(string sqsMessage) var body = JObject.Parse(sqsMessage); return body.Value("Subject") ?? string.Empty; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs index 7bb59b9fb..023957b78 100644 --- a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs +++ b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs @@ -3,19 +3,14 @@ namespace JustSaying.Messaging.MessageSerialization; -public class SystemTextJsonSerializationFactory : IMessageSerializationFactory +public class SystemTextJsonSerializationFactory(JsonSerializerOptions options) : IMessageSerializationFactory { - private readonly SystemTextJsonSerializer _serializer; + private readonly SystemTextJsonSerializer _serializer = new(options); public SystemTextJsonSerializationFactory() : this(null) { } - public SystemTextJsonSerializationFactory(JsonSerializerOptions options) - { - _serializer = new SystemTextJsonSerializer(options); - } - public IMessageSerializer GetSerializer() where T : Message => _serializer; -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs index 7a4cbd68f..50f5c2697 100644 --- a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs +++ b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs @@ -42,17 +42,15 @@ public SystemTextJsonSerializer(JsonSerializerOptions options) /// public string GetMessageSubject(string sqsMessage) { - using (var body = JsonDocument.Parse(sqsMessage)) - { - string subject = string.Empty; - - if (body.RootElement.TryGetProperty("Subject", out var value)) - { - subject = value.GetString() ?? string.Empty; - } + using var body = JsonDocument.Parse(sqsMessage); + string subject = string.Empty; - return subject; + if (body.RootElement.TryGetProperty("Subject", out var value)) + { + subject = value.GetString() ?? string.Empty; } + + return subject; } public MessageAttributes GetMessageAttributes(string message) @@ -86,13 +84,11 @@ public MessageAttributes GetMessageAttributes(string message) /// public Message Deserialize(string message, Type type) { - using (var document = JsonDocument.Parse(message)) - { - JsonElement element = document.RootElement.GetProperty("Message"); - string json = element.ToString(); + using var document = JsonDocument.Parse(message); + JsonElement element = document.RootElement.GetProperty("Message"); + string json = element.ToString(); - return (Message)JsonSerializer.Deserialize(json, type, _options); - } + return (Message)JsonSerializer.Deserialize(json, type, _options); } /// diff --git a/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs b/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs index f58986ba2..6f116d7b9 100644 --- a/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs +++ b/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs @@ -1,13 +1,7 @@ namespace JustSaying.Messaging.MessageSerialization; -public class TypeSerializer +public class TypeSerializer(Type type, IMessageSerializer serializer) { - public Type Type { get; private set; } - public IMessageSerializer Serializer { get; private set; } - - public TypeSerializer(Type type, IMessageSerializer serializer) - { - Type = type; - Serializer = serializer; - } -} \ No newline at end of file + public Type Type { get; private set; } = type; + public IMessageSerializer Serializer { get; private set; } = serializer; +} diff --git a/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs b/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs index b2d05640c..15a75c35a 100644 --- a/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs @@ -10,25 +10,18 @@ namespace JustSaying.Messaging.Middleware.Backoff; /// /// Implements a middleware that will execute an to delay message redelivery when a handler returns false or throws. /// -public sealed class BackoffMiddleware : MiddlewareBase +/// +/// Constructs a with a given backoff strategy and logger/monitor. +/// +/// An to use to determine how long to delay message redelivery when a handler returns false or throws. +/// An to use when logging request failures. +/// An to use when recording request failures. +public sealed class BackoffMiddleware(IMessageBackoffStrategy backoffStrategy, ILoggerFactory loggerFactory, IMessageMonitor monitor) : MiddlewareBase { - private readonly IMessageBackoffStrategy _backoffStrategy; - private readonly ILogger _logger; - private readonly IMessageMonitor _monitor; - - /// - /// Constructs a with a given backoff strategy and logger/monitor. - /// - /// An to use to determine how long to delay message redelivery when a handler returns false or throws. - /// An to use when logging request failures. - /// An to use when recording request failures. - public BackoffMiddleware(IMessageBackoffStrategy backoffStrategy, ILoggerFactory loggerFactory, IMessageMonitor monitor) - { - _backoffStrategy = backoffStrategy ?? throw new ArgumentNullException(nameof(backoffStrategy)); - _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); - _logger = loggerFactory?.CreateLogger() ?? + private readonly IMessageBackoffStrategy _backoffStrategy = backoffStrategy ?? throw new ArgumentNullException(nameof(backoffStrategy)); + private readonly ILogger _logger = loggerFactory?.CreateLogger() ?? throw new ArgumentNullException(nameof(loggerFactory)); - } + private readonly IMessageMonitor _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { @@ -70,7 +63,7 @@ private async Task TryUpdateVisibilityTimeout(HandleMessageContext context, Canc } private static bool TryGetApproxReceiveCount( - IDictionary attributes, + Dictionary attributes, out int approxReceiveCount) { approxReceiveCount = 0; @@ -82,4 +75,4 @@ private static bool TryGetApproxReceiveCount( CultureInfo.InvariantCulture, out approxReceiveCount); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs b/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs index 390f2fe8e..1d2d2a4c0 100644 --- a/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs +++ b/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs @@ -3,7 +3,5 @@ namespace JustSaying.Messaging.Middleware; internal class DelegateMiddleware : MiddlewareBase { protected override async Task RunInnerAsync(TContext context, Func> func, CancellationToken stoppingToken) - { - return await func(stoppingToken).ConfigureAwait(false); - } -} \ No newline at end of file + => await func(stoppingToken).ConfigureAwait(false); +} diff --git a/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs b/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs index f3d561c03..1970a07c1 100644 --- a/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs @@ -7,19 +7,14 @@ namespace JustSaying.Messaging.Middleware.ErrorHandling; /// This middleware calls HandleException(Type messageType), HandleError(Exception ex, Amazon.SQS.Model.Message message), /// and Handled(JustSaying.Models.Message message). /// -public sealed class ErrorHandlerMiddleware : MiddlewareBase +/// +/// Constructs an . +/// +/// The to use to record errors. +/// When the is null. +public sealed class ErrorHandlerMiddleware(IMessageMonitor monitor) : MiddlewareBase { - private readonly IMessageMonitor _monitor; - - /// - /// Constructs an . - /// - /// The to use to record errors. - /// When the is null. - public ErrorHandlerMiddleware(IMessageMonitor monitor) - { - _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); - } + private readonly IMessageMonitor _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { @@ -40,4 +35,4 @@ protected override async Task RunInnerAsync(HandleMessageContext context, _monitor.Handled(context.Message); } } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs b/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs index 7afe333bc..62e06d0ea 100644 --- a/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs @@ -4,24 +4,9 @@ // ReSharper disable once CheckNamespace namespace JustSaying.Messaging.Middleware; -public sealed class ExactlyOnceMiddleware : MiddlewareBase +public sealed class ExactlyOnceMiddleware(IMessageLockAsync messageLock, TimeSpan timeout, string handlerName, ILogger logger) : MiddlewareBase { - private readonly IMessageLockAsync _messageLock; - private readonly TimeSpan _timeout; - private readonly string _lockSuffixKeyForHandler; - private readonly ILogger _logger; - - private const bool RemoveTheMessageFromTheQueue = true; - private const bool LeaveItInTheQueue = false; - - public ExactlyOnceMiddleware(IMessageLockAsync messageLock, TimeSpan timeout, string handlerName, ILogger logger) - { - _messageLock = messageLock; - _timeout = timeout; - _logger = logger; - - _lockSuffixKeyForHandler = $"{typeof(T).FullName.ToLowerInvariant()}-{handlerName}"; - } + private readonly string _lockSuffixKeyForHandler = $"{typeof(T).FullName.ToLowerInvariant()}-{handlerName}"; protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { @@ -30,40 +15,40 @@ protected override async Task RunInnerAsync(HandleMessageContext context, string lockKey = $"{context.Message.UniqueKey()}-{_lockSuffixKeyForHandler}"; - MessageLockResponse lockResponse = await _messageLock.TryAcquireLockAsync(lockKey, _timeout).ConfigureAwait(false); + MessageLockResponse lockResponse = await messageLock.TryAcquireLockAsync(lockKey, timeout).ConfigureAwait(false); if (!lockResponse.DoIHaveExclusiveLock) { if (lockResponse.IsMessagePermanentlyLocked) { - _logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey} as it is permanently locked.", lockKey); - return RemoveTheMessageFromTheQueue; + logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey} as it is permanently locked.", lockKey); + return true; } - _logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey}; returning message to queue.", lockKey); - return LeaveItInTheQueue; + logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey}; returning message to queue.", lockKey); + return false; } try { - _logger.LogDebug("Acquired lock for message with key {MessageLockKey}.", lockKey); + logger.LogDebug("Acquired lock for message with key {MessageLockKey}.", lockKey); bool successfullyHandled = await func(stoppingToken).ConfigureAwait(false); if (successfullyHandled) { - await _messageLock.TryAcquireLockPermanentlyAsync(lockKey).ConfigureAwait(false); + await messageLock.TryAcquireLockPermanentlyAsync(lockKey).ConfigureAwait(false); - _logger.LogDebug("Acquired permanent lock for message with key {MessageLockKey}.", lockKey); + logger.LogDebug("Acquired permanent lock for message with key {MessageLockKey}.", lockKey); } return successfullyHandled; } catch (Exception) { - await _messageLock.ReleaseLockAsync(lockKey).ConfigureAwait(false); - _logger.LogDebug("Released lock for message with key {MessageLockKey}.", lockKey); + await messageLock.ReleaseLockAsync(lockKey).ConfigureAwait(false); + logger.LogDebug("Released lock for message with key {MessageLockKey}.", lockKey); throw; } } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs b/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs index d314dc82c..e1e8c0fca 100644 --- a/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs +++ b/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs @@ -6,69 +6,64 @@ // ReSharper disable once CheckNamespace namespace JustSaying.Messaging.Middleware; -public sealed class HandleMessageContext +/// +/// This class encapsulates a messages context as it passes through a middleware pipeline. +/// +/// The JustSaying message that was deserialized from SQS. +/// The type of the JustSaying message contained in . +/// The queue from which this message was received. +/// The to use to update message visibilities on failure. +/// The to use to remove a message from the queue on success. +public sealed class HandleMessageContext( + string queueName, + Amazon.SQS.Model.Message rawMessage, + Message message, + Type messageType, + IMessageVisibilityUpdater visibilityUpdater, + IMessageDeleter messageDeleter, + Uri queueUri, + MessageAttributes messageAttributes) { - /// - /// This class encapsulates a messages context as it passes through a middleware pipeline. - /// - /// The JustSaying message that was deserialized from SQS. - /// The type of the JustSaying message contained in . - /// The queue from which this message was received. - /// The to use to update message visibilities on failure. - /// The to use to remove a message from the queue on success. - public HandleMessageContext(string queueName, Amazon.SQS.Model.Message rawMessage, Message message, - Type messageType, IMessageVisibilityUpdater visibilityUpdater, IMessageDeleter messageDeleter, - Uri queueUri, MessageAttributes messageAttributes) - { - Message = message; - MessageType = messageType; - QueueName = queueName; - VisibilityUpdater = visibilityUpdater; - MessageDeleter = messageDeleter; - QueueUri = queueUri; - MessageAttributes = messageAttributes; - RawMessage = rawMessage; - } /// /// The queue name from which this message was received. /// - public string QueueName { get; } + public string QueueName { get; } = queueName; /// /// The type of the JustSaying message contained in . /// - public Type MessageType { get; } + public Type MessageType { get; } = messageType; /// /// The JustSaying message that was deserialized from SQS. /// - public Message Message { get; } + public Message Message { get; } = message; /// /// The Absolute Uri of the queue this message came from. /// - public Uri QueueUri { get; } + public Uri QueueUri { get; } = queueUri; /// /// A collection of attributes that were downloaded with this message. /// - public MessageAttributes MessageAttributes { get; } + public MessageAttributes MessageAttributes { get; } = messageAttributes; /// /// The raw SQS message that was downloaded from the queue. /// - public Amazon.SQS.Model.Message RawMessage { get; } + public Amazon.SQS.Model.Message RawMessage { get; } = rawMessage; /// /// An that can be used to update the visibility timeout for this message. /// - public IMessageVisibilityUpdater VisibilityUpdater { get; } + public IMessageVisibilityUpdater VisibilityUpdater { get; } = visibilityUpdater; /// /// An that can be used to delete this message. /// - public IMessageDeleter MessageDeleter { get; } + public IMessageDeleter MessageDeleter { get; } = messageDeleter; /// /// The that occurred in the handling of this message. @@ -83,4 +78,4 @@ public void SetException(Exception e) { HandledException = e; } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs b/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs index 40cf73c70..ac6a0440f 100644 --- a/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs @@ -8,14 +8,9 @@ namespace JustSaying.Messaging.Middleware; /// This middleware is responsible for resolving a message handler and calling it. /// /// The type of the message that the message handler handles. -public sealed class HandlerInvocationMiddleware : MiddlewareBase where T : Message +public sealed class HandlerInvocationMiddleware(Func> handlerResolver) : MiddlewareBase where T : Message { - private readonly Func> _handlerResolver; - - public HandlerInvocationMiddleware(Func> handlerResolver) - { - _handlerResolver = handlerResolver ?? throw new ArgumentNullException(nameof(handlerResolver)); - } + private readonly Func> _handlerResolver = handlerResolver ?? throw new ArgumentNullException(nameof(handlerResolver)); protected override async Task RunInnerAsync( HandleMessageContext context, @@ -32,4 +27,4 @@ protected override async Task RunInnerAsync( return await handler.Handle(context.MessageAs()).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs index 58611914f..77c07c11b 100644 --- a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs +++ b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs @@ -9,28 +9,20 @@ namespace JustSaying.Messaging.Middleware; /// /// A class representing a builder for a middleware pipeline. /// -public sealed class HandlerMiddlewareBuilder +/// +/// Creates a HandlerMiddlewareBuilder instance. +/// +/// An that can create handlers. +/// An that enables resolution of middlewares +/// and middleware services. +public sealed class HandlerMiddlewareBuilder(IHandlerResolver handlerResolver, IServiceResolver serviceResolver) { private Action _configure; - internal IServiceResolver ServiceResolver { get; } - private IHandlerResolver HandlerResolver { get; } + internal IServiceResolver ServiceResolver { get; } = serviceResolver; - private readonly List> _middlewares; + private readonly List> _middlewares = []; private HandleMessageMiddleware _handlerMiddleware; - /// - /// Creates a HandlerMiddlewareBuilder instance. - /// - /// An that can create handlers. - /// An that enables resolution of middlewares - /// and middleware services. - public HandlerMiddlewareBuilder(IHandlerResolver handlerResolver, IServiceResolver serviceResolver) - { - ServiceResolver = serviceResolver; - HandlerResolver = handlerResolver; - _middlewares = new List>(); - } - /// /// Adds a middleware of type to the pipeline which will be resolved from the /// . It will be resolved once when the pipeline is built, and cached @@ -103,7 +95,7 @@ public HandlerMiddlewareBuilder UseHandler() where TMessage : Message $"Handler middleware has already been specified for {typeof(TMessage).Name} on this queue."); } - _handlerMiddleware = new HandlerInvocationMiddleware(HandlerResolver.ResolveHandler); + _handlerMiddleware = new HandlerInvocationMiddleware(handlerResolver.ResolveHandler); return this; } diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs index 0b633ff3b..2b03d39d8 100644 --- a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs +++ b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs @@ -5,7 +5,6 @@ using JustSaying.Messaging.Middleware.MessageContext; using JustSaying.Messaging.Middleware.PostProcessing; using JustSaying.Models; -using HandleMessageMiddleware = JustSaying.Messaging.Middleware.MiddlewareBase; // ReSharper disable once CheckNamespace namespace JustSaying.Messaging.Middleware; diff --git a/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs b/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs index b6d37311e..ba513aa78 100644 --- a/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs @@ -6,23 +6,15 @@ namespace JustSaying.Messaging.Middleware.Logging; /// /// A middleware that logs a rich information or warning event when a message is handled. /// -public sealed class LoggingMiddleware : MiddlewareBase +/// +/// Constructs a . +/// +/// The to write logs to. +public sealed class LoggingMiddleware(ILoggerFactory loggerFactory) : MiddlewareBase { - private readonly ILogger _logger; - - /// - /// Constructs a . - /// - /// The to write logs to. - public LoggingMiddleware(ILoggerFactory loggerFactory) - { - _logger = loggerFactory?.CreateLogger() ?? - throw new ArgumentNullException(nameof(loggerFactory)); - } - - private const string MessageTemplate = "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms."; - private const string Succeeded = nameof(Succeeded); - private const string Failed = nameof(Failed); + private readonly ILogger _logger = + loggerFactory?.CreateLogger() + ?? throw new ArgumentNullException(nameof(loggerFactory)); protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { @@ -42,18 +34,24 @@ protected override async Task RunInnerAsync(HandleMessageContext context, } finally { + const string MessageTemplate = "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms."; + if (dispatchSuccessful) { - _logger.LogInformation(context.HandledException, MessageTemplate, - Succeeded, + _logger.LogInformation( + context.HandledException, + MessageTemplate, + "Succeeded", context.Message.Id, context.MessageType.FullName, watch.ElapsedMilliseconds); } else { - _logger.LogWarning(context.HandledException, MessageTemplate, - Failed, + _logger.LogWarning( + context.HandledException, + MessageTemplate, + "Failed", context.Message.Id, context.MessageType.FullName, watch.ElapsedMilliseconds); diff --git a/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs b/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs index 76357edd0..b3f4991c4 100644 --- a/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs @@ -5,18 +5,13 @@ namespace JustSaying.Messaging.Middleware.MessageContext; /// /// A middleware that sets context that is available in message handlers by resolving an `IMessageContextAccessor`. /// -public sealed class MessageContextAccessorMiddleware : MiddlewareBase +/// +/// Creates an instance of . +/// +/// The to set. +public sealed class MessageContextAccessorMiddleware(IMessageContextAccessor messageContextAccessor) : MiddlewareBase { - private readonly IMessageContextAccessor _messageContextAccessor; - - /// - /// Creates an instance of . - /// - /// The to set. - public MessageContextAccessorMiddleware(IMessageContextAccessor messageContextAccessor) - { - _messageContextAccessor = messageContextAccessor ?? throw new ArgumentNullException(nameof(messageContextAccessor)); - } + private readonly IMessageContextAccessor _messageContextAccessor = messageContextAccessor ?? throw new ArgumentNullException(nameof(messageContextAccessor)); protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { @@ -31,4 +26,4 @@ protected override async Task RunInnerAsync(HandleMessageContext context, _messageContextAccessor.MessageContext = null; } } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs b/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs index 415377fcb..f62b66862 100644 --- a/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs @@ -7,30 +7,21 @@ namespace JustSaying.Messaging.Middleware; /// /// This middleware measures the handler's execution duration and reports the results to an . /// -public sealed class StopwatchMiddleware : MiddlewareBase +/// +/// Creates an instance of a that will report results to an +/// . +/// +/// An to report results to. +/// The type of the handler that results should be reported against. +public sealed class StopwatchMiddleware(IMessageMonitor monitor, Type handlerType) : MiddlewareBase { - private readonly IMessageMonitor _monitor; - private readonly Type _handlerType; - - /// - /// Creates an instance of a that will report results to an - /// . - /// - /// An to report results to. - /// The type of the handler that results should be reported against. - public StopwatchMiddleware(IMessageMonitor monitor, Type handlerType) - { - _monitor = monitor; - _handlerType = handlerType; - } - protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { var watch = Stopwatch.StartNew(); try { - using (_monitor.MeasureDispatch()) + using (monitor.MeasureDispatch()) { return await func(stoppingToken).ConfigureAwait(false); } @@ -38,7 +29,7 @@ protected override async Task RunInnerAsync(HandleMessageContext context, finally { watch.Stop(); - _monitor.HandlerExecutionTime(_handlerType, context.MessageType, watch.Elapsed); + monitor.HandlerExecutionTime(handlerType, context.MessageType, watch.Elapsed); } } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs b/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs index 2dcd1d0e3..84aaa9411 100644 --- a/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs +++ b/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs @@ -32,7 +32,7 @@ public async Task RunAsync( return await func(ct).ConfigureAwait(false); } - else return default(TOut); + else return default; }, stoppingToken).ConfigureAwait(false); } diff --git a/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs b/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs index 45109a217..6c634727d 100644 --- a/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs +++ b/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs @@ -6,19 +6,12 @@ namespace JustSaying.Messaging.Middleware.Receive; /// /// The default middleware to use for the receive pipeline. /// -public class DefaultReceiveMessagesMiddleware : MiddlewareBase> +/// +/// Creates an instance of . +/// +/// The to use. +public class DefaultReceiveMessagesMiddleware(ILogger logger) : MiddlewareBase> { - private readonly ILogger _logger; - - /// - /// Creates an instance of . - /// - /// The to use. - public DefaultReceiveMessagesMiddleware(ILogger logger) - { - _logger = logger; - } - protected override async Task> RunInnerAsync( ReceiveMessagesContext context, Func>> func, @@ -28,7 +21,7 @@ protected override async Task> RunInnerAsync( { var results = await func(stoppingToken).ConfigureAwait(false); - _logger.LogTrace( + logger.LogTrace( "Polled for messages on queue '{QueueName}' in region '{Region}', and received {MessageCount} messages.", context.QueueName, context.RegionName, @@ -38,7 +31,7 @@ protected override async Task> RunInnerAsync( } catch (OperationCanceledException ex) { - _logger.LogTrace( + logger.LogTrace( ex, "Request to get more messages from queue was canceled for queue '{QueueName}' in region '{Region}'," + "likely because there are no messages in the queue. " + @@ -46,11 +39,9 @@ protected override async Task> RunInnerAsync( context.QueueName, context.RegionName); } -#pragma warning disable CA1031 catch (Exception ex) -#pragma warning restore CA1031 { - _logger.LogError( + logger.LogError( ex, "Error receiving messages on queue '{QueueName}' in region '{Region}'.", context.QueueName, @@ -59,4 +50,4 @@ protected override async Task> RunInnerAsync( return Array.Empty(); } -} \ No newline at end of file +} diff --git a/src/JustSaying/Messaging/Monitoring/LogOperation.cs b/src/JustSaying/Messaging/Monitoring/LogOperation.cs index 16d11e251..c30ce0d0e 100644 --- a/src/JustSaying/Messaging/Monitoring/LogOperation.cs +++ b/src/JustSaying/Messaging/Monitoring/LogOperation.cs @@ -3,54 +3,45 @@ namespace JustSaying.Messaging.Monitoring; -internal sealed class LogOperation : IDisposable +internal sealed class LogOperation(ILogger logger, LogLevel logLevel, string message, params object[] args) : IDisposable { - private readonly ILogger _logger; - private readonly string _message; - private readonly object[] _args; - private readonly Stopwatch _watch; - private readonly LogLevel _logLevel; - - private const string MessageTemplate = " finished in {0:0}ms"; - - public LogOperation(ILogger logger, LogLevel logLevel, string message, params object[] args) - { - _logger = logger; - _logLevel = logLevel; - _message = message; - _args = args; - _watch = Stopwatch.StartNew(); - } + private readonly string _message = message; + private readonly object[] _args = args; + private readonly Stopwatch _watch = Stopwatch.StartNew(); public void Dispose() { _watch.Stop(); - var message = $"{_message}{MessageTemplate}"; - var args = _args.Concat(new object[] { _watch.Elapsed.TotalMilliseconds }).ToArray(); + var message = $"{_message} finished in {0:0}ms"; + var args = _args.Concat([_watch.Elapsed.TotalMilliseconds]).ToArray(); - switch (_logLevel) +#pragma warning disable CA2254 + switch (logLevel) { case LogLevel.Trace: - _logger.LogTrace(message, args); + logger.LogTrace(message, args); return; case LogLevel.Debug: - _logger.LogDebug(message, args); + logger.LogDebug(message, args); return; case LogLevel.Information: - _logger.LogInformation(message, args); + logger.LogInformation(message, args); return; case LogLevel.Warning: - _logger.LogWarning(message, args); + logger.LogWarning(message, args); return; case LogLevel.Error: - _logger.LogError(message, args); + logger.LogError(message, args); return; case LogLevel.Critical: - _logger.LogCritical(message, args); + logger.LogCritical(message, args); return; case LogLevel.None: return; + default: + break; } +#pragma warning restore CA2254 } } diff --git a/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs b/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs index bc5fc6252..6919cd773 100644 --- a/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs +++ b/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs @@ -3,7 +3,7 @@ namespace JustSaying.Messaging.Monitoring; internal static class MonitorExtensions { public static Operation MeasureThrottle(this IMessageMonitor messageMonitor) - => new Operation(messageMonitor, (duration, monitor) => + => new(messageMonitor, (duration, monitor) => { if (duration.TotalMilliseconds < 1) return; monitor.IncrementThrottlingStatistic(); @@ -11,12 +11,12 @@ public static Operation MeasureThrottle(this IMessageMonitor messageMonitor) }); public static Operation MeasureDispatch(this IMessageMonitor messageMonitor) - => new Operation(messageMonitor, (duration, monitor) => monitor.HandleTime(duration)); + => new(messageMonitor, (duration, monitor) => monitor.HandleTime(duration)); public static Operation MeasureReceive(this IMessageMonitor messageMonitor, string queueName, string region) - => new Operation(messageMonitor, + => new(messageMonitor, (duration, monitor) => monitor.ReceiveMessageTime(duration, queueName, region)); public static Operation MeasurePublish(this IMessageMonitor messageMonitor) - => new Operation(messageMonitor, (duration, monitor) => monitor.PublishMessageTime(duration)); -} \ No newline at end of file + => new(messageMonitor, (duration, monitor) => monitor.PublishMessageTime(duration)); +} diff --git a/src/JustSaying/Messaging/PublishMetadata.cs b/src/JustSaying/Messaging/PublishMetadata.cs index e800da5af..cde53e33a 100644 --- a/src/JustSaying/Messaging/PublishMetadata.cs +++ b/src/JustSaying/Messaging/PublishMetadata.cs @@ -10,14 +10,11 @@ public class PublishMetadata public PublishMetadata AddMessageAttribute(string key, IReadOnlyCollection data) { - if (data == null) + var mav = new MessageAttributeValue { - throw new ArgumentNullException(nameof(data)); - } - - var mav = new MessageAttributeValue(); - mav.BinaryValue = data; - mav.DataType = "Binary"; + BinaryValue = data ?? throw new ArgumentNullException(nameof(data)), + DataType = "Binary" + }; MessageAttributes[key] = mav; @@ -26,10 +23,7 @@ public PublishMetadata AddMessageAttribute(string key, IReadOnlyCollection public PublishMetadata AddMessageAttribute(string key, MessageAttributeValue value) { - if (MessageAttributes == null) - { - MessageAttributes = new Dictionary(StringComparer.Ordinal); - } + MessageAttributes ??= new Dictionary(StringComparer.Ordinal); MessageAttributes[key] = value; @@ -54,4 +48,4 @@ public PublishMetadata AddMessageAttribute(string key, double value) }); } -} \ No newline at end of file +} diff --git a/src/JustSaying/MessagingBusBuilder.cs b/src/JustSaying/MessagingBusBuilder.cs index 5c958a5b6..b7b77c52e 100644 --- a/src/JustSaying/MessagingBusBuilder.cs +++ b/src/JustSaying/MessagingBusBuilder.cs @@ -79,10 +79,7 @@ public MessagingBusBuilder Client(Action configure) throw new ArgumentNullException(nameof(configure)); } - if (ClientFactoryBuilder == null) - { - ClientFactoryBuilder = new AwsClientFactoryBuilder(this); - } + ClientFactoryBuilder ??= new AwsClientFactoryBuilder(this); configure(ClientFactoryBuilder); @@ -106,10 +103,7 @@ public MessagingBusBuilder Messaging(Action confi throw new ArgumentNullException(nameof(configure)); } - if (MessagingConfig == null) - { - MessagingConfig = new MessagingConfigurationBuilder(this); - } + MessagingConfig ??= new MessagingConfigurationBuilder(this); configure(MessagingConfig); @@ -133,10 +127,7 @@ public MessagingBusBuilder Publications(Action configure) throw new ArgumentNullException(nameof(configure)); } - if (PublicationsBuilder == null) - { - PublicationsBuilder = new PublicationsBuilder(this); - } + PublicationsBuilder ??= new PublicationsBuilder(this); configure(PublicationsBuilder); @@ -233,10 +224,7 @@ public IMessagePublisher BuildPublisher() JustSayingBus bus = CreateBus(config, loggerFactory); IAwsClientFactoryProxy proxy = CreateFactoryProxy(); - if (PublicationsBuilder != null) - { - PublicationsBuilder.Configure(bus, proxy, loggerFactory); - } + PublicationsBuilder?.Configure(bus, proxy, loggerFactory); return bus; } diff --git a/src/JustSaying/Naming/DefaultNamingConventions.cs b/src/JustSaying/Naming/DefaultNamingConventions.cs index b84f044ba..8eb9fbd89 100644 --- a/src/JustSaying/Naming/DefaultNamingConventions.cs +++ b/src/JustSaying/Naming/DefaultNamingConventions.cs @@ -8,10 +8,7 @@ namespace JustSaying.Naming; /// public class DefaultNamingConventions : ITopicNamingConvention, IQueueNamingConvention { - private const int MaxTopicNameLength = 256; - private const int MaxQueueNameLength = 80; - - private static readonly HashSet TypesToMapAutomatically = new HashSet + private static readonly HashSet TypesToMapAutomatically = new() { typeof(string), typeof(object), @@ -34,9 +31,9 @@ public class DefaultNamingConventions : ITopicNamingConvention, IQueueNamingConv typeof(DateTimeOffset) }; - public virtual string TopicName() => CreateResourceName(typeof(T), MaxTopicNameLength); + public virtual string TopicName() => CreateResourceName(typeof(T), maximumLength: 256); - public virtual string QueueName() => CreateResourceName(typeof(T), MaxQueueNameLength); + public virtual string QueueName() => CreateResourceName(typeof(T), maximumLength: 80); private static string CreateResourceName(Type type, int maximumLength) { @@ -73,4 +70,4 @@ private static string GetTypeFriendlyName(Type type) return friendlyName; } -} \ No newline at end of file +} diff --git a/tests/JustSaying.Benchmark/BenchmarkMessage.cs b/tests/JustSaying.Benchmark/BenchmarkMessage.cs index efd9b13ea..26c2afda4 100644 --- a/tests/JustSaying.Benchmark/BenchmarkMessage.cs +++ b/tests/JustSaying.Benchmark/BenchmarkMessage.cs @@ -2,14 +2,8 @@ namespace JustSaying.Benchmark; -public class BenchmarkMessage : Message +public class BenchmarkMessage(TimeSpan sentAtOffset, int sequenceId) : Message { - public BenchmarkMessage(TimeSpan sentAtOffset, int sequenceId) - { - SentAtOffset = sentAtOffset; - SequenceId = sequenceId; - } - - public TimeSpan SentAtOffset { get; } - public int SequenceId { get; } -} \ No newline at end of file + public TimeSpan SentAtOffset { get; } = sentAtOffset; + public int SequenceId { get; } = sequenceId; +} diff --git a/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs b/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs index 418252fae..9cece764e 100644 --- a/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs +++ b/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs @@ -2,18 +2,13 @@ namespace JustSaying.Benchmark; -public class BenchmarkMessageHander : IHandlerAsync +public class BenchmarkMessageHander(IReportConsumerMetric reporter) : IHandlerAsync { - private readonly IReportConsumerMetric _reporter; - - public BenchmarkMessageHander(IReportConsumerMetric reporter) - { - _reporter = reporter; - } + private readonly IReportConsumerMetric _reporter = reporter; public Task Handle(BenchmarkMessage message) { _reporter.Consumed(message.Id); return Task.FromResult(true); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.Benchmark/JustSayingBenchmark.cs b/tests/JustSaying.Benchmark/JustSayingBenchmark.cs index f5fdf4609..a7d102a01 100644 --- a/tests/JustSaying.Benchmark/JustSayingBenchmark.cs +++ b/tests/JustSaying.Benchmark/JustSayingBenchmark.cs @@ -99,7 +99,7 @@ public static async Task RunTest(JustSayingBenchmark options) DrawResponseTimeGraph(messageMetrics, m => m.ConsumeLatency); } - static void RegisterJustSaying(IServiceCollection services) + private static void RegisterJustSaying(IServiceCollection services) { services.AddJustSaying(config => { @@ -113,7 +113,7 @@ static void RegisterJustSaying(IServiceCollection services) services.AddJustSayingHandler(); } - static void DrawResponseTimeGraph(MessageMetric[] metrics, Func selector) + private static void DrawResponseTimeGraph(MessageMetric[] metrics, Func selector) { long maxTime = metrics.Max(selector); long minTime = metrics.Min(selector); @@ -143,4 +143,4 @@ orderby segment.Key new string('*', barLength)); } } -} \ No newline at end of file +} diff --git a/tests/JustSaying.Benchmark/MessageMetric.cs b/tests/JustSaying.Benchmark/MessageMetric.cs index 4435fa2f4..93dc9357e 100644 --- a/tests/JustSaying.Benchmark/MessageMetric.cs +++ b/tests/JustSaying.Benchmark/MessageMetric.cs @@ -1,15 +1,8 @@ namespace JustSaying.Benchmark; -public class MessageMetric +public class MessageMetric(Guid messageId, long ackLatency, long consumeLatency) { - public MessageMetric(Guid messageId, long ackLatency, long consumeLatency) - { - MessageId = messageId; - AckLatency = ackLatency; - ConsumeLatency = consumeLatency; - } - - public Guid MessageId { get; } - public long AckLatency { get; set; } - public long ConsumeLatency { get; set; } -} \ No newline at end of file + public Guid MessageId { get; } = messageId; + public long AckLatency { get; set; } = ackLatency; + public long ConsumeLatency { get; set; } = consumeLatency; +} diff --git a/tests/JustSaying.Benchmark/MessageMetricCapture.cs b/tests/JustSaying.Benchmark/MessageMetricCapture.cs index 9ba514333..d157813e2 100644 --- a/tests/JustSaying.Benchmark/MessageMetricCapture.cs +++ b/tests/JustSaying.Benchmark/MessageMetricCapture.cs @@ -4,29 +4,15 @@ namespace JustSaying.Benchmark; // Borrowed with ❤ from https://github.com/MassTransit/MassTransit-Benchmark/blob/a04a0235e1/src/MassTransit-Benchmark/Latency/MessageMetricCapture.cs -public class MessageMetricCapture : - IReportConsumerMetric +public class MessageMetricCapture(long messageCount) : IReportConsumerMetric { - readonly TaskCompletionSource _consumeCompleted; - readonly ConcurrentBag _consumedMessages; - readonly long _messageCount; - readonly TaskCompletionSource _sendCompleted; - readonly ConcurrentBag _sentMessages; - readonly Stopwatch _stopwatch; - long _consumed; - long _sent; - - public MessageMetricCapture(long messageCount) - { - _messageCount = messageCount; - - _consumedMessages = new ConcurrentBag(); - _sentMessages = new ConcurrentBag(); - _sendCompleted = new TaskCompletionSource(); - _consumeCompleted = new TaskCompletionSource(); - - _stopwatch = Stopwatch.StartNew(); - } + private readonly TaskCompletionSource _consumeCompleted = new(); + private readonly ConcurrentBag _consumedMessages = []; + private readonly TaskCompletionSource _sendCompleted = new(); + private readonly ConcurrentBag _sentMessages = []; + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); + private long _consumed; + private long _sent; public Task SendCompleted => _sendCompleted.Task; public Task ConsumeCompleted => _consumeCompleted.Task; @@ -36,7 +22,7 @@ Task IReportConsumerMetric.Consumed(Guid messageId) _consumedMessages.Add(new ConsumedMessage(messageId, _stopwatch.ElapsedTicks)); long consumed = Interlocked.Increment(ref _consumed); - if (consumed == _messageCount) + if (consumed == messageCount) _consumeCompleted.TrySetResult(_stopwatch.Elapsed); return Task.CompletedTask; @@ -53,7 +39,7 @@ public async Task Sent(Guid messageId, Task sendTask) _sentMessages.Add(new SentMessage(messageId, sendTimestamp, ackTimestamp)); long sent = Interlocked.Increment(ref _sent); - if (sent == _messageCount) + if (sent == messageCount) _sendCompleted.TrySetResult(_stopwatch.Elapsed); } @@ -69,31 +55,16 @@ public MessageMetric[] GetMessageMetrics() .ToArray(); } - - struct SentMessage + private readonly struct SentMessage(Guid messageId, long sendTimestamp, long ackTimestamp) { - public readonly Guid MessageId; - public readonly long SendTimestamp; - public readonly long AckTimestamp; - - public SentMessage(Guid messageId, long sendTimestamp, long ackTimestamp) - { - MessageId = messageId; - SendTimestamp = sendTimestamp; - AckTimestamp = ackTimestamp; - } + public readonly Guid MessageId = messageId; + public readonly long SendTimestamp = sendTimestamp; + public readonly long AckTimestamp = ackTimestamp; } - - struct ConsumedMessage + private readonly struct ConsumedMessage(Guid messageId, long timestamp) { - public readonly Guid MessageId; - public readonly long Timestamp; - - public ConsumedMessage(Guid messageId, long timestamp) - { - MessageId = messageId; - Timestamp = timestamp; - } + public readonly Guid MessageId = messageId; + public readonly long Timestamp = timestamp; } -} \ No newline at end of file +} diff --git a/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs b/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs index f13b80aa3..1a7a2ee25 100644 --- a/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs +++ b/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs @@ -8,14 +8,9 @@ namespace JustSaying; -public class WhenUsingStructureMap +public class WhenUsingStructureMap(ITestOutputHelper outputHelper) { - public WhenUsingStructureMap(ITestOutputHelper outputHelper) - { - OutputHelper = outputHelper; - } - - private ITestOutputHelper OutputHelper { get; } + private ITestOutputHelper OutputHelper { get; } = outputHelper; [AwsFact] public async Task Can_Create_Messaging_Bus_Fluently_For_A_Queue() diff --git a/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs b/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs index 5cd929ac2..71456f9e1 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs @@ -1,17 +1,13 @@ namespace JustSaying.IntegrationTests.Fluent; -public class ActionRunnerTest : IntegrationTestBase +public class ActionRunnerTest(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public ActionRunnerTest(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - protected override TimeSpan Timeout => TimeSpan.FromSeconds(2); [Fact] public async Task TestRunnerWillSucceedOnSuccessfulTask() { - async Task SuccessTask(CancellationToken ctx) => + static async Task SuccessTask(CancellationToken ctx) => await Task.Delay(100, ctx); await RunActionWithTimeout(SuccessTask); @@ -30,7 +26,7 @@ await Assert.ThrowsAsync( [Fact] public async Task TestRunnerWillThrowOnFailure() { - async Task ThrowingTask(CancellationToken ctx) + static async Task ThrowingTask(CancellationToken ctx) { await Task.Delay(100, ctx); throw new InvalidOperationException(); diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs index be9342d15..1be2eb7b4 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs @@ -8,13 +8,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenANamedQueueIsCreated : IntegrationTestBase +public class WhenANamedQueueIsCreated(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenANamedQueueIsCreated(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Error_Queue_Is_Created() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs index dd1ec61fb..ddbfa64ca 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs @@ -8,13 +8,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenCreatingAQueueWithNoErrorQueue : IntegrationTestBase +public class WhenCreatingAQueueWithNoErrorQueue(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenCreatingAQueueWithNoErrorQueue(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Error_Queue_Is_Not_Created() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs index e64277b06..541caf414 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenCreatingErrorQueue : IntegrationTestBase +public class WhenCreatingErrorQueue(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenCreatingErrorQueue(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Retention_Period_Is_Updated() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs index 76bdc3865..433a8b7f6 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenCreatingQueueTwice : IntegrationTestBase +public class WhenCreatingQueueTwice(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenCreatingQueueTwice(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_An_Exception_Is_Not_Thrown() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs index d0997c519..e404c22ff 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenCreatingTopicWithServerSideEncryption : IntegrationTestBase +public class WhenCreatingTopicWithServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenCreatingTopicWithServerSideEncryption(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [NotSimulatorFact] public async Task Can_Create_Topic_With_Encryption() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs index 0d70fe4eb..c71b2130a 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs @@ -8,13 +8,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenQueueIsDeleted : IntegrationTestBase +public class WhenQueueIsDeleted(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenQueueIsDeleted(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Error_Queue_Is_Deleted() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs index 6b35f81c6..0ab8e1fe4 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenRemovingServerSideEncryption : IntegrationTestBase +public class WhenRemovingServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRemovingServerSideEncryption(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [NotSimulatorFact] public async Task Can_Remove_Encryption() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs index 18b268312..1edf876aa 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenRemovingSnsServerSideEncryption : IntegrationTestBase +public class WhenRemovingSnsServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRemovingSnsServerSideEncryption(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [NotSimulatorFact] public async Task Can_Remove_Encryption() { @@ -31,9 +26,9 @@ public async Task Can_Remove_Encryption() await topic.CreateWithEncryptionAsync(new ServerSideEncryption { KmsMasterKeyId = JustSayingConstants.DefaultSnsAttributeEncryptionKeyId }, CancellationToken.None); // Act - await topic.CreateWithEncryptionAsync(new ServerSideEncryption { KmsMasterKeyId = String.Empty }, CancellationToken.None); + await topic.CreateWithEncryptionAsync(new ServerSideEncryption { KmsMasterKeyId = string.Empty }, CancellationToken.None); // Assert topic.ServerSideEncryption.ShouldBeNull(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs index ea1de85b5..c7a31cda4 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs @@ -8,13 +8,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenUpdatingDeliveryDelay : IntegrationTestBase +public class WhenUpdatingDeliveryDelay(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUpdatingDeliveryDelay(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Can_Update_Delivery_Delay() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs index ca1e83c34..f301af89c 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs @@ -8,13 +8,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenUpdatingRedrivePolicy : IntegrationTestBase +public class WhenUpdatingRedrivePolicy(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUpdatingRedrivePolicy(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Can_Update_Redrive_Policy() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs index c10554f77..a5a8bbc13 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs @@ -8,13 +8,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenUpdatingRetentionPeriod : IntegrationTestBase +public class WhenUpdatingRetentionPeriod(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUpdatingRetentionPeriod(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Can_Update_Retention_Period() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs index d0fdcbb92..5320d65e2 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs @@ -13,13 +13,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenUsingABasicThrottle : IntegrationTestBase +public class WhenUsingABasicThrottle(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingABasicThrottle(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - protected override TimeSpan Timeout => TimeSpan.FromMinutes(5); [AwsTheory] diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs index 3cf5cf99a..054e36f94 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenUsingServerSideEncryption : IntegrationTestBase +public class WhenUsingServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingServerSideEncryption(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs index 9b9145c08..3f5e8c75d 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs @@ -6,13 +6,8 @@ namespace JustSaying.IntegrationTests.Fluent.AwsTools; -public class WhenUsingSnsServerSideEncryption : IntegrationTestBase +public class WhenUsingSnsServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingSnsServerSideEncryption(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [NotSimulatorFact] public async Task Then_The_Message_Is_Published() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs index 1492c5faa..e7edf59c9 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs @@ -8,11 +8,8 @@ namespace JustSaying.Fluent.Configuration; -public class WhenUsingACustomSubjectProvider : IntegrationTestBase +public class WhenUsingACustomSubjectProvider(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingACustomSubjectProvider(ITestOutputHelper outputHelper) : base(outputHelper) - { } - [AwsFact] public async Task ThenItIsUsed() { @@ -66,14 +63,9 @@ await Patiently.AssertThatAsync(OutputHelper, }); } - public class ConstantSubjectProvider : IMessageSubjectProvider + public class ConstantSubjectProvider(string subject) : IMessageSubjectProvider { - private readonly string _subject; - - public ConstantSubjectProvider(string subject) - { - _subject = subject; - } + private readonly string _subject = subject; public string GetSubjectForType(Type messageType) { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs index dc3380601..9c025281c 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs @@ -7,12 +7,9 @@ namespace JustSaying.Fluent.Configuration; -public class WhenUsingNamingConventions : IntegrationTestBase +public class WhenUsingNamingConventions(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingNamingConventions(ITestOutputHelper outputHelper) : base(outputHelper) - { } - - class TestNamingConvention : ITopicNamingConvention, IQueueNamingConvention + private class TestNamingConvention : ITopicNamingConvention, IQueueNamingConvention { private readonly DefaultNamingConventions _default; @@ -32,7 +29,7 @@ public string QueueName() } } - [Fact] + [AwsFact] public async Task ThenTheNamingConventionIsApplied() { var services = GivenJustSaying() diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs index 22c9af65b..07ab91dfc 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft; -public class WhenRegisteringAHandlerViaContainerWithMissingRegistration : IntegrationTestBase +public class WhenRegisteringAHandlerViaContainerWithMissingRegistration(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringAHandlerViaContainerWithMissingRegistration(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public void Then_An_Exception_Is_Thrown() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs index fda667862..784394eda 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft; -public class WhenRegisteringASingleHandlerViaContainer : IntegrationTestBase +public class WhenRegisteringASingleHandlerViaContainer(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringASingleHandlerViaContainer(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Handler_Is_Resolved() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs index b1f3c5311..c0e36c408 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft; -public class WhenRegisteringMultipleHandlersViaContainer : IntegrationTestBase +public class WhenRegisteringMultipleHandlersViaContainer(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringMultipleHandlersViaContainer(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public void Then_An_Exception_Is_Thrown() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs index 86f1fc90b..3022ff490 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft; -public class WhenUsingCustomHandlerResolver : IntegrationTestBase +public class WhenUsingCustomHandlerResolver(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingCustomHandlerResolver(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Handler_Is_Resolved_From_The_Custom_Resolver() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs b/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs index 8cc88e44e..6fdd0f6fa 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs @@ -11,22 +11,17 @@ namespace JustSaying.IntegrationTests.Fluent; -public abstract class IntegrationTestBase +public abstract class IntegrationTestBase(ITestOutputHelper outputHelper) { - protected IntegrationTestBase(ITestOutputHelper outputHelper) - { - OutputHelper = outputHelper; - LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(lf => lf.AddXUnit(outputHelper)); - } - protected virtual string AccessKeyId { get; } = "accessKeyId"; protected virtual string SecretAccessKey { get; } = "secretAccessKey"; protected virtual string SessionToken { get; } = "token"; - protected ITestOutputHelper OutputHelper { get; } - protected ILoggerFactory LoggerFactory { get; } + protected ITestOutputHelper OutputHelper { get; } = outputHelper; + + protected ILoggerFactory LoggerFactory { get; } = Microsoft.Extensions.Logging.LoggerFactory.Create(lf => lf.AddXUnit(outputHelper)); protected virtual string RegionName => Region.SystemName; @@ -116,25 +111,23 @@ await action(publisher, listener, serviceProvider, cancellationToken) protected async Task RunActionWithTimeout(Func action) { // See https://speakerdeck.com/davidfowl/scaling-asp-dot-net-core-applications?slide=28 - using (var cts = new CancellationTokenSource()) + using var cts = new CancellationTokenSource(); + var delayTask = Task.Delay(Timeout, cts.Token); + var actionTask = action(cts.Token); + + var resultTask = await Task.WhenAny(actionTask, delayTask) + .ConfigureAwait(false); + + if (resultTask == delayTask) + { + throw new TimeoutException( + $"The tested action took longer than the timeout of {Timeout} to complete."); + } + else { - var delayTask = Task.Delay(Timeout, cts.Token); - var actionTask = action(cts.Token); - - var resultTask = await Task.WhenAny(actionTask, delayTask) - .ConfigureAwait(false); - - if (resultTask == delayTask) - { - throw new TimeoutException( - $"The tested action took longer than the timeout of {Timeout} to complete."); - } - else - { - cts.Cancel(); - } - - await actionTask; + cts.Cancel(); } + + await actionTask; } } diff --git a/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs b/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs index 3f108b075..f75649baa 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs @@ -8,19 +8,12 @@ namespace JustSaying.IntegrationTests; -public class MessagingBusBuilderTests +public class MessagingBusBuilderTests(ITestOutputHelper outputHelper) { - public MessagingBusBuilderTests(ITestOutputHelper outputHelper) - { - OutputHelper = outputHelper; - } - - private ITestOutputHelper OutputHelper { get; } + private ITestOutputHelper OutputHelper { get; } = outputHelper; - private class QueueStore : TestMessageStore + private class QueueStore(ILogger> logger) : TestMessageStore(logger) { - public QueueStore(ILogger> logger) : base(logger) - { } } [AwsFact] @@ -94,21 +87,20 @@ public async Task Can_Create_Messaging_Bus_Fluently_For_A_Topic() IMessagePublisher publisher = serviceProvider.GetRequiredService(); IMessagingBus listener = serviceProvider.GetRequiredService(); - using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(20))) - { - // Act - await listener.StartAsync(source.Token); - await publisher.StartAsync(source.Token); + using var source = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + + // Act + await listener.StartAsync(source.Token); + await publisher.StartAsync(source.Token); - var message = new TopicMessage(); + var message = new TopicMessage(); - await publisher.PublishAsync(message, source.Token); + await publisher.PublishAsync(message, source.Token); - var store = serviceProvider.GetService>(); + var store = serviceProvider.GetService>(); - await Patiently.AssertThatAsync(OutputHelper, - () => store.Messages.Any(msg => msg.Id == message.Id)); - } + await Patiently.AssertThatAsync(OutputHelper, + () => store.Messages.Any(msg => msg.Id == message.Id)); } [AwsFact] @@ -125,12 +117,11 @@ public async Task Can_Create_Messaging_Bus() IMessagePublisher publisher = serviceProvider.GetRequiredService(); IMessagingBus listener = serviceProvider.GetRequiredService(); - using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(20))) - { - // Act - await listener.StartAsync(source.Token); - await publisher.StartAsync(source.Token); - } + using var source = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + + // Act + await listener.StartAsync(source.Token); + await publisher.StartAsync(source.Token); } [AwsFact] @@ -153,26 +144,25 @@ public async Task Can_Create_Messaging_Bus_With_Contributors() IMessagePublisher publisher = serviceProvider.GetRequiredService(); IMessagingBus listener = serviceProvider.GetRequiredService(); - using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(20))) - { - // Act - await listener.StartAsync(source.Token); - await publisher.StartAsync(source.Token); + using var source = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + + // Act + await listener.StartAsync(source.Token); + await publisher.StartAsync(source.Token); - var message = new QueueMessage(); + var message = new QueueMessage(); - await publisher.PublishAsync(message, source.Token); + await publisher.PublishAsync(message, source.Token); - // Assert - var messageStore = serviceProvider.GetService>(); + // Assert + var messageStore = serviceProvider.GetService>(); - await Patiently.AssertThatAsync(OutputHelper, - () => - { - messageStore.Messages.ShouldContain(msg => - msg.Id.Equals(message.Id)); - }); - } + await Patiently.AssertThatAsync(OutputHelper, + () => + { + messageStore.Messages.ShouldContain(msg => + msg.Id.Equals(message.Id)); + }); } private sealed class AwsContributor : IMessageBusConfigurationContributor @@ -185,14 +175,9 @@ public void Configure(MessagingBusBuilder builder) } } - private sealed class MessagingContributor : IMessageBusConfigurationContributor + private sealed class MessagingContributor(IServiceProvider serviceProvider) : IMessageBusConfigurationContributor { - public MessagingContributor(IServiceProvider serviceProvider) - { - ServiceProvider = serviceProvider; - } - - private IServiceProvider ServiceProvider { get; } + private IServiceProvider ServiceProvider { get; } = serviceProvider; public void Configure(MessagingBusBuilder builder) { @@ -259,4 +244,4 @@ public void ReceiveMessageTime(TimeSpan duration, string queueName, string regio public void HandlerExecutionTime(Type handlerType, Type messageType, TimeSpan duration) { } } -} \ No newline at end of file +} diff --git a/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs index 64a322123..1a6e22ba2 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs @@ -8,11 +8,8 @@ namespace JustSaying.Fluent.Monitoring; -public class WhenUsingAMessageMonitor : IntegrationTestBase +public class WhenUsingAMessageMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingAMessageMonitor(ITestOutputHelper outputHelper) : base(outputHelper) - { } - [AwsFact] public async Task MonitorShouldBeCalled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs index 5842d6952..650a9a3c0 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs @@ -4,12 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedToAQueue : IntegrationTestBase +public class WhenAMessageIsPublishedToAQueue(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedToAQueue(ITestOutputHelper outputHelper) - : base(outputHelper) - { } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs index b374406fb..8c00e3d34 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedToAQueueWithSystemTextJson : IntegrationTestBase +public class WhenAMessageIsPublishedToAQueueWithSystemTextJson(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedToAQueueWithSystemTextJson(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs index 55acd0b3b..a2fb59f3b 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedToATenantedTopic - : IntegrationTestBase +public class WhenAMessageIsPublishedToATenantedTopic(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedToATenantedTopic(ITestOutputHelper outputHelper) - : base(outputHelper) - { } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs index 76afb9f66..e6921da68 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedToATopic : IntegrationTestBase +public class WhenAMessageIsPublishedToATopic(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedToATopic(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs index 54678b845..fb579cfcd 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs @@ -5,12 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedToATopicWithACustomName : IntegrationTestBase +public class WhenAMessageIsPublishedToATopicWithACustomName(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedToATopicWithACustomName(ITestOutputHelper outputHelper) - : base(outputHelper) - { } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs index a006c897f..6e4e2aeb0 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedToATopicWithSystemTextJson : IntegrationTestBase +public class WhenAMessageIsPublishedToATopicWithSystemTextJson(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedToATopicWithSystemTextJson(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs index 976d50283..9f3f4f83a 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs @@ -3,12 +3,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenAMessageIsPublishedWithoutStartingThePublisher : IntegrationTestBase +public class WhenAMessageIsPublishedWithoutStartingThePublisher(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAMessageIsPublishedWithoutStartingThePublisher(ITestOutputHelper outputHelper) : base( - outputHelper) - { } - [AwsFact] public async Task Then_The_PushlishShouldThrow() { @@ -33,4 +29,4 @@ await Assert.ThrowsAsync( () => publisher.PublishAsync(message, cancellationToken)); }); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs index 23cc72e52..9d7151191 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenCreatingAMessagePublisher : IntegrationTestBase +public class WhenCreatingAMessagePublisher(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenCreatingAMessagePublisher(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Queues_Exist() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs index 7447babc0..1a67993b0 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs @@ -4,11 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenInterrogatingTheBus : IntegrationTestBase +public class WhenInterrogatingTheBus(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenInterrogatingTheBus(ITestOutputHelper outputHelper) : base(outputHelper) - { } - [AwsFact] public async Task Then_The_Interrogation_Result_Should_Be_Returned() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs index aaeb2b078..9efd68341 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenPublishingWithNoRegisteredMessages : IntegrationTestBase +public class WhenPublishingWithNoRegisteredMessages(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenPublishingWithNoRegisteredMessages(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_An_Exception_Is_Thrown() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs index 4750fb7ab..fd85aaa1d 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenPublishingWithoutAMonitor : IntegrationTestBase +public class WhenPublishingWithoutAMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenPublishingWithoutAMonitor(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task A_Message_Can_Still_Be_Published_To_A_Queue() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs index 6ae62c5fb..ea204a38f 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs @@ -6,12 +6,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenRegisteringAPublisherForRegion : IntegrationTestBase +public class WhenRegisteringAPublisherForRegion(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringAPublisherForRegion(ITestOutputHelper outputHelper) - : base(outputHelper) - { } - [AwsFact] public async Task Then_A_Topic_Is_Created_In_That_Region() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs index c2de04a13..a9b2768e5 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs @@ -7,12 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenRegisteringAPublisherWithTags : IntegrationTestBase +public class WhenRegisteringAPublisherWithTags(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringAPublisherWithTags(ITestOutputHelper outputHelper) - : base(outputHelper) - { } - [NotSimulatorFact] public async Task Then_A_Topic_Is_Created_With_The_Correct_Tags() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs index 910ee6cb0..d777ced30 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Publishing; -public class WhenTheErrorQueueDisabled : IntegrationTestBase +public class WhenTheErrorQueueDisabled(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenTheErrorQueueDisabled(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Error_Queue_Does_Not_Exist() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs index 46dd97a28..4680a7ca3 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs @@ -5,32 +5,19 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -internal class HandlerWithMessageContext : IHandlerAsync +internal class HandlerWithMessageContext( + IMessageContextReader messageContextReader, + Future future, + ILogger logger) : IHandlerAsync { - private readonly ILogger _logger; - private readonly IMessageContextReader _messageContextReader; + private readonly ILogger _logger = logger; + private readonly IMessageContextReader _messageContextReader = messageContextReader; - public HandlerWithMessageContext( - IMessageContextReader messageContextReader, - Future future, - ILogger logger) - { - _messageContextReader = messageContextReader; - Future = future; - _logger = logger; - } - - public Future Future { get; } + public Future Future { get; } = future; public async Task Handle(SimpleMessage message) { - var messageContext = _messageContextReader.MessageContext; - - if (messageContext == null) - { - throw new InvalidOperationException("Message context was not found"); - } - + var messageContext = _messageContextReader.MessageContext ?? throw new InvalidOperationException("Message context was not found"); _logger.LogInformation( "Message context found with queue URI {QueueUri} and message body {MessageBody}.", messageContext.QueueUri, diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs index ff1947576..42bb3854a 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs @@ -7,27 +7,19 @@ namespace JustSaying.Fluent.Subscribing.Newtonsoft; -public class WhenHandlingAMessageWithBinaryAttributes : IntegrationTestBase +public class WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : base(outputHelper) - { } - - public class SimpleMessageWithBinaryAttributesHandler : IHandlerAsync + public class SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync { - private readonly IMessageContextAccessor _contextAccessor; + private readonly IMessageContextAccessor _contextAccessor = contextAccessor; - public SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor) - { - _contextAccessor = contextAccessor; - HandledMessages = new List<(MessageContext, SimpleMessage)>(); - } public Task Handle(SimpleMessage message) { HandledMessages.Add((_contextAccessor.MessageContext, message)); return Task.FromResult(true); } - public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } + public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>(); } [AwsFact] diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs index 3eed19a2f..f7fc244f2 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs @@ -6,27 +6,19 @@ namespace JustSaying.Fluent.Subscribing.Newtonsoft; -public class WhenHandlingAMessageWithStringAttributes : IntegrationTestBase +public class WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : base(outputHelper) - { } - - public class SimpleMessageWithStringAttributesHandler : IHandlerAsync + public class SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync { - private readonly IMessageContextAccessor _contextAccessor; + private readonly IMessageContextAccessor _contextAccessor = contextAccessor; - public SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor) - { - _contextAccessor = contextAccessor; - HandledMessages = new List<(MessageContext, SimpleMessage)>(); - } public Task Handle(SimpleMessage message) { HandledMessages.Add((_contextAccessor.MessageContext, message)); return Task.FromResult(true); } - public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } + public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>(); } [AwsFact] diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs index 585c0ccd7..17614e15e 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs @@ -2,18 +2,13 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class RecordingMessageContextAccessor : IMessageContextAccessor, IMessageContextReader +public class RecordingMessageContextAccessor(IMessageContextAccessor inner) : IMessageContextAccessor, IMessageContextReader { - private readonly IMessageContextAccessor _inner; - private readonly List _valuesWritten = new List(); + private readonly IMessageContextAccessor _inner = inner; + private readonly List _valuesWritten = new(); public IReadOnlyCollection ValuesWritten => _valuesWritten; - public RecordingMessageContextAccessor(IMessageContextAccessor inner) - { - _inner = inner; - } - public MessageContext MessageContext { get => _inner.MessageContext; diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs index a800e0d4a..79f41b583 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs @@ -8,27 +8,19 @@ namespace JustSaying.Fluent.Subscribing.SystemTextJson; -public class WhenHandlingAMessageWithBinaryAttributes : IntegrationTestBase +public class WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : base(outputHelper) - { } - - public class SimpleMessageWithBinaryAttributesHandler : IHandlerAsync + public class SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync { - private readonly IMessageContextAccessor _contextAccessor; + private readonly IMessageContextAccessor _contextAccessor = contextAccessor; - public SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor) - { - _contextAccessor = contextAccessor; - HandledMessages = new List<(MessageContext, SimpleMessage)>(); - } public Task Handle(SimpleMessage message) { HandledMessages.Add((_contextAccessor.MessageContext, message)); return Task.FromResult(true); } - public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } + public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>(); } [AwsFact] diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs index 5a1eb9885..d03cc8762 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs @@ -7,27 +7,19 @@ namespace JustSaying.Fluent.Subscribing.SystemTextJson; -public class WhenHandlingAMessageWithStringAttributes : IntegrationTestBase +public class WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : base(outputHelper) - { } - - public class SimpleMessageWithStringAttributesHandler : IHandlerAsync + public class SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync { - private readonly IMessageContextAccessor _contextAccessor; + private readonly IMessageContextAccessor _contextAccessor = contextAccessor; - public SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor) - { - _contextAccessor = contextAccessor; - HandledMessages = new List<(MessageContext, SimpleMessage)>(); - } public Task Handle(SimpleMessage message) { HandledMessages.Add((_contextAccessor.MessageContext, message)); return Task.FromResult(true); } - public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } + public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>(); } [AwsFact] diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs index 3cb9e2de2..b950e638f 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs @@ -7,13 +7,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenAHandlerThrowsAnExceptionWithAMonitor : IntegrationTestBase +public class WhenAHandlerThrowsAnExceptionWithAMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAHandlerThrowsAnExceptionWithAMonitor(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs index 48d8c29bf..1c730d4c1 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs @@ -6,13 +6,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenAHandlerThrowsAnExceptionWithNoMonitor : IntegrationTestBase +public class WhenAHandlerThrowsAnExceptionWithNoMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAHandlerThrowsAnExceptionWithNoMonitor(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs index 95cca5a07..2f18d3d65 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenAHandlerUsesMessageContext : IntegrationTestBase +public class WhenAHandlerUsesMessageContext(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenAHandlerUsesMessageContext(ITestOutputHelper outputHelper) : - base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs index 36e5a0328..b12c0efea 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs @@ -5,11 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenApplyingDefaultMiddlewares : IntegrationTestBase +public class WhenApplyingDefaultMiddlewares(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenApplyingDefaultMiddlewares(ITestOutputHelper outputHelper) : base(outputHelper) - { } - class OuterTestMiddleware : InspectableMiddleware { } diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs index 08d6e3884..1d00f4a65 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs @@ -5,11 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenDefaultMiddlewaresAreNotApplied : IntegrationTestBase +public class WhenDefaultMiddlewaresAreNotApplied(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenDefaultMiddlewaresAreNotApplied(ITestOutputHelper outputHelper) : base(outputHelper) - { } - [AwsFact] public async Task Then_The_Pipeline_Should_Only_Contain_User_Specified_Middlewares() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs index 935e41a3c..46808b928 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs @@ -6,13 +6,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenHandlerIsDeclaredAsExactlyOnce : IntegrationTestBase +public class WhenHandlerIsDeclaredAsExactlyOnce(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenHandlerIsDeclaredAsExactlyOnce(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Handler_Only_Receives_The_Message_Once() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs index f2ca6e03f..5d3e07668 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs @@ -10,13 +10,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenHandlingMultipleTopics : IntegrationTestBase +public class WhenHandlingMultipleTopics(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenHandlingMultipleTopics(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [NotSimulatorFact] public async Task Sqs_Policy_Is_Applied_With_Wildcard() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs index d207e5009..2f49d461e 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs @@ -11,13 +11,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; /// concurrency of 2, the long running handler will consume one slot, and every other message will be /// processed in order in the other slot. The result should be exactly in-order delivery for this test. /// -public sealed class WhenReceivingIsThrottled : IntegrationTestBase +public sealed class WhenReceivingIsThrottled(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenReceivingIsThrottled(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Messages_Are_Handled_With_Throttle() { @@ -78,40 +73,27 @@ await WhenAsync( }); } - private class WaitingMessage : Message, IComparable + private class WaitingMessage(int order, TimeSpan timeToWait) : Message, IComparable { - public WaitingMessage(int order, TimeSpan timeToWait) - { - Order = order; - TimeToWait = timeToWait; - } - - public TimeSpan TimeToWait { get; } - public int Order { get; } + public TimeSpan TimeToWait { get; } = timeToWait; + public int Order { get; } = order; public int CompareTo(WaitingMessage other) { if (ReferenceEquals(this, other)) return 0; - if (ReferenceEquals(null, other)) return 1; + if (other is null) return 1; return Order.CompareTo(other.Order); } } - private class InspectableWaitingHandler : InspectableHandler + private class InspectableWaitingHandler(ITestOutputHelper outputHelper) : InspectableHandler { - private readonly ITestOutputHelper _output; - - public InspectableWaitingHandler(ITestOutputHelper testOutputHelper) - { - _output = testOutputHelper; - } - public override async Task Handle(WaitingMessage message) { await base.Handle(message); - _output.WriteLine($"Running task {message.Order} which will wait for {message.TimeToWait.TotalMilliseconds}ms"); + outputHelper.WriteLine($"Running task {message.Order} which will wait for {message.TimeToWait.TotalMilliseconds}ms"); await Task.Delay(message.TimeToWait); return true; } } -} \ No newline at end of file +} diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs index d8c2da7ac..c228c7fd7 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs @@ -4,13 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenRegisteringASqsTopicSubscriber : IntegrationTestBase +public class WhenRegisteringASqsTopicSubscriber(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringASqsTopicSubscriber(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_A_Queue_Is_Created() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs index e61c8bc46..6cd60c2a8 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs @@ -6,12 +6,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenRegisteringASqsTopicSubscriberForRegion : IntegrationTestBase +public class WhenRegisteringASqsTopicSubscriberForRegion(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringASqsTopicSubscriberForRegion(ITestOutputHelper outputHelper) - : base(outputHelper) - { } - [AwsFact] public async Task Then_A_Queue_Is_Created() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs index 4eeaf374b..0aad9b72f 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs @@ -8,14 +8,10 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenRegisteringASubscriberWithTags : IntegrationTestBase +public class WhenRegisteringASubscriberWithTags(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { private const string QueueName = "simple-message-queue-with-tags"; - public WhenRegisteringASubscriberWithTags(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - [NotSimulatorFact] public async Task Then_A_Queue_For_Topic_Subscription_Is_Created_With_The_Correct_Tags() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs index 39f2c437a..329788f5a 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs @@ -3,13 +3,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenRegisteringATopicForAGenericMessage : IntegrationTestBase +public class WhenRegisteringATopicForAGenericMessage(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringATopicForAGenericMessage(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_The_Message_Is_Handled() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs index e9343d660..b1e0c05c8 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenRegisteringLongNameMessageTypeTopicSubscriber : IntegrationTestBase +public class WhenRegisteringLongNameMessageTypeTopicSubscriber(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenRegisteringLongNameMessageTypeTopicSubscriber(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_A_Queue_Is_Created() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs index a5f20d376..110ac2f17 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs @@ -4,11 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenSubscribingToMultipleTopics : IntegrationTestBase +public class WhenSubscribingToMultipleTopics(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenSubscribingToMultipleTopics(ITestOutputHelper outputHelper) : base(outputHelper) - { } - [AwsFact] public async Task Then_Both_Handlers_Receive_Messages() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs index 3b1f450cb..c18c27daa 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs @@ -5,13 +5,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenTwoDifferentHandlersHandleAnExactlyOnceMessage : IntegrationTestBase +public class WhenTwoDifferentHandlersHandleAnExactlyOnceMessage(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenTwoDifferentHandlersHandleAnExactlyOnceMessage(ITestOutputHelper outputHelper) - : base(outputHelper) - { - } - [AwsFact] public async Task Then_Both_Handlers_Receive_The_Message() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs index ea0ddf65e..224da29e9 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs @@ -4,11 +4,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class WhenUsingMultipleMiddlewares : IntegrationTestBase +public class WhenUsingMultipleMiddlewares(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public WhenUsingMultipleMiddlewares(ITestOutputHelper outputHelper) : base(outputHelper) - { } - [AwsFact] public async Task Then_The_Middlewares_Are_Called() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs index c3649c70a..71000d989 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs @@ -6,12 +6,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class AddressPubSub : IntegrationTestBase +public class AddressPubSub(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public AddressPubSub(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - [AwsFact] public async Task SimplePubSubWorks() { diff --git a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs index d2e33023c..a209243b9 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs @@ -2,28 +2,21 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; -public class CapturingTestOutputHelper : ITestOutputHelper +public class CapturingTestOutputHelper(ITestOutputHelper inner) : ITestOutputHelper { - private readonly ITestOutputHelper _inner; - private readonly StringBuilder _sb; + private readonly StringBuilder _sb = new(); public string Output => _sb.ToString(); - public CapturingTestOutputHelper(ITestOutputHelper inner) - { - _inner = inner; - _sb = new StringBuilder(); - } - public void WriteLine(string message) { _sb.AppendLine(message); - _inner.WriteLine(message); + inner.WriteLine(message); } public void WriteLine(string format, params object[] args) { _sb.AppendLine(string.Format(format, args)); - _inner.WriteLine(format, args); + inner.WriteLine(format, args); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs index 813226ee2..194b1ba38 100644 --- a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs +++ b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs @@ -5,7 +5,7 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing; public sealed class MessageLockStore : IMessageLockAsync { - private readonly ConcurrentDictionary _store = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _store = new(); public Task TryAcquireLockAsync(string key, TimeSpan howLong) { diff --git a/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs b/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs index 17582e269..75a56205c 100644 --- a/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs +++ b/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs @@ -8,13 +8,8 @@ namespace JustSaying.Logging; -public class LogContextTests : IntegrationTestBase +public class LogContextTests(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper) { - public LogContextTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - - [AwsFact] public async Task PublishToTopicLogsShouldHaveContext() { diff --git a/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs b/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs index 4139ab49c..6c18b7a34 100644 --- a/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs +++ b/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs @@ -4,10 +4,6 @@ namespace JustSaying.IntegrationTests.TestHandlers; public class BlockingOrderProcessor : IHandlerAsync { - public BlockingOrderProcessor() - { - } - public int ReceivedMessageCount { get; private set; } public TaskCompletionSource DoneSignal { get; private set; } @@ -17,4 +13,4 @@ public Task Handle(OrderPlaced message) ReceivedMessageCount++; return Task.FromResult(true); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.IntegrationTests/TestHandlers/Future.cs b/tests/JustSaying.IntegrationTests/TestHandlers/Future.cs index e96440e0d..ff2f6883e 100644 --- a/tests/JustSaying.IntegrationTests/TestHandlers/Future.cs +++ b/tests/JustSaying.IntegrationTests/TestHandlers/Future.cs @@ -3,24 +3,18 @@ namespace JustSaying.IntegrationTests.TestHandlers; -public class Future +public class Future(Func action) where TMessage : Message { - private readonly TaskCompletionSource _doneSignal = new TaskCompletionSource(); - private readonly Func _action; - private readonly List _messages = new List(); + private readonly TaskCompletionSource _doneSignal = new(); + private readonly Func _action = action; + private readonly List _messages = new(); public Future() : this(null) { } - public Future(Func action) - { - _action = action; - ExpectedMessageCount = 1; - } - public async Task Complete(TMessage message) { try @@ -43,7 +37,7 @@ public async Task Complete(TMessage message) public Task DoneSignal => _doneSignal.Task; - public int ExpectedMessageCount { get; set; } + public int ExpectedMessageCount { get; set; } = 1; public int ReceivedMessageCount => _messages.Count; diff --git a/tests/JustSaying.IntegrationTests/TestHandlers/OrderDispatcher.cs b/tests/JustSaying.IntegrationTests/TestHandlers/OrderDispatcher.cs index 1ad65253b..a7b8e0ff8 100644 --- a/tests/JustSaying.IntegrationTests/TestHandlers/OrderDispatcher.cs +++ b/tests/JustSaying.IntegrationTests/TestHandlers/OrderDispatcher.cs @@ -2,18 +2,13 @@ namespace JustSaying.IntegrationTests.TestHandlers; -public class OrderDispatcher : IHandlerAsync +public class OrderDispatcher(Future future) : IHandlerAsync { - public OrderDispatcher(Future future) - { - Future = future; - } - public async Task Handle(OrderPlaced message) { await Future.Complete(message); return true; } - public Future Future { get; } + public Future Future { get; } = future; } \ No newline at end of file diff --git a/tests/JustSaying.IntegrationTests/TestHandlers/OrderPlaced.cs b/tests/JustSaying.IntegrationTests/TestHandlers/OrderPlaced.cs index fc616556e..c1fa5dfa0 100644 --- a/tests/JustSaying.IntegrationTests/TestHandlers/OrderPlaced.cs +++ b/tests/JustSaying.IntegrationTests/TestHandlers/OrderPlaced.cs @@ -2,12 +2,7 @@ namespace JustSaying.IntegrationTests.TestHandlers; -public class OrderPlaced : Message +public class OrderPlaced(string orderId) : Message { - public OrderPlaced(string orderId) - { - OrderId = orderId; - } - - public string OrderId { get; private set; } + public string OrderId { get; private set; } = orderId; } \ No newline at end of file diff --git a/tests/JustSaying.IntegrationTests/TestHandlers/OrderProcessor.cs b/tests/JustSaying.IntegrationTests/TestHandlers/OrderProcessor.cs index ee0e47bc3..343d63ccd 100644 --- a/tests/JustSaying.IntegrationTests/TestHandlers/OrderProcessor.cs +++ b/tests/JustSaying.IntegrationTests/TestHandlers/OrderProcessor.cs @@ -2,18 +2,13 @@ namespace JustSaying.IntegrationTests.TestHandlers; -public class OrderProcessor : IHandlerAsync +public class OrderProcessor(Future future) : IHandlerAsync { - public OrderProcessor(Future future) - { - Future = future; - } - public async Task Handle(OrderPlaced message) { await Future.Complete(message); return true; } - public Future Future { get; } + public Future Future { get; } = future; } \ No newline at end of file diff --git a/tests/JustSaying.IntegrationTests/TestSettings.cs b/tests/JustSaying.IntegrationTests/TestSettings.cs index 060037f4b..e5cc5d402 100644 --- a/tests/JustSaying.IntegrationTests/TestSettings.cs +++ b/tests/JustSaying.IntegrationTests/TestSettings.cs @@ -1 +1 @@ -[assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)] +[assembly: CollectionBehavior(DisableTestParallelization = true)] diff --git a/tests/JustSaying.TestingFramework/AwaitableMiddleware.cs b/tests/JustSaying.TestingFramework/AwaitableMiddleware.cs index 2fc4c3d98..c1aa3e1b7 100644 --- a/tests/JustSaying.TestingFramework/AwaitableMiddleware.cs +++ b/tests/JustSaying.TestingFramework/AwaitableMiddleware.cs @@ -3,16 +3,11 @@ namespace JustSaying.TestingFramework; -public class AwaitableMiddleware : MiddlewareBase +public class AwaitableMiddleware(ITestOutputHelper outputHelper) : MiddlewareBase { - private readonly ITestOutputHelper _outputHelper; + private readonly ITestOutputHelper _outputHelper = outputHelper; public Task Complete { get; private set; } - public AwaitableMiddleware(ITestOutputHelper outputHelper) - { - _outputHelper = outputHelper; - } - protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken) { var tcs = new TaskCompletionSource(); diff --git a/tests/JustSaying.TestingFramework/LocalAwsClientFactory.cs b/tests/JustSaying.TestingFramework/LocalAwsClientFactory.cs index 7604eea5b..a400a192b 100644 --- a/tests/JustSaying.TestingFramework/LocalAwsClientFactory.cs +++ b/tests/JustSaying.TestingFramework/LocalAwsClientFactory.cs @@ -6,14 +6,9 @@ namespace JustSaying.TestingFramework; -public class LocalAwsClientFactory : IAwsClientFactory +public class LocalAwsClientFactory(Uri serviceUrl) : IAwsClientFactory { - public LocalAwsClientFactory(Uri serviceUrl) - { - ServiceUrl = serviceUrl; - } - - private Uri ServiceUrl { get; } + private Uri ServiceUrl { get; } = serviceUrl; public IAmazonSimpleNotificationService GetSnsClient(RegionEndpoint region) { diff --git a/tests/JustSaying.TestingFramework/MessageStoringHandler.cs b/tests/JustSaying.TestingFramework/MessageStoringHandler.cs index f44855896..7b56330dd 100644 --- a/tests/JustSaying.TestingFramework/MessageStoringHandler.cs +++ b/tests/JustSaying.TestingFramework/MessageStoringHandler.cs @@ -22,17 +22,10 @@ public TestMessageStore(ILogger> logger) } } -public class MessageStoringHandler : IHandlerAsync +public class MessageStoringHandler(IMessageStore store, ILogger> logger) : IHandlerAsync { - private readonly ILogger> _logger; - public IMessageStore MessageStore { get; } - - - public MessageStoringHandler(IMessageStore store, ILogger> logger) - { - MessageStore = store; - _logger = logger; - } + private readonly ILogger> _logger = logger; + public IMessageStore MessageStore { get; } = store; public Task Handle(T message) { diff --git a/tests/JustSaying.TestingFramework/Patiently.cs b/tests/JustSaying.TestingFramework/Patiently.cs index a1244f8cb..3d4fae2f8 100644 --- a/tests/JustSaying.TestingFramework/Patiently.cs +++ b/tests/JustSaying.TestingFramework/Patiently.cs @@ -18,8 +18,7 @@ public static async Task AssertThatAsync( ITestOutputHelper output, Action func, [System.Runtime.CompilerServices.CallerMemberName] - string memberName = "", - TimeSpan? timeout = null) + string memberName = "") => await AssertThatAsync(output, () => { diff --git a/tests/JustSaying.TestingFramework/TaskHelpers.cs b/tests/JustSaying.TestingFramework/TaskHelpers.cs index eb1b502c4..e7a8b6e30 100644 --- a/tests/JustSaying.TestingFramework/TaskHelpers.cs +++ b/tests/JustSaying.TestingFramework/TaskHelpers.cs @@ -2,11 +2,8 @@ namespace JustSaying.TestingFramework; public static class TaskHelpers { - private const int DefaultTimeoutMillis = 10000; - private const int DelaySendMillis = 200; - public static async Task WaitWithTimeoutAsync(Task task) - => await WaitWithTimeoutAsync(task, TimeSpan.FromMilliseconds(DefaultTimeoutMillis)) + => await WaitWithTimeoutAsync(task, TimeSpan.FromMilliseconds(10000)) .ConfigureAwait(false); public static async Task WaitWithTimeoutAsync(Task task, TimeSpan timeoutDuration) @@ -22,7 +19,7 @@ public static void DelaySendDone(TaskCompletionSource doneSignal) { Task.Run(async () => { - await Task.Delay(DelaySendMillis).ConfigureAwait(false); + await Task.Delay(200).ConfigureAwait(false); doneSignal.SetResult(null); }); } @@ -44,4 +41,4 @@ public static async Task HandleCancellation(this Task task) return true; } } -} \ No newline at end of file +} diff --git a/tests/JustSaying.TestingFramework/TestException.cs b/tests/JustSaying.TestingFramework/TestException.cs index 3206c6111..60a9ddfd7 100644 --- a/tests/JustSaying.TestingFramework/TestException.cs +++ b/tests/JustSaying.TestingFramework/TestException.cs @@ -1,5 +1,3 @@ -using System.Runtime.Serialization; - namespace JustSaying.TestingFramework; public class TestException : Exception diff --git a/tests/JustSaying.TestingFramework/TrackingLoggingMonitor.cs b/tests/JustSaying.TestingFramework/TrackingLoggingMonitor.cs index 9eb18dfd5..9ab6d46bd 100644 --- a/tests/JustSaying.TestingFramework/TrackingLoggingMonitor.cs +++ b/tests/JustSaying.TestingFramework/TrackingLoggingMonitor.cs @@ -4,62 +4,47 @@ namespace JustSaying.TestingFramework; -public class TrackingLoggingMonitor : IMessageMonitor +public class TrackingLoggingMonitor(ILogger logger) : IMessageMonitor { - private readonly ILogger _logger; - - public TrackingLoggingMonitor(ILogger logger) - { - _logger = logger; - HandledExceptions = new List(); - HandledErrors = new List<(Exception exception, Message message)>(); - HandledTimes = new List(); - HandledThrottlingTime = new List(); - PublishMessageTimes = new List(); - ReceiveMessageTimes = new List<(TimeSpan duration, string queue, string region)>(); - HandlerExecutionTimes = new List<(Type handlerType, Type messageType, TimeSpan duration)>(); - HandledMessages = new List(); - } - - public List<(Type handlerType, Type messageType, TimeSpan duration)> HandlerExecutionTimes { get; } - public IList HandledExceptions { get; } - public IList<(Exception exception, Message message)> HandledErrors { get; } - public IList HandledTimes { get; } - public IList HandledThrottlingTime { get; } - public IList PublishMessageTimes { get; } - public IList HandledMessages { get; } - public IList<(TimeSpan duration, string queue, string region)> ReceiveMessageTimes { get; } + public List<(Type handlerType, Type messageType, TimeSpan duration)> HandlerExecutionTimes { get; } = []; + public IList HandledExceptions { get; } = new List(); + public IList<(Exception exception, Message message)> HandledErrors { get; } = new List<(Exception exception, Message message)>(); + public IList HandledTimes { get; } = new List(); + public IList HandledThrottlingTime { get; } = new List(); + public IList PublishMessageTimes { get; } = new List(); + public IList HandledMessages { get; } = new List(); + public IList<(TimeSpan duration, string queue, string region)> ReceiveMessageTimes { get; } = new List<(TimeSpan duration, string queue, string region)>(); public int IssuesPublishingMessage { get; private set; } public int ThrottlingStatisticIncrements { get; private set; } public void HandleException(Type messageType) { HandledExceptions.Add(messageType); - _logger.LogInformation("Exception occurred when handling message of type {MessageType}", messageType.FullName); + logger.LogInformation("Exception occurred when handling message of type {MessageType}", messageType.FullName); } public void HandleError(Exception ex, Message message) { HandledErrors.Add((ex, message)); - _logger.LogInformation("Handled Error for message type {MessageType}", message.GetType().FullName); + logger.LogInformation("Handled Error for message type {MessageType}", message.GetType().FullName); } public void HandleTime(TimeSpan duration) { HandledTimes.Add(duration); - _logger.LogInformation("Message handled in {Duration}", duration); + logger.LogInformation("Message handled in {Duration}", duration); } public void IssuePublishingMessage() { IssuesPublishingMessage++; - _logger.LogInformation("Problem during publish"); + logger.LogInformation("Problem during publish"); } public void Handled(Models.Message message) { HandledMessages.Add(message); - _logger.LogInformation("Handled message of type {MessageType}", message.GetType()); + logger.LogInformation("Handled message of type {MessageType}", message.GetType()); } public void IncrementThrottlingStatistic() @@ -70,19 +55,19 @@ public void IncrementThrottlingStatistic() public void HandleThrottlingTime(TimeSpan duration) { HandledThrottlingTime.Add(duration); - _logger.LogInformation("MessageReceiveBuffer throttled for {Duration}", duration); + logger.LogInformation("MessageReceiveBuffer throttled for {Duration}", duration); } public void PublishMessageTime(TimeSpan duration) { PublishMessageTimes.Add(duration); - _logger.LogInformation("Message was published in {Duration}", duration); + logger.LogInformation("Message was published in {Duration}", duration); } public void ReceiveMessageTime(TimeSpan duration, string queueName, string region) { ReceiveMessageTimes.Add((duration, queueName, region)); - _logger.LogInformation( + logger.LogInformation( "MessageReceiveBuffer spent {Duration} receiving messages from {QueueName} in region {Region}", duration, queueName, @@ -92,9 +77,9 @@ public void ReceiveMessageTime(TimeSpan duration, string queueName, string regio public void HandlerExecutionTime(Type handlerType, Type messageType, TimeSpan duration) { HandlerExecutionTimes.Add((handlerType, messageType, duration)); - _logger.LogInformation("Handler type {HandlerType} spent {Duration} handling message of type {MessageType}", + logger.LogInformation("Handler type {HandlerType} spent {Duration} handling message of type {MessageType}", handlerType, duration, messageType); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.TestingFramework/TrackingMiddleware.cs b/tests/JustSaying.TestingFramework/TrackingMiddleware.cs index 2041f5079..a7cf172b3 100644 --- a/tests/JustSaying.TestingFramework/TrackingMiddleware.cs +++ b/tests/JustSaying.TestingFramework/TrackingMiddleware.cs @@ -2,18 +2,11 @@ namespace JustSaying.TestingFramework; -public class TrackingMiddleware : MiddlewareBase +public class TrackingMiddleware(string id, Action onBefore, Action onAfter) : MiddlewareBase { - private readonly Action _onBefore; - private readonly Action _onAfter; - private readonly string _id; - - public TrackingMiddleware(string id, Action onBefore, Action onAfter) - { - _id = id; - _onBefore = onBefore; - _onAfter = onAfter; - } + private readonly Action _onBefore = onBefore; + private readonly Action _onAfter = onAfter; + private readonly string _id = id; protected override async Task RunInnerAsync( HandleMessageContext context, @@ -27,4 +20,4 @@ protected override async Task RunInnerAsync( return result; } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageContextAccessorTests.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageContextAccessorTests.cs index dadf7c80e..aafe5efca 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageContextAccessorTests.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageContextAccessorTests.cs @@ -120,8 +120,8 @@ private static MessageContext MakeUniqueMessageContext() return new MessageContext(sqsMessage, queueUri, new MessageAttributes()); } - private static IMessageContextAccessor MakeAccessor() + private static MessageContextAccessor MakeAccessor() { return new MessageContextAccessor(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageDispatcherTests/WhenDispatchingMessage.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageDispatcherTests/WhenDispatchingMessage.cs index f42278344..b478a4b66 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageDispatcherTests/WhenDispatchingMessage.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/MessageDispatcherTests/WhenDispatchingMessage.cs @@ -100,7 +100,7 @@ private MessageDispatcher CreateSystemUnderTestAsync() return dispatcher; } - public class AndHandlerMapDoesNotHaveMatchingHandler : WhenDispatchingMessage + public class AndHandlerMapDoesNotHaveMatchingHandler(ITestOutputHelper outputHelper) : WhenDispatchingMessage(outputHelper) { private const int ExpectedReceiveCount = 1; private readonly TimeSpan _expectedBackoffTimeSpan = TimeSpan.FromMinutes(4); @@ -123,12 +123,9 @@ public void ShouldNotHandleMessage() var testLogger = _loggerFactory.GetTestLoggerSink(); testLogger.LogEntries.ShouldContain(le => le.OriginalFormat == "Failed to dispatch. Middleware for message of type '{MessageTypeName}' not found in middleware map."); } - - public AndHandlerMapDoesNotHaveMatchingHandler(ITestOutputHelper outputHelper) : base(outputHelper) - { } } - public class AndMessageProcessingSucceeds : WhenDispatchingMessage + public class AndMessageProcessingSucceeds(ITestOutputHelper outputHelper) : WhenDispatchingMessage(outputHelper) { protected override void Given() { @@ -161,16 +158,13 @@ public void ShouldDeleteMessageIfHandledSuccessfully() request.QueueUrl.ShouldBe(ExpectedQueueUrl); request.ReceiptHandle.ShouldBe(_sqsMessage.ReceiptHandle); } - - public AndMessageProcessingSucceeds(ITestOutputHelper outputHelper) : base(outputHelper) - { } } - public class AndMessageProcessingFails : WhenDispatchingMessage + public class AndMessageProcessingFails(ITestOutputHelper outputHelper) : WhenDispatchingMessage(outputHelper) { private const int ExpectedReceiveCount = 1; private readonly TimeSpan _expectedBackoffTimeSpan = TimeSpan.FromMinutes(4); - private readonly Exception _expectedException = new Exception("Something failed when processing"); + private readonly Exception _expectedException = new("Something failed when processing"); protected override void Given() { @@ -210,8 +204,5 @@ public void ShouldUpdateMessageVisibility() request.ReceiptHandle.ShouldBe(_sqsMessage.ReceiptHandle); request.VisibilityTimeoutInSeconds.ShouldBe((int)_expectedBackoffTimeSpan.TotalSeconds); } - - public AndMessageProcessingFails(ITestOutputHelper outputHelper) : base(outputHelper) - { } } } diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishing.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishing.cs index e9b9ed9a5..df73de4f3 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishing.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishing.cs @@ -7,8 +7,6 @@ using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; -#pragma warning disable 618 - namespace JustSaying.UnitTests.AwsTools.MessageHandling.Sns.TopicByName; public class WhenPublishing : WhenPublishingTestBase @@ -57,4 +55,4 @@ public void MessageIsPublishedToCorrectLocation() { Sns.Received().PublishAsync(Arg.Is(x => x.TopicArn == TopicArn)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsync.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsync.cs index 560bbf176..6c2d3fbd7 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsync.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsync.cs @@ -7,8 +7,6 @@ using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; -#pragma warning disable 618 - namespace JustSaying.UnitTests.AwsTools.MessageHandling.Sns.TopicByName; public class WhenPublishingAsync : WhenPublishingTestBase @@ -83,4 +81,4 @@ public void MessageAttributeDataTypeIsPublished() { Sns.Received().PublishAsync(Arg.Is(x => x.MessageAttributes.Single().Value.DataType == MessageAttributeDataType)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeHandled.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeHandled.cs index 314932cd3..364bf605b 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeHandled.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeHandled.cs @@ -7,8 +7,6 @@ using NSubstitute; using NSubstitute.Core; -#pragma warning disable 618 - namespace JustSaying.UnitTests.AwsTools.MessageHandling.Sns.TopicByName; public class WhenPublishingAsyncExceptionCanBeHandled : WhenPublishingTestBase @@ -47,4 +45,4 @@ private static Task ThrowsException(CallInfo callInfo) { throw new InternalErrorException("Operation timed out"); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeThrown.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeThrown.cs index 62d758604..e557dbfc9 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeThrown.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncExceptionCanBeThrown.cs @@ -8,8 +8,6 @@ using NSubstitute; using NSubstitute.Core; -#pragma warning disable 618 - namespace JustSaying.UnitTests.AwsTools.MessageHandling.Sns.TopicByName; public class WhenPublishingAsyncExceptionCanBeThrown : WhenPublishingTestBase @@ -60,4 +58,4 @@ private static Task ThrowsException(CallInfo callInfo) { throw new AmazonServiceException("Operation timed out"); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncResponseLoggerIsCalled.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncResponseLoggerIsCalled.cs index 1da233555..bfd59a2c2 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncResponseLoggerIsCalled.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncResponseLoggerIsCalled.cs @@ -10,8 +10,6 @@ using NSubstitute; using NSubstitute.Core; -#pragma warning disable 618 - namespace JustSaying.UnitTests.AwsTools.MessageHandling.Sns.TopicByName; public class WhenPublishingAsyncResultLoggerIsCalled : WhenPublishingTestBase @@ -93,4 +91,4 @@ public void MessageIsForwardedToResponseLogger() { _message.ShouldNotBeNull(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncWithGenericMessageSubjectProvider.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncWithGenericMessageSubjectProvider.cs index 4aac4d842..98806ebe2 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncWithGenericMessageSubjectProvider.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sns/TopicByName/WhenPublishingAsyncWithGenericMessageSubjectProvider.cs @@ -6,8 +6,6 @@ using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; -#pragma warning disable 618 - namespace JustSaying.UnitTests.AwsTools.MessageHandling.Sns.TopicByName; public class WhenPublishingAsyncWithGenericMessageSubjectProvider : WhenPublishingTestBase @@ -60,4 +58,4 @@ public void MessageIsPublishedToCorrectLocation() { Sns.Received().PublishAsync(Arg.Is(x => x.TopicArn == TopicArn)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishing.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishing.cs index ce87b83a4..73fa15b6a 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishing.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishing.cs @@ -12,7 +12,7 @@ public class WhenPublishing : WhenPublishingTestBase { private readonly IMessageSerializationRegister _serializationRegister = Substitute.For(); private const string Url = "https://blablabla/" + QueueName; - private readonly SimpleMessage _message = new SimpleMessage { Content = "Hello" }; + private readonly SimpleMessage _message = new() { Content = "Hello" }; private const string QueueName = "queuename"; private protected override Task CreateSystemUnderTestAsync() diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsync.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsync.cs index 6ca91a932..74bff9492 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsync.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsync.cs @@ -12,7 +12,7 @@ public class WhenPublishingAsync : WhenPublishingTestBase { private readonly IMessageSerializationRegister _serializationRegister = Substitute.For(); private const string Url = "https://blablabla/" + QueueName; - private readonly SimpleMessage _message = new SimpleMessage { Content = "Hello" }; + private readonly SimpleMessage _message = new() { Content = "Hello" }; private const string QueueName = "queuename"; private protected override Task CreateSystemUnderTestAsync() diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsyncResponseLoggerAsyncIsCalled.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsyncResponseLoggerAsyncIsCalled.cs index 6abe6f8f7..87faa815e 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsyncResponseLoggerAsyncIsCalled.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingAsyncResponseLoggerAsyncIsCalled.cs @@ -16,7 +16,7 @@ public class WhenPublishingAsyncResponseLoggerAsyncIsCalled : WhenPublishingTest { private readonly IMessageSerializationRegister _serializationRegister = Substitute.For(); private const string Url = "https://blablabla/" + QueueName; - private readonly SimpleMessage _testMessage = new SimpleMessage { Content = "Hello" }; + private readonly SimpleMessage _testMessage = new() { Content = "Hello" }; private const string QueueName = "queuename"; private const string MessageId = "TestMessage12345"; diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessage.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessage.cs index 67c86af67..d4719cac6 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessage.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessage.cs @@ -13,8 +13,8 @@ public class WhenPublishingDelayedMessage : WhenPublishingTestBase private readonly IMessageSerializationRegister _serializationRegister = Substitute.For(); private const string Url = "https://testurl.com/" + QueueName; - private readonly SimpleMessage _message = new SimpleMessage(); - private readonly PublishMetadata _metadata = new PublishMetadata + private readonly SimpleMessage _message = new(); + private readonly PublishMetadata _metadata = new() { Delay = TimeSpan.FromSeconds(1) }; @@ -29,7 +29,7 @@ private protected override Task CreateSystemUnderTestAsync( protected override void Given() { - Sqs.ListQueuesAsync(Arg.Any()).Returns(new ListQueuesResponse { QueueUrls = new List { Url } }); + Sqs.ListQueuesAsync(Arg.Any()).Returns(new ListQueuesResponse { QueueUrls = [Url] }); Sqs.GetQueueAttributesAsync(Arg.Any()).Returns(new GetQueueAttributesResponse()); } @@ -43,4 +43,4 @@ public void MessageIsPublishedWithDelaySecondsPropertySet() { Sqs.Received().SendMessageAsync(Arg.Is(x => x.DelaySeconds.Equals(1))); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessageAsync.cs b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessageAsync.cs index 0c229df77..fbb28a4d0 100644 --- a/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessageAsync.cs +++ b/tests/JustSaying.UnitTests/AwsTools/MessageHandling/Sqs/WhenPublishingDelayedMessageAsync.cs @@ -12,8 +12,8 @@ public class WhenPublishingDelayedMessageAsync : WhenPublishingTestBase { private readonly IMessageSerializationRegister _serializationRegister = Substitute.For(); private const string Url = "https://blablabla/" + QueueName; - private readonly SimpleMessage _message = new SimpleMessage(); - private readonly PublishMetadata _metadata = new PublishMetadata + private readonly SimpleMessage _message = new(); + private readonly PublishMetadata _metadata = new() { Delay = TimeSpan.FromSeconds(1) }; @@ -28,7 +28,7 @@ private protected override Task CreateSystemUnderTestAsync( protected override void Given() { Sqs.ListQueuesAsync(Arg.Any()) - .Returns(new ListQueuesResponse { QueueUrls = new List { Url } }); + .Returns(new ListQueuesResponse { QueueUrls = [Url] }); Sqs.GetQueueAttributesAsync(Arg.Any()) .Returns(new GetQueueAttributesResponse()); } @@ -43,4 +43,4 @@ public void MessageIsPublishedWithDelaySecondsPropertySet() { Sqs.Received().SendMessageAsync(Arg.Is(x => x.DelaySeconds.Equals(1))); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/AwsTools/TopicCreation/WhenCreatingTopicWithNoPermissions.cs b/tests/JustSaying.UnitTests/AwsTools/TopicCreation/WhenCreatingTopicWithNoPermissions.cs index 323e58cf4..ee5f48d68 100644 --- a/tests/JustSaying.UnitTests/AwsTools/TopicCreation/WhenCreatingTopicWithNoPermissions.cs +++ b/tests/JustSaying.UnitTests/AwsTools/TopicCreation/WhenCreatingTopicWithNoPermissions.cs @@ -9,14 +9,9 @@ namespace JustSaying.UnitTests.AwsTools.TopicCreation; -public class WhenCreatingTopicWithNoPermissions +public class WhenCreatingTopicWithNoPermissions(ITestOutputHelper outputHelper) { - public WhenCreatingTopicWithNoPermissions(ITestOutputHelper outputHelper) - { - OutputHelper = outputHelper; - } - - private ITestOutputHelper OutputHelper { get; } + private ITestOutputHelper OutputHelper { get; } = outputHelper; [Fact] public async Task Arn_Still_Retrieved_When_It_Already_Exists() diff --git a/tests/JustSaying.UnitTests/Fluent/AccountAddressProviderTests.cs b/tests/JustSaying.UnitTests/Fluent/AccountAddressProviderTests.cs index 3e03287f8..119a2789d 100644 --- a/tests/JustSaying.UnitTests/Fluent/AccountAddressProviderTests.cs +++ b/tests/JustSaying.UnitTests/Fluent/AccountAddressProviderTests.cs @@ -62,16 +62,10 @@ public void CanGetAccountTopicByCustomConvention() Assert.Equal("arn:aws:sns:eu-west-1:123456789012:adhoc-topic-name", address); } - private class ManualNamingConvention : IQueueNamingConvention, ITopicNamingConvention + private class ManualNamingConvention(string queueName, string topicName) : IQueueNamingConvention, ITopicNamingConvention { - private readonly string _queueName; - private readonly string _topicName; - - public ManualNamingConvention(string queueName, string topicName) - { - _queueName = queueName; - _topicName = topicName; - } + private readonly string _queueName = queueName; + private readonly string _topicName = topicName; public string QueueName() => _queueName; public string TopicName() => _topicName; diff --git a/tests/JustSaying.UnitTests/Fluent/WhenUsingDefaultServiceResolver.cs b/tests/JustSaying.UnitTests/Fluent/WhenUsingDefaultServiceResolver.cs index 5cdbbf59d..aea392fd2 100644 --- a/tests/JustSaying.UnitTests/Fluent/WhenUsingDefaultServiceResolver.cs +++ b/tests/JustSaying.UnitTests/Fluent/WhenUsingDefaultServiceResolver.cs @@ -9,12 +9,7 @@ namespace JustSaying.UnitTests.Fluent; public class WhenUsingDefaultServiceResolver { - private readonly DefaultServiceResolver _sut; - - public WhenUsingDefaultServiceResolver() - { - _sut = new DefaultServiceResolver(); - } + private readonly DefaultServiceResolver _sut = new(); [Fact] public void ShouldResolveILoggerFactoryToNullLoggerFactory() @@ -69,4 +64,4 @@ public void ShouldResolveIQueueNamingConventionToDefaultNamingConvention() { _sut.ResolveService().ShouldBeOfType(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Fluent/WhenUsingQueueSubscriptionBuilder.cs b/tests/JustSaying.UnitTests/Fluent/WhenUsingQueueSubscriptionBuilder.cs index 27ce37de2..06d84c1cf 100644 --- a/tests/JustSaying.UnitTests/Fluent/WhenUsingQueueSubscriptionBuilder.cs +++ b/tests/JustSaying.UnitTests/Fluent/WhenUsingQueueSubscriptionBuilder.cs @@ -6,12 +6,7 @@ namespace JustSaying.UnitTests.Fluent; public class WhenUsingQueueSubscriptionBuilder { - private readonly QueueSubscriptionBuilder _sut; - - public WhenUsingQueueSubscriptionBuilder() - { - _sut = new QueueSubscriptionBuilder(); - } + private readonly QueueSubscriptionBuilder _sut = new(); [Theory] [InlineData("")] @@ -35,4 +30,4 @@ public void ShouldThrowArgumentExceptionWhenWriteConfigurationIsNull() // Act + Assert Should.Throw(() => _sut.WithReadConfiguration((Action) null)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicPublicationBuilder.cs b/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicPublicationBuilder.cs index 4fa470dc1..5ba58b7ef 100644 --- a/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicPublicationBuilder.cs +++ b/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicPublicationBuilder.cs @@ -6,12 +6,7 @@ namespace JustSaying.UnitTests.Fluent; public class WhenUsingTopicPublicationBuilder { - private readonly TopicPublicationBuilder _sut; - - public WhenUsingTopicPublicationBuilder() - { - _sut = new TopicPublicationBuilder(); - } + private readonly TopicPublicationBuilder _sut = new(); [Theory] [InlineData("")] @@ -35,4 +30,4 @@ public void ShouldThrowArgumentExceptionWhenWriteConfigurationIsNull() // Act + Assert Should.Throw(() => _sut.WithWriteConfiguration((Action) null)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicSubscriberBuilder.cs b/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicSubscriberBuilder.cs index 0880829e9..df2ffa8b3 100644 --- a/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicSubscriberBuilder.cs +++ b/tests/JustSaying.UnitTests/Fluent/WhenUsingTopicSubscriberBuilder.cs @@ -6,12 +6,7 @@ namespace JustSaying.UnitTests.Fluent; public class WhenUsingTopicSubscriberBuilder { - private readonly TopicSubscriptionBuilder _sut; - - public WhenUsingTopicSubscriberBuilder() - { - _sut = new TopicSubscriptionBuilder(); - } + private readonly TopicSubscriptionBuilder _sut = new(); [Theory] [InlineData("")] @@ -35,4 +30,4 @@ public void ShouldThrowArgumentExceptionWhenWriteConfigurationIsNull() // Act + Assert Should.Throw(() => _sut.WithReadConfiguration((Action) null)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/JustSayingBus/GivenAServiceBus.cs b/tests/JustSaying.UnitTests/JustSayingBus/GivenAServiceBus.cs index 1b4377286..e23cee990 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/GivenAServiceBus.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/GivenAServiceBus.cs @@ -7,27 +7,20 @@ namespace JustSaying.UnitTests.JustSayingBus; -public abstract class GivenAServiceBus : IAsyncLifetime +public abstract class GivenAServiceBus(ITestOutputHelper outputHelper) : IAsyncLifetime { protected IMessagingConfig Config; protected TrackingLoggingMonitor Monitor; - protected ILoggerFactory LoggerFactory; + protected ILoggerFactory LoggerFactory = outputHelper.ToLoggerFactory(); private bool _recordThrownExceptions; - public ITestOutputHelper OutputHelper { get; private set; } + public ITestOutputHelper OutputHelper { get; private set; } = outputHelper; protected Exception ThrownException { get; private set; } protected JustSaying.JustSayingBus SystemUnderTest { get; private set; } protected static readonly TimeSpan TimeoutPeriod = TimeSpan.FromSeconds(1); - - public GivenAServiceBus(ITestOutputHelper outputHelper) - { - OutputHelper = outputHelper; - LoggerFactory = outputHelper.ToLoggerFactory(); - } - public virtual async Task InitializeAsync() { Given(); diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenAddingAPublisherWithNoTopic.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenAddingAPublisherWithNoTopic.cs index 7915ffae8..c590fdb94 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenAddingAPublisherWithNoTopic.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenAddingAPublisherWithNoTopic.cs @@ -4,7 +4,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenAddingAPublisherWithNoTopic : GivenAServiceBus +public class WhenAddingAPublisherWithNoTopic(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { protected override void Given() { @@ -23,7 +23,4 @@ public void ExceptionThrown() { ThrownException.ShouldNotBeNull(); } - - public WhenAddingAPublisherWithNoTopic(ITestOutputHelper outputHelper) : base(outputHelper) - { } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingFails.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingFails.cs index 5bbefab3b..4e07ed155 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingFails.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingFails.cs @@ -5,7 +5,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenPublishingFails : GivenAServiceBus +public class WhenPublishingFails(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { private readonly IMessagePublisher _publisher = Substitute.For(); private const int PublishAttempts = 2; @@ -41,7 +41,4 @@ public void EventPublicationWasAttemptedTheConfiguredNumberOfTimes() .Received(PublishAttempts) .PublishAsync(Arg.Any(), Arg.Any(), Arg.Any()); } - - public WhenPublishingFails(ITestOutputHelper outputHelper) : base(outputHelper) - { } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingMessages.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingMessages.cs index fe7458eb3..1ae0e0b1a 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingMessages.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingMessages.cs @@ -5,7 +5,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenPublishingMessages : GivenAServiceBus +public class WhenPublishingMessages(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { private readonly IMessagePublisher _publisher = Substitute.For(); @@ -30,7 +30,4 @@ public void PublishMessageTimeStatsSent() { Monitor.PublishMessageTimes.ShouldHaveSingleItem(); } - - public WhenPublishingMessages(ITestOutputHelper outputHelper) : base(outputHelper) - { } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingWithoutRegistering.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingWithoutRegistering.cs index 2ce7c4a64..5c3ab042c 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingWithoutRegistering.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenPublishingWithoutRegistering.cs @@ -4,7 +4,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenPublishingWithoutRegistering : GivenAServiceBus +public class WhenPublishingWithoutRegistering(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { protected override void Given() { @@ -22,7 +22,4 @@ public void InvalidOperationIsThrown() { ThrownException.ShouldBeAssignableTo(); } - - public WhenPublishingWithoutRegistering(ITestOutputHelper outputHelper) : base(outputHelper) - { } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringMessageHandlers.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringMessageHandlers.cs index 8c591012b..124af09fc 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringMessageHandlers.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringMessageHandlers.cs @@ -8,7 +8,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenRegisteringMessageHandlers : GivenAServiceBus +public class WhenRegisteringMessageHandlers(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { private ISqsQueue _queue; private IHandlerAsync _handler1; @@ -46,7 +46,4 @@ public void HandlersAreAdded() } public class Message2 : Message { } - - public WhenRegisteringMessageHandlers(ITestOutputHelper outputHelper) : base(outputHelper) - { } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringPublishers.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringPublishers.cs index 71288ae23..325787c63 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringPublishers.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringPublishers.cs @@ -6,7 +6,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenRegisteringPublishers : GivenAServiceBus +public class WhenRegisteringPublishers(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { private IMessagePublisher _publisher; @@ -57,7 +57,4 @@ public void AndInterrogationShowsPublishersHaveBeenSet() publishedTypes.ShouldContainKey(nameof(OrderAccepted)); publishedTypes.ShouldContainKey(nameof(OrderRejected)); } - - public WhenRegisteringPublishers(ITestOutputHelper outputHelper) : base(outputHelper) - { } } diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringSubscribers.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringSubscribers.cs index 6acac1fc7..ce6ae44a2 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringSubscribers.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringSubscribers.cs @@ -5,7 +5,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public sealed class WhenRegisteringSubscribers : GivenAServiceBus, IDisposable +public sealed class WhenRegisteringSubscribers(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper), IDisposable { private FakeSqsQueue _queue1; private FakeSqsQueue _queue2; @@ -15,7 +15,7 @@ protected override void Given() { base.Given(); - IEnumerable GetMessages(CancellationToken cancellationToken) + static IEnumerable GetMessages(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { @@ -78,7 +78,4 @@ public void Dispose() { _cts?.Dispose(); } - - public WhenRegisteringSubscribers(ITestOutputHelper outputHelper) : base(outputHelper) - { } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringTheSamePublisherTwice.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringTheSamePublisherTwice.cs index 1e0a30eda..74b42581c 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringTheSamePublisherTwice.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenRegisteringTheSamePublisherTwice.cs @@ -5,7 +5,7 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenRegisteringTheSamePublisherTwice : GivenAServiceBus +public class WhenRegisteringTheSamePublisherTwice(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { private IMessagePublisher _publisher; @@ -40,7 +40,4 @@ public void AndInterrogationShowsNonDuplicatedPublishers() publishedTypes.ShouldContainKey(nameof(Message)); } - - public WhenRegisteringTheSamePublisherTwice(ITestOutputHelper outputHelper) : base(outputHelper) - { } } diff --git a/tests/JustSaying.UnitTests/JustSayingBus/WhenSubscribingAndNotPassingATopic.cs b/tests/JustSaying.UnitTests/JustSayingBus/WhenSubscribingAndNotPassingATopic.cs index fc2ca5150..963bd27e1 100644 --- a/tests/JustSaying.UnitTests/JustSayingBus/WhenSubscribingAndNotPassingATopic.cs +++ b/tests/JustSaying.UnitTests/JustSayingBus/WhenSubscribingAndNotPassingATopic.cs @@ -1,6 +1,6 @@ namespace JustSaying.UnitTests.JustSayingBus; -public class WhenSubscribingAndNotPassingATopic : GivenAServiceBus +public class WhenSubscribingAndNotPassingATopic(ITestOutputHelper outputHelper) : GivenAServiceBus(outputHelper) { protected override void Given() { @@ -19,7 +19,4 @@ public void ArgExceptionThrown() { ((ArgumentException)ThrownException).ParamName.ShouldBe("queue"); } - - public WhenSubscribingAndNotPassingATopic(ITestOutputHelper outputHelper) : base(outputHelper) - { } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/ChannelsTests.cs b/tests/JustSaying.UnitTests/Messaging/Channels/ChannelsTests.cs index 6bbc52a43..4c8d19c62 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/ChannelsTests.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/ChannelsTests.cs @@ -15,7 +15,6 @@ using Newtonsoft.Json; // ReSharper disable PossibleNullReferenceException -#pragma warning disable 4014 namespace JustSaying.UnitTests.Messaging.Channels; @@ -333,7 +332,7 @@ IEnumerable GetMessages(CancellationToken cancellationToken) return new FakeSqsQueue(ct => Task.FromResult(GetMessages(ct))); } - private IMessageReceiveBuffer CreateMessageReceiveBuffer( + private MessageReceiveBuffer CreateMessageReceiveBuffer( ISqsQueue sqsQueue, int prefetch = 10, int receiveBufferSize = 10) @@ -350,7 +349,7 @@ private IMessageReceiveBuffer CreateMessageReceiveBuffer( LoggerFactory.CreateLogger()); } - private IMultiplexerSubscriber CreateSubscriber(IMessageDispatcher dispatcher) + private MultiplexerSubscriber CreateSubscriber(IMessageDispatcher dispatcher) { return new MultiplexerSubscriber(dispatcher, Guid.NewGuid().ToString(), LoggerFactory.CreateLogger()); @@ -376,7 +375,7 @@ private ISubscriptionGroup CreateSubscriptionGroup( return consumerGroupFactory.Create(defaults, settings); } - private IMultiplexer CreateMultiplexer(int channelCapacity = 100) + private MergingMultiplexer CreateMultiplexer(int channelCapacity = 100) { return new MergingMultiplexer( channelCapacity, diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeAmazonSqs.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeAmazonSqs.cs index 39459422b..5bfeacfc3 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeAmazonSqs.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeAmazonSqs.cs @@ -4,20 +4,12 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public sealed class FakeAmazonSqs : IAmazonSQS +public sealed class FakeAmazonSqs(Func> getMessages) : IAmazonSQS { - private readonly Func> _getMessages; + private readonly Func> _getMessages = getMessages; - public IList DeleteMessageRequests { get; } - public IList ReceiveMessageRequests { get; } - - - public FakeAmazonSqs(Func> getMessages) - { - _getMessages = getMessages; - DeleteMessageRequests = new List(); - ReceiveMessageRequests = new List(); - } + public IList DeleteMessageRequests { get; } = new List(); + public IList ReceiveMessageRequests { get; } = new List(); public void Dispose() { } diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeChangeMessageVisbilityRequest.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeChangeMessageVisbilityRequest.cs deleted file mode 100644 index c70117a7e..000000000 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeChangeMessageVisbilityRequest.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; - -public class FakeChangeMessageVisbilityRequest -{ - public FakeChangeMessageVisbilityRequest(string queueUrl, string receiptHandle, int visibilityTimeoutInSeconds) - { - QueueUrl = queueUrl; - ReceiptHandle = receiptHandle; - VisibilityTimeoutInSeconds = visibilityTimeoutInSeconds; - } - - public string QueueUrl { get; } - public string ReceiptHandle { get; } - public int VisibilityTimeoutInSeconds { get; } -} \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeChangeMessageVisibilityRequest.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeChangeMessageVisibilityRequest.cs new file mode 100644 index 000000000..32718dbb6 --- /dev/null +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeChangeMessageVisibilityRequest.cs @@ -0,0 +1,8 @@ +namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; + +public class FakeChangeMessageVisibilityRequest(string queueUrl, string receiptHandle, int visibilityTimeoutInSeconds) +{ + public string QueueUrl { get; } = queueUrl; + public string ReceiptHandle { get; } = receiptHandle; + public int VisibilityTimeoutInSeconds { get; } = visibilityTimeoutInSeconds; +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDeleteMessageRequest.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDeleteMessageRequest.cs index ec50f4b68..f66b2e285 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDeleteMessageRequest.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDeleteMessageRequest.cs @@ -1,13 +1,7 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class FakeDeleteMessageRequest +public class FakeDeleteMessageRequest(string queueUrl, string receiptHandle) { - public FakeDeleteMessageRequest(string queueUrl, string receiptHandle) - { - QueueUrl = queueUrl; - ReceiptHandle = receiptHandle; - } - - public string QueueUrl { get; } - public string ReceiptHandle { get; } + public string QueueUrl { get; } = queueUrl; + public string ReceiptHandle { get; } = receiptHandle; } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDispatcher.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDispatcher.cs index 3e5897688..3b879f6cd 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDispatcher.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeDispatcher.cs @@ -3,21 +3,14 @@ namespace JustSaying.UnitTests.Messaging.Channels.TestHelpers; -internal class FakeDispatcher : IMessageDispatcher +internal class FakeDispatcher(Action spy = null) : IMessageDispatcher { - private readonly Action _spy; - - public FakeDispatcher(Action spy = null) - { - _spy = spy; - } - public Task DispatchMessageAsync(IQueueMessageContext messageContext, CancellationToken cancellationToken) { - _spy?.Invoke(); + spy?.Invoke(); DispatchedMessages.Add(messageContext); return Task.CompletedTask; } public IList DispatchedMessages { get; } = new List(); -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageLock.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageLock.cs index 758d592a8..b8dad88ea 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageLock.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageLock.cs @@ -2,24 +2,16 @@ namespace JustSaying.UnitTests.Messaging.Channels.TestHelpers; -public class FakeMessageLock : IMessageLockAsync +public class FakeMessageLock(bool exclusive = true) : IMessageLockAsync { - private readonly bool _exclusive; - - public FakeMessageLock(bool exclusive = true) - { - _exclusive = exclusive; - MessageLockRequests = new List<(string key, TimeSpan howLong, bool isPermanent)>(); - } - - public IList<(string key, TimeSpan howLong, bool isPermanent)> MessageLockRequests { get; } + public IList<(string key, TimeSpan howLong, bool isPermanent)> MessageLockRequests { get; } = new List<(string key, TimeSpan howLong, bool isPermanent)>(); public Task TryAcquireLockPermanentlyAsync(string key) { MessageLockRequests.Add((key, TimeSpan.MaxValue, true)); return Task.FromResult(new MessageLockResponse { - DoIHaveExclusiveLock = _exclusive + DoIHaveExclusiveLock = exclusive }); } @@ -28,7 +20,7 @@ public Task TryAcquireLockAsync(string key, TimeSpan howLon MessageLockRequests.Add((key, howLong, false)); return Task.FromResult(new MessageLockResponse { - DoIHaveExclusiveLock = _exclusive + DoIHaveExclusiveLock = exclusive }); } @@ -36,4 +28,4 @@ public Task ReleaseLockAsync(string key) { return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageVisbilityUpdater.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageVisibilityUpdater.cs similarity index 80% rename from tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageVisbilityUpdater.cs rename to tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageVisibilityUpdater.cs index 8f9959909..1bcbef787 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageVisbilityUpdater.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeMessageVisibilityUpdater.cs @@ -2,10 +2,10 @@ namespace JustSaying.UnitTests.Messaging.Channels.Fakes; -public class FakeVisbilityUpdater : IMessageVisibilityUpdater +public class FakeVisibilityUpdater : IMessageVisibilityUpdater { public Task UpdateMessageVisibilityTimeout(TimeSpan visibilityTimeout, CancellationToken cancellationToken) { return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeReceiveMessagesRequest.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeReceiveMessagesRequest.cs index 631d0f824..0e7dc5ce6 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeReceiveMessagesRequest.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeReceiveMessagesRequest.cs @@ -1,19 +1,10 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class FakeReceiveMessagesRequest +public class FakeReceiveMessagesRequest(string queueUrl, int maxNumOfMessages, int secondsWaitTime, IList attributesToLoad, int numMessagesReceived) { - public FakeReceiveMessagesRequest(string queueUrl, int maxNumOfMessages, int secondsWaitTime, IList attributesToLoad, int numMessagesReceived) - { - QueueUrl = queueUrl; - MaxNumOfMessages = maxNumOfMessages; - SecondsWaitTime = secondsWaitTime; - AttributesToLoad = attributesToLoad; - NumMessagesReceived = numMessagesReceived; - } - - public string QueueUrl { get; } - public int MaxNumOfMessages { get; } - public int NumMessagesReceived { get; } - public int SecondsWaitTime { get; } - public IList AttributesToLoad { get; } + public string QueueUrl { get; } = queueUrl; + public int MaxNumOfMessages { get; } = maxNumOfMessages; + public int NumMessagesReceived { get; } = numMessagesReceived; + public int SecondsWaitTime { get; } = secondsWaitTime; + public IList AttributesToLoad { get; } = attributesToLoad; } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeSqsQueue.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeSqsQueue.cs index 065be510f..7df6a0375 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeSqsQueue.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeSqsQueue.cs @@ -4,31 +4,22 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class FakeSqsQueue : ISqsQueue +public class FakeSqsQueue(Func>> messageProducer, string queueName = "fake-queue-name") : ISqsQueue { - private readonly Func>> _messageProducer; - - public FakeSqsQueue(Func>> messageProducer, string queueName = "fake-queue-name") - { - _messageProducer = messageProducer; - QueueName = queueName; - RegionSystemName = "fake-region"; - Uri = new Uri("http://test.com"); - Arn = $"arn:aws:fake-region:123456789012:{queueName}"; - } + private readonly Func>> _messageProducer = messageProducer; public InterrogationResult Interrogate() { return InterrogationResult.Empty; } - public string QueueName { get; } - public string RegionSystemName { get; } - public Uri Uri { get; set; } - public string Arn { get; } + public string QueueName { get; } = queueName; + public string RegionSystemName { get; } = "fake-region"; + public Uri Uri { get; set; } = new Uri("http://test.com"); + public string Arn { get; } = $"arn:aws:fake-region:123456789012:{queueName}"; public List DeleteMessageRequests { get; } = new(); - public List ChangeMessageVisbilityRequests { get; } = new(); + public List ChangeMessageVisbilityRequests { get; } = new(); public List TagQueueRequests { get; } = new(); public List ReceiveMessageRequests { get; } = new(); @@ -57,7 +48,7 @@ public async Task> ReceiveMessagesAsync(string queueUrl, int maxN public Task ChangeMessageVisibilityAsync(string queueUrl, string receiptHandle, int visibilityTimeoutInSeconds, CancellationToken cancellationToken) { - ChangeMessageVisbilityRequests.Add(new FakeChangeMessageVisbilityRequest(queueUrl, receiptHandle, visibilityTimeoutInSeconds)); + ChangeMessageVisbilityRequests.Add(new FakeChangeMessageVisibilityRequest(queueUrl, receiptHandle, visibilityTimeoutInSeconds)); return Task.CompletedTask; } } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeTagQueueRequest.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeTagQueueRequest.cs index d431b5352..a2aa502c9 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeTagQueueRequest.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/FakeTagQueueRequest.cs @@ -1,13 +1,7 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class FakeTagQueueRequest +public class FakeTagQueueRequest(string queueUrl, Dictionary tags) { - public FakeTagQueueRequest(string queueUrl, Dictionary tags) - { - QueueUrl = queueUrl; - Tags = tags; - } - - public string QueueUrl { get; } - public Dictionary Tags { get; } + public string QueueUrl { get; } = queueUrl; + public Dictionary Tags { get; } = tags; } \ No newline at end of file diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/InMemoryServiceResolver.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/InMemoryServiceResolver.cs index 7c18e41a7..346b4037a 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/InMemoryServiceResolver.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/InMemoryServiceResolver.cs @@ -14,7 +14,7 @@ public class InMemoryServiceResolver : IServiceResolver, IHandlerResolver private static readonly Action Configure = (sc, outputHelper, monitor) => sc.AddLogging(l => l.AddXUnit(outputHelper)) - .AddSingleton(monitor) + .AddSingleton(monitor) .AddSingleton() .AddSingleton() .AddSingleton(new MessageContextAccessor()); @@ -48,4 +48,4 @@ public T ResolveOptionalService() where T : class { return _provider.GetService(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/TestHandler.cs b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/TestHandler.cs index ae2e02199..4a1d0d598 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/TestHandler.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/Fakes/TestHandler.cs @@ -2,20 +2,13 @@ namespace JustSaying.UnitTests.Messaging.Channels.TestHelpers; -public class TestHandler : IHandlerAsync +public class TestHandler(Action spy) : IHandlerAsync { - private readonly Action _spy; - - public TestHandler(Action spy) - { - _spy = spy; - } - public async Task Handle(T testMessage) { - _spy?.Invoke(testMessage); + spy?.Invoke(testMessage); await Task.Delay(100); return true; } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenReceivingShouldStop.cs b/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenReceivingShouldStop.cs index 89c2bd808..94889eefa 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenReceivingShouldStop.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenReceivingShouldStop.cs @@ -13,7 +13,7 @@ public class WhenReceivingShouldStop private class TestMessage : Message { } private int _callCount; - private readonly IMessageReceivePauseSignal _messageReceivePauseSignal; + private readonly MessageReceivePauseSignal _messageReceivePauseSignal; private readonly MessageReceiveBuffer _messageReceiveBuffer; public WhenReceivingShouldStop(ITestOutputHelper testOutputHelper) diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenSqsIsSlow.cs b/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenSqsIsSlow.cs index 30aaf95f8..c6ff0bd17 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenSqsIsSlow.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/MessageReceiveBufferTests/WhenSqsIsSlow.cs @@ -25,7 +25,7 @@ public WhenSqsIsSlow(ITestOutputHelper testOutputHelper) var messages = new List { new TestMessage() }; var queue = new FakeSqsQueue(async ct => { - await Task.Delay(100); + await Task.Delay(100, ct); Interlocked.Increment(ref _callCount); return messages; }); diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/MultiplexerTests/MergingMultiplexerTests.cs b/tests/JustSaying.UnitTests/Messaging/Channels/MultiplexerTests/MergingMultiplexerTests.cs index f0840a2f5..81efb1220 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/MultiplexerTests/MergingMultiplexerTests.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/MultiplexerTests/MergingMultiplexerTests.cs @@ -5,21 +5,15 @@ namespace JustSaying.UnitTests.Messaging.Channels.MultiplexerTests; -public class MergingMultiplexerTests +public class MergingMultiplexerTests(ITestOutputHelper outputHelper) { - private readonly ITestOutputHelper _outputHelper; private static readonly TimeSpan TimeoutPeriod = TimeSpan.FromSeconds(1); - public MergingMultiplexerTests(ITestOutputHelper outputHelper) - { - _outputHelper = outputHelper; - } - [Fact] public async Task Starting_Twice_Returns_Same_Task() { // Arrange - using var multiplexer = new MergingMultiplexer(10, _outputHelper.ToLogger()); + using var multiplexer = new MergingMultiplexer(10, outputHelper.ToLogger()); var cts = new CancellationTokenSource(); @@ -45,7 +39,7 @@ public async Task Starting_Twice_Returns_Same_Task() public void Cannot_Add_Invalid_Reader() { // Arrange - using var multiplexer = new MergingMultiplexer(10, _outputHelper.ToLogger()); + using var multiplexer = new MergingMultiplexer(10, outputHelper.ToLogger()); // Act and Assert Assert.Throws(() => multiplexer.ReadFrom(null)); @@ -55,7 +49,7 @@ public void Cannot_Add_Invalid_Reader() public void Cannot_Get_Messages_Before_Started() { // Arrange - using var multiplexer = new MergingMultiplexer(10, _outputHelper.ToLogger()); + using var multiplexer = new MergingMultiplexer(10, outputHelper.ToLogger()); // Act and Assert Assert.ThrowsAsync(async () => await ReadAllMessages(multiplexer)); @@ -65,7 +59,7 @@ public void Cannot_Get_Messages_Before_Started() public async Task When_Reader_Does_Not_Complete_Readers_Not_Completed() { // Arrange - using var multiplexer = new MergingMultiplexer(10, _outputHelper.ToLogger()); + using var multiplexer = new MergingMultiplexer(10, outputHelper.ToLogger()); var cts = new CancellationTokenSource(); @@ -92,7 +86,7 @@ public async Task When_Reader_Does_Not_Complete_Readers_Not_Completed() public async Task When_Reader_Completes_When_All_Readers_Completed() { // Arrange - using var multiplexer = new MergingMultiplexer(10, _outputHelper.ToLogger()); + using var multiplexer = new MergingMultiplexer(10, outputHelper.ToLogger()); var cts = new CancellationTokenSource(); @@ -109,14 +103,14 @@ public async Task When_Reader_Completes_When_All_Readers_Completed() channel2.Writer.Complete(); // Assert - await Patiently.AssertThatAsync(_outputHelper, () => multiplexerRunTask.IsCompletedSuccessfully); + await Patiently.AssertThatAsync(outputHelper, () => multiplexerRunTask.IsCompletedSuccessfully); cts.Cancel(); } - private static async Task ReadAllMessages(IMultiplexer multiplexer) + private static async Task ReadAllMessages(MergingMultiplexer multiplexer) { await foreach (var _ in multiplexer.GetMessagesAsync()) { } } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupCollectionTests.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupCollectionTests.cs index bfe16e456..764dc8228 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupCollectionTests.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupCollectionTests.cs @@ -8,7 +8,6 @@ using JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; using Microsoft.Extensions.Logging; using NSubstitute; -using HandleMessageMiddleware = JustSaying.Messaging.Middleware.MiddlewareBase; namespace JustSaying.UnitTests.Messaging.Channels; @@ -99,7 +98,7 @@ private JustSaying.JustSayingBus CreateBus() return bus; } - private static ISqsQueue TestQueue( + private static FakeSqsQueue TestQueue( IMessageSerializationRegister messageSerializationRegister, string queueName, Action spy = null) diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandler.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandler.cs index 83ad4bdbb..5565d62c6 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandler.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandler.cs @@ -9,16 +9,12 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenExactlyOnceIsAppliedToHandler : BaseSubscriptionGroupTests +public class WhenExactlyOnceIsAppliedToHandler(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private ISqsQueue _queue; private readonly int _expectedTimeout = 5; private FakeMessageLock _messageLock; - public WhenExactlyOnceIsAppliedToHandler(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { } - protected override void Given() { _queue = CreateSuccessfulTestQueue("TestQueue", new TestMessage()); diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandlerWithoutExplicitTimeout.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandlerWithoutExplicitTimeout.cs index 5465b099d..603fd35f1 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandlerWithoutExplicitTimeout.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenExactlyOnceIsAppliedToHandlerWithoutExplicitTimeout.cs @@ -9,17 +9,12 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenExactlyOnceIsAppliedWithoutSpecificTimeout : BaseSubscriptionGroupTests +public class WhenExactlyOnceIsAppliedWithoutSpecificTimeout(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private ISqsQueue _queue; private readonly int _maximumTimeout = (int)TimeSpan.MaxValue.TotalSeconds; private FakeMessageLock _messageLock; - public WhenExactlyOnceIsAppliedWithoutSpecificTimeout(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { - } - protected override void Given() { _queue = CreateSuccessfulTestQueue(Guid.NewGuid().ToString(), new TestMessage()); diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningStartsAndStops.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningStartsAndStops.cs index ca30890c0..f28137d11 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningStartsAndStops.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningStartsAndStops.cs @@ -4,7 +4,7 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenListeningStartsAndStops : BaseSubscriptionGroupTests +public class WhenListeningStartsAndStops(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private const string AttributeMessageContentsRunning = @"Message Contents Running"; private const string AttributeMessageContentsAfterStop = @"Message Contents After Stop"; @@ -13,11 +13,6 @@ public class WhenListeningStartsAndStops : BaseSubscriptionGroupTests private bool _running; private FakeSqsQueue _queue; - public WhenListeningStartsAndStops(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { - } - protected override void Given() { // we expect to get max 10 messages per batch diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningWithMultipleGroups.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningWithMultipleGroups.cs index e8e3cc485..daf449cc4 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningWithMultipleGroups.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenListeningWithMultipleGroups.cs @@ -4,16 +4,10 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenListeningWithMultipleGroups : BaseSubscriptionGroupTests +public class WhenListeningWithMultipleGroups(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { - private readonly ISqsQueue _queueB; - private readonly ISqsQueue _queueA; - - public WhenListeningWithMultipleGroups(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - _queueA = CreateSuccessfulTestQueue("EC159934-A30E-45B0-9186-78853F7D3BED", new TestMessage()); - _queueB = CreateSuccessfulTestQueue("C7506B3F-81DA-4898-82A5-C0293523592A", new TestMessage()); - } + private readonly ISqsQueue _queueB = CreateSuccessfulTestQueue("C7506B3F-81DA-4898-82A5-C0293523592A", new TestMessage()); + private readonly ISqsQueue _queueA = CreateSuccessfulTestQueue("EC159934-A30E-45B0-9186-78853F7D3BED", new TestMessage()); protected override Dictionary SetupBusConfig() { diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingFails.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingFails.cs index ee03aa925..b0453430c 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingFails.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingFails.cs @@ -1,14 +1,9 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenMessageHandlingFails : BaseSubscriptionGroupTests +public class WhenMessageHandlingFails(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private FakeSqsQueue _queue; - public WhenMessageHandlingFails(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { - } - protected override void Given() { _queue = CreateSuccessfulTestQueue(Guid.NewGuid().ToString(), new TestMessage()); diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingSucceeds.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingSucceeds.cs index 7a8eda4e9..b7b466c35 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingSucceeds.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingSucceeds.cs @@ -2,19 +2,15 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenMessageHandlingSucceeds : BaseSubscriptionGroupTests +public class WhenMessageHandlingSucceeds(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { - private string _messageBody = "Expected Message Body"; + private const string MessageBody = "Expected Message Body"; private FakeSqsQueue _queue; - public WhenMessageHandlingSucceeds(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { } - protected override void Given() { _queue = CreateSuccessfulTestQueue(Guid.NewGuid().ToString(), - ct => Task.FromResult(new List { new TestMessage { Body = _messageBody } }.AsEnumerable())); + ct => Task.FromResult(new List { new TestMessage { Body = MessageBody } }.AsEnumerable())); Queues.Add(_queue); } @@ -23,7 +19,7 @@ protected override void Given() public void MessagesGetDeserializedByCorrectHandler() { SerializationRegister.ReceivedDeserializationRequests.ShouldAllBe( - msg => msg == _messageBody); + msg => msg == MessageBody); } [Fact] @@ -52,4 +48,4 @@ public void ExceptionIsNotLoggedToMonitor() { Monitor.HandledExceptions.ShouldBeEmpty(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingThrows.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingThrows.cs index ad7d4501a..16654bf4a 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingThrows.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenMessageHandlingThrows.cs @@ -2,15 +2,11 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenMessageHandlingThrows : BaseSubscriptionGroupTests +public class WhenMessageHandlingThrows(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private bool _firstTime = true; private FakeSqsQueue _queue; - public WhenMessageHandlingThrows(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { } - protected override void Given() { _queue = CreateSuccessfulTestQueue("TestQueue", new TestMessage()); diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInMessageProcessing.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInMessageProcessing.cs index 231827589..d17b64fca 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInMessageProcessing.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInMessageProcessing.cs @@ -4,15 +4,11 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenThereAreExceptionsInMessageProcessing : BaseSubscriptionGroupTests +public class WhenThereAreExceptionsInMessageProcessing(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private ISqsQueue _queue; private int _callCount; - public WhenThereAreExceptionsInMessageProcessing(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { } - protected override void Given() { ConcurrencyLimit = 1; diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInSqsCalling.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInSqsCalling.cs index d789720f8..22c59d168 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInSqsCalling.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenThereAreExceptionsInSqsCalling.cs @@ -4,16 +4,11 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public class WhenThereAreExceptionsInSqsCalling : BaseSubscriptionGroupTests +public class WhenThereAreExceptionsInSqsCalling(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper) { private ISqsQueue _queue; private int _callCount; - public WhenThereAreExceptionsInSqsCalling(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { - } - protected override void Given() { _queue = CreateSuccessfulTestQueue("TestQueue", ExceptionOnFirstCall()); diff --git a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenUsingSqsQueueByName.cs b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenUsingSqsQueueByName.cs index 971ae37f5..093955b68 100644 --- a/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenUsingSqsQueueByName.cs +++ b/tests/JustSaying.UnitTests/Messaging/Channels/SubscriptionGroupTests/WhenUsingSqsQueueByName.cs @@ -1,5 +1,4 @@ using Amazon; -using Amazon.SQS; using Amazon.SQS.Model; using JustSaying.AwsTools.MessageHandling; using JustSaying.TestingFramework; @@ -8,17 +7,13 @@ namespace JustSaying.UnitTests.Messaging.Channels.SubscriptionGroupTests; -public sealed class WhenUsingSqsQueueByName : BaseSubscriptionGroupTests, IDisposable +public sealed class WhenUsingSqsQueueByName(ITestOutputHelper testOutputHelper) : BaseSubscriptionGroupTests(testOutputHelper), IDisposable { private ISqsQueue _queue; - private IAmazonSQS _client; - readonly string MessageTypeString = typeof(SimpleMessage).ToString(); + private FakeAmazonSqs _client; + readonly string MessageTypeString = nameof(SimpleMessage); const string MessageBody = "object"; - public WhenUsingSqsQueueByName(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { } - protected override void Given() { int retryCount = 1; @@ -56,12 +51,12 @@ private static ReceiveMessageResponse GenerateResponseMessages( { Messages = new List { - new Message + new() { MessageId = messageId.ToString(), Body = SqsMessageBody(messageType) }, - new Message + new() { MessageId = messageId.ToString(), Body = "{\"Subject\":\"SOME_UNKNOWN_MESSAGE\"," + @@ -80,4 +75,4 @@ public void Dispose() { _client.Dispose(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/MessageHandling/WhenEnsuringMessageIsOnlyHandledExactlyOnce.cs b/tests/JustSaying.UnitTests/Messaging/MessageHandling/WhenEnsuringMessageIsOnlyHandledExactlyOnce.cs index 3019c04cf..d70b6a764 100644 --- a/tests/JustSaying.UnitTests/Messaging/MessageHandling/WhenEnsuringMessageIsOnlyHandledExactlyOnce.cs +++ b/tests/JustSaying.UnitTests/Messaging/MessageHandling/WhenEnsuringMessageIsOnlyHandledExactlyOnce.cs @@ -9,15 +9,8 @@ namespace JustSaying.UnitTests.Messaging.MessageHandling; -public class WhenEnsuringMessageIsOnlyHandledExactlyOnce +public class WhenEnsuringMessageIsOnlyHandledExactlyOnce(ITestOutputHelper outputHelper) { - private readonly ITestOutputHelper _outputHelper; - - public WhenEnsuringMessageIsOnlyHandledExactlyOnce(ITestOutputHelper outputHelper) - { - _outputHelper = outputHelper; - } - [Fact] public async Task WhenMessageIsLockedByAnotherHandler_MessageWillBeLeftInTheQueue() { @@ -25,7 +18,7 @@ public async Task WhenMessageIsLockedByAnotherHandler_MessageWillBeLeftInTheQueu var testResolver = new InMemoryServiceResolver(sc => sc .AddLogging(l => - l.AddXUnit(_outputHelper)) + l.AddXUnit(outputHelper)) .AddSingleton(messageLock)); var monitor = new TrackingLoggingMonitor(LoggerFactory.Create(lf => lf.AddXUnit()).CreateLogger()); @@ -44,4 +37,4 @@ public async Task WhenMessageIsLockedByAnotherHandler_MessageWillBeLeftInTheQueu handler.ReceivedMessages.ShouldBeEmpty(); result.ShouldBeFalse(); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Middleware/DelegateMessageHandlingMiddleware.cs b/tests/JustSaying.UnitTests/Messaging/Middleware/DelegateMessageHandlingMiddleware.cs index b5434e054..4d6217c76 100644 --- a/tests/JustSaying.UnitTests/Messaging/Middleware/DelegateMessageHandlingMiddleware.cs +++ b/tests/JustSaying.UnitTests/Messaging/Middleware/DelegateMessageHandlingMiddleware.cs @@ -7,14 +7,9 @@ namespace JustSaying.UnitTests.AwsTools.MessageHandling; /// A utility middleware that removes the need for handler boilerplate, and creates an inline handler pipeline /// /// -public class DelegateMessageHandlingMiddleware : MiddlewareBase where TMessage : Message +public class DelegateMessageHandlingMiddleware(Func> func) : MiddlewareBase where TMessage : Message { - private readonly Func> _func; - - public DelegateMessageHandlingMiddleware(Func> func) - { - _func = func; - } + private readonly Func> _func = func; protected override async Task RunInnerAsync( HandleMessageContext context, diff --git a/tests/JustSaying.UnitTests/Messaging/Middleware/TestHandleMessageContextBuilder.cs b/tests/JustSaying.UnitTests/Messaging/Middleware/TestHandleMessageContextBuilder.cs index d2563e496..237b60787 100644 --- a/tests/JustSaying.UnitTests/Messaging/Middleware/TestHandleMessageContextBuilder.cs +++ b/tests/JustSaying.UnitTests/Messaging/Middleware/TestHandleMessageContextBuilder.cs @@ -15,7 +15,7 @@ public static HandleMessageContext From(TMessage message = default, st new Message(), message ?? new TMessage(), typeof(TMessage), - new FakeVisbilityUpdater(), + new FakeVisibilityUpdater(), new FakeMessageDeleter(), new Uri("http://test-queue"), new MessageAttributes()); diff --git a/tests/JustSaying.UnitTests/Messaging/Policies/ExamplePolicies/PollyMiddleware.cs b/tests/JustSaying.UnitTests/Messaging/Policies/ExamplePolicies/PollyMiddleware.cs index 8e5046753..54cbe48bc 100644 --- a/tests/JustSaying.UnitTests/Messaging/Policies/ExamplePolicies/PollyMiddleware.cs +++ b/tests/JustSaying.UnitTests/Messaging/Policies/ExamplePolicies/PollyMiddleware.cs @@ -3,20 +3,13 @@ namespace JustSaying.UnitTests.Messaging.Policies.ExamplePolicies; -public class PollyMiddleware : MiddlewareBase +public class PollyMiddleware(IAsyncPolicy policy) : MiddlewareBase { - private readonly IAsyncPolicy _policy; - - public PollyMiddleware(IAsyncPolicy policy) - { - _policy = policy; - } - protected override async Task RunInnerAsync( TContext context, Func> func, CancellationToken stoppingToken) { - return await _policy.ExecuteAsync(() => func(stoppingToken)); + return await policy.ExecuteAsync(() => func(stoppingToken)); } -} \ No newline at end of file +} diff --git a/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenAddingASerializerTwice.cs b/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenAddingASerializerTwice.cs index 74b3f6c9b..71266c68b 100644 --- a/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenAddingASerializerTwice.cs +++ b/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenAddingASerializerTwice.cs @@ -6,7 +6,7 @@ namespace JustSaying.UnitTests.Messaging.Serialization.SerializationRegister; public class WhenAddingASerializerTwice : XBehaviourTest { protected override MessageSerializationRegister CreateSystemUnderTest() => - new MessageSerializationRegister( + new( new NonGenericMessageSubjectProvider(), new NewtonsoftSerializationFactory()); diff --git a/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenDeserializingMessage.cs b/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenDeserializingMessage.cs index 314291da3..9a46693a6 100644 --- a/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenDeserializingMessage.cs +++ b/tests/JustSaying.UnitTests/Messaging/Serialization/SerializationRegister/WhenDeserializingMessage.cs @@ -5,7 +5,7 @@ namespace JustSaying.UnitTests.Messaging.Serialization.SerializationRegister; public class WhenDeserializingMessage : XBehaviourTest { protected override MessageSerializationRegister CreateSystemUnderTest() => - new MessageSerializationRegister( + new( new NonGenericMessageSubjectProvider(), new NewtonsoftSerializationFactory()); diff --git a/tests/JustSaying.UnitTests/Naming/DefaultNamingConventionsTests.cs b/tests/JustSaying.UnitTests/Naming/DefaultNamingConventionsTests.cs index 3cd3d74fc..5cfb427a7 100644 --- a/tests/JustSaying.UnitTests/Naming/DefaultNamingConventionsTests.cs +++ b/tests/JustSaying.UnitTests/Naming/DefaultNamingConventionsTests.cs @@ -5,7 +5,7 @@ namespace JustSaying.UnitTests.Naming; public class DefaultNamingConventionsTests { - private readonly DefaultNamingConventions Sut = new DefaultNamingConventions(); + private readonly DefaultNamingConventions Sut = new(); [Fact] public void WhenGeneratingTopicName_ForNonGenericType_ThenTheCorrectNameShouldBeReturned() diff --git a/tests/JustSaying.UnitTests/TestSettings.cs b/tests/JustSaying.UnitTests/TestSettings.cs index 060037f4b..e5cc5d402 100644 --- a/tests/JustSaying.UnitTests/TestSettings.cs +++ b/tests/JustSaying.UnitTests/TestSettings.cs @@ -1 +1 @@ -[assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)] +[assembly: CollectionBehavior(DisableTestParallelization = true)] diff --git a/tests/JustSaying.UnitTests/WhenPublishEndpointIsNotProvided.cs b/tests/JustSaying.UnitTests/WhenPublishEndpointIsNotProvided.cs index 9fad1da01..0031da3b1 100644 --- a/tests/JustSaying.UnitTests/WhenPublishEndpointIsNotProvided.cs +++ b/tests/JustSaying.UnitTests/WhenPublishEndpointIsNotProvided.cs @@ -22,7 +22,7 @@ public void ThrowsException() } protected override SqsReadConfiguration CreateSystemUnderTest() - => new SqsReadConfiguration(SubscriptionType.ToTopic) + => new(SubscriptionType.ToTopic) { MessageRetention = JustSayingConstants.MinimumRetentionPeriod.Add(TimeSpan.FromSeconds(1)), TopicName = "ATopic",