Files
ersatztv/ErsatzTV.Tests/Controllers/LocalLibrariesControllerTests.cs
T
timothyandClaude Opus 4.8 ef2bd65c27
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 10s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m12s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 3m4s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m17s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m36s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
feat(api): #286 — mount the whole /api surface at /api/v1
Version every /api route to /api/v1 (251 controller routes + ~24 Location
headers + the scanner callback URL + the Startup request-log literal),
uniform across the machine API, auth, scanner and scripted-build surfaces.

Add ApiVersionRewriteMiddleware: a legacy unversioned /api/* request is
rewritten (NOT redirected) to /api/v1/* in-pipeline — method, body, auth
headers and query survive — carrying RFC 8594 Deprecation/Sunset headers,
so curl / the future MCP server / bookmarks keep working. An already-
versioned path passes through; a future /api/v2 is never forced to v1.

Standardize the route convention (leading-slash absolute route per method,
no class-[Route] — except the two Scanner/Scripted controllers whose ~all
actions share a parametrized {id} prefix), enforced by ApiRouteVersioningTests
(^/api/v\d+/ over the whole Controllers.Api surface; browser-nav
/auth/oidc/login is out of scope).

Regenerate v1.json (160 paths, all /api/v1)/endpoint-index/v1.d.ts; sweep 945
SPA request literals + the test mocks (regex + positional URL parsers). /api/v1
is additive-only after freeze; the legacy-rewrite shim sunsets in ~2 releases
(owner decision) with removal tracked as a Phase-3 follow-up.

Docs: decisions.md 2026-07-13, api-conventions §1/§9, rest-api/spa-conventions/
blazor-route-parity/e2e-local/domain-model.

fixes #286
refs #197

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 00:30:20 +02:00

364 lines
16 KiB
C#

using System.Reflection;
using ErsatzTV.Application.Libraries;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.MediaSources;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Locking;
using ErsatzTV.Core.Interfaces.Repositories;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Testably.Abstractions.Testing;
using Unit = LanguageExt.Unit;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class LocalLibrariesControllerTests
{
private LocalLibrariesController _controller = null!;
private IEntityLocker _entityLocker = null!;
private MockFileSystem _fileSystem = null!;
private ILibraryRepository _libraryRepository = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_entityLocker = Substitute.For<IEntityLocker>();
_fileSystem = new MockFileSystem();
_libraryRepository = Substitute.For<ILibraryRepository>();
_controller = new LocalLibrariesController(_mediator, _entityLocker, _fileSystem, _libraryRepository);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute(nameof(LocalLibrariesController.GetAll), "GET", "/api/v1/libraries/local");
ShouldHaveActionRoute(nameof(LocalLibrariesController.GetById), "GET", "/api/v1/libraries/local/{id:int}");
ShouldHaveActionRoute(nameof(LocalLibrariesController.Create), "POST", "/api/v1/libraries/local");
ShouldHaveActionRoute(nameof(LocalLibrariesController.Update), "PUT", "/api/v1/libraries/local/{id:int}");
ShouldHaveActionRoute(nameof(LocalLibrariesController.Delete), "DELETE", "/api/v1/libraries/local/{id:int}");
ShouldHaveActionRoute(
nameof(LocalLibrariesController.MovePath),
"POST",
"/api/v1/libraries/local/paths/{pathId:int}/move");
ShouldHaveActionRoute(
nameof(LocalLibrariesController.CheckPathExists),
"POST",
"/api/v1/libraries/local/path-exists");
}
[Test]
public async Task GetAll_Should_Project_Libraries_And_Lock_State()
{
_mediator.Send(Arg.Any<GetAllLocalLibraries>(), Arg.Any<CancellationToken>())
.Returns(new List<LocalLibraryViewModel>
{
new(1, "Movies", LibraryMediaKind.Movies, 0),
new(2, "TV Shows", LibraryMediaKind.Shows, 0)
});
_entityLocker.IsLibraryLocked(1).Returns(true);
_entityLocker.IsLibraryLocked(2).Returns(false);
List<LocalLibraryResponseModel> result = await _controller.GetAll(CancellationToken.None);
result.Count.ShouldBe(2);
result[0].ShouldBe(new LocalLibraryResponseModel(1, "Movies", LibraryMediaKind.Movies, true));
result[1].ShouldBe(new LocalLibraryResponseModel(2, "TV Shows", LibraryMediaKind.Shows, false));
}
[Test]
public async Task GetById_Should_Return_404_When_Missing()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Option<LocalLibraryViewModel>.None);
IActionResult result = await _controller.GetById(99, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
notFound.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status404NotFound);
}
[Test]
public async Task GetById_Should_Return_Detail_With_Paths_And_Counts()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Some(new LocalLibraryViewModel(3, "Movies", LibraryMediaKind.Movies, 0)));
_mediator.Send(Arg.Any<GetLocalLibraryPaths>(), Arg.Any<CancellationToken>())
.Returns(new List<LocalLibraryPathViewModel> { new(10, 3, "/media/movies") });
_mediator.Send(Arg.Any<CountMediaItemsByLibrary>(), Arg.Any<CancellationToken>()).Returns(5);
_mediator.Send(Arg.Any<CountMediaItemsByLibraryPath>(), Arg.Any<CancellationToken>()).Returns(5);
_entityLocker.IsLibraryLocked(3).Returns(false);
IActionResult result = await _controller.GetById(3, CancellationToken.None);
var ok = result.ShouldBeOfType<OkObjectResult>();
var detail = ok.Value.ShouldBeOfType<LocalLibraryDetailResponseModel>();
detail.Id.ShouldBe(3);
detail.MediaItemCount.ShouldBe(5);
detail.Paths.Count.ShouldBe(1);
detail.Paths[0].ShouldBe(new LocalLibraryPathResponseModel(10, "/media/movies", 5));
}
[Test]
public async Task Create_Should_Return_201_With_Location_And_Body()
{
_mediator.Send(Arg.Any<CreateLocalLibrary>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, LocalLibraryViewModel>(
new LocalLibraryViewModel(5, "Movies", LibraryMediaKind.Movies, 0)));
IActionResult result = await _controller.Create(
new CreateLocalLibraryRequest("Movies", LibraryMediaKind.Movies, ["/media/movies"]),
CancellationToken.None);
var created = result.ShouldBeOfType<CreatedResult>();
created.Location.ShouldBe("/api/v1/libraries/local/5");
created.Value.ShouldBeOfType<LocalLibraryResponseModel>().Name.ShouldBe("Movies");
await _mediator.Received(1).Send(
Arg.Is<CreateLocalLibrary>(c => c.Name == "Movies" && c.MediaKind == LibraryMediaKind.Movies),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Create_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<CreateLocalLibrary>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, LocalLibraryViewModel>(BaseError.New("bad")));
IActionResult result = await _controller.Create(
new CreateLocalLibraryRequest(string.Empty, LibraryMediaKind.Movies, []),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Update_Should_Return_404_When_Missing()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Option<LocalLibraryViewModel>.None);
IActionResult result = await _controller.Update(
99,
new UpdateLocalLibraryRequest("New Name", []),
CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
notFound.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status404NotFound);
await _mediator.DidNotReceive().Send(Arg.Any<UpdateLocalLibrary>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_409_When_Locked()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Some(new LocalLibraryViewModel(3, "Movies", LibraryMediaKind.Movies, 0)));
_entityLocker.IsLibraryLocked(3).Returns(true);
IActionResult result = await _controller.Update(
3,
new UpdateLocalLibraryRequest("New Name", []),
CancellationToken.None);
var conflict = result.ShouldBeOfType<ConflictObjectResult>();
conflict.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status409Conflict);
await _mediator.DidNotReceive().Send(Arg.Any<UpdateLocalLibrary>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Update_Should_Return_422_On_Validation_Error()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Some(new LocalLibraryViewModel(3, "Movies", LibraryMediaKind.Movies, 0)));
_entityLocker.IsLibraryLocked(3).Returns(false);
_mediator.Send(Arg.Any<UpdateLocalLibrary>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, LocalLibraryViewModel>(BaseError.New("bad")));
IActionResult result = await _controller.Update(
3,
new UpdateLocalLibraryRequest("New Name", []),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task Update_Should_Reload_And_Return_Detail_On_Success()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(
Some(new LocalLibraryViewModel(3, "Movies", LibraryMediaKind.Movies, 0)),
Some(new LocalLibraryViewModel(3, "New Name", LibraryMediaKind.Movies, 0)));
_entityLocker.IsLibraryLocked(3).Returns(false);
_mediator.Send(Arg.Any<UpdateLocalLibrary>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, LocalLibraryViewModel>(
new LocalLibraryViewModel(3, "New Name", LibraryMediaKind.Movies, 0)));
_mediator.Send(Arg.Any<GetLocalLibraryPaths>(), Arg.Any<CancellationToken>())
.Returns(new List<LocalLibraryPathViewModel>());
_mediator.Send(Arg.Any<CountMediaItemsByLibrary>(), Arg.Any<CancellationToken>()).Returns(0);
IActionResult result = await _controller.Update(
3,
new UpdateLocalLibraryRequest("New Name", []),
CancellationToken.None);
var ok = result.ShouldBeOfType<OkObjectResult>();
ok.Value.ShouldBeOfType<LocalLibraryDetailResponseModel>().Name.ShouldBe("New Name");
await _mediator.Received(1).Send(
Arg.Is<UpdateLocalLibrary>(c => c.Id == 3 && c.Name == "New Name"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Delete_Should_Return_404_When_Missing()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Option<LocalLibraryViewModel>.None);
IActionResult result = await _controller.Delete(99, CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
notFound.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status404NotFound);
await _mediator.DidNotReceive().Send(Arg.Any<DeleteLocalLibrary>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Delete_Should_Return_409_When_Locked()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Some(new LocalLibraryViewModel(3, "Movies", LibraryMediaKind.Movies, 0)));
_entityLocker.IsLibraryLocked(3).Returns(true);
IActionResult result = await _controller.Delete(3, CancellationToken.None);
var conflict = result.ShouldBeOfType<ConflictObjectResult>();
conflict.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status409Conflict);
await _mediator.DidNotReceive().Send(Arg.Any<DeleteLocalLibrary>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Delete_Should_Return_204_On_Success()
{
_mediator.Send(Arg.Any<GetLocalLibraryById>(), Arg.Any<CancellationToken>())
.Returns(Some(new LocalLibraryViewModel(3, "Movies", LibraryMediaKind.Movies, 0)));
_entityLocker.IsLibraryLocked(3).Returns(false);
_mediator.Send(Arg.Any<DeleteLocalLibrary>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.Delete(3, CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<DeleteLocalLibrary>(c => c.LocalLibraryId == 3),
Arg.Any<CancellationToken>());
}
[Test]
public async Task MovePath_Should_Return_404_When_Path_Unknown()
{
_libraryRepository.GetLibraryIdForPath(999).Returns(Option<int>.None);
IActionResult result = await _controller.MovePath(
999,
new MoveLocalLibraryPathRequest(2),
CancellationToken.None);
var notFound = result.ShouldBeOfType<NotFoundObjectResult>();
notFound.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status404NotFound);
await _mediator.DidNotReceive().Send(Arg.Any<MoveLocalLibraryPath>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task MovePath_Should_Return_409_When_Source_Library_Locked()
{
_libraryRepository.GetLibraryIdForPath(10).Returns(Some(1));
_entityLocker.IsLibraryLocked(1).Returns(true);
IActionResult result = await _controller.MovePath(
10,
new MoveLocalLibraryPathRequest(2),
CancellationToken.None);
var conflict = result.ShouldBeOfType<ConflictObjectResult>();
conflict.Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(StatusCodes.Status409Conflict);
await _mediator.DidNotReceive().Send(Arg.Any<MoveLocalLibraryPath>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task MovePath_Should_Return_204_On_Success()
{
_libraryRepository.GetLibraryIdForPath(10).Returns(Some(1));
_entityLocker.IsLibraryLocked(1).Returns(false);
_mediator.Send(Arg.Any<MoveLocalLibraryPath>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.MovePath(
10,
new MoveLocalLibraryPathRequest(2),
CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(
Arg.Is<MoveLocalLibraryPath>(c => c.LibraryPathId == 10 && c.TargetLibraryId == 2),
Arg.Any<CancellationToken>());
}
[Test]
public async Task MovePath_Should_Return_422_When_Handler_Rejects_Move_After_PreCheck_Passes()
{
// documents the residual check-then-act race (design #202 §C5): the pre-check passed, but
// the handler's own validation (e.g. same-kind/different-library) still fails 422, not 404.
_libraryRepository.GetLibraryIdForPath(10).Returns(Some(1));
_entityLocker.IsLibraryLocked(1).Returns(false);
_mediator.Send(Arg.Any<MoveLocalLibraryPath>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(BaseError.New("Target library must be different from the source path's current library")));
IActionResult result = await _controller.MovePath(
10,
new MoveLocalLibraryPathRequest(1),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public void CheckPathExists_Should_Return_True_When_Directory_Exists()
{
_fileSystem.Directory.CreateDirectory("/media/movies");
IActionResult result = _controller.CheckPathExists(new LocalPathCheckRequest("/media/movies"));
var ok = result.ShouldBeOfType<OkObjectResult>();
ok.Value.ShouldBeOfType<LocalPathCheckResponseModel>().Exists.ShouldBeTrue();
}
[Test]
public void CheckPathExists_Should_Return_False_When_Directory_Missing()
{
IActionResult result = _controller.CheckPathExists(new LocalPathCheckRequest("/media/does-not-exist"));
var ok = result.ShouldBeOfType<OkObjectResult>();
ok.Value.ShouldBeOfType<LocalPathCheckResponseModel>().Exists.ShouldBeFalse();
}
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
{
MethodInfo action = typeof(LocalLibrariesController).GetMethod(actionName)
?? throw new AssertionException($"Missing action {actionName}");
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain(httpMethod);
attribute.Template.ShouldBe(route);
}
}