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).
138 lines
4.4 KiB
C#
138 lines
4.4 KiB
C#
using ErrorOr;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Musify.Api.Extensions;
|
|
using Xunit;
|
|
|
|
namespace Musify.Api.Tests.Extensions;
|
|
|
|
public sealed class ErrorOrHttpExtensionsTests
|
|
{
|
|
// The concrete IResult types (NoContent, UnauthorizedHttpResult, ...) resolve logging/problem-
|
|
// details services from HttpContext.RequestServices when they execute, so it can't be empty.
|
|
private static readonly IServiceProvider Services = new ServiceCollection().AddLogging().AddProblemDetails().BuildServiceProvider();
|
|
|
|
private static async Task<(int StatusCode, string Body)> ExecuteAsync(IResult result)
|
|
{
|
|
var context = new DefaultHttpContext { RequestServices = Services };
|
|
var bodyStream = new MemoryStream();
|
|
context.Response.Body = bodyStream;
|
|
|
|
await result.ExecuteAsync(context);
|
|
|
|
bodyStream.Position = 0;
|
|
using var reader = new StreamReader(bodyStream);
|
|
return (context.Response.StatusCode, await reader.ReadToEndAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_Success_ReturnsNoContent()
|
|
{
|
|
ErrorOr<Success> result = new Success();
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status204NoContent, statusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_Value_ReturnsOkWithTheValue()
|
|
{
|
|
ErrorOr<string> result = "hello";
|
|
|
|
var (statusCode, body) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status200OK, statusCode);
|
|
Assert.Contains("hello", body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_NotFoundError_ReturnsNotFound()
|
|
{
|
|
ErrorOr<string> result = Error.NotFound(description: "not here");
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status404NotFound, statusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_UnauthorizedError_ReturnsUnauthorized()
|
|
{
|
|
ErrorOr<string> result = Error.Unauthorized();
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status401Unauthorized, statusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_ForbiddenError_ReturnsForbidden()
|
|
{
|
|
ErrorOr<string> result = Error.Forbidden();
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status403Forbidden, statusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_ConflictError_ReturnsConflict()
|
|
{
|
|
ErrorOr<string> result = Error.Conflict();
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status409Conflict, statusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_FailureError_ReturnsProblem500()
|
|
{
|
|
ErrorOr<string> result = Error.Failure();
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status500InternalServerError, statusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToHttpResult_ValidationErrors_ReturnsValidationProblem()
|
|
{
|
|
ErrorOr<string> result = new List<Error>
|
|
{
|
|
Error.Validation("Name", "Name is required"),
|
|
Error.Validation("Name", "Name is too long"),
|
|
Error.Validation("Age", "Age must be positive"),
|
|
};
|
|
|
|
var (statusCode, body) = await ExecuteAsync(result.ToHttpResult());
|
|
|
|
Assert.Equal(StatusCodes.Status400BadRequest, statusCode);
|
|
Assert.Contains("Name is required", body);
|
|
Assert.Contains("Age must be positive", body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToCreatedResult_Success_ReturnsCreatedAtTheGivenLocation()
|
|
{
|
|
ErrorOr<string> result = "the-id";
|
|
|
|
var context = new DefaultHttpContext { RequestServices = Services, Response = { Body = new MemoryStream() } };
|
|
await result.ToCreatedResult(value => $"/things/{value}").ExecuteAsync(context);
|
|
|
|
Assert.Equal(StatusCodes.Status201Created, context.Response.StatusCode);
|
|
Assert.Equal("/things/the-id", context.Response.Headers.Location);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ToCreatedResult_Error_ReturnsTheMappedErrorStatus()
|
|
{
|
|
ErrorOr<string> result = Error.Conflict();
|
|
|
|
var (statusCode, _) = await ExecuteAsync(result.ToCreatedResult(value => $"/things/{value}"));
|
|
|
|
Assert.Equal(StatusCodes.Status409Conflict, statusCode);
|
|
}
|
|
}
|