Files
ersatztv/ErsatzTV.Tests/Controllers/SearchControllerTests.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

197 lines
7.2 KiB
C#

using System.Reflection;
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Application.MediaItems;
using ErsatzTV.Application.Search;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Core.Api.Scheduling;
using ErsatzTV.Core.Api.Search;
using ErsatzTV.Core.Domain;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class SearchControllerTests
{
private SearchController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new SearchController(_mediator);
}
[Test]
public void Controller_Should_Expose_Search_Route_With_Stable_Operation_Name()
{
MethodInfo action = typeof(SearchController).GetMethod(nameof(SearchController.Search))
?? throw new AssertionException($"Missing action {nameof(SearchController.Search)}");
var attribute = action.GetCustomAttributes<HttpGetAttribute>().Single();
attribute.Template.ShouldBe("/api/v1/search");
attribute.Name.ShouldBe("Search");
}
[Test]
public async Task Search_Should_Return_422_For_Empty_Query()
{
IActionResult result = await _controller.Search(" ", 0, 50, CancellationToken.None);
var unprocessable = result.ShouldBeOfType<UnprocessableEntityObjectResult>();
unprocessable.StatusCode.ShouldBe(422);
await _mediator.DidNotReceive().Send(Arg.Any<GetSearchResults>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Search_Should_Clamp_PageSize_And_Send_Query()
{
_mediator.Send(Arg.Any<GetSearchResults>(), Arg.Any<CancellationToken>())
.Returns(EmptyResults());
IActionResult result = await _controller.Search("star", 0, 500, CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>();
await _mediator.Received(1).Send(
Arg.Is<GetSearchResults>(q => q.Query == "star" && q.PageSize == 100),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Search_Should_Thread_PageNum_And_Clamp_Negative()
{
_mediator.Send(Arg.Any<GetSearchResults>(), Arg.Any<CancellationToken>())
.Returns(EmptyResults());
// A valid page number is threaded through; a negative one clamps to 0.
await _controller.Search("star", 3, 50, CancellationToken.None);
await _mediator.Received(1).Send(
Arg.Is<GetSearchResults>(q => q.Query == "star" && q.PageNum == 3 && q.PageSize == 50),
Arg.Any<CancellationToken>());
await _controller.Search("star", -7, 50, CancellationToken.None);
await _mediator.Received(1).Send(
Arg.Is<GetSearchResults>(q => q.Query == "star" && q.PageNum == 0 && q.PageSize == 50),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Search_Should_Return_Grouped_Results()
{
SearchResultsResponseModel results = EmptyResults();
_mediator.Send(Arg.Any<GetSearchResults>(), Arg.Any<CancellationToken>()).Returns(results);
IActionResult result = await _controller.Search("star", 0, 50, CancellationToken.None);
var ok = result.ShouldBeOfType<OkObjectResult>();
ok.Value.ShouldBe(results);
}
[Test]
public void Controller_Should_Expose_SearchAllItems_Route_With_Stable_Operation_Name()
{
MethodInfo action = typeof(SearchController).GetMethod(nameof(SearchController.SearchAllItems))
?? throw new AssertionException($"Missing action {nameof(SearchController.SearchAllItems)}");
var attribute = action.GetCustomAttributes<HttpGetAttribute>().Single();
attribute.Template.ShouldBe("/api/v1/search/all-items");
attribute.Name.ShouldBe("SearchAllItems");
}
[Test]
public async Task SearchAllItems_Should_Return_422_For_Empty_Query()
{
IActionResult result = await _controller.SearchAllItems(" ", CancellationToken.None);
var unprocessable = result.ShouldBeOfType<UnprocessableEntityObjectResult>();
unprocessable.StatusCode.ShouldBe(422);
await _mediator.DidNotReceive().Send(Arg.Any<QuerySearchIndexAllItems>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task SearchAllItems_Should_Map_Id_Lists()
{
_mediator.Send(Arg.Any<QuerySearchIndexAllItems>(), Arg.Any<CancellationToken>())
.Returns(new SearchResultAllItemsViewModel(
[1, 2],
[3],
[],
[],
[],
[],
[],
[],
[],
[]));
IActionResult result = await _controller.SearchAllItems("star", CancellationToken.None);
var body = result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<SearchResultAllItemsResponseModel>();
body.MovieIds.ShouldBe(new List<int> { 1, 2 });
body.ShowIds.ShouldBe(new List<int> { 3 });
await _mediator.Received(1).Send(
Arg.Is<QuerySearchIndexAllItems>(q => q.Query == "star"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task SearchCollections_Should_Map_To_Picker_Options()
{
_mediator.Send(Arg.Any<SearchCollections>(), Arg.Any<CancellationToken>())
.Returns(new List<MediaCollectionViewModel>
{
new(CollectionType.Collection, 3, "Movies", false, new MediaItemState())
});
List<SchedulingPickerOptionResponseModel> result =
await _controller.SearchCollections("mov", CancellationToken.None);
result.ShouldHaveSingleItem();
result[0].Id.ShouldBe(3);
result[0].Name.ShouldBe("Movies");
await _mediator.Received(1).Send(
Arg.Is<SearchCollections>(q => q.Query == "mov"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task SearchTelevisionShows_Should_Map_MediaItemId_To_Option_Id()
{
_mediator.Send(Arg.Any<SearchTelevisionShows>(), Arg.Any<CancellationToken>())
.Returns(new List<NamedMediaItemViewModel> { new(42, "The Show") });
List<SchedulingPickerOptionResponseModel> result =
await _controller.SearchTelevisionShows("show", CancellationToken.None);
result.ShouldHaveSingleItem();
result[0].Id.ShouldBe(42);
result[0].Name.ShouldBe("The Show");
}
[Test]
public async Task SearchSmartCollections_Should_Map_To_Picker_Options()
{
_mediator.Send(Arg.Any<SearchSmartCollections>(), Arg.Any<CancellationToken>())
.Returns(new List<SmartCollectionViewModel> { new(9, "Recent", "query") });
List<SchedulingPickerOptionResponseModel> result =
await _controller.SearchSmartCollections("rec", CancellationToken.None);
result.ShouldHaveSingleItem();
result[0].Id.ShouldBe(9);
}
private static SearchResultsResponseModel EmptyResults()
{
var empty = new SearchResultGroupResponseModel(0, []);
return new SearchResultsResponseModel(empty, empty, empty, empty, empty, empty, empty, empty, empty, empty);
}
}