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).
This commit is contained in:
+39
-6
@@ -78,13 +78,21 @@ openssl rsa -in deploy/keys/stream_private.pem -pubout -out deploy/keys/stream_p
|
||||
dotnet test backend/Musify.slnx
|
||||
```
|
||||
|
||||
`backend/Tests/` (carpeta `/Tests/` en el `.slnx`) tiene dos proyectos xUnit,
|
||||
sin Docker ni Postgres real:
|
||||
`backend/Tests/` (carpeta `/Tests/` en el `.slnx`) tiene cinco proyectos xUnit:
|
||||
|
||||
| Proyecto | Cubre |
|
||||
|---|---|
|
||||
| `Musify.Domain.Tests` | Lógica de los value objects (`TrackAudio`/`TrackPictures`: `IsProcessed`, `IsFailed`, `IsInProgress`). Las entidades son en su mayoría anémicas — sin comportamiento propio, nada más que testear ahí. |
|
||||
| `Musify.Application.Tests` | Los ~45 handlers y servicios de `Musify.Application` (Albums, Tracks, PlayLists, Users, Mixes, YouTube). |
|
||||
| Proyecto | Cubre | Docker |
|
||||
|---|---|---|
|
||||
| `Musify.Domain.Tests` | Lógica de los value objects (`TrackAudio`/`TrackPictures`: `IsProcessed`, `IsFailed`, `IsInProgress`). Las entidades son en su mayoría anémicas — sin comportamiento propio, nada más que testear ahí. | No |
|
||||
| `Musify.Application.Tests` | Los ~45 handlers y servicios de `Musify.Application` (Albums, Tracks, PlayLists, Users, Mixes, YouTube). | No |
|
||||
| `Musify.Infrastructure.Tests` | `Database`/migraciones, `StorageService`, `StreamTicketService`, `AuditableEntityInterceptor`, `PictureService`, `SingleFlightCache`, `PlayListPresetSeeder`. | **Sí** |
|
||||
| `Musify.Api.Tests` | Endpoints HTTP reales (routing, auth, `ValidationFilter`, mapeo `ErrorOr`→HTTP) vía `WebApplicationFactory`, más `ErrorOrHttpExtensions`/`CurrentUser`/validators FluentValidation en aislado. | **Sí** |
|
||||
| `Musify.StreamingGateway.Tests` | `TicketValidator` (RS256) y `TicketValidationMiddleware` (traversal, límites de prefijo, extracción de ticket). | No |
|
||||
|
||||
`Musify.Worker` no tiene proyecto de test: su `Program.cs` es puro *wiring* de
|
||||
DI/host (Hangfire, MassTransit, jobs) — la lógica real que ejecuta vive en
|
||||
`Musify.Infrastructure`, ya cubierta ahí.
|
||||
|
||||
### Application.Tests: por qué SQLite en memoria y no mocks
|
||||
|
||||
`IDatabase` expone `DbSet<T>` directamente, así que los handlers arman LINQ
|
||||
real (`Where`, `Include`, `Select`...) contra él — no se puede mockear eso con
|
||||
@@ -97,6 +105,31 @@ construyen entidades y configuración con valores por defecto sensatos.
|
||||
`IStorageService`, `IEventBus`, `IYouTubeMusicService`, etc. sí se mockean con
|
||||
NSubstitute, al ser interfaces normales.
|
||||
|
||||
### Infrastructure.Tests y Api.Tests: Testcontainers
|
||||
|
||||
Estos dos sí necesitan Docker corriendo. Levantan un Postgres real
|
||||
(`Testcontainers.PostgreSql`) y, en `Infrastructure.Tests`, también un
|
||||
SeaweedFS real (mismo `chrislusf/seaweedfs:latest` e imagen/comando que
|
||||
`deploy/compose.yml`, no MinIO) — así `StorageService` se prueba contra el
|
||||
mismo backend S3-compatible que usa producción, no contra AWS S3. Los
|
||||
contenedores se levantan una vez por corrida (`ICollectionFixture`), con
|
||||
migraciones EF Core reales aplicadas contra el Postgres efímero.
|
||||
|
||||
`Api.Tests` usa `WebApplicationFactory<Program>` contra ese mismo Postgres —
|
||||
routing, auth y validación reales — pero sustituye por fakes los servicios que
|
||||
hablan por red (`IStorageService`, `IEventBus`, `IYouTubeMusicService`,
|
||||
`IStreamTicketService`) y el esquema de autenticación JWT real por un handler
|
||||
de prueba (ver `TestSupport/FakeAuthenticationHandler.cs`) que autentica según
|
||||
un header, sin necesitar un Zitadel real.
|
||||
|
||||
Escribir estos tests contra el backend real encontró y arregló dos bugs reales
|
||||
(no simulados): `StorageService.RemoveFolderAsync` reventaba con
|
||||
`NullReferenceException` contra SeaweedFS (su respuesta `DeleteObjects` omite
|
||||
la lista `<Error>` cuando no hay errores, a diferencia de AWS S3), y
|
||||
`AuditableEntityInterceptor` nunca actualizaba `UpdatedAt` en una actualización
|
||||
normal (carga → modifica → guarda) porque corría antes de que EF detectara los
|
||||
cambios pendientes.
|
||||
|
||||
## Config (AppSettings)
|
||||
|
||||
Convención: `AppSettings.json` es la plantilla con valores vacíos o neutros;
|
||||
|
||||
+6
-4
@@ -59,11 +59,13 @@ Cliente web (SvelteKit 2 + Svelte 5 + Tailwind 4). La sesión OIDC vive en el
|
||||
servidor (cookie cifrada); las llamadas al backend salen del servidor con el
|
||||
access token, y las subidas se hacen contra las URLs prefirmadas de S3.
|
||||
|
||||
## Musify.Domain.Tests + Musify.Application.Tests
|
||||
## Tests
|
||||
|
||||
`backend/Tests/`, carpeta `/Tests/` en el `.slnx`. xUnit, sin Docker ni Postgres
|
||||
real — `Application.Tests` corre los handlers contra SQLite en memoria (ver
|
||||
[development.md](development.md#tests)).
|
||||
`backend/Tests/`, carpeta `/Tests/` en el `.slnx`: cinco proyectos xUnit —
|
||||
`Musify.Domain.Tests`, `Musify.Application.Tests` (SQLite en memoria, sin
|
||||
Docker), `Musify.Infrastructure.Tests` y `Musify.Api.Tests` (Testcontainers:
|
||||
Postgres + SeaweedFS reales) y `Musify.StreamingGateway.Tests`. Detalle en
|
||||
[development.md](development.md#tests).
|
||||
|
||||
## Otras carpetas
|
||||
|
||||
|
||||
Reference in New Issue
Block a user