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).
118 lines
4.4 KiB
C#
118 lines
4.4 KiB
C#
using System.Text.Json;
|
|
using Amazon.S3;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Musify.Infrastructure.Configuration;
|
|
using Musify.Infrastructure.Persistence;
|
|
using Testcontainers.PostgreSql;
|
|
using DotNet.Testcontainers.Builders;
|
|
using DotNet.Testcontainers.Containers;
|
|
using Xunit;
|
|
|
|
namespace Musify.Infrastructure.Tests.TestSupport;
|
|
|
|
/// <summary>
|
|
/// One Postgres container and one SeaweedFS container (same image and startup
|
|
/// command as <c>deploy/compose.yml</c>), started once for every test in the
|
|
/// <see cref="InfrastructureCollection"/> and torn down when the run finishes.
|
|
/// EF Core migrations run once here too, against the real <c>Database</c>
|
|
/// DbContext, so a broken migration fails the whole run immediately.
|
|
/// </summary>
|
|
public sealed class InfrastructureTestFixture : IAsyncLifetime
|
|
{
|
|
public const string S3AccessKey = "musify-test";
|
|
public const string S3SecretKey = "musify-test-secret";
|
|
public const string S3Bucket = "musify-test-bucket";
|
|
|
|
private readonly PostgreSqlContainer postgres = new PostgreSqlBuilder("postgres:17-alpine")
|
|
.WithDatabase("musify_test")
|
|
.WithUsername("postgres")
|
|
.WithPassword("postgres")
|
|
.Build();
|
|
|
|
private readonly IContainer seaweedFs = new ContainerBuilder("chrislusf/seaweedfs:latest")
|
|
.WithEntrypoint("/bin/sh", "-c")
|
|
.WithCommand(BuildSeaweedFsStartupScript())
|
|
.WithPortBinding(9333, assignRandomHostPort: true)
|
|
.WithPortBinding(8333, assignRandomHostPort: true)
|
|
.WithWaitStrategy(Wait.ForUnixContainer()
|
|
.UntilHttpRequestIsSucceeded(request => request.ForPort(9333).ForPath("/cluster/healthz")))
|
|
.Build();
|
|
|
|
public string ConnectionString => postgres.GetConnectionString();
|
|
|
|
public string S3ServiceUrl => $"http://{seaweedFs.Hostname}:{seaweedFs.GetMappedPublicPort(8333)}";
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
await Task.WhenAll(postgres.StartAsync(), seaweedFs.StartAsync());
|
|
|
|
await using var database = new Database(new DatabaseConfiguration { ConnectionString = ConnectionString });
|
|
await database.Database.MigrateAsync();
|
|
|
|
// SeaweedFS does not auto-create buckets (see deploy/compose.yml's seaweedfs-init).
|
|
using var s3 = CreateS3Client();
|
|
await s3.PutBucketAsync(S3Bucket);
|
|
}
|
|
|
|
public async Task DisposeAsync()
|
|
{
|
|
await postgres.DisposeAsync();
|
|
await seaweedFs.DisposeAsync();
|
|
}
|
|
|
|
/// <summary>A fresh, DI-wired <see cref="Database"/>, so <c>AuditableEntityInterceptor</c>
|
|
/// (attached in <c>AddDatabase</c>'s DI registration, not in the class itself) is active —
|
|
/// same wiring the real app uses, not a bare <c>new Database(...)</c>.</summary>
|
|
public Database CreateDatabase()
|
|
{
|
|
var configuration = new ConfigurationBuilder()
|
|
.AddInMemoryCollection([new("Database:ConnectionString", ConnectionString)])
|
|
.Build();
|
|
|
|
var services = new ServiceCollection();
|
|
services.AddDatabase(configuration);
|
|
return services.BuildServiceProvider().GetRequiredService<Database>();
|
|
}
|
|
|
|
/// <summary>An <see cref="IAmazonS3"/> client configured exactly like
|
|
/// <c>ServicesDependencyInjection.AddStorageService</c>, pointed at the SeaweedFS container.</summary>
|
|
public IAmazonS3 CreateS3Client() =>
|
|
new AmazonS3Client(S3AccessKey, S3SecretKey, new AmazonS3Config
|
|
{
|
|
ServiceURL = S3ServiceUrl,
|
|
ForcePathStyle = true,
|
|
UseHttp = true,
|
|
});
|
|
|
|
private static string BuildSeaweedFsStartupScript()
|
|
{
|
|
var identity = JsonSerializer.Serialize(new
|
|
{
|
|
identities = new[]
|
|
{
|
|
new
|
|
{
|
|
name = "musify-test",
|
|
credentials = new[] { new { accessKey = S3AccessKey, secretKey = S3SecretKey } },
|
|
actions = new[] { "Admin", "Read", "Write" }
|
|
}
|
|
}
|
|
});
|
|
|
|
return $"""
|
|
cat > /tmp/s3.conf <<'JSON'
|
|
{identity}
|
|
JSON
|
|
exec weed server -ip.bind=0.0.0.0 -dir=/data -master.volumeSizeLimitMB=1024 -volume.max=0 -filer -s3 -s3.config=/tmp/s3.conf
|
|
""";
|
|
}
|
|
}
|
|
|
|
[CollectionDefinition(Name)]
|
|
public sealed class InfrastructureCollection : ICollectionFixture<InfrastructureTestFixture>
|
|
{
|
|
public const string Name = "Infrastructure";
|
|
}
|