Files
Musify/backend/Tests/Musify.Infrastructure.Tests/Services/PlayListPresetSeederTests.cs
T
Admin a26f4b43fd Add Infrastructure/Api/StreamingGateway test projects
Second pass on backend/Tests/, covering what Domain+Application (the first
pass) deliberately left out — the parts that talk to real infrastructure:

  Musify.Infrastructure.Tests   Database/migrations, StorageService,
                                 StreamTicketService, AuditableEntityInterceptor,
                                 PictureService, SingleFlightCache,
                                 PlayListPresetSeeder.
  Musify.Api.Tests               Real HTTP endpoints via WebApplicationFactory
                                 (routing, auth, ValidationFilter, ErrorOr->HTTP
                                 mapping), plus isolated unit tests for
                                 ErrorOrHttpExtensions, CurrentUser and the
                                 FluentValidation validators.
  Musify.StreamingGateway.Tests  TicketValidator (RS256) and
                                 TicketValidationMiddleware (path traversal,
                                 prefix boundary, ticket extraction).

Musify.Worker gets no test project: its Program.cs is pure DI/host wiring
(Hangfire, MassTransit, jobs); the logic it runs lives in Musify.Infrastructure,
already covered there.

Per the user's direction, the parts that touch real infrastructure use
Testcontainers instead of fakes: a real Postgres (Testcontainers.PostgreSql)
for Infrastructure.Tests and Api.Tests, and — matching deploy/compose.yml
exactly (chrislusf/seaweedfs:latest, same startup command), not MinIO — a
real SeaweedFS container for StorageService. Api.Tests boots the actual
Musify.Api host against that Postgres (real routing/auth/validation) but
substitutes the services that talk over the network (storage, YouTube, the
message bus, stream-ticket signing) with NSubstitute fakes, and swaps the
JwtBearer scheme for a test-only header-based one (FakeAuthenticationHandler)
so tests don't need a reachable Zitadel. Application.Tests' approach — a real
DbContext (SQLite in-memory) rather than mocking IDatabase, since it exposes
DbSet<T> directly and handlers compose real LINQ queries against it — carries
over into Infrastructure.Tests/Api.Tests via real Postgres instead.

Testing against the real backend (not a fake) found two genuine production
bugs, both fixed here:

- StorageService.RemoveFolderAsync threw NullReferenceException against
  SeaweedFS: its DeleteObjects response omits the <Error> list entirely when
  nothing failed, which the AWS SDK deserializes as null rather than an empty
  list (real AWS S3 always returns one). Now treats null as no errors.
- AuditableEntityInterceptor never bumped UpdatedAt on a normal update (load,
  mutate a property, SaveChanges) — only on insert. SavingChanges(Async) fires
  before EF's own automatic change detection for that save, so an entity
  modified through a plain property setter still reported EntityState.Unchanged
  inside the interceptor. Now calls ChangeTracker.DetectChanges() explicitly
  first, which is the documented fix for exactly this interceptor pattern.

Also required to make the Api host testable: Program.cs now ends with `public
partial class Program;` (WebApplicationFactory<Program> needs the top-level-
statements Program class to be public — no behavior change), and
Directory.Packages.props gains Microsoft.AspNetCore.Mvc.Testing, Testcontainers
and Testcontainers.PostgreSql.

249 tests total across all five projects, all green: `dotnet test
backend/Musify.slnx` (needs Docker running for Infrastructure.Tests and
Api.Tests).
2026-09-09 21:39:06 +02:00

103 lines
4.1 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Musify.Application.Configuration;
using Musify.Application.Contracts;
using Musify.Infrastructure.Configuration;
using Musify.Infrastructure.Services;
using Musify.Infrastructure.Tests.TestSupport;
using Xunit;
namespace Musify.Infrastructure.Tests.Services;
[Collection(InfrastructureCollection.Name)]
public sealed class PlayListPresetSeederTests(InfrastructureTestFixture fixture)
{
private static PlayListConfiguration NewConfiguration(bool overwritePresetPictures) => new()
{
Routes = new PlayListRoutes { ParentFolders = $"PlayLists-{Guid.NewGuid():N}" },
SeedPresetPictures = true,
OverwritePresetPictures = overwritePresetPictures
};
private (PlayListPresetSeeder Seeder, IStorageService Storage) Build(PlayListConfiguration configuration)
{
var services = new ServiceCollection();
services.AddSingleton(configuration);
services.AddSingleton(new ApplicationStorageConfiguration { Bucket = InfrastructureTestFixture.S3Bucket });
services.AddSingleton<IStorageService>(_ => new StorageService(
fixture.CreateDatabase(),
fixture.CreateS3Client(),
NullLogger<StorageService>.Instance,
new InfrastructureStorageConfiguration
{
Address = fixture.S3ServiceUrl,
AccessKey = InfrastructureTestFixture.S3AccessKey,
SecretAccessKey = InfrastructureTestFixture.S3SecretKey,
ForcePathStyle = true,
UseHttp = true,
}));
services.AddSingleton<IPictureService>(new PictureService(NullLogger<PictureService>.Instance));
var provider = services.BuildServiceProvider();
var seeder = new PlayListPresetSeeder(provider.GetRequiredService<IServiceScopeFactory>(), NullLogger<PlayListPresetSeeder>.Instance);
return (seeder, provider.GetRequiredService<IStorageService>());
}
private static async Task RunToCompletionAsync(PlayListPresetSeeder seeder)
{
await seeder.StartAsync(CancellationToken.None);
await (seeder.ExecuteTask ?? Task.CompletedTask);
}
[Fact]
public async Task ExecuteAsync_SeedsAllFourPresetPictures()
{
var configuration = NewConfiguration(overwritePresetPictures: false);
var (seeder, storage) = Build(configuration);
await RunToCompletionAsync(seeder);
var routes = configuration.Routes;
foreach (var key in new[]
{
routes.BuildOriginalPicturePath(routes.PresetOriginalPicture),
routes.PresetSmallPicturePath,
routes.PresetMediumPicturePath,
routes.PresetLargePicturePath
})
{
var metadata = await storage.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, CancellationToken.None);
Assert.True(metadata is not null, $"expected {key} to have been seeded");
}
}
[Fact]
public async Task ExecuteAsync_RunTwiceWithoutOverwrite_StaysIdempotent()
{
var configuration = NewConfiguration(overwritePresetPictures: false);
var (firstSeeder, storage) = Build(configuration);
await RunToCompletionAsync(firstSeeder);
var (secondSeeder, _) = Build(configuration);
await RunToCompletionAsync(secondSeeder);
var metadata = await storage.HeadObjectAsync(
InfrastructureTestFixture.S3Bucket, configuration.Routes.PresetSmallPicturePath, CancellationToken.None);
Assert.NotNull(metadata);
}
[Fact]
public async Task ExecuteAsync_SeedPresetPicturesDisabled_UploadsNothing()
{
var configuration = NewConfiguration(overwritePresetPictures: false);
configuration.SeedPresetPictures = false;
var (seeder, storage) = Build(configuration);
await RunToCompletionAsync(seeder);
var metadata = await storage.HeadObjectAsync(
InfrastructureTestFixture.S3Bucket, configuration.Routes.PresetSmallPicturePath, CancellationToken.None);
Assert.Null(metadata);
}
}