Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cancellation token handling #44

Merged
merged 2 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace OddsCollector.Functions.Tests.Infrastructure.CancellationToken;

internal static class CancellationTokenGenerator
{
public static async Task<System.Threading.CancellationToken> GetRequestedForCancellationToken()
{
var cancellationTokenSource = new CancellationTokenSource();

await cancellationTokenSource.CancelAsync();

return cancellationTokenSource.Token;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.Extensions.Logging;

namespace OddsCollector.Functions.Tests.Infrastructure.Logger;

internal static class LoggerFactory
{
public static ILogger<T> GetLoggerMock<T>() where T : class
{
return Substitute.For<ILogger<T>>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.Azure.Functions.Worker;

namespace OddsCollector.Functions.Tests.Infrastructure.ServiceBus;

internal static class ServiceBusMessageActionsFactory
{
public static ServiceBusMessageActions GetServiceBusMessageActionsMock()
{
return Substitute.For<ServiceBusMessageActions>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ namespace OddsCollector.Functions.Tests.Infrastructure.ServiceBus;

internal static class ServiceBusReceivedMessageFactory
{
public static ServiceBusReceivedMessage CreateFromObject(object obj)
public static IEnumerable<ServiceBusReceivedMessage> CreateFromObjects(IEnumerable<object> objects)
{
return objects.Select(CreateFromObject);
}

private static ServiceBusReceivedMessage CreateFromObject(object obj)
{
var serialized = Encoding.ASCII.GetBytes(JsonSerializer.Serialize(obj))
.Select(x => new ReadOnlyMemory<byte>([x]));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using NSubstitute.ExceptionExtensions;
using OddsCollector.Functions.Models;
using OddsCollector.Functions.OddsApi;
using LoggerFactory = OddsCollector.Functions.Tests.Infrastructure.Logger.LoggerFactory;

namespace OddsCollector.Functions.Tests.Tests.Functions;

Expand All @@ -15,18 +16,16 @@ public async Task Run_WithValidParameters_ReturnsEventResults()
// Arrange
IEnumerable<EventResult> expectedEventResults = new List<EventResult> { new() };

var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.EventResultsFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.EventResultsFunction>();

var clientStub = Substitute.For<IOddsApiClient>();
clientStub.GetEventResultsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(expectedEventResults));
var clientStub = GetOddsApiClientStub(expectedEventResults);

var function = new OddsCollector.Functions.Functions.EventResultsFunction(loggerMock, clientStub);

var token = new CancellationToken();
var cancellationToken = new CancellationToken();

// Act
var eventResults = await function.Run(token);
var eventResults = await function.Run(cancellationToken);

// Assert
eventResults.Should().NotBeNull().And.BeEquivalentTo(expectedEventResults);
Expand All @@ -40,18 +39,18 @@ public async Task Run_WithException_ReturnsEmptyEventResults()
// Arrange
var exception = new Exception();

var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.EventResultsFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.EventResultsFunction>();

var clientStub = Substitute.For<IOddsApiClient>();
clientStub.GetEventResultsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.Throws(exception);

var function = new OddsCollector.Functions.Functions.EventResultsFunction(loggerMock, clientStub);

var token = new CancellationToken();
var cancellationToken = new CancellationToken();

// Act
var eventResults = await function.Run(token);
var eventResults = await function.Run(cancellationToken);

// Assert
eventResults.Should().NotBeNull().And.BeEmpty();
Expand All @@ -66,22 +65,30 @@ public async Task Run_WithValidParameters_ReturnsNoEventResults()
// Arrange
IEnumerable<EventResult> expectedEventResults = new List<EventResult>();

var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.EventResultsFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.EventResultsFunction>();

var clientStub = Substitute.For<IOddsApiClient>();
clientStub.GetEventResultsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(expectedEventResults));
var clientStub = GetOddsApiClientStub(expectedEventResults);

var function = new OddsCollector.Functions.Functions.EventResultsFunction(loggerMock, clientStub);

var token = new CancellationToken();
var cancellationToken = new CancellationToken();

// Act
var eventResults = await function.Run(token);
var eventResults = await function.Run(cancellationToken);

// Assert
eventResults.Should().NotBeNull().And.BeEquivalentTo(expectedEventResults);

loggerMock.ReceivedWithAnyArgs().LogWarning(string.Empty, 1);
}

private static IOddsApiClient GetOddsApiClientStub(IEnumerable<EventResult> expectedEventResults)
{
var clientStub = Substitute.For<IOddsApiClient>();

clientStub.GetEventResultsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(expectedEventResults));

return clientStub;
}
}
63 changes: 48 additions & 15 deletions OddsCollector.Functions.Tests/Tests/Functions/PredictionFunction.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using NSubstitute.ReceivedExtensions;
using NSubstitute.ReceivedExtensions;
using OddsCollector.Functions.Models;
using OddsCollector.Functions.Strategies;
using OddsCollector.Functions.Tests.Infrastructure.CancellationToken;
using OddsCollector.Functions.Tests.Infrastructure.Data;
using OddsCollector.Functions.Tests.Infrastructure.Logger;
using OddsCollector.Functions.Tests.Infrastructure.ServiceBus;

namespace OddsCollector.Functions.Tests.Tests.Functions;
Expand All @@ -15,16 +14,18 @@ internal class PredictionFunction
public async Task Run_WithValidServiceBusMessage_ReturnsEventPrediction()
{
// Arrange
var loggerStub = Substitute.For<ILogger<OddsCollector.Functions.Functions.PredictionFunction>>();
var loggerStub = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.PredictionFunction>();

var upcomingEvent = new UpcomingEventBuilder().SetSampleData().Instance;

var expectedPrediction = new EventPredictionBuilder().SetSampleData().Instance;

ServiceBusReceivedMessage[] receivedMessages =
[ServiceBusReceivedMessageFactory.CreateFromObject(upcomingEvent)];
var receivedMessages =
ServiceBusReceivedMessageFactory.CreateFromObjects([
upcomingEvent
]).ToArray();

var actionsMock = Substitute.For<ServiceBusMessageActions>();
var actionsMock = ServiceBusMessageActionsFactory.GetServiceBusMessageActionsMock();

var strategyStub = Substitute.For<IPredictionStrategy>();
strategyStub.GetPrediction(Arg.Any<UpcomingEvent>(), Arg.Any<DateTime>()).Returns(expectedPrediction);
Expand All @@ -43,11 +44,43 @@ public async Task Run_WithValidServiceBusMessage_ReturnsEventPrediction()
await actionsMock.Received(Quantity.Exactly(1)).CompleteMessageAsync(receivedMessages[0], token);
}

[Test]
public async Task Run_WithValidServiceBusMessageAndRequestedCancellation_ReturnsNoPredictions()
{
// Arrange
var loggerStub = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.PredictionFunction>();

var upcomingEvent = new UpcomingEventBuilder().SetSampleData().Instance;

var expectedPrediction = new EventPredictionBuilder().SetSampleData().Instance;

var receivedMessages =
ServiceBusReceivedMessageFactory.CreateFromObjects([
upcomingEvent
]).ToArray();

var actionsMock = ServiceBusMessageActionsFactory.GetServiceBusMessageActionsMock();

var strategyStub = Substitute.For<IPredictionStrategy>();
strategyStub.GetPrediction(Arg.Any<UpcomingEvent>(), Arg.Any<DateTime>()).Returns(expectedPrediction);

var function = new OddsCollector.Functions.Functions.PredictionFunction(loggerStub, strategyStub);

var cancellationToken = await CancellationTokenGenerator.GetRequestedForCancellationToken();

// Act
var prediction = await function.Run(receivedMessages, actionsMock, cancellationToken)
.ConfigureAwait(false);

// Assert
prediction.Should().NotBeNull().And.HaveCount(0);
}

[Test]
public async Task Run_WithInvalidItems_ReturnsSuccessfullyProcessedEventPredictions()
{
// Arrange
var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.PredictionFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.PredictionFunction>();

var goodUpcomingEvent = new UpcomingEventBuilder().SetSampleData().Instance;

Expand All @@ -56,13 +89,13 @@ public async Task Run_WithInvalidItems_ReturnsSuccessfullyProcessedEventPredicti

var expectedPrediction = new EventPredictionBuilder().SetSampleData().Instance;

ServiceBusReceivedMessage[] receivedMessages =
[
ServiceBusReceivedMessageFactory.CreateFromObject(badUpcomingEvent),
ServiceBusReceivedMessageFactory.CreateFromObject(goodUpcomingEvent)
];
var receivedMessages =
ServiceBusReceivedMessageFactory.CreateFromObjects([
badUpcomingEvent,
goodUpcomingEvent
]).ToArray();

var actionsMock = Substitute.For<ServiceBusMessageActions>();
var actionsMock = ServiceBusMessageActionsFactory.GetServiceBusMessageActionsMock();

var exception = new Exception();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
using System.Text.Json;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using OddsCollector.Functions.Models;
using OddsCollector.Functions.Tests.Infrastructure.Data;
using OddsCollector.Functions.Tests.Infrastructure.Logger;

namespace OddsCollector.Functions.Tests.Tests.Functions;

Expand All @@ -14,7 +14,7 @@ internal class PredictionsHttpFunction
public void Run_WithValidArguments_ReturnsValidResponse()
{
// Arrange
var loggerStub = Substitute.For<ILogger<OddsCollector.Functions.Functions.PredictionsHttpFunction>>();
var loggerStub = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.PredictionsHttpFunction>();

var function = new OddsCollector.Functions.Functions.PredictionsHttpFunction(loggerStub);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using NSubstitute.ExceptionExtensions;
using OddsCollector.Functions.Models;
using OddsCollector.Functions.OddsApi;
using LoggerFactory = OddsCollector.Functions.Tests.Infrastructure.Logger.LoggerFactory;

namespace OddsCollector.Functions.Tests.Tests.Functions;

Expand All @@ -15,7 +16,7 @@ public async Task Run_WithValidParameters_ReturnsEventResults()
// Arrange
IEnumerable<UpcomingEvent> expectedEventResults = new List<UpcomingEvent> { new() };

var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.UpcomingEventsFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.UpcomingEventsFunction>();

var clientStub = Substitute.For<IOddsApiClient>();
clientStub.GetUpcomingEventsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
Expand All @@ -38,7 +39,7 @@ public async Task Run_WithException_ReturnsEmptyEventResults()
// Arrange
var exception = new Exception();

var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.UpcomingEventsFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.UpcomingEventsFunction>();

var clientStub = Substitute.For<IOddsApiClient>();
clientStub.GetUpcomingEventsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
Expand All @@ -62,7 +63,7 @@ public async Task Run_WithValidParameters_ReturnsNoEventResults()
// Arrange
IEnumerable<UpcomingEvent> expectedEventResults = new List<UpcomingEvent>();

var loggerMock = Substitute.For<ILogger<OddsCollector.Functions.Functions.UpcomingEventsFunction>>();
var loggerMock = LoggerFactory.GetLoggerMock<OddsCollector.Functions.Functions.UpcomingEventsFunction>();

var clientStub = Substitute.For<IOddsApiClient>();
clientStub.GetUpcomingEventsAsync(Arg.Any<Guid>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
Expand Down
77 changes: 77 additions & 0 deletions OddsCollector.Functions.Tests/Tests/OddsApi/OddsApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using OddsCollector.Functions.OddsApi.Configuration;
using OddsCollector.Functions.OddsApi.Converter;
using OddsCollector.Functions.OddsApi.WebApi;
using OddsCollector.Functions.Tests.Infrastructure.CancellationToken;

namespace OddsCollector.Functions.Tests.Tests.OddsApi;

Expand Down Expand Up @@ -118,4 +119,80 @@ public async Task GetEventResultsAsync_WithLeagues_ReturnsEventResults()
firstReceivedArguments[1].Should().Be(traceId);
firstReceivedArguments[2].Should().Be(timestamp);
}

[Test]
public async Task GetUpcomingEventsAsync_WithLeaguesAndRequestedCancellation_ReturnsNoUpcomingEvents()
{
// Arrange
ICollection<Anonymous2> rawUpcomingEvents = [new Anonymous2()];
var webApiClientMock = Substitute.For<IClient>();
webApiClientMock
.OddsAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Regions>(), Arg.Any<Markets>(),
Arg.Any<DateFormat>(), Arg.Any<OddsFormat>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<CancellationToken>())
.Returns(Task.FromResult(rawUpcomingEvents));

// ReSharper disable once CollectionNeverUpdated.Local
List<UpcomingEvent> upcomingEvents = [];
var converterMock = Substitute.For<IOddsApiObjectConverter>();
converterMock.ToUpcomingEvents(Arg.Any<ICollection<Anonymous2>?>(), Arg.Any<Guid>(), Arg.Any<DateTime>())
.Returns(new List<UpcomingEvent>());

const string secretValue = nameof(secretValue);

const string league = nameof(league);
var optionsStub = Substitute.For<IOptions<OddsApiClientOptions>>();
optionsStub.Value.Returns(new OddsApiClientOptions { Leagues = [league], ApiKey = secretValue });

var oddsClient =
new OddsCollector.Functions.OddsApi.OddsApiClient(optionsStub, webApiClientMock, converterMock);

var traceId = Guid.NewGuid();
var timestamp = DateTime.UtcNow;

var cancellationToken = await CancellationTokenGenerator.GetRequestedForCancellationToken();

// Act
var results = (await oddsClient.GetUpcomingEventsAsync(traceId, timestamp, cancellationToken)).ToList();

// Assert
results.Should().NotBeNull().And.HaveCount(0);
}

[Test]
public async Task GetEventResultsAsync_WithLeaguesAndRequestedCancellation_ReturnsNoEventResults()
{
// Arrange
ICollection<Anonymous3> rawEventResults = [new Anonymous3()];
var webApiClientMock = Substitute.For<IClient>();
webApiClientMock.ScoresAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<int?>(),
Arg.Any<CancellationToken>())
.Returns(Task.FromResult(rawEventResults));

// ReSharper disable once CollectionNeverUpdated.Local
List<EventResult> eventResults = [];
var converterMock = Substitute.For<IOddsApiObjectConverter>();
converterMock.ToEventResults(Arg.Any<ICollection<Anonymous3>?>(), Arg.Any<Guid>(), Arg.Any<DateTime>())
.Returns(eventResults);

const string secretValue = nameof(secretValue);

const string league = nameof(league);
var optionsStub = Substitute.For<IOptions<OddsApiClientOptions>>();
optionsStub.Value.Returns(new OddsApiClientOptions { Leagues = [league], ApiKey = secretValue });

var oddsClient =
new OddsCollector.Functions.OddsApi.OddsApiClient(optionsStub, webApiClientMock, converterMock);

var traceId = Guid.NewGuid();
var timestamp = DateTime.UtcNow;

var cancellationToken = await CancellationTokenGenerator.GetRequestedForCancellationToken();

// Act
var results = (await oddsClient.GetEventResultsAsync(traceId, timestamp, cancellationToken)).ToList();

// Assert
results.Should().NotBeNull().And.HaveCount(0);
}
}
5 changes: 5 additions & 0 deletions OddsCollector.Functions/Functions/PredictionFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public async Task<EventPrediction[]> Run(

foreach (var message in messages)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}

try
{
var upcomingEvent = message.Body.ToObjectFromJson<UpcomingEvent>();
Expand Down
Loading