Files
ersatztv/ErsatzTV.Tests/Controllers/PlexMediaSourcesControllerTests.cs
T
timothyandClaude Opus 4.8 628c9d7228 feat(235): F9 API parity — library deep-scan, external-collections scan, scan-show outcome enum (#235 slice B)
Closes the two F9 Libraries.razor parity gaps and normalizes scan-show error
mapping to ProblemDetails.

TASK 1 — library-wide deep scan:
- QueueLibraryScanByLibraryId gains optional `bool DeepScan = false`; handler
  threads it into ForceSynchronize{Plex,Jellyfin,Emby}LibraryById.
- POST /api/libraries/{id}/scan?deep=false binds it via [FromQuery].

TASK 2 — external-collections scan (new endpoints):
- POST /api/media-sources/{plex|jellyfin|emby}/{id}/scan-collections?deep=false
  acquires the per-source collections lock (§3b: lock IS the running scan → 409),
  enqueues Synchronize{X}Collections(id, ForceScan:true, deep) to the scanner
  channel, returns 202; compensating-unlock on enqueue throw.

TASK 3 — scan-show normalization:
- New QueueShowScanResult enum; handler returns it instead of bool.
- POST /api/libraries/{id}/scan-show now maps 202/404/409/422 (all errors
  ProblemDetails) instead of 200/404/400-anonymous-object.
- Updated the lone Blazor caller (TelevisionSeasonList.razor).

Tests: LibrariesController (scan deep=true, scan-show enum→status), the three
media-source controllers (scan-collections route/404/409/202/compensating-unlock),
and handler tests for both changed handlers (deep threading + show-scan outcomes).
Docs: api-conventions §3b exemplar + blazor-route-parity §5 F9 gate.

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

533 lines
21 KiB
C#

using System.Reflection;
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Plex;
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.Plex;
using ErsatzTV.Core.Plex;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class PlexMediaSourcesControllerTests
{
private ChannelWriter<IScannerBackgroundServiceRequest> _channel = null!;
private PlexMediaSourcesController _controller = null!;
private IEntityLocker _entityLocker = null!;
private IMediator _mediator = null!;
private IPlexSecretStore _plexSecretStore = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_entityLocker = Substitute.For<IEntityLocker>();
_plexSecretStore = Substitute.For<IPlexSecretStore>();
_channel = Substitute.For<ChannelWriter<IScannerBackgroundServiceRequest>>();
_controller = new PlexMediaSourcesController(_mediator, _entityLocker, _plexSecretStore, _channel);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute(nameof(PlexMediaSourcesController.GetState), "GET", "/api/media-sources/plex");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.StartPinFlow),
"POST",
"/api/media-sources/plex/pin-flow");
ShouldHaveActionRoute(nameof(PlexMediaSourcesController.SignOutOfPlex), "POST", "/api/media-sources/plex/sign-out");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.GetLibraries),
"GET",
"/api/media-sources/plex/{id:int}/libraries");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.ReplaceLibraryPreferences),
"PUT",
"/api/media-sources/plex/{id:int}/libraries");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.GetPathReplacements),
"GET",
"/api/media-sources/plex/{id:int}/path-replacements");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.ReplacePathReplacements),
"PUT",
"/api/media-sources/plex/{id:int}/path-replacements");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.RefreshLibraries),
"POST",
"/api/media-sources/plex/{id:int}/refresh-libraries");
ShouldHaveActionRoute(
nameof(PlexMediaSourcesController.ScanCollections),
"POST",
"/api/media-sources/plex/{id:int}/scan-collections");
}
// ----- P1 GetState -----
[Test]
public async Task GetState_Should_Stamp_Authorized_Locked_And_Servers()
{
_mediator.Send(Arg.Any<GetAllPlexMediaSources>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexMediaSourceViewModel> { new(3, "Server", "http://plex:32400") });
_plexSecretStore.GetUserAuthTokens()
.Returns(new List<PlexUserAuthToken> { new("me@example.com", "token") });
_entityLocker.IsPlexLocked().Returns(true);
RemoteMediaSourceStateResponseModel result = await _controller.GetState(CancellationToken.None);
result.IsAuthorized.ShouldBeTrue();
result.IsLocked.ShouldBeTrue();
result.Servers.Single().Id.ShouldBe(3);
result.Servers.Single().Address.ShouldBe("http://plex:32400");
}
[Test]
public async Task GetState_Should_Report_Unauthorized_With_No_Tokens()
{
_mediator.Send(Arg.Any<GetAllPlexMediaSources>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexMediaSourceViewModel>());
_plexSecretStore.GetUserAuthTokens().Returns(new List<PlexUserAuthToken>());
RemoteMediaSourceStateResponseModel result = await _controller.GetState(CancellationToken.None);
result.IsAuthorized.ShouldBeFalse();
}
// ----- P2 StartPinFlow -----
[Test]
public async Task StartPinFlow_Should_Return_409_When_Lock_Held()
{
_entityLocker.LockPlex().Returns(false);
IActionResult result = await _controller.StartPinFlow(CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(409);
await _mediator.DidNotReceive().Send(Arg.Any<StartPlexPinFlow>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task StartPinFlow_Should_Return_200_And_Hold_Lock_On_Success()
{
_entityLocker.LockPlex().Returns(true);
_mediator.Send(Arg.Any<StartPlexPinFlow>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, string>("https://app.plex.tv/auth#?code=abc"));
IActionResult result = await _controller.StartPinFlow(CancellationToken.None);
var model = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<PlexPinFlowResponseModel>();
model.AuthUrl.ShouldBe("https://app.plex.tv/auth#?code=abc");
// the Right/200 path keeps the lock held for the background flow
_entityLocker.DidNotReceive().UnlockPlex();
}
[Test]
public async Task StartPinFlow_Should_Compensate_Unlock_On_Left()
{
_entityLocker.LockPlex().Returns(true);
_mediator.Send(Arg.Any<StartPlexPinFlow>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, string>(BaseError.New("plex.tv error")));
IActionResult result = await _controller.StartPinFlow(CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
_entityLocker.Received(1).UnlockPlex();
}
[Test]
public async Task StartPinFlow_Should_Compensate_Unlock_On_Thrown_Dispatch()
{
_entityLocker.LockPlex().Returns(true);
_mediator.Send(Arg.Any<StartPlexPinFlow>(), Arg.Any<CancellationToken>())
.Returns<Either<BaseError, string>>(_ => throw new InvalidOperationException("channel closed"));
await Should.ThrowAsync<InvalidOperationException>(() => _controller.StartPinFlow(CancellationToken.None));
_entityLocker.Received(1).UnlockPlex();
}
// ----- P3 SignOut -----
[Test]
public async Task SignOut_Should_Return_409_When_Lock_Held()
{
_entityLocker.LockPlex().Returns(false);
IActionResult result = await _controller.SignOutOfPlex(CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(409);
await _mediator.DidNotReceive().Send(Arg.Any<SignOutOfPlex>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task SignOut_Should_Return_204_And_Not_Release_In_Controller()
{
_entityLocker.LockPlex().Returns(true);
_mediator.Send(Arg.Any<SignOutOfPlex>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.SignOutOfPlex(CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
await _mediator.Received(1).Send(Arg.Any<SignOutOfPlex>(), Arg.Any<CancellationToken>());
// the handler is the designated releaser (finally) — the controller must not double-release
_entityLocker.DidNotReceive().UnlockPlex();
}
// ----- P4 GetLibraries -----
[Test]
public async Task GetLibraries_Should_Return_404_When_Source_Missing()
{
SourceExists(false);
IActionResult result = await _controller.GetLibraries(9, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task GetLibraries_Should_Return_200_List()
{
SourceExists(true);
_mediator.Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexLibraryViewModel> { new(5, "Movies", LibraryMediaKind.Movies, true) });
IActionResult result = await _controller.GetLibraries(3, CancellationToken.None);
var list = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<List<RemoteLibraryResponseModel>>();
list.Single().Id.ShouldBe(5);
list.Single().ShouldSyncItems.ShouldBeTrue();
}
// ----- P5 ReplaceLibraryPreferences -----
[Test]
public async Task ReplaceLibraries_Should_Return_404_When_Source_Missing()
{
SourceExists(false);
IActionResult result = await _controller.ReplaceLibraryPreferences(
9,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(5, true)]),
CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<UpdatePlexLibraryPreferences>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task ReplaceLibraries_Should_Return_422_When_Id_Not_Owned()
{
SourceExists(true);
_mediator.Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexLibraryViewModel> { new(5, "Movies", LibraryMediaKind.Movies, true) });
IActionResult result = await _controller.ReplaceLibraryPreferences(
3,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(999, true)]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<UpdatePlexLibraryPreferences>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task ReplaceLibraries_Should_Return_422_For_Zero_Id_Row()
{
SourceExists(true);
_mediator.Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexLibraryViewModel> { new(5, "Movies", LibraryMediaKind.Movies, true) });
IActionResult result = await _controller.ReplaceLibraryPreferences(
3,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(0, true)]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<UpdatePlexLibraryPreferences>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task ReplaceLibraries_Should_Return_422_When_An_Owned_Library_Is_Missing()
{
SourceExists(true);
_mediator.Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexLibraryViewModel>
{
new(5, "Movies", LibraryMediaKind.Movies, true),
new(6, "Shows", LibraryMediaKind.Shows, true)
});
// request omits owned id 6 -> 422: the PUT is a complete flag document (§C4a), matching Jellyfin/Emby
IActionResult result = await _controller.ReplaceLibraryPreferences(
3,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(5, true)]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<UpdatePlexLibraryPreferences>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task ReplaceLibraries_Should_Save_Enqueue_Ordered_Pair_And_Return_Reloaded()
{
SourceExists(true);
// owned set for validation, then the reloaded set (drives the sync loop + the response)
_mediator.Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexLibraryViewModel> { new(5, "Shows", LibraryMediaKind.Shows, true) });
_mediator.Send(Arg.Any<UpdatePlexLibraryPreferences>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
_entityLocker.LockLibrary(5).Returns(true);
IActionResult result = await _controller.ReplaceLibraryPreferences(
3,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(5, true)]),
CancellationToken.None);
var list = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<List<RemoteLibraryResponseModel>>();
list.Single().Id.ShouldBe(5);
// library message carries Unlock:false; the networks message carries the single release Unlock:true
Received.InOrder(() =>
{
_channel.WriteAsync(
Arg.Is<SynchronizePlexLibraryByIdIfNeeded>(s => s.PlexLibraryId == 5 && !s.Unlock),
Arg.Any<CancellationToken>());
_channel.WriteAsync(
Arg.Is<SynchronizePlexNetworks>(n => n.PlexLibraryId == 5 && n.Unlock),
Arg.Any<CancellationToken>());
});
}
[Test]
public async Task ReplaceLibraries_Should_Skip_Enqueue_For_Locked_Library()
{
SourceExists(true);
_mediator.Send(Arg.Any<GetPlexLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexLibraryViewModel> { new(5, "Shows", LibraryMediaKind.Shows, true) });
_mediator.Send(Arg.Any<UpdatePlexLibraryPreferences>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
_entityLocker.LockLibrary(5).Returns(false);
IActionResult result = await _controller.ReplaceLibraryPreferences(
3,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(5, true)]),
CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>();
await _channel.DidNotReceive().WriteAsync(
Arg.Any<IScannerBackgroundServiceRequest>(),
Arg.Any<CancellationToken>());
}
// ----- P6 GetPathReplacements -----
[Test]
public async Task GetPathReplacements_Should_Return_404_When_Source_Missing()
{
SourceExists(false);
IActionResult result = await _controller.GetPathReplacements(9, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task GetPathReplacements_Should_Map_Plex_Path_To_Remote_Path()
{
SourceExists(true);
_mediator.Send(Arg.Any<GetPlexPathReplacementsBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexPathReplacementViewModel> { new(7, "/plex", "/local") });
IActionResult result = await _controller.GetPathReplacements(3, CancellationToken.None);
var list = result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<List<PathReplacementResponseModel>>();
list.Single().RemotePath.ShouldBe("/plex");
list.Single().LocalPath.ShouldBe("/local");
}
// ----- P7 ReplacePathReplacements -----
[Test]
public async Task ReplacePathReplacements_Should_Return_404_When_Source_Missing()
{
SourceExists(false);
IActionResult result = await _controller.ReplacePathReplacements(
9,
new ReplacePathReplacementsRequest([new PathReplacementItemRequest(0, "/remote", "/local")]),
CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
await _mediator.DidNotReceive().Send(Arg.Any<UpdatePlexPathReplacements>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task ReplacePathReplacements_Should_Return_422_On_Handler_Left()
{
SourceExists(true);
_mediator.Send(Arg.Any<UpdatePlexPathReplacements>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(BaseError.New("cross-source")));
IActionResult result = await _controller.ReplacePathReplacements(
3,
new ReplacePathReplacementsRequest([new PathReplacementItemRequest(99, "/remote", "/local")]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
}
[Test]
public async Task ReplacePathReplacements_Should_Return_200_Reloaded_On_Success()
{
SourceExists(true);
_mediator.Send(Arg.Any<UpdatePlexPathReplacements>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
_mediator.Send(Arg.Any<GetPlexPathReplacementsBySourceId>(), Arg.Any<CancellationToken>())
.Returns(new List<PlexPathReplacementViewModel> { new(7, "/plex", "/local") });
IActionResult result = await _controller.ReplacePathReplacements(
3,
new ReplacePathReplacementsRequest([new PathReplacementItemRequest(7, "/plex", "/local")]),
CancellationToken.None);
var list = result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<List<PathReplacementResponseModel>>();
list.Single().Id.ShouldBe(7);
}
// ----- P8 RefreshLibraries -----
[Test]
public async Task RefreshLibraries_Should_Return_404_When_Source_Missing()
{
SourceExists(false);
IActionResult result = await _controller.RefreshLibraries(9, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
await _channel.DidNotReceive().WriteAsync(
Arg.Any<IScannerBackgroundServiceRequest>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task RefreshLibraries_Should_Return_409_When_Plex_Locked()
{
SourceExists(true);
_entityLocker.IsPlexLocked().Returns(true);
IActionResult result = await _controller.RefreshLibraries(3, CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(409);
await _channel.DidNotReceive().WriteAsync(
Arg.Any<IScannerBackgroundServiceRequest>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task RefreshLibraries_Should_Return_202_And_Enqueue()
{
SourceExists(true);
_entityLocker.IsPlexLocked().Returns(false);
IActionResult result = await _controller.RefreshLibraries(3, CancellationToken.None);
result.ShouldBeOfType<AcceptedResult>();
await _channel.Received(1).WriteAsync(
Arg.Is<SynchronizePlexLibraries>(s => s.PlexMediaSourceId == 3),
Arg.Any<CancellationToken>());
}
// ----- P9 ScanCollections -----
[Test]
public async Task ScanCollections_Should_Return_404_When_Source_Missing()
{
SourceExists(false);
IActionResult result = await _controller.ScanCollections(9, cancellationToken: CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
_entityLocker.DidNotReceive().LockPlexCollections();
await _channel.DidNotReceive().WriteAsync(
Arg.Any<IScannerBackgroundServiceRequest>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task ScanCollections_Should_Return_409_When_Collections_Locked()
{
SourceExists(true);
_entityLocker.LockPlexCollections().Returns(false);
IActionResult result = await _controller.ScanCollections(3, cancellationToken: CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().Value.ShouldBeOfType<ProblemDetails>().Status.ShouldBe(409);
await _channel.DidNotReceive().WriteAsync(
Arg.Any<IScannerBackgroundServiceRequest>(),
Arg.Any<CancellationToken>());
}
[Test]
public async Task ScanCollections_Should_Return_202_And_Enqueue()
{
SourceExists(true);
_entityLocker.LockPlexCollections().Returns(true);
IActionResult result = await _controller.ScanCollections(3, deep: true, CancellationToken.None);
result.ShouldBeOfType<AcceptedResult>();
await _channel.Received(1).WriteAsync(
Arg.Is<SynchronizePlexCollections>(s => s.PlexMediaSourceId == 3 && s.ForceScan && s.DeepScan),
Arg.Any<CancellationToken>());
}
[Test]
public async Task ScanCollections_Should_Compensate_Unlock_When_Enqueue_Throws()
{
SourceExists(true);
_entityLocker.LockPlexCollections().Returns(true);
_channel.WriteAsync(Arg.Any<SynchronizePlexCollections>(), Arg.Any<CancellationToken>())
.Returns<ValueTask>(_ => throw new InvalidOperationException("channel closed"));
await Should.ThrowAsync<InvalidOperationException>(
() => _controller.ScanCollections(3, cancellationToken: CancellationToken.None));
_entityLocker.Received(1).UnlockPlexCollections();
}
private void SourceExists(bool exists) =>
_mediator.Send(Arg.Any<GetPlexMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(exists
? Option<PlexMediaSourceViewModel>.Some(new PlexMediaSourceViewModel(3, "Server", "http://plex:32400"))
: Option<PlexMediaSourceViewModel>.None);
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
{
MethodInfo action = typeof(PlexMediaSourcesController).GetMethod(actionName)
?? throw new AssertionException($"Missing action {actionName}");
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain(httpMethod);
attribute.Template.ShouldBe(route);
}
}