Files
maraphon-app/tests/Marathon.Application.Tests/UseCases/PullUpcomingEventsUseCaseTests.cs
T
alexei.dolgolyov 2acbaa5b77 feat(phase-4): application layer + background workers — 202/202 tests green
Use cases (Marathon.Application/UseCases/):
- PullUpcomingEventsUseCase: scrape + persist new events + capture pre-match snapshots
- PullLiveOddsUseCase: refresh live snapshots for all stored events
- PullResultsUseCase: Phase 4 scaffold; delegates to ScrapeResultsAsync (Phase 3 no-op);
  Phase 8 will replace with watch-list polling
- ExportToExcelUseCase: resolves export dir from StorageOptions, delegates to IExcelExporter

ApplicationModule.AddMarathonApplication(IServiceCollection) — no IConfiguration needed.

Background workers (Marathon.Infrastructure/Workers/):
- UpcomingEventsPoller: Cronos 6-field cron schedule (default every 6 h)
- LiveOddsPoller: fixed interval (WorkerOptions.LivePollIntervalSeconds, default 30 s)
- ResultsWatchListPoller: scaffold, disabled by default (WorkerOptions.ResultsPollerEnabled=false)
All three: exception-swallowing, cancellation-aware, scoped DI via CreateAsyncScope().

InfrastructureModule.AddMarathonInfrastructure(IServiceCollection, IConfiguration):
- Composes AddMarathonPersistence + AddMarathonScraping + WorkerOptions + 3 hosted services

App.xaml.cs: replace reflection-based TryAddApplicationAndInfrastructure with direct
AddMarathonApplication() + AddMarathonInfrastructure(config) calls.

Resolved Phase 3 TODO: bind Sports:Basketball:QuarterMode from config in ScrapingModule.

appsettings.json: add Workers.LivePollIntervalSeconds, ResultsPollIntervalSeconds,
ResultsPollerEnabled; add Sports.Basketball.QuarterMode.

Settings.razor + WorkerOptions (UI) + SharedResource.*.resx: surface new Workers fields.

Tests: +14 Application use-case tests, +3 Infrastructure worker tests (185 → 202 total).
2026-05-05 12:28:15 +03:00

125 lines
5.1 KiB
C#

using FluentAssertions;
using Marathon.Application.Abstractions;
using Marathon.Application.UseCases;
using Marathon.Domain.Entities;
using Marathon.Domain.Enums;
using Marathon.Domain.ValueObjects;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
namespace Marathon.Application.Tests.UseCases;
public sealed class PullUpcomingEventsUseCaseTests
{
private readonly IOddsScraper _scraper = Substitute.For<IOddsScraper>();
private readonly IEventRepository _eventRepo = Substitute.For<IEventRepository>();
private readonly ISnapshotRepository _snapshotRepo = Substitute.For<ISnapshotRepository>();
private PullUpcomingEventsUseCase CreateSut() =>
new(_scraper, _eventRepo, _snapshotRepo,
NullLogger<PullUpcomingEventsUseCase>.Instance);
[Fact]
public async Task Should_PersistNewEventsAndCaptureSnapshots_When_ScraperReturnsEvents()
{
// Arrange: scraper returns 2 events, neither exists in DB
var ev1 = TestFixtures.MakeEvent("11111111");
var ev2 = TestFixtures.MakeEvent("22222222");
var events = new List<Event> { ev1, ev2 }.AsReadOnly();
_scraper.ScrapeUpcomingAsync(null, Arg.Any<CancellationToken>()).Returns(events);
_eventRepo.GetAsync(Arg.Any<EventId>(), Arg.Any<CancellationToken>()).Returns((Event?)null);
_scraper.ScrapeEventOddsAsync(Arg.Any<EventId>(), OddsSource.PreMatch, Arg.Any<CancellationToken>())
.Returns(ci => TestFixtures.MakeSnapshot(ci.Arg<EventId>()));
var sut = CreateSut();
// Act
var (processed, newEvents, snapshots) = await sut.ExecuteAsync(CancellationToken.None);
// Assert
processed.Should().Be(2);
newEvents.Should().Be(2);
snapshots.Should().Be(2);
await _eventRepo.Received(2).AddAsync(Arg.Any<Event>(), Arg.Any<CancellationToken>());
await _snapshotRepo.Received(2).AddAsync(Arg.Any<OddsSnapshot>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Should_SkipExistingEvents_When_EventAlreadyInDatabase()
{
// Arrange: 3 events from scraper — 1 already in DB, 2 new
var ev1 = TestFixtures.MakeEvent("11111111"); // already in DB
var ev2 = TestFixtures.MakeEvent("22222222"); // new
var ev3 = TestFixtures.MakeEvent("33333333"); // new
var events = new List<Event> { ev1, ev2, ev3 }.AsReadOnly();
_scraper.ScrapeUpcomingAsync(null, Arg.Any<CancellationToken>()).Returns(events);
// ev1 exists, ev2/ev3 do not
_eventRepo.GetAsync(ev1.Id, Arg.Any<CancellationToken>()).Returns(ev1);
_eventRepo.GetAsync(ev2.Id, Arg.Any<CancellationToken>()).Returns((Event?)null);
_eventRepo.GetAsync(ev3.Id, Arg.Any<CancellationToken>()).Returns((Event?)null);
_scraper.ScrapeEventOddsAsync(Arg.Any<EventId>(), OddsSource.PreMatch, Arg.Any<CancellationToken>())
.Returns(ci => TestFixtures.MakeSnapshot(ci.Arg<EventId>()));
var sut = CreateSut();
// Act
var (processed, newEvents, snapshots) = await sut.ExecuteAsync(CancellationToken.None);
// Assert
processed.Should().Be(3);
newEvents.Should().Be(2, "ev1 was already in the database");
snapshots.Should().Be(3, "snapshots are captured for all events regardless of duplicate status");
await _eventRepo.Received(2).AddAsync(Arg.Any<Event>(), Arg.Any<CancellationToken>());
await _eventRepo.DidNotReceive().AddAsync(ev1, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Should_ContinueProcessing_When_SnapshotCaptureFailsForOneEvent()
{
// Arrange: 2 events — snapshot for first throws, second succeeds
var ev1 = TestFixtures.MakeEvent("11111111");
var ev2 = TestFixtures.MakeEvent("22222222");
var events = new List<Event> { ev1, ev2 }.AsReadOnly();
_scraper.ScrapeUpcomingAsync(null, Arg.Any<CancellationToken>()).Returns(events);
_eventRepo.GetAsync(Arg.Any<EventId>(), Arg.Any<CancellationToken>()).Returns((Event?)null);
_scraper.ScrapeEventOddsAsync(ev1.Id, OddsSource.PreMatch, Arg.Any<CancellationToken>())
.ThrowsAsync(new HttpRequestException("site down"));
_scraper.ScrapeEventOddsAsync(ev2.Id, OddsSource.PreMatch, Arg.Any<CancellationToken>())
.Returns(TestFixtures.MakeSnapshot(ev2.Id));
var sut = CreateSut();
// Act — should not throw
var (processed, newEvents, snapshots) = await sut.ExecuteAsync(CancellationToken.None);
// Assert
processed.Should().Be(2);
newEvents.Should().Be(2);
snapshots.Should().Be(1, "only ev2 snapshot succeeded");
}
[Fact]
public async Task Should_ReturnZeros_When_ScraperReturnsNoEvents()
{
_scraper.ScrapeUpcomingAsync(null, Arg.Any<CancellationToken>())
.Returns(Array.Empty<Event>());
var sut = CreateSut();
var (processed, newEvents, snapshots) = await sut.ExecuteAsync(CancellationToken.None);
processed.Should().Be(0);
newEvents.Should().Be(0);
snapshots.Should().Be(0);
}
}