diff --git a/tests/Carina.Api.Tests/Feature/Epg/ProgrammeFeedStreamTests.cs b/tests/Carina.Api.Tests/Feature/Epg/ProgrammeFeedStreamTests.cs index b5222557b..76e3d3362 100644 --- a/tests/Carina.Api.Tests/Feature/Epg/ProgrammeFeedStreamTests.cs +++ b/tests/Carina.Api.Tests/Feature/Epg/ProgrammeFeedStreamTests.cs @@ -1,6 +1,8 @@ using System.Net; using Carina.Api.Events; +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Auth; using Carina.Domain.Base; using Carina.Domain.Channels; using Carina.Domain.Programmes; @@ -13,6 +15,8 @@ public sealed class ProgrammeFeedStreamTests { private static readonly DateTime At = new(2026, 8, 18, 12, 0, 0, DateTimeKind.Utc); + private static readonly Uri Bulk = new(ProgrammeFeedStream.Path, UriKind.Relative); + [Fact] public async Task TheFeedHandsBackOneProgrammePerLineAndSaysHowFarItGot() { @@ -205,6 +209,48 @@ public async Task ARebuildDiscardsTheGuideAndAFreshCollectionRestoresIt() StringComparison.Ordinal); } + [Fact] + public async Task TheFeedIsHandedToACallerCarryingASessionCookie() + { + await using AuthProbe probe = AuthProbe.OverHttp(); + await probe.SignedInAsync(); + + using HttpResponseMessage response = await probe.Client.GetAsync( + Bulk, + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(ProgrammeFeedStream.ContentType, response.Content.Headers.ContentType?.MediaType); + } + + [Fact] + public async Task TheFeedIsRefusedToACallerCarryingNoCookie() + { + await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); + + using HttpResponseMessage response = await probe.Client.GetAsync( + Bulk, + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Empty(await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task TheNextFeedAfterThatSessionEndedIsRefused() + { + await using AuthProbe probe = AuthProbe.OverHttp(); + AuthSession session = await probe.SignedInAsync(); + + session.Revoke(DateTime.UtcNow); + + using HttpResponseMessage response = await probe.Client.GetAsync( + Bulk, + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + private static string? Cursor(HttpResponseMessage response) => response.Headers.TryGetValues(ProgrammeFeedStream.CursorHeader, out IEnumerable? carried) ? carried.First() diff --git a/tests/Carina.Api.Tests/FeatureTest/LongLivedConnectionTests.cs b/tests/Carina.Api.Tests/Feature/Events/AppEventStreamTests.cs similarity index 53% rename from tests/Carina.Api.Tests/FeatureTest/LongLivedConnectionTests.cs rename to tests/Carina.Api.Tests/Feature/Events/AppEventStreamTests.cs index 96a894d8c..c0b2f0c04 100644 --- a/tests/Carina.Api.Tests/FeatureTest/LongLivedConnectionTests.cs +++ b/tests/Carina.Api.Tests/Feature/Events/AppEventStreamTests.cs @@ -1,112 +1,157 @@ using System.Net; +using System.Net.Http.Headers; +using System.Text.Json.Nodes; using Carina.Api.Events; +using Carina.Api.Tests.FeatureTest; using Carina.Domain.Auth; using Carina.Infrastructure.Events; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Puppis.Contracts; -namespace Carina.Api.Tests.FeatureTest; +namespace Carina.Api.Tests.Feature.Events; -public sealed class LongLivedConnectionTests +[Trait("Category", "Feature")] +public sealed class AppEventStreamTests(TestingWebApplicationFactory factory) + : IClassFixture { private static readonly Uri Events = new(AppEventStream.Path, UriKind.Relative); - private static readonly Uri Bulk = new(ProgrammeFeedStream.Path, UriKind.Relative); - [Fact] - public async Task AStreamIsOpenedForACallerCarryingASessionCookie() + public async Task TheStreamIsBehindTheSameDenialAsEveryOtherSurfaceOnceASchemeIsRegistered() { - await using AuthProbe probe = AuthProbe.OverHttp(); - await probe.SignedInAsync(); + using HttpClient client = factory.WithTestScheme().CreateClient(); + using HttpResponseMessage response = await client.GetAsync(Events); - using HttpResponseMessage response = await probe.Client.GetAsync( - Events, - HttpCompletionOption.ResponseHeadersRead); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task AnAuthenticatedListenerIsAnsweredWithAnEventStream() + { + using HttpClient client = factory.CreateAuthenticatedClient(); + using HttpResponseMessage response = await client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(AppEventStream.ContentType, response.Content.Headers.ContentType?.MediaType); } [Fact] - public async Task AStreamIsRefusedToACallerCarryingNoCookie() + public async Task ASignalRaisedOnTheHubArrivesOnTheOpenStream() + { + using WebApplicationFactory authenticated = factory.WithTestScheme(); + AppEventHub hub = authenticated.Services.GetRequiredService(); + + using HttpClient client = authenticated.CreateClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue(TestAuthenticationHandler.SchemeName, "anything"); + + using HttpResponseMessage response = await client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await response.Content.ReadAsStreamAsync(); + using var reader = new StreamReader(body); + + hub.Signal(AppEventName.Tuners); + + string? name = await reader.ReadLineAsync(); + + Assert.Equal("event: tuners", name); + } + + [Fact] + public async Task TheStreamIsAbsentFromTheDocumentThatNamesIt() + { + JsonNode document = await ServedOpenApi.FetchAsync(factory); + + Assert.DoesNotContain( + AppEventStream.Path, + document["paths"]!.AsObject().Select(path => path.Key), + StringComparer.Ordinal); + } + + [Fact] + public async Task AListenerCarryingNoCookieIsRefusedRatherThanHandedAStreamThatCarriesTheRefusal() { await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); + probe.Client.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue(AppEventStream.ContentType)); using HttpResponseMessage response = await probe.Client.GetAsync( Events, HttpCompletionOption.ResponseHeadersRead); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.NotEqual(AppEventStream.ContentType, response.Content.Headers.ContentType?.MediaType); + Assert.Empty(response.Headers.WwwAuthenticate); + Assert.Null(response.Headers.Location); + Assert.Empty(await response.Content.ReadAsByteArrayAsync()); } [Fact] - public async Task AStreamThatIsAlreadyOpenKeepsCarryingSignalsAfterItsSessionIsEnded() + public async Task AStreamOpenedForACallerIsMarkedSoNothingInFrontHandsItToTheNextCaller() { await using AuthProbe probe = AuthProbe.OverHttp(); - AuthSession session = await probe.SignedInAsync(); - AppEventHub hub = probe.Wired.Services.GetRequiredService(); + await probe.SignedInAsync(); using HttpResponseMessage response = await probe.Client.GetAsync( Events, HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await response.Content.ReadAsStreamAsync(); - using var reader = new StreamReader(body); - - session.Revoke(DateTime.UtcNow); - - hub.Signal(AppEventName.Tuners); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("event: tuners", await reader.ReadLineAsync()); + Assert.True(response.Headers.CacheControl?.NoCache); } [Fact] - public async Task TheNextConnectionAfterThatSessionEndedIsRefused() + public async Task AStreamIsOpenedForACallerCarryingASessionCookie() { await using AuthProbe probe = AuthProbe.OverHttp(); - AuthSession session = await probe.SignedInAsync(); - - session.Revoke(DateTime.UtcNow); + await probe.SignedInAsync(); using HttpResponseMessage response = await probe.Client.GetAsync( Events, HttpCompletionOption.ResponseHeadersRead); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(AppEventStream.ContentType, response.Content.Headers.ContentType?.MediaType); } [Fact] - public async Task TheFeedIsHandedToACallerCarryingASessionCookie() + public async Task AStreamIsRefusedToACallerCarryingNoCookie() { - await using AuthProbe probe = AuthProbe.OverHttp(); - await probe.SignedInAsync(); + await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); using HttpResponseMessage response = await probe.Client.GetAsync( - Bulk, + Events, HttpCompletionOption.ResponseHeadersRead); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(ProgrammeFeedStream.ContentType, response.Content.Headers.ContentType?.MediaType); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } [Fact] - public async Task TheFeedIsRefusedToACallerCarryingNoCookie() + public async Task AStreamThatIsAlreadyOpenKeepsCarryingSignalsAfterItsSessionIsEnded() { - await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); + await using AuthProbe probe = AuthProbe.OverHttp(); + AuthSession session = await probe.SignedInAsync(); + AppEventHub hub = probe.Wired.Services.GetRequiredService(); using HttpResponseMessage response = await probe.Client.GetAsync( - Bulk, + Events, HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await response.Content.ReadAsStreamAsync(); + using var reader = new StreamReader(body); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Empty(await response.Content.ReadAsByteArrayAsync()); + session.Revoke(DateTime.UtcNow); + + hub.Signal(AppEventName.Tuners); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("event: tuners", await reader.ReadLineAsync()); } [Fact] - public async Task TheNextFeedAfterThatSessionEndedIsRefused() + public async Task TheNextConnectionAfterThatSessionEndedIsRefused() { await using AuthProbe probe = AuthProbe.OverHttp(); AuthSession session = await probe.SignedInAsync(); @@ -114,7 +159,7 @@ public async Task TheNextFeedAfterThatSessionEndedIsRefused() session.Revoke(DateTime.UtcNow); using HttpResponseMessage response = await probe.Client.GetAsync( - Bulk, + Events, HttpCompletionOption.ResponseHeadersRead); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); diff --git a/tests/Carina.Api.Tests/Feature/Services/AddCandidateChannelActionTests.cs b/tests/Carina.Api.Tests/Feature/Services/AddCandidateChannelActionTests.cs new file mode 100644 index 000000000..85f6a4f2e --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Services/AddCandidateChannelActionTests.cs @@ -0,0 +1,138 @@ +using System.Net; +using System.Text.Json; + +using Carina.Domain.Channels; + +using Puppis.Contracts; + +using static Carina.Api.Tests.Feature.Services.CatalogFeature; + +namespace Carina.Api.Tests.Feature.Services; + +[Trait("Category", "Feature")] +public sealed class AddCandidateChannelActionTests +{ + [Fact] + public async Task AChannelAddedByHandArrivesNeedingRevalidation() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new { tuning = new { system = "isdbT", physicalChannel = OtherTerrestrial } }); + + Assert.Equal(HttpStatusCode.Created, status); + Assert.Equal(2, body.GetProperty("data").GetProperty("candidateCount").GetInt32()); + Assert.Contains( + feature.Candidates.Candidates, + candidate => candidate.Tuning.PhysicalChannel == OtherTerrestrial && candidate.NeedsRevalidation); + } + + [Fact] + public async Task AChannelOutsideTheRangeTheStandardAllowsIsRefusedWithTheRangeItBroke() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new { tuning = new { system = "isdbT", physicalChannel = 12 } }); + + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("13", body.GetProperty("message").GetString()!, StringComparison.Ordinal); + Assert.Single(feature.Candidates.Candidates); + } + + [Fact] + public async Task ASatelliteSlotTheDemodulatorCannotReachIsRefused() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new { tuning = new { system = "isdbSBs", physicalChannel = 7, transportStreamId = SatelliteStream } }); + + Assert.Equal(HttpStatusCode.BadRequest, status); + } + + [Fact] + public async Task AChannelNoTunerInServiceCanReceiveIsRefusedWithWhatItClashedWith() + { + await using var feature = new CatalogFeature(); + feature.Driver.Tuners = [new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle)]; + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new + { + tuning = new + { + system = "isdbSBs", + physicalChannel = SatelliteSlot, + transportStreamId = SatelliteStream, + }, + }); + + Assert.Equal(HttpStatusCode.UnprocessableEntity, status); + Assert.Contains("satellite", body.GetProperty("message").GetString()!, StringComparison.Ordinal); + Assert.Single(feature.Candidates.Candidates); + } + + [Fact] + public async Task ADisabledTunerNoLongerCountsAsSomethingThatCanReceive() + { + await using var feature = new CatalogFeature(); + feature.Driver.Tuners = + [ + new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle), + new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Disabled), + ]; + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new + { + tuning = new + { + system = "isdbSBs", + physicalChannel = SatelliteSlot, + transportStreamId = SatelliteStream, + }, + }); + + Assert.Equal(HttpStatusCode.UnprocessableEntity, status); + } + + [Fact] + public async Task AChannelIsNotSavedWhileTheTunersItNeedsCannotBeAskedAbout() + { + await using var feature = new CatalogFeature(); + feature.Driver.Unreachable = "the driver socket is not there"; + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new { tuning = new { system = "isdbT", physicalChannel = OtherTerrestrial } }); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, status); + Assert.Single(feature.Candidates.Candidates); + } + + [Fact] + public async Task AChannelTheServiceAlreadyCarriesIsNotAddedTwice() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.PostAsync( + $"{OneService}/candidate-channels", + new { tuning = new { system = "isdbT", physicalChannel = Terrestrial } }); + + Assert.Equal(HttpStatusCode.Conflict, status); + Assert.Single(feature.Candidates.Candidates); + } +} diff --git a/tests/Carina.Api.Tests/Feature/Services/CatalogFeature.cs b/tests/Carina.Api.Tests/Feature/Services/CatalogFeature.cs new file mode 100644 index 000000000..e7a04a8cd --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Services/CatalogFeature.cs @@ -0,0 +1,157 @@ +using System.Net; +using System.Text.Json; + +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Channels; +using Carina.Domain.Driver; +using Carina.Domain.Reservations; +using Carina.TestSupport; + +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; + +namespace Carina.Api.Tests.Feature.Services; + +internal sealed class CatalogFeature : IAsyncDisposable +{ + public const int Terrestrial = 53; + public const int OtherTerrestrial = 55; + public const int ThirdTerrestrial = 57; + public const int SatelliteSlot = 5; + public const int SatelliteStream = 50001; + + public const string OneService = "/api/services/1-101"; + + private readonly TestingWebApplicationFactory factory = new(); + + public CatalogFeature() + => Client = factory + .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => + { + services.AddSingleton(Services); + services.AddSingleton(Logos); + services.AddSingleton(Candidates); + services.AddSingleton(Driver); + services.AddSingleton(Notices); + })) + .CreateAuthenticatedClient(); + + public HttpClient Client { get; } + + public HeldServices Services { get; } = new(); + + public HeldLogos Logos { get; } = new(); + + public HeldCandidates Candidates { get; } = new(); + + public TunerHoldingDriverClient Driver { get; } = new(); + + public CountedNotices Notices { get; } = new(); + + public CandidateChannel Seed(int serviceId, string name, params TuningParameters[] tunings) + { + BroadcastService service = BroadcastService.Discover( + new NetworkId(1), + new ServiceId(serviceId), + name, + ServiceCategory.Television, + TunerHoldingDriverClient.At); + + Services.Services.Add(service); + Logos.Services.Add(service); + + foreach (TuningParameters tuning in tunings) + { + Candidates.Candidates.Add(CandidateChannel.Discover( + CandidateChannelId.New(), + new NetworkId(1), + new ServiceId(serviceId), + tuning, + TunerHoldingDriverClient.At)); + } + + return Candidates.Candidates[^1]; + } + + public void Measure(int candidate, int cnrMilliDecibels) + => Candidates.Candidates[candidate].RecordTuningSuccess( + SignalMeasurement.WithLock(TunerHoldingDriverClient.At, cnrMilliDecibels), + TunerHoldingDriverClient.At); + + public void Refuse(int candidate, int times) + { + for (int failure = 0; failure < times; failure++) + { + Candidates.Candidates[candidate].RecordTuningFailure( + RotationBackoff.Default, + TunerHoldingDriverClient.At); + } + } + + public async Task SelectTheWeakerOfTwoChannelsAsync() + { + Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + Measure(0, 12_000); + Measure(1, 29_000); + + await PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = Candidates.Candidates[0].Id.Value }); + } + + public Task<(HttpStatusCode Status, JsonElement Body)> GetAsync(string path) + => SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri(path, UriKind.Relative))); + + public Task<(HttpStatusCode Status, JsonElement Body)> DeleteAsync(string path) + => SendAsync(new HttpRequestMessage(HttpMethod.Delete, new Uri(path, UriKind.Relative)) + { + Content = JsonContent.Create(new { }), + }); + + public Task<(HttpStatusCode Status, JsonElement Body)> PutAsync(string path, object body) + => SendAsync(new HttpRequestMessage(HttpMethod.Put, new Uri(path, UriKind.Relative)) + { + Content = JsonContent.Create(body), + }); + + public Task<(HttpStatusCode Status, JsonElement Body)> PostAsync(string path, object body) + => SendAsync(new HttpRequestMessage(HttpMethod.Post, new Uri(path, UriKind.Relative)) + { + Content = JsonContent.Create(body), + }); + + public async ValueTask DisposeAsync() + { + Client.Dispose(); + await factory.DisposeAsync(); + } + + public static StationLogo Logo(int logoId) + => StationLogo.Collect( + new NetworkId(1), + new LogoId(logoId), + 0x05, + 3, + 64, + 36, + [0x89, 0x50, 0x4E, 0x47], + new DateTime(2026, 9, 5, 0, 0, 0, DateTimeKind.Utc)); + + public static IReadOnlyList Receptions(JsonElement listed) + => [.. listed.EnumerateArray().Select(service => service.GetProperty("reception").GetString())]; + + private async Task<(HttpStatusCode Status, JsonElement Body)> SendAsync(HttpRequestMessage request) + { + using (request) + { + using HttpResponseMessage response = await Client.SendAsync(request); + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + + return (response.StatusCode, document.RootElement.Clone()); + } + } +} diff --git a/tests/Carina.Api.Tests/Feature/Services/DeleteCandidateChannelActionTests.cs b/tests/Carina.Api.Tests/Feature/Services/DeleteCandidateChannelActionTests.cs new file mode 100644 index 000000000..72d73e9fa --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Services/DeleteCandidateChannelActionTests.cs @@ -0,0 +1,113 @@ +using System.Net; +using System.Text.Json; + +using Carina.Api.Common; +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Channels; +using Carina.Domain.Reservations; + +using static Carina.Api.Tests.Feature.Services.CatalogFeature; + +namespace Carina.Api.Tests.Feature.Services; + +[Trait("Category", "Feature")] +public sealed class DeleteCandidateChannelActionTests +{ + [Fact] + public async Task ACandidateNamedByTheUuidThatIsAllZeroesIsRefusedAsARequestAndNothingIsRemoved() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "Two ways in", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.DeleteAsync( + $"{OneService}/candidate-channels/{Guid.Empty}"); + + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal(CandidateChannelIdText.Description, body.GetProperty("message").GetString()); + Assert.Single(feature.Candidates.Candidates); + } + + [Fact] + public async Task DeletingACandidateLeavesTheServiceAndItsOtherChannelsInPlace() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + CandidateChannel doomed = feature.Candidates.Candidates[0]; + + (HttpStatusCode status, JsonElement body) = await feature.DeleteAsync( + $"{OneService}/candidate-channels/{doomed.Id.Value}"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(1, body.GetProperty("data").GetProperty("candidateCount").GetInt32()); + Assert.Single(feature.Services.Services); + } + + [Fact] + public async Task DeletingTheSelectedCandidateLeavesNothingSelectedRatherThanARepointing() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + CandidateChannel chosen = feature.Candidates.Candidates[0]; + await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = chosen.Id.Value }); + + (HttpStatusCode status, JsonElement body) = await feature.DeleteAsync( + $"{OneService}/candidate-channels/{chosen.Id.Value}"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal( + System.Text.Json.JsonValueKind.Null, + body.GetProperty("data").GetProperty("selectedChannel").ValueKind); + } + + [Fact] + public async Task DeletingTheSelectedCandidateAsksForTheAllocationToBeSettledAgain() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + CandidateChannel chosen = feature.Candidates.Candidates[0]; + await feature.Candidates.SelectAsync( + chosen.Id, + SelectionSource.Manual, + null, + TunerHoldingDriverClient.At, + CancellationToken.None); + + (HttpStatusCode status, JsonElement _) = await feature.DeleteAsync( + $"{OneService}/candidate-channels/{chosen.Id.Value}"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal([RecalculationTrigger.SelectedChannelChanged], feature.Notices.Nudged); + } + + [Fact] + public async Task DeletingACandidateOfAnotherServiceIsRefused() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + CandidateChannel elsewhere = feature.Seed(102, "Second", TuningParameters.Terrestrial(OtherTerrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.DeleteAsync( + $"{OneService}/candidate-channels/{elsewhere.Id.Value}"); + + Assert.Equal(HttpStatusCode.Conflict, status); + Assert.Equal(2, feature.Candidates.Candidates.Count); + Assert.Empty(feature.Notices.Nudged); + } +} diff --git a/tests/Carina.Api.Tests/Feature/Services/GetServiceActionTests.cs b/tests/Carina.Api.Tests/Feature/Services/GetServiceActionTests.cs new file mode 100644 index 000000000..0b4b37c93 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Services/GetServiceActionTests.cs @@ -0,0 +1,149 @@ +using System.Net; +using System.Text.Json; + +using Carina.Api.Common; +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Channels; + +using Puppis.Contracts; + +using static Carina.Api.Tests.Feature.Services.CatalogFeature; + +namespace Carina.Api.Tests.Feature.Services; + +[Trait("Category", "Feature")] +public sealed class GetServiceActionTests +{ + [Fact] + public async Task TheDetailCarriesEveryCandidateChannelAndWhichOneIsSelected() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + await feature.Candidates.SelectAsync( + feature.Candidates.Candidates[0].Id, + SelectionSource.Manual, + null, + TunerHoldingDriverClient.At, + CancellationToken.None); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync(OneService); + JsonElement data = body.GetProperty("data"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(2, data.GetProperty("candidateCount").GetInt32()); + Assert.Equal( + Terrestrial, + data.GetProperty("selectedChannel").GetProperty("physicalChannel").GetInt32()); + Assert.Equal( + "manual", + data.GetProperty("candidates")[0].GetProperty("selection").GetProperty("source").GetString()); + } + + [Theory] + [InlineData("/api/services/70000-1")] + [InlineData("/api/services/1-70000")] + [InlineData("/api/services/-1-101")] + public async Task AServiceNamedOutsideTheRangeOfItsIdsIsRefusedAsARequestAndNotAFault(string path) + { + await using var feature = new CatalogFeature(); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync(path); + + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal(ServiceKeyText.Description, body.GetProperty("message").GetString()); + } + + [Fact] + public async Task AServiceNobodyEverFoundIsAnsweredAsNotFound() + { + await using var feature = new CatalogFeature(); + + (HttpStatusCode status, JsonElement _) = await feature.GetAsync("/api/services/1-999"); + + Assert.Equal(HttpStatusCode.NotFound, status); + } + + [Fact] + public async Task TheDetailOfAServiceNoTunerReceivesSaysSoToo() + { + await using var feature = new CatalogFeature(); + feature.Driver.Tuners = [new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle)]; + feature.Seed(101, "Sky", TuningParameters.Bs(SatelliteSlot, new TransportStreamId(SatelliteStream))); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync(OneService); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("noTunerInService", body.GetProperty("data").GetProperty("reception").GetString()); + } + + [Fact] + public async Task SayingTheSelectionIsOutrankedDoesNotMoveTheSelection() + { + await using var feature = new CatalogFeature(); + await feature.SelectTheWeakerOfTwoChannelsAsync(); + + await feature.GetAsync(OneService); + + CandidateChannel held = Assert.Single( + feature.Candidates.Candidates, + candidate => candidate.IsSelected); + + Assert.Equal(Terrestrial, held.Tuning.PhysicalChannel); + Assert.Equal(SelectionSource.Manual, held.SelectionSource); + } + + [Fact] + public async Task EveryCatalogSurfaceIsBehindTheSameDenialAsTheRestOnceASchemeIsRegistered() + { + using var app = new TestingWebApplicationFactory(); + using HttpClient client = app.WithTestScheme().CreateClient(); + + Assert.Equal( + HttpStatusCode.Unauthorized, + (await client.GetAsync(new Uri(OneService, UriKind.Relative))).StatusCode); + } + + [Fact] + public async Task AServiceThatBroadcastsNoLogoSaysSoRatherThanOfferingAnAddressThatAnswersNothing() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + feature.Logos.Services[0].BroadcastsNoLogo(); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync(OneService); + JsonElement found = body.GetProperty("data"); + + Assert.Equal("noPictureIsBroadcast", found.GetProperty("logoDeclaration").GetString()); + Assert.Equal(JsonValueKind.Null, found.GetProperty("logo").ValueKind); + } + + [Fact] + public async Task AServiceWhoseLogoIsNamedButNotYetCollectedOffersNoAddressForIt() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + feature.Logos.Services[0].NamesTheLogo(new LogoId(261)); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync(OneService); + JsonElement found = body.GetProperty("data"); + + Assert.Equal("inTheCommonDataTable", found.GetProperty("logoDeclaration").GetString()); + Assert.Equal(JsonValueKind.Null, found.GetProperty("logo").ValueKind); + } + + [Fact] + public async Task AServiceNobodyHasReadTheDescriptionOfSaysThatRatherThanThatItHasNoLogo() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync(OneService); + + Assert.Equal("notYetRead", body.GetProperty("data").GetProperty("logoDeclaration").GetString()); + } +} diff --git a/tests/Carina.Api.Tests/Feature/Services/ListServicesActionTests.cs b/tests/Carina.Api.Tests/Feature/Services/ListServicesActionTests.cs new file mode 100644 index 000000000..86bd09a94 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Services/ListServicesActionTests.cs @@ -0,0 +1,299 @@ +using System.Net; +using System.Text.Json; + +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Channels; + +using Puppis.Contracts; + +using static Carina.Api.Tests.Feature.Services.CatalogFeature; + +namespace Carina.Api.Tests.Feature.Services; + +[Trait("Category", "Feature")] +public sealed class ListServicesActionTests +{ + [Fact] + public async Task TheListNamesEveryServiceWithItsIdentifiersAndCategory() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + feature.Seed(102, "Second", TuningParameters.Terrestrial(OtherTerrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement listed = body.GetProperty("data"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(2, listed.GetArrayLength()); + Assert.Equal(1, listed[0].GetProperty("networkId").GetInt32()); + Assert.Equal(101, listed[0].GetProperty("serviceId").GetInt32()); + Assert.Equal("television", listed[0].GetProperty("category").GetString()); + } + + [Fact] + public async Task TwoServicesSharingANameAreStillToldApartByTheirIdentifiers() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "Same name", TuningParameters.Terrestrial(Terrestrial)); + feature.Seed(102, "Same name", TuningParameters.Terrestrial(OtherTerrestrial)); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + + Assert.Equal( + [101, 102], + body.GetProperty("data").EnumerateArray() + .Select(service => service.GetProperty("serviceId").GetInt32())); + } + + [Fact] + public async Task ASatelliteServiceIsSaidToBeOutOfReceptionOnceItsOnlyTunerIsTurnedOffAndIsKept() + { + await using var feature = new CatalogFeature(); + feature.Driver.Tuners = + [ + new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle), + new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Disabled), + ]; + feature.Seed(101, "Ground", TuningParameters.Terrestrial(Terrestrial)); + feature.Seed(102, "Sky", TuningParameters.Bs(SatelliteSlot, new TransportStreamId(SatelliteStream))); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement listed = body.GetProperty("data"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(["receivable", "noTunerInService"], Receptions(listed)); + Assert.Equal(2, feature.Services.Services.Count); + Assert.Equal(2, feature.Candidates.Candidates.Count); + } + + [Fact] + public async Task TurningTheSatelliteTunerBackOnMakesTheSameServiceReceivableAgain() + { + await using var feature = new CatalogFeature(); + feature.Driver.Tuners = + [ + new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Disabled), + ]; + feature.Seed(102, "Sky", TuningParameters.Bs(SatelliteSlot, new TransportStreamId(SatelliteStream))); + + Assert.Equal(["noTunerInService"], Receptions((await feature.GetAsync("/api/services")).Body.GetProperty("data"))); + + feature.Driver.Tuners = [new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Idle)]; + + Assert.Equal(["receivable"], Receptions((await feature.GetAsync("/api/services")).Body.GetProperty("data"))); + } + + [Fact] + public async Task TunersThatCannotBeAskedAboutLeaveReceptionUnknownRatherThanOut() + { + await using var feature = new CatalogFeature(); + feature.Driver.Unreachable = "no socket"; + feature.Seed(101, "Ground", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(["unknown"], Receptions(body.GetProperty("data"))); + } + + [Fact] + public async Task TheListNamesTheChannelThatMeasuredBetterThanTheSelectedOne() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + feature.Measure(0, 12_000); + feature.Measure(1, 29_000); + + await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement listed = body.GetProperty("data")[0]; + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal( + Terrestrial, + listed.GetProperty("selectedChannel").GetProperty("physicalChannel").GetInt32()); + Assert.Equal( + OtherTerrestrial, + listed.GetProperty("betterChannel").GetProperty("physicalChannel").GetInt32()); + } + + [Fact] + public async Task TheListNamesNoBetterChannelWhenTheMeasurementsAlreadyFavourTheSelectedOne() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + feature.Measure(0, 29_000); + feature.Measure(1, 12_000); + + await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + + Assert.Equal( + System.Text.Json.JsonValueKind.Null, + body.GetProperty("data")[0].GetProperty("betterChannel").ValueKind); + } + + [Fact] + public async Task AChannelChosenByHandIsSaidToBeOutrankedJustAsOneAScanChoseWouldBe() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + feature.Measure(0, 12_000); + feature.Measure(1, 29_000); + + await feature.Candidates.SelectAsync( + feature.Candidates.Candidates[0].Id, + SelectionSource.Manual, + null, + TunerHoldingDriverClient.At, + CancellationToken.None); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement listed = body.GetProperty("data")[0]; + + Assert.Equal( + "manual", + listed.GetProperty("candidates")[0].GetProperty("selection").GetProperty("source").GetString()); + Assert.Equal( + OtherTerrestrial, + listed.GetProperty("betterChannel").GetProperty("physicalChannel").GetInt32()); + } + + [Fact] + public async Task AServiceWithNowhereToTuneIsNotSaidToHaveABetterChannel() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + feature.Measure(0, 12_000); + feature.Measure(1, 29_000); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + + Assert.Equal( + System.Text.Json.JsonValueKind.Null, + body.GetProperty("data")[0].GetProperty("betterChannel").ValueKind); + } + + [Fact] + public async Task SayingTheSelectionIsOutrankedDoesNotMoveTheSelection() + { + await using var feature = new CatalogFeature(); + await feature.SelectTheWeakerOfTwoChannelsAsync(); + + await feature.GetAsync("/api/services"); + + CandidateChannel held = Assert.Single( + feature.Candidates.Candidates, + candidate => candidate.IsSelected); + + Assert.Equal(Terrestrial, held.Tuning.PhysicalChannel); + Assert.Equal(SelectionSource.Manual, held.SelectionSource); + } + + [Fact] + public async Task ACandidateThatKeptFailingSaysSoOnTheListWithoutOpeningIt() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + feature.Measure(0, 21_000); + feature.Refuse(1, RotationBackoff.Default.FailureCeiling); + + (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement candidates = body.GetProperty("data")[0].GetProperty("candidates"); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("active", candidates[0].GetProperty("rotationState").GetString()); + Assert.Equal("needsAttention", candidates[1].GetProperty("rotationState").GetString()); + Assert.Equal( + RotationBackoff.Default.FailureCeiling, + candidates[1].GetProperty("consecutiveFailures").GetInt32()); + Assert.NotEqual( + JsonValueKind.Null, + candidates[1].GetProperty("needsAttentionSince").ValueKind); + } + + [Fact] + public async Task ACandidateStillBackingOffSaysWhenItIsDueAgainRatherThanThatItIsGone() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "One way in", TuningParameters.Terrestrial(Terrestrial)); + feature.Refuse(0, 1); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement candidate = body.GetProperty("data")[0].GetProperty("candidates")[0]; + + Assert.Equal("backingOff", candidate.GetProperty("rotationState").GetString()); + Assert.Equal( + new DateTimeOffset(TunerHoldingDriverClient.At.Add(RotationBackoff.Default.FirstDelay)), + candidate.GetProperty("nextAttemptAt").GetDateTimeOffset()); + } + + [Fact] + public async Task EveryCatalogSurfaceIsBehindTheSameDenialAsTheRestOnceASchemeIsRegistered() + { + using var app = new TestingWebApplicationFactory(); + using HttpClient client = app.WithTestScheme().CreateClient(); + + Assert.Equal( + HttpStatusCode.Unauthorized, + (await client.GetAsync(new Uri("/api/services", UriKind.Relative))).StatusCode); + } + + [Fact] + public async Task AServiceWhoseLogoHasBeenCollectedSaysSoAndWhereToAskForIt() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + feature.Logos.Services[0].NamesTheLogo(new LogoId(261)); + feature.Logos.Logos.Add(Logo(261)); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement listed = body.GetProperty("data")[0]; + + Assert.Equal("inTheCommonDataTable", listed.GetProperty("logoDeclaration").GetString()); + Assert.Equal("/api/services/1-101/logo", listed.GetProperty("logo").GetProperty("url").GetString()); + } + + [Fact] + public async Task TwoServicesOfOneStationBothPointAtTheirOwnAddressForTheLogoTheyShare() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + feature.Seed(102, "Second", TuningParameters.Terrestrial(Terrestrial)); + feature.Logos.Services[0].NamesTheLogo(new LogoId(261)); + feature.Logos.Services[1].NamesTheLogo(new LogoId(261)); + feature.Logos.Logos.Add(Logo(261)); + + (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); + JsonElement listed = body.GetProperty("data"); + + Assert.Equal("/api/services/1-101/logo", listed[0].GetProperty("logo").GetProperty("url").GetString()); + Assert.Equal("/api/services/1-102/logo", listed[1].GetProperty("logo").GetProperty("url").GetString()); + } +} diff --git a/tests/Carina.Api.Tests/Feature/Services/PutSelectedChannelActionTests.cs b/tests/Carina.Api.Tests/Feature/Services/PutSelectedChannelActionTests.cs new file mode 100644 index 000000000..1871bb16a --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Services/PutSelectedChannelActionTests.cs @@ -0,0 +1,161 @@ +using System.Net; +using System.Text.Json; + +using Carina.Api.Common; +using Carina.Domain.Channels; +using Carina.Domain.Reservations; + +using static Carina.Api.Tests.Feature.Services.CatalogFeature; + +namespace Carina.Api.Tests.Feature.Services; + +[Trait("Category", "Feature")] +public sealed class PutSelectedChannelActionTests +{ + [Fact] + public async Task ASelectedChannelThatChangedAsksForTheAllocationToBeSettledAgain() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + CandidateChannel second = feature.Candidates.Candidates[1]; + + (HttpStatusCode status, JsonElement _) = await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = second.Id.Value }); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal([RecalculationTrigger.SelectedChannelChanged], feature.Notices.Nudged); + } + + [Fact] + public async Task ASelectedChannelNamedByTheUuidThatIsAllZeroesIsRefusedAsARequestAndNothingMoves() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "Two ways in", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement body) = await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = Guid.Empty }); + + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal(CandidateChannelIdText.Description, body.GetProperty("message").GetString()); + Assert.Empty(feature.Notices.Nudged); + } + + [Fact] + public async Task ASelectedChannelOnAServiceNobodyEverFoundAsksForNothing() + { + await using var feature = new CatalogFeature(); + + (HttpStatusCode status, JsonElement _) = await feature.PutAsync( + "/api/services/1-999/selected-channel", + new { candidateChannelId = Guid.NewGuid() }); + + Assert.Equal(HttpStatusCode.NotFound, status); + Assert.Empty(feature.Notices.Nudged); + } + + [Fact] + public async Task SwitchingTheSelectedCandidateChangesWhichChannelTheServiceTunesFrom() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + CandidateChannel second = feature.Candidates.Candidates[1]; + + (HttpStatusCode status, JsonElement body) = await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = second.Id.Value }); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal( + OtherTerrestrial, + body.GetProperty("data").GetProperty("selectedChannel").GetProperty("physicalChannel").GetInt32()); + } + + [Fact] + public async Task OnlyOneCandidateIsEverSelectedAndTheDatabaseIsWhatHoldsThat() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Three ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial), + TuningParameters.Terrestrial(ThirdTerrestrial)); + + foreach (CandidateChannel candidate in feature.Candidates.Candidates.ToArray()) + { + await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = candidate.Id.Value }); + } + + Assert.Single(feature.Candidates.Candidates, candidate => candidate.IsSelected); + Assert.Equal( + ThirdTerrestrial, + feature.Candidates.Candidates.Single(candidate => candidate.IsSelected).Tuning.PhysicalChannel); + } + + [Fact] + public async Task ClearingTheSelectionLeavesTheServiceWithNowhereToTuneRatherThanARepointing() + { + await using var feature = new CatalogFeature(); + feature.Seed( + 101, + "Two ways in", + TuningParameters.Terrestrial(Terrestrial), + TuningParameters.Terrestrial(OtherTerrestrial)); + + await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); + + (HttpStatusCode status, JsonElement body) = await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = (Guid?)null }); + + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal( + System.Text.Json.JsonValueKind.Null, + body.GetProperty("data").GetProperty("selectedChannel").ValueKind); + Assert.DoesNotContain(feature.Candidates.Candidates, candidate => candidate.IsSelected); + } + + [Fact] + public async Task SelectingACandidateThatBelongsToAnotherServiceIsRefused() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + CandidateChannel elsewhere = feature.Seed(102, "Second", TuningParameters.Terrestrial(OtherTerrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = elsewhere.Id.Value }); + + Assert.Equal(HttpStatusCode.Conflict, status); + Assert.DoesNotContain(feature.Candidates.Candidates, candidate => candidate.IsSelected); + } + + [Fact] + public async Task SelectingACandidateNobodyHoldsIsAnsweredAsNotFound() + { + await using var feature = new CatalogFeature(); + feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); + + (HttpStatusCode status, JsonElement _) = await feature.PutAsync( + $"{OneService}/selected-channel", + new { candidateChannelId = Guid.NewGuid() }); + + Assert.Equal(HttpStatusCode.NotFound, status); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/VersionEndpointTests.cs b/tests/Carina.Api.Tests/Feature/Version/GetVersionActionTests.cs similarity index 80% rename from tests/Carina.Api.Tests/FeatureTest/VersionEndpointTests.cs rename to tests/Carina.Api.Tests/Feature/Version/GetVersionActionTests.cs index 2b3ce6842..72eba1e96 100644 --- a/tests/Carina.Api.Tests/FeatureTest/VersionEndpointTests.cs +++ b/tests/Carina.Api.Tests/Feature/Version/GetVersionActionTests.cs @@ -2,10 +2,12 @@ using System.Text.Json; using Carina.Api.Common; +using Carina.Api.Tests.FeatureTest; -namespace Carina.Api.Tests.FeatureTest; +namespace Carina.Api.Tests.Feature.Version; -public sealed class VersionEndpointTests(TestingWebApplicationFactory factory) +[Trait("Category", "Feature")] +public sealed class GetVersionActionTests(TestingWebApplicationFactory factory) : IClassFixture { private static readonly Uri TheSurface = new("/api/version", UriKind.Relative); diff --git a/tests/Carina.Api.Tests/FeatureTest/AppEventStreamTests.cs b/tests/Carina.Api.Tests/FeatureTest/AppEventStreamTests.cs deleted file mode 100644 index 5d178dd2d..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/AppEventStreamTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Net; -using System.Net.Http.Headers; -using System.Text.Json.Nodes; - -using Carina.Api.Events; -using Carina.Infrastructure.Events; - -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.Extensions.DependencyInjection; - -using Puppis.Contracts; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class AppEventStreamTests(TestingWebApplicationFactory factory) - : IClassFixture -{ - private static readonly Uri Events = new(AppEventStream.Path, UriKind.Relative); - - [Fact] - public void ASignalFrameCarriesABareDataLineSoAnEventSourceDispatchesItWithoutAPayload() - { - Assert.Equal("event: tuners\ndata\n\n", AppEventStream.Frame(AppEvents.Tuners)); - } - - [Fact] - public async Task TheStreamIsBehindTheSameDenialAsEveryOtherSurfaceOnceASchemeIsRegistered() - { - using HttpClient client = factory.WithTestScheme().CreateClient(); - using HttpResponseMessage response = await client.GetAsync(Events); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - [Fact] - public async Task AnAuthenticatedListenerIsAnsweredWithAnEventStream() - { - using HttpClient client = factory.CreateAuthenticatedClient(); - using HttpResponseMessage response = await client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(AppEventStream.ContentType, response.Content.Headers.ContentType?.MediaType); - } - - [Fact] - public async Task ASignalRaisedOnTheHubArrivesOnTheOpenStream() - { - using WebApplicationFactory authenticated = factory.WithTestScheme(); - AppEventHub hub = authenticated.Services.GetRequiredService(); - - using HttpClient client = authenticated.CreateClient(); - client.DefaultRequestHeaders.Authorization = - new AuthenticationHeaderValue(TestAuthenticationHandler.SchemeName, "anything"); - - using HttpResponseMessage response = await client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await response.Content.ReadAsStreamAsync(); - using var reader = new StreamReader(body); - - hub.Signal(AppEventName.Tuners); - - string? name = await reader.ReadLineAsync(); - - Assert.Equal("event: tuners", name); - } - - [Fact] - public async Task TheStreamIsAbsentFromTheDocumentThatNamesIt() - { - JsonNode document = await ServedOpenApi.FetchAsync(factory); - - Assert.DoesNotContain( - AppEventStream.Path, - document["paths"]!.AsObject().Select(path => path.Key), - StringComparer.Ordinal); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/EventStreamRefusalTests.cs b/tests/Carina.Api.Tests/FeatureTest/EventStreamRefusalTests.cs deleted file mode 100644 index e32ca9afc..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/EventStreamRefusalTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Net; -using System.Net.Http.Headers; - -using Carina.Api.Events; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class EventStreamRefusalTests -{ - private static readonly Uri Events = new(AppEventStream.Path, UriKind.Relative); - - [Fact] - public async Task AListenerCarryingNoCookieIsRefusedRatherThanHandedAStreamThatCarriesTheRefusal() - { - await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); - probe.Client.DefaultRequestHeaders.Accept.Add( - new MediaTypeWithQualityHeaderValue(AppEventStream.ContentType)); - - using HttpResponseMessage response = await probe.Client.GetAsync( - Events, - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.NotEqual(AppEventStream.ContentType, response.Content.Headers.ContentType?.MediaType); - Assert.Empty(response.Headers.WwwAuthenticate); - Assert.Null(response.Headers.Location); - Assert.Empty(await response.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task AStreamOpenedForACallerIsMarkedSoNothingInFrontHandsItToTheNextCaller() - { - await using AuthProbe probe = AuthProbe.OverHttp(); - await probe.SignedInAsync(); - - using HttpResponseMessage response = await probe.Client.GetAsync( - Events, - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.True(response.Headers.CacheControl?.NoCache); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/ServiceCatalogEndpointTests.cs b/tests/Carina.Api.Tests/FeatureTest/ServiceCatalogEndpointTests.cs deleted file mode 100644 index 669cabc09..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/ServiceCatalogEndpointTests.cs +++ /dev/null @@ -1,808 +0,0 @@ -using System.Net; -using System.Text.Json; - -using Carina.Api.Common; -using Carina.Domain.Channels; -using Carina.Domain.Reservations; - -using Puppis.Contracts; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class ServiceCatalogEndpointTests -{ - private const int Terrestrial = 53; - private const int OtherTerrestrial = 55; - private const int ThirdTerrestrial = 57; - private const int SatelliteSlot = 5; - private const int SatelliteStream = 50001; - - private const string OneService = "/api/services/1-101"; - - [Fact] - public async Task TheListNamesEveryServiceWithItsIdentifiersAndCategory() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - feature.Seed(102, "Second", TuningParameters.Terrestrial(OtherTerrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement listed = body.GetProperty("data"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal(2, listed.GetArrayLength()); - Assert.Equal(1, listed[0].GetProperty("networkId").GetInt32()); - Assert.Equal(101, listed[0].GetProperty("serviceId").GetInt32()); - Assert.Equal("television", listed[0].GetProperty("category").GetString()); - } - - [Fact] - public async Task TwoServicesSharingANameAreStillToldApartByTheirIdentifiers() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "Same name", TuningParameters.Terrestrial(Terrestrial)); - feature.Seed(102, "Same name", TuningParameters.Terrestrial(OtherTerrestrial)); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - - Assert.Equal( - [101, 102], - body.GetProperty("data").EnumerateArray() - .Select(service => service.GetProperty("serviceId").GetInt32())); - } - - [Fact] - public async Task TheDetailCarriesEveryCandidateChannelAndWhichOneIsSelected() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - await feature.Candidates.SelectAsync( - feature.Candidates.Candidates[0].Id, - SelectionSource.Manual, - null, - TunerHoldingDriverClient.At, - CancellationToken.None); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync(OneService); - JsonElement data = body.GetProperty("data"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal(2, data.GetProperty("candidateCount").GetInt32()); - Assert.Equal( - Terrestrial, - data.GetProperty("selectedChannel").GetProperty("physicalChannel").GetInt32()); - Assert.Equal( - "manual", - data.GetProperty("candidates")[0].GetProperty("selection").GetProperty("source").GetString()); - } - - [Fact] - public async Task ASelectedChannelThatChangedAsksForTheAllocationToBeSettledAgain() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - CandidateChannel second = feature.Candidates.Candidates[1]; - - (HttpStatusCode status, JsonElement _) = await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = second.Id.Value }); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal([RecalculationTrigger.SelectedChannelChanged], feature.Notices.Nudged); - } - - [Theory] - [InlineData("/api/services/70000-1")] - [InlineData("/api/services/1-70000")] - [InlineData("/api/services/-1-101")] - public async Task AServiceNamedOutsideTheRangeOfItsIdsIsRefusedAsARequestAndNotAFault(string path) - { - await using var feature = new CatalogFeature(); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync(path); - - Assert.Equal(HttpStatusCode.BadRequest, status); - Assert.Equal(ServiceKeyText.Description, body.GetProperty("message").GetString()); - } - - [Fact] - public async Task ASelectedChannelNamedByTheUuidThatIsAllZeroesIsRefusedAsARequestAndNothingMoves() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "Two ways in", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = Guid.Empty }); - - Assert.Equal(HttpStatusCode.BadRequest, status); - Assert.Equal(CandidateChannelIdText.Description, body.GetProperty("message").GetString()); - Assert.Empty(feature.Notices.Nudged); - } - - [Fact] - public async Task ACandidateNamedByTheUuidThatIsAllZeroesIsRefusedAsARequestAndNothingIsRemoved() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "Two ways in", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.DeleteAsync( - $"{OneService}/candidate-channels/{Guid.Empty}"); - - Assert.Equal(HttpStatusCode.BadRequest, status); - Assert.Equal(CandidateChannelIdText.Description, body.GetProperty("message").GetString()); - Assert.Single(feature.Candidates.Candidates); - } - - [Fact] - public async Task ASelectedChannelOnAServiceNobodyEverFoundAsksForNothing() - { - await using var feature = new CatalogFeature(); - - (HttpStatusCode status, JsonElement _) = await feature.PutAsync( - "/api/services/1-999/selected-channel", - new { candidateChannelId = Guid.NewGuid() }); - - Assert.Equal(HttpStatusCode.NotFound, status); - Assert.Empty(feature.Notices.Nudged); - } - - [Fact] - public async Task AServiceNobodyEverFoundIsAnsweredAsNotFound() - { - await using var feature = new CatalogFeature(); - - (HttpStatusCode status, JsonElement _) = await feature.GetAsync("/api/services/1-999"); - - Assert.Equal(HttpStatusCode.NotFound, status); - } - - [Fact] - public async Task SwitchingTheSelectedCandidateChangesWhichChannelTheServiceTunesFrom() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - CandidateChannel second = feature.Candidates.Candidates[1]; - - (HttpStatusCode status, JsonElement body) = await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = second.Id.Value }); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal( - OtherTerrestrial, - body.GetProperty("data").GetProperty("selectedChannel").GetProperty("physicalChannel").GetInt32()); - } - - [Fact] - public async Task OnlyOneCandidateIsEverSelectedAndTheDatabaseIsWhatHoldsThat() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Three ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial), - TuningParameters.Terrestrial(ThirdTerrestrial)); - - foreach (CandidateChannel candidate in feature.Candidates.Candidates.ToArray()) - { - await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = candidate.Id.Value }); - } - - Assert.Single(feature.Candidates.Candidates, candidate => candidate.IsSelected); - Assert.Equal( - ThirdTerrestrial, - feature.Candidates.Candidates.Single(candidate => candidate.IsSelected).Tuning.PhysicalChannel); - } - - [Fact] - public async Task ClearingTheSelectionLeavesTheServiceWithNowhereToTuneRatherThanARepointing() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); - - (HttpStatusCode status, JsonElement body) = await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = (Guid?)null }); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal( - System.Text.Json.JsonValueKind.Null, - body.GetProperty("data").GetProperty("selectedChannel").ValueKind); - Assert.DoesNotContain(feature.Candidates.Candidates, candidate => candidate.IsSelected); - } - - [Fact] - public async Task SelectingACandidateThatBelongsToAnotherServiceIsRefused() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - CandidateChannel elsewhere = feature.Seed(102, "Second", TuningParameters.Terrestrial(OtherTerrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = elsewhere.Id.Value }); - - Assert.Equal(HttpStatusCode.Conflict, status); - Assert.DoesNotContain(feature.Candidates.Candidates, candidate => candidate.IsSelected); - } - - [Fact] - public async Task SelectingACandidateNobodyHoldsIsAnsweredAsNotFound() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = Guid.NewGuid() }); - - Assert.Equal(HttpStatusCode.NotFound, status); - } - - [Fact] - public async Task AChannelAddedByHandArrivesNeedingRevalidation() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new { tuning = new { system = "isdbT", physicalChannel = OtherTerrestrial } }); - - Assert.Equal(HttpStatusCode.Created, status); - Assert.Equal(2, body.GetProperty("data").GetProperty("candidateCount").GetInt32()); - Assert.Contains( - feature.Candidates.Candidates, - candidate => candidate.Tuning.PhysicalChannel == OtherTerrestrial && candidate.NeedsRevalidation); - } - - [Fact] - public async Task AChannelOutsideTheRangeTheStandardAllowsIsRefusedWithTheRangeItBroke() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new { tuning = new { system = "isdbT", physicalChannel = 12 } }); - - Assert.Equal(HttpStatusCode.BadRequest, status); - Assert.Contains("13", body.GetProperty("message").GetString()!, StringComparison.Ordinal); - Assert.Single(feature.Candidates.Candidates); - } - - [Fact] - public async Task ASatelliteSlotTheDemodulatorCannotReachIsRefused() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new { tuning = new { system = "isdbSBs", physicalChannel = 7, transportStreamId = SatelliteStream } }); - - Assert.Equal(HttpStatusCode.BadRequest, status); - } - - [Fact] - public async Task AChannelNoTunerInServiceCanReceiveIsRefusedWithWhatItClashedWith() - { - await using var feature = new CatalogFeature(); - feature.Driver.Tuners = [new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle)]; - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new - { - tuning = new - { - system = "isdbSBs", - physicalChannel = SatelliteSlot, - transportStreamId = SatelliteStream, - }, - }); - - Assert.Equal(HttpStatusCode.UnprocessableEntity, status); - Assert.Contains("satellite", body.GetProperty("message").GetString()!, StringComparison.Ordinal); - Assert.Single(feature.Candidates.Candidates); - } - - [Fact] - public async Task ADisabledTunerNoLongerCountsAsSomethingThatCanReceive() - { - await using var feature = new CatalogFeature(); - feature.Driver.Tuners = - [ - new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle), - new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Disabled), - ]; - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new - { - tuning = new - { - system = "isdbSBs", - physicalChannel = SatelliteSlot, - transportStreamId = SatelliteStream, - }, - }); - - Assert.Equal(HttpStatusCode.UnprocessableEntity, status); - } - - [Fact] - public async Task ASatelliteServiceIsSaidToBeOutOfReceptionOnceItsOnlyTunerIsTurnedOffAndIsKept() - { - await using var feature = new CatalogFeature(); - feature.Driver.Tuners = - [ - new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle), - new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Disabled), - ]; - feature.Seed(101, "Ground", TuningParameters.Terrestrial(Terrestrial)); - feature.Seed(102, "Sky", TuningParameters.Bs(SatelliteSlot, new TransportStreamId(SatelliteStream))); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement listed = body.GetProperty("data"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal(["receivable", "noTunerInService"], Receptions(listed)); - Assert.Equal(2, feature.Services.Services.Count); - Assert.Equal(2, feature.Candidates.Candidates.Count); - } - - [Fact] - public async Task TurningTheSatelliteTunerBackOnMakesTheSameServiceReceivableAgain() - { - await using var feature = new CatalogFeature(); - feature.Driver.Tuners = - [ - new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Disabled), - ]; - feature.Seed(102, "Sky", TuningParameters.Bs(SatelliteSlot, new TransportStreamId(SatelliteStream))); - - Assert.Equal(["noTunerInService"], Receptions((await feature.GetAsync("/api/services")).Body.GetProperty("data"))); - - feature.Driver.Tuners = [new TunerSnapshot("adapter1", TunerKind.Satellite, TunerState.Idle)]; - - Assert.Equal(["receivable"], Receptions((await feature.GetAsync("/api/services")).Body.GetProperty("data"))); - } - - [Fact] - public async Task TheDetailOfAServiceNoTunerReceivesSaysSoToo() - { - await using var feature = new CatalogFeature(); - feature.Driver.Tuners = [new TunerSnapshot("adapter0", TunerKind.Terrestrial, TunerState.Idle)]; - feature.Seed(101, "Sky", TuningParameters.Bs(SatelliteSlot, new TransportStreamId(SatelliteStream))); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync(OneService); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal("noTunerInService", body.GetProperty("data").GetProperty("reception").GetString()); - } - - [Fact] - public async Task TunersThatCannotBeAskedAboutLeaveReceptionUnknownRatherThanOut() - { - await using var feature = new CatalogFeature(); - feature.Driver.Unreachable = "no socket"; - feature.Seed(101, "Ground", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal(["unknown"], Receptions(body.GetProperty("data"))); - } - - [Fact] - public async Task AChannelIsNotSavedWhileTheTunersItNeedsCannotBeAskedAbout() - { - await using var feature = new CatalogFeature(); - feature.Driver.Unreachable = "the driver socket is not there"; - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new { tuning = new { system = "isdbT", physicalChannel = OtherTerrestrial } }); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, status); - Assert.Single(feature.Candidates.Candidates); - } - - [Fact] - public async Task AChannelTheServiceAlreadyCarriesIsNotAddedTwice() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.PostAsync( - $"{OneService}/candidate-channels", - new { tuning = new { system = "isdbT", physicalChannel = Terrestrial } }); - - Assert.Equal(HttpStatusCode.Conflict, status); - Assert.Single(feature.Candidates.Candidates); - } - - [Fact] - public async Task DeletingACandidateLeavesTheServiceAndItsOtherChannelsInPlace() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - CandidateChannel doomed = feature.Candidates.Candidates[0]; - - (HttpStatusCode status, JsonElement body) = await feature.DeleteAsync( - $"{OneService}/candidate-channels/{doomed.Id.Value}"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal(1, body.GetProperty("data").GetProperty("candidateCount").GetInt32()); - Assert.Single(feature.Services.Services); - } - - [Fact] - public async Task DeletingTheSelectedCandidateLeavesNothingSelectedRatherThanARepointing() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - CandidateChannel chosen = feature.Candidates.Candidates[0]; - await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = chosen.Id.Value }); - - (HttpStatusCode status, JsonElement body) = await feature.DeleteAsync( - $"{OneService}/candidate-channels/{chosen.Id.Value}"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal( - System.Text.Json.JsonValueKind.Null, - body.GetProperty("data").GetProperty("selectedChannel").ValueKind); - } - - [Fact] - public async Task DeletingTheSelectedCandidateAsksForTheAllocationToBeSettledAgain() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - - CandidateChannel chosen = feature.Candidates.Candidates[0]; - await feature.Candidates.SelectAsync( - chosen.Id, - SelectionSource.Manual, - null, - TunerHoldingDriverClient.At, - CancellationToken.None); - - (HttpStatusCode status, JsonElement _) = await feature.DeleteAsync( - $"{OneService}/candidate-channels/{chosen.Id.Value}"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal([RecalculationTrigger.SelectedChannelChanged], feature.Notices.Nudged); - } - - [Fact] - public async Task DeletingACandidateOfAnotherServiceIsRefused() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - CandidateChannel elsewhere = feature.Seed(102, "Second", TuningParameters.Terrestrial(OtherTerrestrial)); - - (HttpStatusCode status, JsonElement _) = await feature.DeleteAsync( - $"{OneService}/candidate-channels/{elsewhere.Id.Value}"); - - Assert.Equal(HttpStatusCode.Conflict, status); - Assert.Equal(2, feature.Candidates.Candidates.Count); - Assert.Empty(feature.Notices.Nudged); - } - - [Fact] - public async Task TheListNamesTheChannelThatMeasuredBetterThanTheSelectedOne() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - feature.Measure(0, 12_000); - feature.Measure(1, 29_000); - - await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement listed = body.GetProperty("data")[0]; - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal( - Terrestrial, - listed.GetProperty("selectedChannel").GetProperty("physicalChannel").GetInt32()); - Assert.Equal( - OtherTerrestrial, - listed.GetProperty("betterChannel").GetProperty("physicalChannel").GetInt32()); - } - - [Fact] - public async Task TheListNamesNoBetterChannelWhenTheMeasurementsAlreadyFavourTheSelectedOne() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - feature.Measure(0, 29_000); - feature.Measure(1, 12_000); - - await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - - Assert.Equal( - System.Text.Json.JsonValueKind.Null, - body.GetProperty("data")[0].GetProperty("betterChannel").ValueKind); - } - - [Fact] - public async Task AChannelChosenByHandIsSaidToBeOutrankedJustAsOneAScanChoseWouldBe() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - feature.Measure(0, 12_000); - feature.Measure(1, 29_000); - - await feature.Candidates.SelectAsync( - feature.Candidates.Candidates[0].Id, - SelectionSource.Manual, - null, - TunerHoldingDriverClient.At, - CancellationToken.None); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement listed = body.GetProperty("data")[0]; - - Assert.Equal( - "manual", - listed.GetProperty("candidates")[0].GetProperty("selection").GetProperty("source").GetString()); - Assert.Equal( - OtherTerrestrial, - listed.GetProperty("betterChannel").GetProperty("physicalChannel").GetInt32()); - } - - [Fact] - public async Task AServiceWithNowhereToTuneIsNotSaidToHaveABetterChannel() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - feature.Measure(0, 12_000); - feature.Measure(1, 29_000); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - - Assert.Equal( - System.Text.Json.JsonValueKind.Null, - body.GetProperty("data")[0].GetProperty("betterChannel").ValueKind); - } - - [Fact] - public async Task SayingTheSelectionIsOutrankedDoesNotMoveTheSelection() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - feature.Measure(0, 12_000); - feature.Measure(1, 29_000); - - await feature.PutAsync( - $"{OneService}/selected-channel", - new { candidateChannelId = feature.Candidates.Candidates[0].Id.Value }); - - await feature.GetAsync("/api/services"); - await feature.GetAsync(OneService); - - CandidateChannel held = Assert.Single( - feature.Candidates.Candidates, - candidate => candidate.IsSelected); - - Assert.Equal(Terrestrial, held.Tuning.PhysicalChannel); - Assert.Equal(SelectionSource.Manual, held.SelectionSource); - } - - [Fact] - public async Task ACandidateThatKeptFailingSaysSoOnTheListWithoutOpeningIt() - { - await using var feature = new CatalogFeature(); - feature.Seed( - 101, - "Two ways in", - TuningParameters.Terrestrial(Terrestrial), - TuningParameters.Terrestrial(OtherTerrestrial)); - feature.Measure(0, 21_000); - feature.Refuse(1, RotationBackoff.Default.FailureCeiling); - - (HttpStatusCode status, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement candidates = body.GetProperty("data")[0].GetProperty("candidates"); - - Assert.Equal(HttpStatusCode.OK, status); - Assert.Equal("active", candidates[0].GetProperty("rotationState").GetString()); - Assert.Equal("needsAttention", candidates[1].GetProperty("rotationState").GetString()); - Assert.Equal( - RotationBackoff.Default.FailureCeiling, - candidates[1].GetProperty("consecutiveFailures").GetInt32()); - Assert.NotEqual( - JsonValueKind.Null, - candidates[1].GetProperty("needsAttentionSince").ValueKind); - } - - [Fact] - public async Task ACandidateStillBackingOffSaysWhenItIsDueAgainRatherThanThatItIsGone() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "One way in", TuningParameters.Terrestrial(Terrestrial)); - feature.Refuse(0, 1); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement candidate = body.GetProperty("data")[0].GetProperty("candidates")[0]; - - Assert.Equal("backingOff", candidate.GetProperty("rotationState").GetString()); - Assert.Equal( - new DateTimeOffset(TunerHoldingDriverClient.At.Add(RotationBackoff.Default.FirstDelay)), - candidate.GetProperty("nextAttemptAt").GetDateTimeOffset()); - } - - [Fact] - public async Task EveryCatalogSurfaceIsBehindTheSameDenialAsTheRestOnceASchemeIsRegistered() - { - using var app = new TestingWebApplicationFactory(); - using HttpClient client = app.WithTestScheme().CreateClient(); - - Assert.Equal( - HttpStatusCode.Unauthorized, - (await client.GetAsync(new Uri("/api/services", UriKind.Relative))).StatusCode); - Assert.Equal( - HttpStatusCode.Unauthorized, - (await client.GetAsync(new Uri(OneService, UriKind.Relative))).StatusCode); - } - - [Fact] - public async Task AServiceWhoseLogoHasBeenCollectedSaysSoAndWhereToAskForIt() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - feature.Logos.Services[0].NamesTheLogo(new LogoId(261)); - feature.Logos.Logos.Add(Logo(261)); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement listed = body.GetProperty("data")[0]; - - Assert.Equal("inTheCommonDataTable", listed.GetProperty("logoDeclaration").GetString()); - Assert.Equal("/api/services/1-101/logo", listed.GetProperty("logo").GetProperty("url").GetString()); - } - - [Fact] - public async Task TwoServicesOfOneStationBothPointAtTheirOwnAddressForTheLogoTheyShare() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - feature.Seed(102, "Second", TuningParameters.Terrestrial(Terrestrial)); - feature.Logos.Services[0].NamesTheLogo(new LogoId(261)); - feature.Logos.Services[1].NamesTheLogo(new LogoId(261)); - feature.Logos.Logos.Add(Logo(261)); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync("/api/services"); - JsonElement listed = body.GetProperty("data"); - - Assert.Equal("/api/services/1-101/logo", listed[0].GetProperty("logo").GetProperty("url").GetString()); - Assert.Equal("/api/services/1-102/logo", listed[1].GetProperty("logo").GetProperty("url").GetString()); - } - - [Fact] - public async Task AServiceThatBroadcastsNoLogoSaysSoRatherThanOfferingAnAddressThatAnswersNothing() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - feature.Logos.Services[0].BroadcastsNoLogo(); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync(OneService); - JsonElement found = body.GetProperty("data"); - - Assert.Equal("noPictureIsBroadcast", found.GetProperty("logoDeclaration").GetString()); - Assert.Equal(JsonValueKind.Null, found.GetProperty("logo").ValueKind); - } - - [Fact] - public async Task AServiceWhoseLogoIsNamedButNotYetCollectedOffersNoAddressForIt() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - feature.Logos.Services[0].NamesTheLogo(new LogoId(261)); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync(OneService); - JsonElement found = body.GetProperty("data"); - - Assert.Equal("inTheCommonDataTable", found.GetProperty("logoDeclaration").GetString()); - Assert.Equal(JsonValueKind.Null, found.GetProperty("logo").ValueKind); - } - - [Fact] - public async Task AServiceNobodyHasReadTheDescriptionOfSaysThatRatherThanThatItHasNoLogo() - { - await using var feature = new CatalogFeature(); - feature.Seed(101, "First", TuningParameters.Terrestrial(Terrestrial)); - - (HttpStatusCode _, JsonElement body) = await feature.GetAsync(OneService); - - Assert.Equal("notYetRead", body.GetProperty("data").GetProperty("logoDeclaration").GetString()); - } - - private static StationLogo Logo(int logoId) - => StationLogo.Collect( - new NetworkId(1), - new LogoId(logoId), - 0x05, - 3, - 64, - 36, - [0x89, 0x50, 0x4E, 0x47], - new DateTime(2026, 9, 5, 0, 0, 0, DateTimeKind.Utc)); - - private static IReadOnlyList Receptions(JsonElement listed) - => [.. listed.EnumerateArray().Select(service => service.GetProperty("reception").GetString())]; -} diff --git a/tests/Carina.Api.Tests/FeatureTest/CatalogFeature.cs b/tests/Carina.Api.Tests/FeatureTest/TunerHoldingDriverClient.cs similarity index 52% rename from tests/Carina.Api.Tests/FeatureTest/CatalogFeature.cs rename to tests/Carina.Api.Tests/FeatureTest/TunerHoldingDriverClient.cs index 181ec9a15..d894feb5c 100644 --- a/tests/Carina.Api.Tests/FeatureTest/CatalogFeature.cs +++ b/tests/Carina.Api.Tests/FeatureTest/TunerHoldingDriverClient.cs @@ -1,14 +1,4 @@ -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; - -using Carina.Domain.Channels; using Carina.Domain.Driver; -using Carina.Domain.Reservations; -using Carina.TestSupport; - -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; using Puppis.Contracts; @@ -122,110 +112,3 @@ public Task>> GetStorageAsync( CancellationToken cancellationToken) => throw new NotSupportedException(); } - -internal sealed class CatalogFeature : IAsyncDisposable -{ - private readonly TestingWebApplicationFactory factory = new(); - - public CatalogFeature() - => Client = factory - .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => - { - services.AddSingleton(Services); - services.AddSingleton(Logos); - services.AddSingleton(Candidates); - services.AddSingleton(Driver); - services.AddSingleton(Notices); - })) - .CreateAuthenticatedClient(); - - public HttpClient Client { get; } - - public HeldServices Services { get; } = new(); - - public HeldLogos Logos { get; } = new(); - - public HeldCandidates Candidates { get; } = new(); - - public TunerHoldingDriverClient Driver { get; } = new(); - - public CountedNotices Notices { get; } = new(); - - public CandidateChannel Seed(int serviceId, string name, params TuningParameters[] tunings) - { - BroadcastService service = BroadcastService.Discover( - new NetworkId(1), - new ServiceId(serviceId), - name, - ServiceCategory.Television, - TunerHoldingDriverClient.At); - - Services.Services.Add(service); - Logos.Services.Add(service); - - foreach (TuningParameters tuning in tunings) - { - Candidates.Candidates.Add(CandidateChannel.Discover( - CandidateChannelId.New(), - new NetworkId(1), - new ServiceId(serviceId), - tuning, - TunerHoldingDriverClient.At)); - } - - return Candidates.Candidates[^1]; - } - - public void Measure(int candidate, int cnrMilliDecibels) - => Candidates.Candidates[candidate].RecordTuningSuccess( - SignalMeasurement.WithLock(TunerHoldingDriverClient.At, cnrMilliDecibels), - TunerHoldingDriverClient.At); - - public void Refuse(int candidate, int times) - { - for (int failure = 0; failure < times; failure++) - { - Candidates.Candidates[candidate].RecordTuningFailure( - RotationBackoff.Default, - TunerHoldingDriverClient.At); - } - } - - public Task<(HttpStatusCode Status, JsonElement Body)> GetAsync(string path) - => SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri(path, UriKind.Relative))); - - public Task<(HttpStatusCode Status, JsonElement Body)> DeleteAsync(string path) - => SendAsync(new HttpRequestMessage(HttpMethod.Delete, new Uri(path, UriKind.Relative)) - { - Content = JsonContent.Create(new { }), - }); - - public Task<(HttpStatusCode Status, JsonElement Body)> PutAsync(string path, object body) - => SendAsync(new HttpRequestMessage(HttpMethod.Put, new Uri(path, UriKind.Relative)) - { - Content = JsonContent.Create(body), - }); - - public Task<(HttpStatusCode Status, JsonElement Body)> PostAsync(string path, object body) - => SendAsync(new HttpRequestMessage(HttpMethod.Post, new Uri(path, UriKind.Relative)) - { - Content = JsonContent.Create(body), - }); - - public async ValueTask DisposeAsync() - { - Client.Dispose(); - await factory.DisposeAsync(); - } - - private async Task<(HttpStatusCode Status, JsonElement Body)> SendAsync(HttpRequestMessage request) - { - using (request) - { - using HttpResponseMessage response = await Client.SendAsync(request); - using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - - return (response.StatusCode, document.RootElement.Clone()); - } - } -} diff --git a/tests/Carina.Api.Tests/Unit/AppEventStreamKeepaliveTests.cs b/tests/Carina.Api.Tests/Unit/App/Events/AppEventStreamTests.cs similarity index 91% rename from tests/Carina.Api.Tests/Unit/AppEventStreamKeepaliveTests.cs rename to tests/Carina.Api.Tests/Unit/App/Events/AppEventStreamTests.cs index cc39e8d22..eaf2bfcb7 100644 --- a/tests/Carina.Api.Tests/Unit/AppEventStreamKeepaliveTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Events/AppEventStreamTests.cs @@ -1,5 +1,3 @@ -using System.Text; - using Carina.Api.Events; using Carina.Infrastructure.Events; @@ -7,7 +5,7 @@ using Puppis.Contracts; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Events; internal sealed class Sink : Stream { @@ -53,17 +51,24 @@ public string Text() { lock (gate) { - return Encoding.UTF8.GetString([.. written]); + return System.Text.Encoding.UTF8.GetString([.. written]); } } } -public sealed class AppEventStreamKeepaliveTests +[Trait("Category", "Unit")] +public sealed class AppEventStreamTests { private static readonly TimeSpan Quickly = TimeSpan.FromMilliseconds(20); private static readonly TimeSpan LongEnough = TimeSpan.FromSeconds(5); + [Fact] + public void ASignalFrameCarriesABareDataLineSoAnEventSourceDispatchesItWithoutAPayload() + { + Assert.Equal("event: tuners\ndata\n\n", AppEventStream.Frame(AppEvents.Tuners)); + } + [Fact] public void TheKeepaliveIsACommentSoAnEventSourceDispatchesNothingForIt() { diff --git a/tests/Carina.Api.Tests/Unit/DeclaredVersionTests.cs b/tests/Carina.Api.Tests/Unit/App/Version/DeclaredVersionTests.cs similarity index 96% rename from tests/Carina.Api.Tests/Unit/DeclaredVersionTests.cs rename to tests/Carina.Api.Tests/Unit/App/Version/DeclaredVersionTests.cs index 5ee9820d9..e22e78eb1 100644 --- a/tests/Carina.Api.Tests/Unit/DeclaredVersionTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Version/DeclaredVersionTests.cs @@ -3,8 +3,9 @@ using Carina.Api.Common; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Version; +[Trait("Category", "Unit")] public sealed class DeclaredVersionTests { [Fact] diff --git a/tests/Carina.Conventions.Tests/TestLayoutRules.cs b/tests/Carina.Conventions.Tests/TestLayoutRules.cs index 23ecd9bac..cbe065115 100644 --- a/tests/Carina.Conventions.Tests/TestLayoutRules.cs +++ b/tests/Carina.Conventions.Tests/TestLayoutRules.cs @@ -19,15 +19,7 @@ public static class TestLayoutRules public static readonly IReadOnlyList AreasNotYetMoved = [ - "Base", - "Configuration", - "DependencyInjection", - "Events", "Health", - "Net", - "Persistence", - "Services", - "Version", ]; /// @@ -56,6 +48,7 @@ public static class TestLayoutRules new("Encodings", "src/Carina.Infrastructure/Configuration/EncodingOptions.cs"), new("Epg", "src/Carina.Api/Events/ProgrammeFeedReaders.cs"), new("Epg", "src/Carina.Api/Events/ProgrammeFeedStream.cs"), + new("Events", "src/Carina.Api/Events/AppEventStream.cs"), new("Integrity", "src/Carina.Api/Services/IntegrityService.cs"), new("Integrity", "src/Carina.Db/Migrations/20260914005111_AFindingNamedForTheFactItIsAbout.cs"), new("Integrity", "src/Carina.Infrastructure/Configuration/IntegrityOptions.cs"), @@ -70,6 +63,9 @@ public static class TestLayoutRules new("Notifications", "src/Carina.Api/Services/NotificationRuleService.cs"), new("Notifications", "src/Carina.Db/Migrations/20261110182416_AProgrammeCanBeWatchedWithoutBeingRecorded.cs"), new("Notifications", "src/Carina.Db/Migrations/20261112182442_ANoticeCanBeSentToABrowser.cs"), + new("Persistence", "src/Carina.Db/CarinaDbContextFactory.cs"), + new("Persistence", "src/Carina.Db/DbEntryPoint.cs"), + new("Persistence", "src/Carina.Db/MigrationLock.cs"), new("Playback", "src/Carina.Api/Playback/AskedDecoding.cs"), new("Playback", "src/Carina.Api/Playback/AskedFormat.cs"), new("Playback", "src/Carina.Api/Playback/ByteRange.cs"), @@ -113,6 +109,7 @@ public static class TestLayoutRules new("Streaming", "src/Carina.Api/Live/LiveWireSocket.cs"), new("Thumbnails", "src/Carina.Api/Playback/ScrubDelivery.cs"), new("Thumbnails", "src/Carina.Api/Playback/ThumbnailDelivery.cs"), + new("Version", "src/Carina.Api/Common/DeclaredVersion.cs"), ]; /// diff --git a/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/DbEntryPointTests.cs b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/DbEntryPointTests.cs new file mode 100644 index 000000000..86ce8c086 --- /dev/null +++ b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/DbEntryPointTests.cs @@ -0,0 +1,32 @@ +using Npgsql; + +namespace Carina.Db.Tests.DbIntegration.Infra.Persistence; + +[Collection(ConnectionEnvironmentCollection.Name)] +[Trait("Category", "DbIntegration")] +public sealed class DbEntryPointTests +{ + [Fact] + public async Task EntryPointMigratesRepeatablyAndFailsLoudlyOnBadCredentials() + { + string connectionString = MigrationScratch.ConnectionString(); + + using (new EnvironmentVariableScope(CarinaDbContextFactory.ConnectionStringVariable, connectionString)) + { + Assert.Equal(DbEntryPoint.SuccessExitCode, await DbEntryPoint.RunAsync(["--migrate"], new StringWriter())); + Assert.Equal(DbEntryPoint.SuccessExitCode, await DbEntryPoint.RunAsync(["--migrate"], new StringWriter())); + } + + string wrongPassword = new NpgsqlConnectionStringBuilder(connectionString) { Password = "wrong" }.ConnectionString; + + using (new EnvironmentVariableScope(CarinaDbContextFactory.ConnectionStringVariable, wrongPassword)) + { + var error = new StringWriter(); + + int exitCode = await DbEntryPoint.RunAsync(["--migrate"], error); + + Assert.Equal(DbEntryPoint.MigrationFailedExitCode, exitCode); + Assert.Contains("Carina.Db --migrate failed", error.ToString(), StringComparison.Ordinal); + } + } +} diff --git a/tests/Carina.Db.Tests/MigrationLockTests.cs b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/MigrationLockTests.cs similarity index 98% rename from tests/Carina.Db.Tests/MigrationLockTests.cs rename to tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/MigrationLockTests.cs index 342a557b3..b6708e168 100644 --- a/tests/Carina.Db.Tests/MigrationLockTests.cs +++ b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/MigrationLockTests.cs @@ -4,7 +4,7 @@ using Npgsql; -namespace Carina.Db.Tests; +namespace Carina.Db.Tests.DbIntegration.Infra.Persistence; [Collection(ConnectionEnvironmentCollection.Name)] [Trait("Category", "DbIntegration")] diff --git a/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/MigrationScratch.cs b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/MigrationScratch.cs new file mode 100644 index 000000000..363d02de5 --- /dev/null +++ b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/MigrationScratch.cs @@ -0,0 +1,20 @@ +using Npgsql; + +namespace Carina.Db.Tests.DbIntegration.Infra.Persistence; + +internal static class MigrationScratch +{ + private const string ScratchDatabase = "carina_migration_test"; + + public static string ConnectionString() + { + string? configured = Environment.GetEnvironmentVariable(CarinaDbContextFactory.ConnectionStringVariable); + if (string.IsNullOrWhiteSpace(configured)) + { + throw new InvalidOperationException( + $"DbIntegration tests need {CarinaDbContextFactory.ConnectionStringVariable} pointing at the compose db service."); + } + + return new NpgsqlConnectionStringBuilder(configured) { Database = ScratchDatabase }.ConnectionString; + } +} diff --git a/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/PersistenceSchemaTests.cs b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/PersistenceSchemaTests.cs new file mode 100644 index 000000000..2cebcb5ed --- /dev/null +++ b/tests/Carina.Db.Tests/DbIntegration/Infra/Persistence/PersistenceSchemaTests.cs @@ -0,0 +1,39 @@ +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; + +namespace Carina.Db.Tests.DbIntegration.Infra.Persistence; + +[Collection(ConnectionEnvironmentCollection.Name)] +[Trait("Category", "DbIntegration")] +public sealed class PersistenceSchemaTests +{ + [Fact] + public async Task AppliesEveryMigrationToAnEmptyDatabase() + { + await using CarinaDbContext context = CarinaDbContextFactory.Create(MigrationScratch.ConnectionString()); + await context.Database.EnsureDeletedAsync(); + + await context.Database.MigrateAsync(); + + string[] applied = (await context.Database.GetAppliedMigrationsAsync()).ToArray(); + Assert.EndsWith("_Initial", applied[0], StringComparison.Ordinal); + Assert.Equal(context.Database.GetMigrations(), applied); + Assert.Empty(await context.Database.GetPendingMigrationsAsync()); + + Assert.False(context.Database.HasPendingModelChanges()); + } + + [Fact] + public async Task ReRunningTheMigrationsIsIdempotent() + { + await using CarinaDbContext context = CarinaDbContextFactory.Create(MigrationScratch.ConnectionString()); + await context.Database.EnsureDeletedAsync(); + await context.Database.MigrateAsync(); + string[] firstRun = (await context.Database.GetAppliedMigrationsAsync()).ToArray(); + + await context.Database.MigrateAsync(); + + Assert.Equal(firstRun, await context.Database.GetAppliedMigrationsAsync()); + } +} diff --git a/tests/Carina.Db.Tests/MigrationCultureTests.cs b/tests/Carina.Db.Tests/MigrationCultureTests.cs deleted file mode 100644 index 1ee910645..000000000 --- a/tests/Carina.Db.Tests/MigrationCultureTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Globalization; - -namespace Carina.Db.Tests; - -[Collection(ConnectionEnvironmentCollection.Name)] -public sealed class MigrationCultureTests -{ - [Fact] - public async Task TheEntryPointDecidesItsOwnCultureRatherThanTakingOneFromTheEnvironment() - { - CultureInfo? held = CultureInfo.DefaultThreadCurrentCulture; - CultureInfo? spoken = CultureInfo.DefaultThreadCurrentUICulture; - - try - { - CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("tr-TR"); - CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("tr-TR"); - - Assert.Equal( - DbEntryPoint.UsageExitCode, - await DbEntryPoint.RunAsync(["--not-a-thing-it-does"], new StringWriter())); - Assert.Same(CultureInfo.InvariantCulture, CultureInfo.DefaultThreadCurrentCulture); - Assert.Same(CultureInfo.InvariantCulture, CultureInfo.DefaultThreadCurrentUICulture); - } - finally - { - CultureInfo.DefaultThreadCurrentCulture = held; - CultureInfo.DefaultThreadCurrentUICulture = spoken; - } - } -} diff --git a/tests/Carina.Db.Tests/MigrationPipelineTests.cs b/tests/Carina.Db.Tests/MigrationPipelineTests.cs deleted file mode 100644 index 28a50fcd9..000000000 --- a/tests/Carina.Db.Tests/MigrationPipelineTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -using Carina.Infrastructure.Persistence; - -using Microsoft.EntityFrameworkCore; - -using Npgsql; - -namespace Carina.Db.Tests; - -[Collection(ConnectionEnvironmentCollection.Name)] -[Trait("Category", "DbIntegration")] -public sealed class MigrationPipelineTests -{ - private const string ScratchDatabase = "carina_migration_test"; - - private static string ScratchConnectionString() - { - string? configured = Environment.GetEnvironmentVariable(CarinaDbContextFactory.ConnectionStringVariable); - if (string.IsNullOrWhiteSpace(configured)) - { - throw new InvalidOperationException( - $"DbIntegration tests need {CarinaDbContextFactory.ConnectionStringVariable} pointing at the compose db service."); - } - - return new NpgsqlConnectionStringBuilder(configured) { Database = ScratchDatabase }.ConnectionString; - } - - [Fact] - public async Task AppliesEveryMigrationToAnEmptyDatabase() - { - await using CarinaDbContext context = CarinaDbContextFactory.Create(ScratchConnectionString()); - await context.Database.EnsureDeletedAsync(); - - await context.Database.MigrateAsync(); - - string[] applied = (await context.Database.GetAppliedMigrationsAsync()).ToArray(); - Assert.EndsWith("_Initial", applied[0], StringComparison.Ordinal); - Assert.Equal(context.Database.GetMigrations(), applied); - Assert.Empty(await context.Database.GetPendingMigrationsAsync()); - - Assert.False(context.Database.HasPendingModelChanges()); - } - - [Fact] - public async Task ReRunningTheMigrationsIsIdempotent() - { - await using CarinaDbContext context = CarinaDbContextFactory.Create(ScratchConnectionString()); - await context.Database.EnsureDeletedAsync(); - await context.Database.MigrateAsync(); - string[] firstRun = (await context.Database.GetAppliedMigrationsAsync()).ToArray(); - - await context.Database.MigrateAsync(); - - Assert.Equal(firstRun, await context.Database.GetAppliedMigrationsAsync()); - } - - [Fact] - public async Task EntryPointMigratesRepeatablyAndFailsLoudlyOnBadCredentials() - { - string connectionString = ScratchConnectionString(); - - using (new EnvironmentVariableScope(CarinaDbContextFactory.ConnectionStringVariable, connectionString)) - { - Assert.Equal(DbEntryPoint.SuccessExitCode, await DbEntryPoint.RunAsync(["--migrate"], new StringWriter())); - Assert.Equal(DbEntryPoint.SuccessExitCode, await DbEntryPoint.RunAsync(["--migrate"], new StringWriter())); - } - - string wrongPassword = new NpgsqlConnectionStringBuilder(connectionString) { Password = "wrong" }.ConnectionString; - - using (new EnvironmentVariableScope(CarinaDbContextFactory.ConnectionStringVariable, wrongPassword)) - { - var error = new StringWriter(); - - int exitCode = await DbEntryPoint.RunAsync(["--migrate"], error); - - Assert.Equal(DbEntryPoint.MigrationFailedExitCode, exitCode); - Assert.Contains("Carina.Db --migrate failed", error.ToString(), StringComparison.Ordinal); - } - } -} diff --git a/tests/Carina.Db.Tests/CarinaDbContextFactoryTests.cs b/tests/Carina.Db.Tests/Unit/Infra/Persistence/CarinaDbContextFactoryTests.cs similarity index 95% rename from tests/Carina.Db.Tests/CarinaDbContextFactoryTests.cs rename to tests/Carina.Db.Tests/Unit/Infra/Persistence/CarinaDbContextFactoryTests.cs index 5033a8222..c4baaec24 100644 --- a/tests/Carina.Db.Tests/CarinaDbContextFactoryTests.cs +++ b/tests/Carina.Db.Tests/Unit/Infra/Persistence/CarinaDbContextFactoryTests.cs @@ -1,10 +1,10 @@ using Carina.Infrastructure.Persistence; -using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace Carina.Db.Tests; +namespace Carina.Db.Tests.Unit.Infra.Persistence; +[Trait("Category", "Unit")] public sealed class CarinaDbContextFactoryTests { private const string ConnectionString = "Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"; diff --git a/tests/Carina.Db.Tests/DbEntryPointTests.cs b/tests/Carina.Db.Tests/Unit/Infra/Persistence/DbEntryPointTests.cs similarity index 87% rename from tests/Carina.Db.Tests/DbEntryPointTests.cs rename to tests/Carina.Db.Tests/Unit/Infra/Persistence/DbEntryPointTests.cs index 32e55480f..f3df3d475 100644 --- a/tests/Carina.Db.Tests/DbEntryPointTests.cs +++ b/tests/Carina.Db.Tests/Unit/Infra/Persistence/DbEntryPointTests.cs @@ -1,11 +1,14 @@ +using System.Globalization; using System.Net; using System.Net.Sockets; using Carina.Infrastructure.Migration; +using Carina.TestSupport; -namespace Carina.Db.Tests; +namespace Carina.Db.Tests.Unit.Infra.Persistence; [Collection(ConnectionEnvironmentCollection.Name)] +[Trait("Category", "Unit")] public sealed class DbEntryPointTests { [Theory] @@ -97,8 +100,7 @@ public async Task RefusesToCarryIntoADirectoryThisInstallationDeclaresNoRootFor( } finally { - Directory.Delete(from, recursive: true); - Directory.Delete(into, recursive: true); + TemporaryDirectories.RemoveAll(new DirectoryInfo(from), new DirectoryInfo(into)); } } @@ -133,8 +135,7 @@ public async Task ADirectoryNoRootIsDeclaredForIsRefusedBeforeAnythingReachesFor } finally { - Directory.Delete(from, recursive: true); - Directory.Delete(into, recursive: true); + TemporaryDirectories.RemoveAll(new DirectoryInfo(from), new DirectoryInfo(into)); } } @@ -168,41 +169,10 @@ await ComplainedAboutAsync( } finally { - Directory.Delete(from, recursive: true); - Directory.Delete(into, recursive: true); + TemporaryDirectories.RemoveAll(new DirectoryInfo(from), new DirectoryInfo(into)); } } - private static async Task ComplainedAboutAsync( - string from, - string into, - bool declaring, - string? source) - { - using EnvironmentVariableScope declared = declaring - ? Declaring(into) - : new EnvironmentVariableScope( - MigrationRootSettings.DeclarationVariable, - "primary=/srv/somewhere-else"); - using var reaching = new EnvironmentVariableScope(MigrationSourceSettings.ConnectionVariable, source); - var error = new StringWriter(); - - Assert.Equal( - DbEntryPoint.UnusableConfigurationExitCode, - await DbEntryPoint.RunAsync(["--carry", "--from", from, "--into", into], error)); - - string said = error.ToString(); - - return Assert.Single( - new[] - { - MigrationRootSettings.DeclarationVariable, - MigrationSourceSettings.ConnectionVariable, - CarinaDbContextFactory.ConnectionStringVariable, - }, - named => said.Contains(named, StringComparison.Ordinal)); - } - [Fact] public async Task ADirectoryThisInstallationDeclaresARootForIsNotRefusedForWantOfADeclaration() { @@ -224,8 +194,7 @@ public async Task ADirectoryThisInstallationDeclaresARootForIsNotRefusedForWantO } finally { - Directory.Delete(from, recursive: true); - Directory.Delete(into, recursive: true); + TemporaryDirectories.RemoveAll(new DirectoryInfo(from), new DirectoryInfo(into)); } } @@ -251,8 +220,7 @@ public async Task RefusesToCarryWhenNothingSaysHowToReachTheSourceSystem() } finally { - Directory.Delete(from, recursive: true); - Directory.Delete(into, recursive: true); + TemporaryDirectories.RemoveAll(new DirectoryInfo(from), new DirectoryInfo(into)); } } @@ -276,8 +244,7 @@ public async Task RefusesToCarryWhenWhatSaysHowToReachTheSourceSystemNamesNoData } finally { - Directory.Delete(from, recursive: true); - Directory.Delete(into, recursive: true); + TemporaryDirectories.RemoveAll(new DirectoryInfo(from), new DirectoryInfo(into)); } } @@ -307,6 +274,60 @@ public async Task FailsLoudlyOnAMalformedConnectionString() Assert.Contains("Carina.Db --migrate failed", error.ToString(), StringComparison.Ordinal); } + [Fact] + public async Task TheEntryPointDecidesItsOwnCultureRatherThanTakingOneFromTheEnvironment() + { + CultureInfo? held = CultureInfo.DefaultThreadCurrentCulture; + CultureInfo? spoken = CultureInfo.DefaultThreadCurrentUICulture; + + try + { + CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("tr-TR"); + CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("tr-TR"); + + Assert.Equal( + DbEntryPoint.UsageExitCode, + await DbEntryPoint.RunAsync(["--not-a-thing-it-does"], new StringWriter())); + Assert.Same(CultureInfo.InvariantCulture, CultureInfo.DefaultThreadCurrentCulture); + Assert.Same(CultureInfo.InvariantCulture, CultureInfo.DefaultThreadCurrentUICulture); + } + finally + { + CultureInfo.DefaultThreadCurrentCulture = held; + CultureInfo.DefaultThreadCurrentUICulture = spoken; + } + } + + private static async Task ComplainedAboutAsync( + string from, + string into, + bool declaring, + string? source) + { + using EnvironmentVariableScope declared = declaring + ? Declaring(into) + : new EnvironmentVariableScope( + MigrationRootSettings.DeclarationVariable, + "primary=/srv/somewhere-else"); + using var reaching = new EnvironmentVariableScope(MigrationSourceSettings.ConnectionVariable, source); + var error = new StringWriter(); + + Assert.Equal( + DbEntryPoint.UnusableConfigurationExitCode, + await DbEntryPoint.RunAsync(["--carry", "--from", from, "--into", into], error)); + + string said = error.ToString(); + + return Assert.Single( + new[] + { + MigrationRootSettings.DeclarationVariable, + MigrationSourceSettings.ConnectionVariable, + CarinaDbContextFactory.ConnectionStringVariable, + }, + named => said.Contains(named, StringComparison.Ordinal)); + } + private static EnvironmentVariableScope Declaring(string into) => new(MigrationRootSettings.DeclarationVariable, $"primary={into}"); diff --git a/tests/Carina.Domain.Tests/BroadcastDayTests.cs b/tests/Carina.Domain.Tests/Unit/Base/BroadcastDayTests.cs similarity index 95% rename from tests/Carina.Domain.Tests/BroadcastDayTests.cs rename to tests/Carina.Domain.Tests/Unit/Base/BroadcastDayTests.cs index 28d1c6a6e..d71b5bcf0 100644 --- a/tests/Carina.Domain.Tests/BroadcastDayTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Base/BroadcastDayTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Base; -namespace Carina.Domain.Tests; +namespace Carina.Domain.Tests.Unit.Base; +[Trait("Category", "Unit")] public sealed class BroadcastDayTests { [Fact] diff --git a/tests/Carina.Domain.Tests/CommonValueObjectTests.cs b/tests/Carina.Domain.Tests/Unit/Base/CommonValueObjectTests.cs similarity index 94% rename from tests/Carina.Domain.Tests/CommonValueObjectTests.cs rename to tests/Carina.Domain.Tests/Unit/Base/CommonValueObjectTests.cs index 2f315f1d4..fb13c1a2c 100644 --- a/tests/Carina.Domain.Tests/CommonValueObjectTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Base/CommonValueObjectTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Base; -namespace Carina.Domain.Tests; +namespace Carina.Domain.Tests.Unit.Base; +[Trait("Category", "Unit")] public sealed class CommonValueObjectTests { [Fact] diff --git a/tests/Carina.Domain.Tests/JapanTimeZoneTests.cs b/tests/Carina.Domain.Tests/Unit/Base/JapanTimeZoneTests.cs similarity index 94% rename from tests/Carina.Domain.Tests/JapanTimeZoneTests.cs rename to tests/Carina.Domain.Tests/Unit/Base/JapanTimeZoneTests.cs index eae198a58..7d3cd5f84 100644 --- a/tests/Carina.Domain.Tests/JapanTimeZoneTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Base/JapanTimeZoneTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Base; -namespace Carina.Domain.Tests; +namespace Carina.Domain.Tests.Unit.Base; +[Trait("Category", "Unit")] public sealed class JapanTimeZoneTests { [Fact] diff --git a/tests/Carina.Domain.Tests/ProgrammeNoteTests.cs b/tests/Carina.Domain.Tests/Unit/Base/ProgrammeNoteTests.cs similarity index 66% rename from tests/Carina.Domain.Tests/ProgrammeNoteTests.cs rename to tests/Carina.Domain.Tests/Unit/Base/ProgrammeNoteTests.cs index 0017ec0b1..2ab23727b 100644 --- a/tests/Carina.Domain.Tests/ProgrammeNoteTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Base/ProgrammeNoteTests.cs @@ -1,9 +1,8 @@ using Carina.Domain.Base; -using Carina.Domain.Encodings; -using Carina.Domain.Streaming; -namespace Carina.Domain.Tests; +namespace Carina.Domain.Tests.Unit.Base; +[Trait("Category", "Unit")] public sealed class ProgrammeNoteTests { [Theory] @@ -46,22 +45,4 @@ public void ANoteIsCutAfterThePathsAreTakenOutSoTheLengthIsWhatIsActuallyKept() Assert.Equal($"{ProgrammeNote.InsteadOfAPath} is gone", ProgrammeNote.Of(said, 20)); } - - [Fact(DisplayName = "what an encode failure keeps names no path on this machine, as the live side already did")] - public void WhatAnEncodeFailureKeepsNamesNoPathOnThisMachine() - { - const string said = "[out#0 @ 0x1] Error opening output /srv/encoded/k-1.mp4: No space left on device"; - - Assert.DoesNotContain('/', EncodeNote.Of(said)); - Assert.Contains("No space left on device", EncodeNote.Of(said), StringComparison.Ordinal); - } - - [Fact] - public void TheLiveSideAndTheEncodeSideHideAPathTheSameWay() - { - const string said = "could not open /dev/dri/renderD128"; - - Assert.Equal(TranscoderNote.Of(said), EncodeNote.Of(said)); - Assert.Equal(ProgrammeNote.Of(said, ProgrammeNote.Longest), EncodeNote.Of(said)); - } } diff --git a/tests/Carina.Domain.Tests/Unit/Encodings/EncodeNoteTests.cs b/tests/Carina.Domain.Tests/Unit/Encodings/EncodeNoteTests.cs new file mode 100644 index 000000000..af294f094 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Encodings/EncodeNoteTests.cs @@ -0,0 +1,27 @@ +using Carina.Domain.Base; +using Carina.Domain.Encodings; +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Encodings; + +[Trait("Category", "Unit")] +public sealed class EncodeNoteTests +{ + [Fact(DisplayName = "what an encode failure keeps names no path on this machine, as the live side already did")] + public void WhatAnEncodeFailureKeepsNamesNoPathOnThisMachine() + { + const string said = "[out#0 @ 0x1] Error opening output /srv/encoded/k-1.mp4: No space left on device"; + + Assert.DoesNotContain('/', EncodeNote.Of(said)); + Assert.Contains("No space left on device", EncodeNote.Of(said), StringComparison.Ordinal); + } + + [Fact] + public void TheLiveSideAndTheEncodeSideHideAPathTheSameWay() + { + const string said = "could not open /dev/dri/renderD128"; + + Assert.Equal(TranscoderNote.Of(said), EncodeNote.Of(said)); + Assert.Equal(ProgrammeNote.Of(said, ProgrammeNote.Longest), EncodeNote.Of(said)); + } +} diff --git a/tests/Carina.Infrastructure.Tests/CarinaDbContextConventionTests.cs b/tests/Carina.Infrastructure.Tests/CarinaDbContextConventionTests.cs deleted file mode 100644 index 54aaa3869..000000000 --- a/tests/Carina.Infrastructure.Tests/CarinaDbContextConventionTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Carina.Infrastructure.Persistence; - -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata; - -namespace Carina.Infrastructure.Tests; - -internal sealed class ConventionProbe -{ - public int Id { get; set; } - public DateTime RecordedAt { get; set; } -} - -public sealed class CarinaDbContextConventionTests -{ - private sealed class ProbeDbContext(DbContextOptions options) : CarinaDbContext(options) - { - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity(); - } - } - - private static ProbeDbContext Probe() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase("Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"); - - return new ProbeDbContext(builder.Options); - } - - [Fact] - public void NamesTablesAndColumnsInSnakeCase() - { - using ProbeDbContext context = Probe(); - - IEntityType entity = context.Model.FindEntityType(typeof(ConventionProbe))!; - - Assert.Equal("convention_probe", entity.GetTableName()); - Assert.Equal("recorded_at", entity.FindProperty(nameof(ConventionProbe.RecordedAt))!.GetColumnName()); - } - - [Fact] - public void RoutesEveryDateTimeThroughTheUtcConverter() - { - using ProbeDbContext context = Probe(); - - IProperty property = context.Model.FindEntityType(typeof(ConventionProbe))! - .FindProperty(nameof(ConventionProbe.RecordedAt))!; - - Assert.IsType(property.GetValueConverter()); - } -} diff --git a/tests/Carina.Infrastructure.Tests/ChannelSchemaTests.cs b/tests/Carina.Infrastructure.Tests/ChannelSchemaTests.cs deleted file mode 100644 index f4fc3b3f0..000000000 --- a/tests/Carina.Infrastructure.Tests/ChannelSchemaTests.cs +++ /dev/null @@ -1,360 +0,0 @@ -using Carina.Domain.Channels; -using Carina.Domain.Programmes; -using Carina.Domain.Scans; -using Carina.Infrastructure.Persistence; - -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; - -namespace Carina.Infrastructure.Tests; - -public sealed class ChannelSchemaTests -{ - private static CarinaDbContext Carina() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase("Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"); - - return new CarinaDbContext(builder.Options); - } - - private static IModel Schema(CarinaDbContext context) - => context.GetService().Model; - - private static IEntityType Entity(CarinaDbContext context) - => Schema(context).FindEntityType(typeof(TEntity))!; - - // Tuning and the signal readings are complex properties rather than owned entities: - // they carry no identity, so two rows may hold the very same instance. - private static IEnumerable ColumnsOf(IEntityType entity, string valueObject) - => entity.GetComplexProperties() - .Single(property => property.Name == valueObject) - .ComplexType.GetProperties() - .Select(property => property.GetColumnName()); - - private static IEnumerable EveryProperty(ITypeBase type) - => [ - .. type.GetProperties(), - .. type.GetComplexProperties().SelectMany(property => EveryProperty(property.ComplexType)), - ]; - - [Fact(DisplayName = "a candidate keeps its latest score as one reading, not a history of them")] - public void ACandidateKeepsItsLatestScoreAsOneReading() - { - using CarinaDbContext context = Carina(); - IEntityType candidate = Entity(context); - - Assert.Equal( - [ - "score_bit_error_rate_highest", - "score_cnr_lowest_milli_decibels", - "score_evaluated_at", - "score_lock_rate", - "score_measured_from", - "score_measured_until", - "score_samples", - ], - ColumnsOf(candidate, nameof(CandidateChannel.Score)).Order(StringComparer.Ordinal)); - Assert.Contains("ck_candidate_channel_score", candidate.GetCheckConstraints().Select(check => check.Name)); - } - - [Fact] - public void AServiceIsKeyedByItsBroadcastIdentifiersAlone() - { - using CarinaDbContext context = Carina(); - - IKey key = Entity(context).FindPrimaryKey()!; - - Assert.Equal( - ["network_id", "service_id"], - key.Properties.Select(property => property.GetColumnName())); - } - - [Fact] - public void ACandidateChannelPointsAtItsServiceAndNothingPointsBack() - { - using CarinaDbContext context = Carina(); - - IForeignKey foreignKey = Assert.Single(Entity(context).GetForeignKeys()); - - Assert.Equal("broadcast_service", foreignKey.PrincipalEntityType.GetTableName()); - Assert.Equal( - ["network_id", "service_id"], - foreignKey.Properties.Select(property => property.GetColumnName())); - Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); - } - - [Fact] - public void OnlyOneCandidatePerServiceCanBeSelected() - { - using CarinaDbContext context = Carina(); - - IIndex index = Assert.Single( - Entity(context).GetIndexes(), - candidate => candidate.GetDatabaseName() == "ux_candidate_channel_selected"); - - Assert.True(index.IsUnique); - Assert.Equal("is_selected", index.GetFilter()); - Assert.Equal( - ["network_id", "service_id"], - index.Properties.Select(property => property.GetColumnName())); - } - - [Fact] - public void OnlyOneScanCanBeRunning() - { - using CarinaDbContext context = Carina(); - - IIndex index = Assert.Single( - Entity(context).GetIndexes(), - run => run.GetDatabaseName() == "ux_scan_run_running"); - - Assert.True(index.IsUnique); - Assert.Equal("state = 'Running'", index.GetFilter()); - } - - [Fact] - public void AnAttemptCarriesTheTuningItUsedRatherThanTheCandidateItCameFrom() - { - using CarinaDbContext context = Carina(); - - IEntityType attempt = Entity(context); - - Assert.Equal( - ["scan_run"], - attempt.GetForeignKeys().Select(key => key.PrincipalEntityType.GetTableName())); - Assert.Contains( - ColumnsOf(attempt, nameof(ScanRunAttempt.Tuning)), - column => column == "tune_system"); - } - - [Fact] - public void EveryTableAProgrammeCanComeFromIsAValueTheDatabaseKnows() - { - using CarinaDbContext context = Carina(); - - ICheckConstraint check = Assert.Single( - Entity(context).GetCheckConstraints(), - constraint => constraint.Name == "ck_programme_source"); - - foreach (string source in Enum.GetNames()) - { - Assert.Contains($"'{source}'", check.Sql, StringComparison.Ordinal); - } - } - - [Fact] - public void EveryWayAVisitCanEndIsAValueTheDatabaseKnows() - { - using CarinaDbContext context = Carina(); - - ICheckConstraint check = Assert.Single( - Entity(context).GetCheckConstraints(), - constraint => constraint.Name == "ck_stream_visit_outcome"); - - foreach (string outcome in Enum.GetNames()) - { - Assert.Contains($"'{outcome}'", check.Sql, StringComparison.Ordinal); - } - } - - [Fact] - public void TheFourWaysOfFailingAreValuesTheDatabaseKnows() - { - using CarinaDbContext context = Carina(); - - ICheckConstraint check = Assert.Single( - Entity(context).GetCheckConstraints(), - constraint => constraint.Name == "ck_scan_run_attempt_outcome"); - - foreach (string outcome in Enum.GetNames()) - { - Assert.Contains($"'{outcome}'", check.Sql, StringComparison.Ordinal); - } - } - - [Fact] - public void AFailedOrCancelledScanCarriesAReasonTheDatabaseInsistsOn() - { - using CarinaDbContext context = Carina(); - - IEnumerable names = Entity(context).GetCheckConstraints().Select(constraint => constraint.Name); - - Assert.Contains("ck_scan_run_reason", names); - } - - [Fact] - public void ADefinitionThatCannotBeReceivedIsRefusedByTheDatabaseToo() - { - using CarinaDbContext context = Carina(); - - IEnumerable names = Entity(context).GetCheckConstraints().Select(constraint => constraint.Name); - - Assert.Contains("ck_candidate_channel_tuning", names); - } - - [Fact] - public void SelectionCarriesItsSourceAndTheReadingTakenAtTheTime() - { - using CarinaDbContext context = Carina(); - - Assert.Contains( - "selected_cnr_milli_decibels", - ColumnsOf(Entity(context), nameof(CandidateChannel.SelectionMeasurement))); - Assert.Contains("selection_source", Entity(context) - .GetProperties() - .Select(property => property.GetColumnName())); - } - - [Fact] - public void LeavingRotationIsAColumnRatherThanSomethingToInferFromLogs() - { - using CarinaDbContext context = Carina(); - - string[] columns = Entity(context) - .GetProperties() - .Select(property => property.GetColumnName()) - .ToArray(); - - Assert.Contains("rotation_state", columns); - Assert.Contains("consecutive_failures", columns); - Assert.Contains("next_attempt_at", columns); - Assert.Contains("needs_attention_since", columns); - Assert.Contains("needs_revalidation", columns); - } - - [Fact] - public void NoValueObjectOfThisDomainIsAnEntityInItsOwnRight() - { - using CarinaDbContext context = Carina(); - - Assert.DoesNotContain( - Schema(context).GetEntityTypes(), - entity => entity.FindOwnership() is not null); - } - - [Fact] - public void ATallyIsKeyedByTheStreamTheServiceAndTheTable() - { - using CarinaDbContext context = Carina(); - - IKey key = Entity(context).FindPrimaryKey()!; - - Assert.Equal( - ["network_id", "transport_stream_id", "service_id", "table_id"], - key.Properties.Select(property => property.GetColumnName())); - } - - [Fact] - public void ATallyGoesWithTheVisitItCounted() - { - using CarinaDbContext context = Carina(); - - IForeignKey foreignKey = Assert.Single(Entity(context).GetForeignKeys()); - - Assert.Equal("stream_visit", foreignKey.PrincipalEntityType.GetTableName()); - Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); - } - - [Fact] - public void EveryTableOfThisDomainIsNamedInSnakeCase() - { - using CarinaDbContext context = Carina(); - - Assert.Equal( - [ - "archived_programme", - "auth_session", - "broadcast_service", - "candidate_channel", - "collection_epoch", - "data_broadcast_settings", - "encode_auto_run", - "encode_chapter", - "encode_destination", - "encode_job", - "encode_profile", - "encode_scratch_file", - "integrity_check", - "integrity_finding", - "local_account", - "logo_visit", - "migration_channel_proposal", - "migration_detail", - "migration_loss", - "migration_rule_proposal", - "migration_run", - "migration_standing", - "migration_tally", - "notification_delivery", - "notification_destination", - "notification_event", - "notification_rule", - "notification_settings", - "notification_watch", - "oidc_config", - "playback_position", - "programme", - "quality_incident", - "quality_session_measurement", - "quality_signal_rollup", - "quality_signal_sample", - "quality_threshold", - "quality_threshold_change", - "recording", - "reservation", - "reservation_outcome", - "rule", - "satellite_transport_stream", - "scan_run", - "scan_run_attempt", - "segment_catalog_entry", - "segment_catalog_occurrence", - "segment_detection", - "segment_extraction", - "segment_learning_data", - "segment_learning_round", - "segment_model_version", - "segment_seek_event", - "segment_settings", - "segment_skip_event", - "service_reach_config", - "station_logo", - "stream_visit", - "stream_visit_tally", - ], - Schema(context).GetEntityTypes() - .Where(entity => entity.FindOwnership() is null) - .Select(entity => entity.GetTableName()) - .OfType() - .Order(StringComparer.Ordinal)); - } - - [Fact] - public void TheOnlyShapeReadFromAQueryRatherThanATableIsTheSearchAcrossBothLayers() - { - using CarinaDbContext context = Carina(); - - Assert.Equal( - [nameof(ProgrammeMatch)], - Schema(context).GetEntityTypes() - .Where(entity => entity.GetTableName() is null) - .Select(entity => entity.ClrType.Name) - .Order(StringComparer.Ordinal)); - } - - [Fact] - public void EveryTimeOfThisDomainGoesThroughTheUtcConverter() - { - using CarinaDbContext context = Carina(); - - IProperty[] times = Schema(context).GetEntityTypes() - .SelectMany(EveryProperty) - .Where(property => property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?)) - .ToArray(); - - Assert.NotEmpty(times); - Assert.All(times, property => Assert.IsType(property.GetValueConverter())); - } -} diff --git a/tests/Carina.Infrastructure.Tests/DatabaseBoundedReadTests.cs b/tests/Carina.Infrastructure.Tests/DbIntegration/Domain/Base/BoundedReadTests.cs similarity index 71% rename from tests/Carina.Infrastructure.Tests/DatabaseBoundedReadTests.cs rename to tests/Carina.Infrastructure.Tests/DbIntegration/Domain/Base/BoundedReadTests.cs index 3945ddc3b..d1ae3ecdc 100644 --- a/tests/Carina.Infrastructure.Tests/DatabaseBoundedReadTests.cs +++ b/tests/Carina.Infrastructure.Tests/DbIntegration/Domain/Base/BoundedReadTests.cs @@ -7,22 +7,30 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; -namespace Carina.Infrastructure.Tests; +namespace Carina.Infrastructure.Tests.DbIntegration.Domain.Base; [Collection(RepositoryDatabaseCollection.Name)] [Trait("Category", "DbIntegration")] -public sealed class DatabaseBoundedReadTests(RepositoryDatabase database) +public sealed class BoundedReadTests(RepositoryDatabase database) : IAsyncLifetime { private static readonly CancellationToken Cancel = CancellationToken.None; private static readonly DateTime At = new(2026, 9, 14, 0, 0, 0, DateTimeKind.Utc); + private readonly ServiceProvider container = database.Infrastructure(); + + public Task InitializeAsync() => Task.CompletedTask; + + public async Task DisposeAsync() => await container.DisposeAsync(); + [Fact] public async Task TheConnectionCarriesTheTimeTheStatementWasGivenWhileTheReadRuns() { - await using CarinaDbContext context = database.Open(); - var bounded = new DatabaseBoundedRead(context); + await using AsyncServiceScope scope = container.CreateAsyncScope(); + CarinaDbContext context = Context(scope); + IBoundedRead bounded = Bounded(scope); string shown = await bounded.NoLongerThanAsync( TimeSpan.FromSeconds(30), @@ -35,8 +43,9 @@ public async Task TheConnectionCarriesTheTimeTheStatementWasGivenWhileTheReadRun [Fact] public async Task TheTimeItWasGivenIsGoneAgainOnceTheReadIsOver() { - await using CarinaDbContext context = database.Open(); - var bounded = new DatabaseBoundedRead(context); + await using AsyncServiceScope scope = container.CreateAsyncScope(); + CarinaDbContext context = Context(scope); + IBoundedRead bounded = Bounded(scope); await bounded.NoLongerThanAsync( TimeSpan.FromSeconds(30), @@ -49,8 +58,9 @@ await bounded.NoLongerThanAsync( [Fact] public async Task AReadThatRunsPastTheTimeItWasGivenIsStopped() { - await using CarinaDbContext context = database.Open(); - var bounded = new DatabaseBoundedRead(context); + await using AsyncServiceScope scope = container.CreateAsyncScope(); + CarinaDbContext context = Context(scope); + IBoundedRead bounded = Bounded(scope); ReadTookTooLongException stopped = await Assert.ThrowsAsync( () => bounded.NoLongerThanAsync( @@ -64,8 +74,9 @@ public async Task AReadThatRunsPastTheTimeItWasGivenIsStopped() [Fact] public async Task TheConnectionIsUsableAgainAfterAReadWasStopped() { - await using CarinaDbContext context = database.Open(); - var bounded = new DatabaseBoundedRead(context); + await using AsyncServiceScope scope = container.CreateAsyncScope(); + CarinaDbContext context = Context(scope); + IBoundedRead bounded = Bounded(scope); await Assert.ThrowsAsync( () => bounded.NoLongerThanAsync( @@ -84,11 +95,11 @@ await bounded.NoLongerThanAsync( [Fact] public async Task WhatTheReadFoundIsWhatComesBack() { - await using CarinaDbContext context = database.Open(); + await using AsyncServiceScope scope = container.CreateAsyncScope(); Assert.Equal( 7, - await new DatabaseBoundedRead(context).NoLongerThanAsync( + await Bounded(scope).NoLongerThanAsync( TimeSpan.FromSeconds(30), _ => Task.FromResult(7), Cancel)); @@ -97,10 +108,10 @@ public async Task WhatTheReadFoundIsWhatComesBack() [Fact] public async Task AReadGivenNoTimeAtAllIsRefusedBeforeTheStoreIsTouched() { - await using CarinaDbContext context = database.Open(); + await using AsyncServiceScope scope = container.CreateAsyncScope(); await Assert.ThrowsAsync( - () => new DatabaseBoundedRead(context).NoLongerThanAsync( + () => Bounded(scope).NoLongerThanAsync( TimeSpan.Zero, _ => Task.FromResult(0), Cancel)); @@ -109,10 +120,13 @@ await Assert.ThrowsAsync( [Fact] public async Task AWriteInsideTheReadThatRanOutOfTimeIsStoppedTheSameWay() { - await using CarinaDbContext context = database.Open(new SlowedInserts()); + await using ServiceProvider slowed = database.Infrastructure(services => services.ConfigureDbContext( + options => options.AddInterceptors(new SlowedInserts()))); + await using AsyncServiceScope scope = slowed.CreateAsyncScope(); + CarinaDbContext context = Context(scope); ReadTookTooLongException stopped = await Assert.ThrowsAsync( - () => new DatabaseBoundedRead(context).NoLongerThanAsync( + () => Bounded(scope).NoLongerThanAsync( TimeSpan.FromMilliseconds(200), cancellationToken => Begun(context, cancellationToken), Cancel)); @@ -124,11 +138,12 @@ public async Task AWriteInsideTheReadThatRanOutOfTimeIsStoppedTheSameWay() [Fact] public async Task AReaderWhoWentAwayIsNotReadAsAStoreThatTookTooLong() { - await using CarinaDbContext context = database.Open(); + await using AsyncServiceScope scope = container.CreateAsyncScope(); + CarinaDbContext context = Context(scope); using var goingAway = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); await Assert.ThrowsAnyAsync( - () => new DatabaseBoundedRead(context).NoLongerThanAsync( + () => Bounded(scope).NoLongerThanAsync( TimeSpan.FromSeconds(30), cancellationToken => context.Database.ExecuteSqlRawAsync("SELECT pg_sleep(5)", cancellationToken), goingAway.Token)); @@ -137,16 +152,23 @@ await Assert.ThrowsAnyAsync( [Fact] public async Task AReadStartedWhileTheStoreIsAlreadyInATransactionIsRefused() { - await using CarinaDbContext context = database.Open(); + await using AsyncServiceScope scope = container.CreateAsyncScope(); + CarinaDbContext context = Context(scope); await using IDbContextTransaction already = await context.Database.BeginTransactionAsync(Cancel); await Assert.ThrowsAsync( - () => new DatabaseBoundedRead(context).NoLongerThanAsync( + () => Bounded(scope).NoLongerThanAsync( TimeSpan.FromSeconds(30), _ => Task.FromResult(0), Cancel)); } + private static CarinaDbContext Context(AsyncServiceScope scope) + => scope.ServiceProvider.GetRequiredService(); + + private static IBoundedRead Bounded(AsyncServiceScope scope) + => scope.ServiceProvider.GetRequiredService(); + private static async Task Begun(CarinaDbContext context, CancellationToken cancellationToken) { await context.Set().AddAsync(CollectionEpoch.Begin(At), cancellationToken); diff --git a/tests/Carina.Infrastructure.Tests/Fixtures/Persistence/CarinaModel.cs b/tests/Carina.Infrastructure.Tests/Fixtures/Persistence/CarinaModel.cs new file mode 100644 index 000000000..c74ead641 --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Fixtures/Persistence/CarinaModel.cs @@ -0,0 +1,42 @@ +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace Carina.Infrastructure.Tests.Fixtures.Persistence; + +internal static class CarinaModel +{ + private const string Placeholder = "Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"; + + public static DbContextOptions Options() + { + var builder = new DbContextOptionsBuilder(); + builder.UseCarinaDatabase(Placeholder); + + return builder.Options; + } + + public static CarinaDbContext Context() => new(Options()); + + public static IModel Schema(CarinaDbContext context) + => context.GetService().Model; + + public static IEntityType Entity(CarinaDbContext context) + => Schema(context).FindEntityType(typeof(TEntity))!; + + // Tuning and the signal readings are complex properties rather than owned entities: + // they carry no identity, so two rows may hold the very same instance. + public static IEnumerable ColumnsOf(IEntityType entity, string valueObject) + => entity.GetComplexProperties() + .Single(property => property.Name == valueObject) + .ComplexType.GetProperties() + .Select(property => property.GetColumnName()); + + public static IEnumerable EveryProperty(ITypeBase type) + => [ + .. type.GetProperties(), + .. type.GetComplexProperties().SelectMany(property => EveryProperty(property.ComplexType)), + ]; +} diff --git a/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleSelfCheckTests.cs b/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleSelfCheckTests.cs index f48174a39..83467e4f5 100644 --- a/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleSelfCheckTests.cs +++ b/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleSelfCheckTests.cs @@ -4,6 +4,7 @@ using Carina.Infrastructure.Tests.Fixtures.Library; using Carina.Infrastructure.Tests.Fixtures.Migration; using Carina.Infrastructure.Tests.Fixtures.Notifications; +using Carina.Infrastructure.Tests.Fixtures.Persistence; using Carina.Infrastructure.Tests.Fixtures.Programmes; using Carina.Infrastructure.Tests.Fixtures.Quality; using Carina.Infrastructure.Tests.Fixtures.Recordings; @@ -56,13 +57,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } - private static ViolatingDbContext Violating() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase("Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"); - - return new ViolatingDbContext(builder.Options); - } + private static ViolatingDbContext Violating() => new(CarinaModel.Options()); [Fact] public void DetectsAReservationThatHoldsAForeignKeyToAChannelDefinition() diff --git a/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleTests.cs b/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleTests.cs index 1ccbb3389..5c3151873 100644 --- a/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleTests.cs +++ b/tests/Carina.Infrastructure.Tests/PersistenceBoundaryRuleTests.cs @@ -4,22 +4,16 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + namespace Carina.Infrastructure.Tests; public sealed class PersistenceBoundaryRuleTests { - private static CarinaDbContext Carina() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase("Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"); - - return new CarinaDbContext(builder.Options); - } - [Fact] public void TheCarinaModelDeclaresNoBoundaryBreakingForeignKeys() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Empty(PersistenceBoundaryRules.BoundaryBreakingForeignKeys(context.Model)); } @@ -27,7 +21,7 @@ public void TheCarinaModelDeclaresNoBoundaryBreakingForeignKeys() [Fact] public void EveryEntityInTheCarinaModelDeclaresWhichFamilyItBelongsTo() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Empty(PersistenceBoundaryRules.UnclassifiedEntityTypes(context.Model)); } @@ -35,7 +29,7 @@ public void EveryEntityInTheCarinaModelDeclaresWhichFamilyItBelongsTo() [Fact] public void BothSidesOfTheReservationBoundaryAreInTheModelForTheRuleToWeigh() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( ["reservation", "reservation_outcome", "rule"], @@ -48,7 +42,7 @@ public void BothSidesOfTheReservationBoundaryAreInTheModelForTheRuleToWeigh() [Fact] public void TheLedgerIsInTheModelForThoseRulesToWeigh() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( ["recording"], @@ -58,7 +52,7 @@ public void TheLedgerIsInTheModelForThoseRulesToWeigh() [Fact] public void WhatTheLedgerCheckWritesIsItsOwnFamilyAndHoldsNoKeyIntoTheLedger() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( ["integrity_check", "integrity_finding"], @@ -76,7 +70,7 @@ public void WhatTheLedgerCheckWritesIsItsOwnFamilyAndHoldsNoKeyIntoTheLedger() [Fact(DisplayName = "the encode ledger is six tables, and its foreign keys never leave it")] public void TheEncodeLedgerIsSixTablesAndItsForeignKeysNeverLeaveIt() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( ["encode_auto_run", "encode_chapter", "encode_destination", "encode_job", "encode_profile", "encode_scratch_file"], @@ -103,7 +97,7 @@ public void TheEncodeLedgerIsSixTablesAndItsForeignKeysNeverLeaveIt() [Fact(DisplayName = "an encode job reaches the recording it encodes by value, not by key")] public void AnEncodeJobReachesTheRecordingItEncodesByValue() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IEntityType job = context.Model.GetEntityTypes().Single(entityType => entityType.GetTableName() == "encode_job"); @@ -114,7 +108,7 @@ public void AnEncodeJobReachesTheRecordingItEncodesByValue() [Fact] public void ARecordingStillReachesTheServiceAndTheProgrammeItRecordedByValue() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IReadOnlyList columns = [.. context.Model .GetEntityTypes() @@ -132,7 +126,7 @@ public void ARecordingStillReachesTheServiceAndTheProgrammeItRecordedByValue() [Fact] public void AReservationStillReachesTheServiceItRecordsByValue() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IReadOnlyList columns = [.. context.Model .GetEntityTypes() @@ -149,7 +143,7 @@ public void AReservationStillReachesTheServiceItRecordsByValue() [Fact(DisplayName = "the quality tables are six, and none of them holds a key into another domain")] public void TheQualityTablesAreSixAndNoneOfThemHoldsAKeyIntoAnotherDomain() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( [ @@ -171,7 +165,7 @@ public void TheQualityTablesAreSixAndNoneOfThemHoldsAKeyIntoAnotherDomain() [Fact(DisplayName = "BR-ND-009: the notification tables are six and the only keys they hold run from a delivery to its event and its destination")] public void TheNotificationTablesAreSixAndNoneOfThemHoldsAKeyIntoAnotherDomain() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( [ @@ -200,7 +194,7 @@ public void TheNotificationTablesAreSixAndNoneOfThemHoldsAKeyIntoAnotherDomain() [Fact(DisplayName = "what quality watches it reaches by value, so dropping its tables drags nothing away")] public void WhatQualityWatchesItReachesByValue() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IReadOnlyList columns = [.. context.Model .GetEntityTypes() @@ -218,7 +212,7 @@ public void WhatQualityWatchesItReachesByValue() [Fact] public void WhatTheMigrationRecordsIsSevenTablesAndItsForeignKeysNeverLeaveIt() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( [ @@ -255,7 +249,7 @@ public void WhatTheMigrationRecordsIsSevenTablesAndItsForeignKeysNeverLeaveIt() [Fact(DisplayName = "where the watching got to reaches the recording by value, holding no key into the ledger")] public void WhereTheWatchingGotToReachesTheRecordingByValue() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( ["playback_position"], @@ -275,7 +269,7 @@ public void WhereTheWatchingGotToReachesTheRecordingByValue() [Fact(DisplayName = "BR-CD-002: the segment tables are the learning data, the settings, the catalog, the versions of the model, the detections, the skip events, the seeks and the rounds of learning taken, and the only keys among them are a stretch's into its entry and a detection's and a skip event's into their version")] public void TheSegmentTablesHoldNoKeyIntoAnotherDomain() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( [ @@ -309,7 +303,7 @@ public void TheSegmentTablesHoldNoKeyIntoAnotherDomain() [Fact(DisplayName = "BR-BD-016: the data broadcast keeps one table, its settings, which holds no key and is held by none")] public void TheDataBroadcastKeepsOneTableWithNoKey() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( ["data_broadcast_settings"], @@ -329,7 +323,7 @@ public void TheDataBroadcastKeepsOneTableWithNoKey() [InlineData("segment_seek_event")] public void TheLearningDataReachesTheRecordingByValue(string table) { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IEntityType learning = context.Model.GetEntityTypes().Single(entityType => entityType.GetTableName() == table); @@ -343,7 +337,7 @@ public void TheLearningDataReachesTheRecordingByValue(string table) [Fact(DisplayName = "the room the learning data takes is measured over every segment table, and over no other")] public void TheRoomTheLearningDataTakesIsMeasuredOverEverySegmentTable() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Equal( PersistenceBoundaryRules.TablesOf(context.Model, PersistenceFamily.Segments), @@ -353,7 +347,7 @@ public void TheRoomTheLearningDataTakesIsMeasuredOverEverySegmentTable() [Fact] public void WhatCouldNotBeMigratedIsNeverCountedByAnotherDomain() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.DoesNotContain( context.Model.GetEntityTypes().SelectMany(entityType => entityType.GetForeignKeys()), diff --git a/tests/Carina.Infrastructure.Tests/RecordingKeylessRuleTests.cs b/tests/Carina.Infrastructure.Tests/RecordingKeylessRuleTests.cs index a3fc4f013..c319cfd2e 100644 --- a/tests/Carina.Infrastructure.Tests/RecordingKeylessRuleTests.cs +++ b/tests/Carina.Infrastructure.Tests/RecordingKeylessRuleTests.cs @@ -3,6 +3,8 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + namespace Carina.Infrastructure.Tests; public sealed class RecordingKeylessRuleTests @@ -16,21 +18,13 @@ public sealed class RecordingKeylessRuleTests "programme", ]; - private static CarinaDbContext Carina() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase("Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"); - - return new CarinaDbContext(builder.Options); - } - private static IEntityType TableOf(CarinaDbContext context, string table) => context.Model.GetEntityTypes().Single(entityType => entityType.GetTableName() == table); [Fact(DisplayName = "the ledger declares no foreign key at all")] public void TheLedgerDeclaresNoForeignKeyAtAll() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Empty(TableOf(context, Ledger) .GetForeignKeys() @@ -41,7 +35,7 @@ public void TheLedgerDeclaresNoForeignKeyAtAll() [Fact(DisplayName = "rebuilding the guide or dropping a channel definition drags no recording away")] public void RebuildingTheGuideOrDroppingAChannelDefinitionDragsNoRecordingAway() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); Assert.Empty(context.Model .GetEntityTypes() @@ -55,7 +49,7 @@ public void RebuildingTheGuideOrDroppingAChannelDefinitionDragsNoRecordingAway() [Fact(DisplayName = "the three tables it must not point at are in the model, for the rule to have weighed them")] public void TheThreeTablesItMustNotPointAtAreInTheModel() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IReadOnlyList tables = [.. context.Model .GetEntityTypes() @@ -72,7 +66,7 @@ public void TheThreeTablesItMustNotPointAtAreInTheModel() [Fact(DisplayName = "what the ledger keeps of the guide is a copy it took, not a key it holds")] public void WhatTheLedgerKeepsOfTheGuideIsACopyItTook() { - using CarinaDbContext context = Carina(); + using CarinaDbContext context = Context(); IReadOnlyList columns = [.. TableOf(context, Ledger) .GetProperties() diff --git a/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleSelfCheckTests.cs b/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleSelfCheckTests.cs index e9efa72a3..910de94bd 100644 --- a/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleSelfCheckTests.cs +++ b/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleSelfCheckTests.cs @@ -1,5 +1,6 @@ using Carina.Domain.Reservations; using Carina.Infrastructure.Persistence; +using Carina.Infrastructure.Tests.Fixtures.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; @@ -35,7 +36,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [Fact] public void DetectsAReservationThatCanWriteTheClaimOnInsert() { - using var context = new ClaimWritingDbContext(ReservationModel.Options()); + using var context = new ClaimWritingDbContext(CarinaModel.Options()); Assert.Equal( ["reservation.started_at"], @@ -45,7 +46,7 @@ public void DetectsAReservationThatCanWriteTheClaimOnInsert() [Fact] public void DetectsAReservationThatCanWriteTheOutcomeOnUpdate() { - using var context = new OutcomeWritingDbContext(ReservationModel.Options()); + using var context = new OutcomeWritingDbContext(CarinaModel.Options()); Assert.Equal( ["reservation.recording_outcome"], @@ -55,7 +56,7 @@ public void DetectsAReservationThatCanWriteTheOutcomeOnUpdate() [Fact] public void FindsBothColumnsInEitherModelSoAnEmptyAnswerIsNeverAnEmptySearch() { - using var context = new ClaimWritingDbContext(ReservationModel.Options()); + using var context = new ClaimWritingDbContext(CarinaModel.Options()); Assert.Equal( ["reservation.recording_outcome", "reservation.started_at"], diff --git a/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleTests.cs b/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleTests.cs index 03b17e5c5..4818763b8 100644 --- a/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleTests.cs +++ b/tests/Carina.Infrastructure.Tests/RecordingOwnedColumnRuleTests.cs @@ -1,4 +1,5 @@ using Carina.Infrastructure.Persistence; +using Carina.Infrastructure.Tests.Fixtures.Persistence; using Microsoft.EntityFrameworkCore; @@ -9,7 +10,7 @@ public sealed class RecordingOwnedColumnRuleTests [Fact] public void TheReservationCannotWriteTheClaimOrTheOutcomeThroughTheChangeTracker() { - using CarinaDbContext context = ReservationModel.Carina(); + using CarinaDbContext context = CarinaModel.Context(); Assert.Empty(RecordingOwnedColumnRules.WritableThroughTheChangeTracker(context.Model)); } @@ -17,7 +18,7 @@ public void TheReservationCannotWriteTheClaimOrTheOutcomeThroughTheChangeTracker [Fact] public void ThoseColumnsAreOnTheReservationForTheRuleToFind() { - using CarinaDbContext context = ReservationModel.Carina(); + using CarinaDbContext context = CarinaModel.Context(); Assert.Equal( ["reservation.recording_outcome", "reservation.started_at"], @@ -27,7 +28,7 @@ public void ThoseColumnsAreOnTheReservationForTheRuleToFind() [Fact] public void TheLedgerKeepsItsOwnOutcomeColumnRatherThanBorrowingTheReservationsOne() { - using CarinaDbContext context = ReservationModel.Carina(); + using CarinaDbContext context = CarinaModel.Context(); Assert.DoesNotContain( "reservation_outcome.recording_outcome", diff --git a/tests/Carina.Infrastructure.Tests/ReservationModel.cs b/tests/Carina.Infrastructure.Tests/ReservationModel.cs deleted file mode 100644 index 7ac12e484..000000000 --- a/tests/Carina.Infrastructure.Tests/ReservationModel.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Carina.Infrastructure.Persistence; - -using Microsoft.EntityFrameworkCore; - -namespace Carina.Infrastructure.Tests; - -internal static class ReservationModel -{ - private const string Placeholder = "Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"; - - public static DbContextOptions Options() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase(Placeholder); - - return builder.Options; - } - - public static CarinaDbContext Carina() => new(Options()); -} diff --git a/tests/Carina.Infrastructure.Tests/SharedValueObjectTrackingTests.cs b/tests/Carina.Infrastructure.Tests/SharedValueObjectTrackingTests.cs deleted file mode 100644 index 07acd524d..000000000 --- a/tests/Carina.Infrastructure.Tests/SharedValueObjectTrackingTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Carina.Domain.Channels; -using Carina.Domain.Scans; -using Carina.Infrastructure.Persistence; - -using Microsoft.EntityFrameworkCore; - -namespace Carina.Infrastructure.Tests; - -public sealed class SharedValueObjectTrackingTests -{ - private static readonly DateTime At = new(2026, 8, 15, 0, 0, 0, DateTimeKind.Utc); - - private static CarinaDbContext Carina() - { - var builder = new DbContextOptionsBuilder(); - builder.UseCarinaDatabase("Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"); - - return new CarinaDbContext(builder.Options); - } - - [Fact] - public void TwoCandidatesMayBeTunedByTheVerySameParameters() - { - using CarinaDbContext context = Carina(); - var carrying = TuningParameters.Terrestrial(27); - - context.Attach(Candidate(1, carrying)); - - context.Add(Candidate(2, carrying)); - - Assert.Equal(2, context.ChangeTracker.Entries().Count()); - } - - [Fact] - public void TwoCandidatesMayCarryTheVerySameReading() - { - using CarinaDbContext context = Carina(); - var measured = SignalMeasurement.WithLock(At, 21_000); - CandidateChannel first = Candidate(1, TuningParameters.Terrestrial(27)); - CandidateChannel second = Candidate(2, TuningParameters.Terrestrial(27)); - first.RecordTuningSuccess(measured, At); - second.RecordTuningSuccess(measured, At); - context.Attach(first); - - context.Add(second); - - Assert.Equal(2, context.ChangeTracker.Entries().Count()); - } - - [Fact] - public void TwoAttemptsMayBeTunedByTheVerySameParametersAndCarryTheVerySameReading() - { - using CarinaDbContext context = Carina(); - var carrying = TuningParameters.Terrestrial(27); - var measured = SignalMeasurement.WithLock(At, 21_000); - context.Attach(Attempt(carrying, measured)); - - context.Add(Attempt(carrying, measured)); - - Assert.Equal(2, context.ChangeTracker.Entries().Count()); - } - - [Fact] - public void OneReadingMayBeKeptByBothAnAttemptAndACandidateAtOnce() - { - using CarinaDbContext context = Carina(); - var measured = SignalMeasurement.WithLock(At, 21_000); - CandidateChannel candidate = Candidate(1, TuningParameters.Terrestrial(27)); - candidate.RecordTuningSuccess(measured, At); - context.Attach(Attempt(TuningParameters.Terrestrial(27), measured)); - - context.Add(candidate); - - Assert.Single(context.ChangeTracker.Entries()); - } - - private static CandidateChannel Candidate(int service, TuningParameters carrying) - => CandidateChannel.Discover( - CandidateChannelId.New(), - new NetworkId(1), - new ServiceId(service), - carrying, - At); - - private static ScanRunAttempt Attempt(TuningParameters carrying, SignalMeasurement measured) - => ScanRunAttempt.Rehydrate( - ScanRunAttemptId.New(), - ScanRunId.New(), - carrying, - ScanAttemptOutcome.Succeeded, - measured, - null, - null, - At, - At); -} diff --git a/tests/Carina.Infrastructure.Tests/Configuration/CaptionOptionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/CaptionOptionsTests.cs similarity index 96% rename from tests/Carina.Infrastructure.Tests/Configuration/CaptionOptionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/CaptionOptionsTests.cs index 404239f9e..1cf2f364d 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/CaptionOptionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/CaptionOptionsTests.cs @@ -3,8 +3,9 @@ using Microsoft.Extensions.Configuration; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Configuration; +[Trait("Category", "Unit")] public sealed class CaptionOptionsTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Configuration/CollectionOptionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/CollectionOptionsTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Configuration/CollectionOptionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/CollectionOptionsTests.cs index 3f24443eb..89168379a 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/CollectionOptionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/CollectionOptionsTests.cs @@ -8,8 +8,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Configuration; +[Trait("Category", "Unit")] public sealed class CollectionOptionsTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Configuration/MachineOptionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/MachineOptionsTests.cs similarity index 96% rename from tests/Carina.Infrastructure.Tests/Configuration/MachineOptionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/MachineOptionsTests.cs index 1e3108e8e..c63f7bd99 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/MachineOptionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/MachineOptionsTests.cs @@ -4,8 +4,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Configuration; +[Trait("Category", "Unit")] public sealed class MachineOptionsTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Configuration/ProgrammeFeedOptionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/ProgrammeFeedOptionsTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Configuration/ProgrammeFeedOptionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/ProgrammeFeedOptionsTests.cs index 7f2cb4bde..5730203d9 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/ProgrammeFeedOptionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/ProgrammeFeedOptionsTests.cs @@ -4,8 +4,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Configuration; +[Trait("Category", "Unit")] public sealed class ProgrammeFeedOptionsTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Configuration/ThumbnailOptionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/ThumbnailOptionsTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Configuration/ThumbnailOptionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/ThumbnailOptionsTests.cs index 2d23d4f09..867e1919a 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/ThumbnailOptionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/ThumbnailOptionsTests.cs @@ -3,8 +3,9 @@ using Microsoft.Extensions.Configuration; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Configuration; +[Trait("Category", "Unit")] public sealed class ThumbnailOptionsTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Configuration/TranscodingOptionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/TranscodingOptionsTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Configuration/TranscodingOptionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/TranscodingOptionsTests.cs index 53ec7e7e8..b7b2a63c8 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/TranscodingOptionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Configuration/TranscodingOptionsTests.cs @@ -4,8 +4,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Configuration; +[Trait("Category", "Unit")] public sealed class TranscodingOptionsTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/ServiceCollectionExtensionsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/DependencyInjection/ServiceCollectionExtensionsTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/ServiceCollectionExtensionsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/DependencyInjection/ServiceCollectionExtensionsTests.cs index 8230164c0..e8ff842df 100644 --- a/tests/Carina.Infrastructure.Tests/ServiceCollectionExtensionsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/DependencyInjection/ServiceCollectionExtensionsTests.cs @@ -47,8 +47,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests; +namespace Carina.Infrastructure.Tests.Unit.Infra.DependencyInjection; +[Trait("Category", "Unit")] public sealed class ServiceCollectionExtensionsTests { private const string ConnectionString = "Host=db;Port=5432;Database=carina;Username=carina;Password=placeholder"; diff --git a/tests/Carina.Infrastructure.Tests/Configuration/OneCardValidationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Encodings/OneCardValidationTests.cs similarity index 95% rename from tests/Carina.Infrastructure.Tests/Configuration/OneCardValidationTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Encodings/OneCardValidationTests.cs index f01269c99..8425c1e86 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/OneCardValidationTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Encodings/OneCardValidationTests.cs @@ -3,8 +3,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Encodings; +[Trait("Category", "Unit")] public sealed class OneCardValidationTests { [Theory] diff --git a/tests/Carina.Infrastructure.Tests/Configuration/RootsHeldApartValidationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Encodings/RootsHeldApartValidationTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Configuration/RootsHeldApartValidationTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Encodings/RootsHeldApartValidationTests.cs index 279a6dc31..ec535b96e 100644 --- a/tests/Carina.Infrastructure.Tests/Configuration/RootsHeldApartValidationTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Encodings/RootsHeldApartValidationTests.cs @@ -3,8 +3,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace Carina.Infrastructure.Tests.Configuration; +namespace Carina.Infrastructure.Tests.Unit.Infra.Encodings; +[Trait("Category", "Unit")] public sealed class RootsHeldApartValidationTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventHubLifetimeTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventHubLifetimeTests.cs new file mode 100644 index 000000000..cdf0530c6 --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventHubLifetimeTests.cs @@ -0,0 +1,26 @@ +using Carina.Infrastructure.Events; + +using Puppis.Contracts; + +using static Carina.Infrastructure.Tests.Unit.Infra.Events.AppEventListening; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Events; + +[Trait("Category", "Unit")] +public sealed class AppEventHubLifetimeTests +{ + [Fact] + public async Task StoppingTheAppClosesTheHubSoNoListenerIsLeftHanging() + { + var hub = new AppEventHub(); + var lifetime = new AppEventHubLifetime(hub); + + Assert.True(hub.TryListen(out AppEventListener? listener)); + + Task> waiting = Next(listener); + await lifetime.StopAsync(CancellationToken.None); + + Assert.True(hub.IsClosed); + await Assert.ThrowsAnyAsync(() => waiting); + } +} diff --git a/tests/Carina.Infrastructure.Tests/AppEventHubTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventHubTests.cs similarity index 78% rename from tests/Carina.Infrastructure.Tests/AppEventHubTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventHubTests.cs index ca5a74753..c4431f331 100644 --- a/tests/Carina.Infrastructure.Tests/AppEventHubTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventHubTests.cs @@ -2,19 +2,13 @@ using Puppis.Contracts; -namespace Carina.Infrastructure.Tests; +using static Carina.Infrastructure.Tests.Unit.Infra.Events.AppEventListening; +namespace Carina.Infrastructure.Tests.Unit.Infra.Events; + +[Trait("Category", "Unit")] public sealed class AppEventHubTests { - private static readonly TimeSpan Soon = TimeSpan.FromSeconds(10); - - private static async Task> Next(AppEventListener listener) - { - using var deadline = new CancellationTokenSource(Soon); - - return await listener.TakeAsync(deadline.Token); - } - [Fact] public async Task ASignalReachesEveryListener() { @@ -114,21 +108,6 @@ public void AClosedHubTakesNoFurtherListeners() Assert.False(hub.TryListen(out _)); } - [Fact] - public async Task StoppingTheAppClosesTheHubSoNoListenerIsLeftHanging() - { - var hub = new AppEventHub(); - var lifetime = new AppEventHubLifetime(hub); - - Assert.True(hub.TryListen(out AppEventListener? listener)); - - Task> waiting = Next(listener); - await lifetime.StopAsync(CancellationToken.None); - - Assert.True(hub.IsClosed); - await Assert.ThrowsAnyAsync(() => waiting); - } - [Fact] public async Task ClosingTheHubEndsTheWaitOfAListenerAlreadyInside() { diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventListening.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventListening.cs new file mode 100644 index 000000000..331fb6725 --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Events/AppEventListening.cs @@ -0,0 +1,17 @@ +using Carina.Infrastructure.Events; + +using Puppis.Contracts; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Events; + +internal static class AppEventListening +{ + private static readonly TimeSpan Soon = TimeSpan.FromSeconds(10); + + public static async Task> Next(AppEventListener listener) + { + using var deadline = new CancellationTokenSource(Soon); + + return await listener.TakeAsync(deadline.Token); + } +} diff --git a/tests/Carina.Infrastructure.Tests/Net/PublicAddressesTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Net/PublicAddressesTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Net/PublicAddressesTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Net/PublicAddressesTests.cs index 02e3af1fd..9cfa76be5 100644 --- a/tests/Carina.Infrastructure.Tests/Net/PublicAddressesTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Net/PublicAddressesTests.cs @@ -3,8 +3,9 @@ using Carina.Infrastructure.DataBroadcast; using Carina.Infrastructure.Net; -namespace Carina.Infrastructure.Tests.Net; +namespace Carina.Infrastructure.Tests.Unit.Infra.Net; +[Trait("Category", "Unit")] public sealed class PublicAddressesTests { [Theory(DisplayName = "BR-BD-011: an address on this machine, on the networks around it or kept for something else is not public")] diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/BroadcastServiceConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/BroadcastServiceConfigurationTests.cs new file mode 100644 index 000000000..ca45c946c --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/BroadcastServiceConfigurationTests.cs @@ -0,0 +1,25 @@ +using Carina.Domain.Channels; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class BroadcastServiceConfigurationTests +{ + [Fact] + public void AServiceIsKeyedByItsBroadcastIdentifiersAlone() + { + using CarinaDbContext context = Context(); + + IKey key = Entity(context).FindPrimaryKey()!; + + Assert.Equal( + ["network_id", "service_id"], + key.Properties.Select(property => property.GetColumnName())); + } +} diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/CandidateChannelConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/CandidateChannelConfigurationTests.cs new file mode 100644 index 000000000..0c29ee871 --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/CandidateChannelConfigurationTests.cs @@ -0,0 +1,103 @@ +using Carina.Domain.Channels; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class CandidateChannelConfigurationTests +{ + [Fact(DisplayName = "a candidate keeps its latest score as one reading, not a history of them")] + public void ACandidateKeepsItsLatestScoreAsOneReading() + { + using CarinaDbContext context = Context(); + IEntityType candidate = Entity(context); + + Assert.Equal( + [ + "score_bit_error_rate_highest", + "score_cnr_lowest_milli_decibels", + "score_evaluated_at", + "score_lock_rate", + "score_measured_from", + "score_measured_until", + "score_samples", + ], + ColumnsOf(candidate, nameof(CandidateChannel.Score)).Order(StringComparer.Ordinal)); + Assert.Contains("ck_candidate_channel_score", candidate.GetCheckConstraints().Select(check => check.Name)); + } + + [Fact] + public void ACandidateChannelPointsAtItsServiceAndNothingPointsBack() + { + using CarinaDbContext context = Context(); + + IForeignKey foreignKey = Assert.Single(Entity(context).GetForeignKeys()); + + Assert.Equal("broadcast_service", foreignKey.PrincipalEntityType.GetTableName()); + Assert.Equal( + ["network_id", "service_id"], + foreignKey.Properties.Select(property => property.GetColumnName())); + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + } + + [Fact] + public void OnlyOneCandidatePerServiceCanBeSelected() + { + using CarinaDbContext context = Context(); + + IIndex index = Assert.Single( + Entity(context).GetIndexes(), + candidate => candidate.GetDatabaseName() == "ux_candidate_channel_selected"); + + Assert.True(index.IsUnique); + Assert.Equal("is_selected", index.GetFilter()); + Assert.Equal( + ["network_id", "service_id"], + index.Properties.Select(property => property.GetColumnName())); + } + + [Fact] + public void ADefinitionThatCannotBeReceivedIsRefusedByTheDatabaseToo() + { + using CarinaDbContext context = Context(); + + IEnumerable names = Entity(context).GetCheckConstraints().Select(constraint => constraint.Name); + + Assert.Contains("ck_candidate_channel_tuning", names); + } + + [Fact] + public void SelectionCarriesItsSourceAndTheReadingTakenAtTheTime() + { + using CarinaDbContext context = Context(); + + Assert.Contains( + "selected_cnr_milli_decibels", + ColumnsOf(Entity(context), nameof(CandidateChannel.SelectionMeasurement))); + Assert.Contains("selection_source", Entity(context) + .GetProperties() + .Select(property => property.GetColumnName())); + } + + [Fact] + public void LeavingRotationIsAColumnRatherThanSomethingToInferFromLogs() + { + using CarinaDbContext context = Context(); + + string[] columns = Entity(context) + .GetProperties() + .Select(property => property.GetColumnName()) + .ToArray(); + + Assert.Contains("rotation_state", columns); + Assert.Contains("consecutive_failures", columns); + Assert.Contains("next_attempt_at", columns); + Assert.Contains("needs_attention_since", columns); + Assert.Contains("needs_revalidation", columns); + } +} diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/CarinaDbContextTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/CarinaDbContextTests.cs new file mode 100644 index 000000000..49201d82c --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/CarinaDbContextTests.cs @@ -0,0 +1,242 @@ +using Carina.Domain.Channels; +using Carina.Domain.Programmes; +using Carina.Domain.Scans; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +internal sealed class ConventionProbe +{ + public int Id { get; set; } + public DateTime RecordedAt { get; set; } +} + +[Trait("Category", "Unit")] +public sealed class CarinaDbContextTests +{ + private static readonly DateTime At = new(2026, 8, 15, 0, 0, 0, DateTimeKind.Utc); + + [Fact] + public void NamesTablesAndColumnsInSnakeCase() + { + using ProbeDbContext context = Probe(); + + IEntityType entity = context.Model.FindEntityType(typeof(ConventionProbe))!; + + Assert.Equal("convention_probe", entity.GetTableName()); + Assert.Equal("recorded_at", entity.FindProperty(nameof(ConventionProbe.RecordedAt))!.GetColumnName()); + } + + [Fact] + public void RoutesEveryDateTimeThroughTheUtcConverter() + { + using ProbeDbContext context = Probe(); + + IProperty property = context.Model.FindEntityType(typeof(ConventionProbe))! + .FindProperty(nameof(ConventionProbe.RecordedAt))!; + + Assert.IsType(property.GetValueConverter()); + } + + [Fact] + public void NoValueObjectOfThisDomainIsAnEntityInItsOwnRight() + { + using CarinaDbContext context = Context(); + + Assert.DoesNotContain( + Schema(context).GetEntityTypes(), + entity => entity.FindOwnership() is not null); + } + + [Fact] + public void EveryTableOfThisDomainIsNamedInSnakeCase() + { + using CarinaDbContext context = Context(); + + Assert.Equal( + [ + "archived_programme", + "auth_session", + "broadcast_service", + "candidate_channel", + "collection_epoch", + "data_broadcast_settings", + "encode_auto_run", + "encode_chapter", + "encode_destination", + "encode_job", + "encode_profile", + "encode_scratch_file", + "integrity_check", + "integrity_finding", + "local_account", + "logo_visit", + "migration_channel_proposal", + "migration_detail", + "migration_loss", + "migration_rule_proposal", + "migration_run", + "migration_standing", + "migration_tally", + "notification_delivery", + "notification_destination", + "notification_event", + "notification_rule", + "notification_settings", + "notification_watch", + "oidc_config", + "playback_position", + "programme", + "quality_incident", + "quality_session_measurement", + "quality_signal_rollup", + "quality_signal_sample", + "quality_threshold", + "quality_threshold_change", + "recording", + "reservation", + "reservation_outcome", + "rule", + "satellite_transport_stream", + "scan_run", + "scan_run_attempt", + "segment_catalog_entry", + "segment_catalog_occurrence", + "segment_detection", + "segment_extraction", + "segment_learning_data", + "segment_learning_round", + "segment_model_version", + "segment_seek_event", + "segment_settings", + "segment_skip_event", + "service_reach_config", + "station_logo", + "stream_visit", + "stream_visit_tally", + ], + Schema(context).GetEntityTypes() + .Where(entity => entity.FindOwnership() is null) + .Select(entity => entity.GetTableName()) + .OfType() + .Order(StringComparer.Ordinal)); + } + + [Fact] + public void TheOnlyShapeReadFromAQueryRatherThanATableIsTheSearchAcrossBothLayers() + { + using CarinaDbContext context = Context(); + + Assert.Equal( + [nameof(ProgrammeMatch)], + Schema(context).GetEntityTypes() + .Where(entity => entity.GetTableName() is null) + .Select(entity => entity.ClrType.Name) + .Order(StringComparer.Ordinal)); + } + + [Fact] + public void EveryTimeOfThisDomainGoesThroughTheUtcConverter() + { + using CarinaDbContext context = Context(); + + IProperty[] times = Schema(context).GetEntityTypes() + .SelectMany(EveryProperty) + .Where(property => property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?)) + .ToArray(); + + Assert.NotEmpty(times); + Assert.All(times, property => Assert.IsType(property.GetValueConverter())); + } + + [Fact] + public void TwoCandidatesMayBeTunedByTheVerySameParameters() + { + using CarinaDbContext context = Context(); + var carrying = TuningParameters.Terrestrial(27); + + context.Attach(Candidate(1, carrying)); + + context.Add(Candidate(2, carrying)); + + Assert.Equal(2, context.ChangeTracker.Entries().Count()); + } + + [Fact] + public void TwoCandidatesMayCarryTheVerySameReading() + { + using CarinaDbContext context = Context(); + var measured = SignalMeasurement.WithLock(At, 21_000); + CandidateChannel first = Candidate(1, TuningParameters.Terrestrial(27)); + CandidateChannel second = Candidate(2, TuningParameters.Terrestrial(27)); + first.RecordTuningSuccess(measured, At); + second.RecordTuningSuccess(measured, At); + context.Attach(first); + + context.Add(second); + + Assert.Equal(2, context.ChangeTracker.Entries().Count()); + } + + [Fact] + public void TwoAttemptsMayBeTunedByTheVerySameParametersAndCarryTheVerySameReading() + { + using CarinaDbContext context = Context(); + var carrying = TuningParameters.Terrestrial(27); + var measured = SignalMeasurement.WithLock(At, 21_000); + context.Attach(Attempt(carrying, measured)); + + context.Add(Attempt(carrying, measured)); + + Assert.Equal(2, context.ChangeTracker.Entries().Count()); + } + + [Fact] + public void OneReadingMayBeKeptByBothAnAttemptAndACandidateAtOnce() + { + using CarinaDbContext context = Context(); + var measured = SignalMeasurement.WithLock(At, 21_000); + CandidateChannel candidate = Candidate(1, TuningParameters.Terrestrial(27)); + candidate.RecordTuningSuccess(measured, At); + context.Attach(Attempt(TuningParameters.Terrestrial(27), measured)); + + context.Add(candidate); + + Assert.Single(context.ChangeTracker.Entries()); + } + + private static ProbeDbContext Probe() => new(Options()); + + private static CandidateChannel Candidate(int service, TuningParameters carrying) + => CandidateChannel.Discover( + CandidateChannelId.New(), + new NetworkId(1), + new ServiceId(service), + carrying, + At); + + private static ScanRunAttempt Attempt(TuningParameters carrying, SignalMeasurement measured) + => ScanRunAttempt.Rehydrate( + ScanRunAttemptId.New(), + ScanRunId.New(), + carrying, + ScanAttemptOutcome.Succeeded, + measured, + null, + null, + At, + At); + + private sealed class ProbeDbContext(DbContextOptions options) : CarinaDbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(); + } + } +} diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ProgrammeConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ProgrammeConfigurationTests.cs new file mode 100644 index 000000000..f953b4bed --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ProgrammeConfigurationTests.cs @@ -0,0 +1,28 @@ +using Carina.Domain.Programmes; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class ProgrammeConfigurationTests +{ + [Fact] + public void EveryTableAProgrammeCanComeFromIsAValueTheDatabaseKnows() + { + using CarinaDbContext context = Context(); + + ICheckConstraint check = Assert.Single( + Entity(context).GetCheckConstraints(), + constraint => constraint.Name == "ck_programme_source"); + + foreach (string source in Enum.GetNames()) + { + Assert.Contains($"'{source}'", check.Sql, StringComparison.Ordinal); + } + } +} diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ScanRunAttemptConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ScanRunAttemptConfigurationTests.cs new file mode 100644 index 000000000..5bced88be --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ScanRunAttemptConfigurationTests.cs @@ -0,0 +1,43 @@ +using Carina.Domain.Scans; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class ScanRunAttemptConfigurationTests +{ + [Fact] + public void AnAttemptCarriesTheTuningItUsedRatherThanTheCandidateItCameFrom() + { + using CarinaDbContext context = Context(); + + IEntityType attempt = Entity(context); + + Assert.Equal( + ["scan_run"], + attempt.GetForeignKeys().Select(key => key.PrincipalEntityType.GetTableName())); + Assert.Contains( + ColumnsOf(attempt, nameof(ScanRunAttempt.Tuning)), + column => column == "tune_system"); + } + + [Fact] + public void TheFourWaysOfFailingAreValuesTheDatabaseKnows() + { + using CarinaDbContext context = Context(); + + ICheckConstraint check = Assert.Single( + Entity(context).GetCheckConstraints(), + constraint => constraint.Name == "ck_scan_run_attempt_outcome"); + + foreach (string outcome in Enum.GetNames()) + { + Assert.Contains($"'{outcome}'", check.Sql, StringComparison.Ordinal); + } + } +} diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ScanRunConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ScanRunConfigurationTests.cs new file mode 100644 index 000000000..cc10de775 --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/ScanRunConfigurationTests.cs @@ -0,0 +1,36 @@ +using Carina.Domain.Scans; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class ScanRunConfigurationTests +{ + [Fact] + public void OnlyOneScanCanBeRunning() + { + using CarinaDbContext context = Context(); + + IIndex index = Assert.Single( + Entity(context).GetIndexes(), + run => run.GetDatabaseName() == "ux_scan_run_running"); + + Assert.True(index.IsUnique); + Assert.Equal("state = 'Running'", index.GetFilter()); + } + + [Fact] + public void AFailedOrCancelledScanCarriesAReasonTheDatabaseInsistsOn() + { + using CarinaDbContext context = Context(); + + IEnumerable names = Entity(context).GetCheckConstraints().Select(constraint => constraint.Name); + + Assert.Contains("ck_scan_run_reason", names); + } +} diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/StreamVisitConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/StreamVisitConfigurationTests.cs new file mode 100644 index 000000000..c1951dc91 --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/StreamVisitConfigurationTests.cs @@ -0,0 +1,39 @@ +using Carina.Domain.Programmes; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class StreamVisitConfigurationTests +{ + [Fact] + public void EveryWayAVisitCanEndIsAValueTheDatabaseKnows() + { + using CarinaDbContext context = Context(); + + ICheckConstraint check = Assert.Single( + Entity(context).GetCheckConstraints(), + constraint => constraint.Name == "ck_stream_visit_outcome"); + + foreach (string outcome in Enum.GetNames()) + { + Assert.Contains($"'{outcome}'", check.Sql, StringComparison.Ordinal); + } + } + + [Fact] + public void ATallyGoesWithTheVisitItCounted() + { + using CarinaDbContext context = Context(); + + IForeignKey foreignKey = Assert.Single(Entity(context).GetForeignKeys()); + + Assert.Equal("stream_visit", foreignKey.PrincipalEntityType.GetTableName()); + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + } +} diff --git a/tests/Carina.Infrastructure.Tests/UtcDateTimeConverterTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/UtcDateTimeConverterTests.cs similarity index 92% rename from tests/Carina.Infrastructure.Tests/UtcDateTimeConverterTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/UtcDateTimeConverterTests.cs index 640ff99a8..4eae3ecf0 100644 --- a/tests/Carina.Infrastructure.Tests/UtcDateTimeConverterTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/UtcDateTimeConverterTests.cs @@ -1,7 +1,8 @@ using Carina.Infrastructure.Persistence; -namespace Carina.Infrastructure.Tests; +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; +[Trait("Category", "Unit")] public sealed class UtcDateTimeConverterTests { private static readonly UtcDateTimeConverter Converter = new(); diff --git a/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/VisitTallyConfigurationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/VisitTallyConfigurationTests.cs new file mode 100644 index 000000000..2a5f44eac --- /dev/null +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Persistence/VisitTallyConfigurationTests.cs @@ -0,0 +1,25 @@ +using Carina.Domain.Programmes; +using Carina.Infrastructure.Persistence; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +using static Carina.Infrastructure.Tests.Fixtures.Persistence.CarinaModel; + +namespace Carina.Infrastructure.Tests.Unit.Infra.Persistence; + +[Trait("Category", "Unit")] +public sealed class VisitTallyConfigurationTests +{ + [Fact] + public void ATallyIsKeyedByTheStreamTheServiceAndTheTable() + { + using CarinaDbContext context = Context(); + + IKey key = Entity(context).FindPrimaryKey()!; + + Assert.Equal( + ["network_id", "transport_stream_id", "service_id", "table_id"], + key.Properties.Select(property => property.GetColumnName())); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/TemporaryDirectories.cs b/tests/Carina.TestSupport/TemporaryDirectories.cs similarity index 81% rename from tests/Carina.Api.Tests/FeatureTest/TemporaryDirectories.cs rename to tests/Carina.TestSupport/TemporaryDirectories.cs index 1bd425188..48528228d 100644 --- a/tests/Carina.Api.Tests/FeatureTest/TemporaryDirectories.cs +++ b/tests/Carina.TestSupport/TemporaryDirectories.cs @@ -1,9 +1,9 @@ -namespace Carina.Api.Tests.FeatureTest; +namespace Carina.TestSupport; /// -/// Removes the directories a feature made for itself, every one of them even when removing another fails. +/// Removes the directories a test made for itself, every one of them even when removing another fails. /// -internal static class TemporaryDirectories +public static class TemporaryDirectories { public static void RemoveAll(params DirectoryInfo[] directories) {