using System.Reflection; using ErsatzTV.Application.Scheduling; using ErsatzTV.Controllers.Api; using ErsatzTV.Controllers.Api.Requests; using ErsatzTV.Core; using ErsatzTV.Core.Api.Scheduling; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Domain.Scheduling; using ErsatzTV.Core.Errors; 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 static LanguageExt.Prelude; using Unit = LanguageExt.Unit; namespace ErsatzTV.Tests.Controllers; [TestFixture] public class BlockControllerTests { private BlockController _controller = null!; private IMediator _mediator = null!; [SetUp] public void SetUp() { _mediator = Substitute.For(); _controller = new BlockController(_mediator) { // Provide a real HttpContext so the ETag/If-Match concurrency headers (#253) can be // read from Request and written to Response. ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; } [Test] public void Controller_Should_Expose_Idiomatic_Rest_Routes() { ShouldHaveActionRoute(nameof(BlockController.GetGroups), "GET", "/api/v1/blocks/groups"); ShouldHaveActionRoute(nameof(BlockController.CreateGroup), "POST", "/api/v1/blocks/groups"); ShouldHaveActionRoute(nameof(BlockController.DeleteGroup), "DELETE", "/api/v1/blocks/groups/{id:int}"); ShouldHaveActionRoute(nameof(BlockController.GetAll), "GET", "/api/v1/blocks"); ShouldHaveActionRoute(nameof(BlockController.GetById), "GET", "/api/v1/blocks/{id:int}"); ShouldHaveActionRoute(nameof(BlockController.Create), "POST", "/api/v1/blocks"); ShouldHaveActionRoute(nameof(BlockController.Delete), "DELETE", "/api/v1/blocks/{id:int}"); ShouldHaveActionRoute(nameof(BlockController.GetItems), "GET", "/api/v1/blocks/{id:int}/items"); ShouldHaveActionRoute(nameof(BlockController.Replace), "PUT", "/api/v1/blocks/{id:int}"); ShouldHaveActionRoute(nameof(BlockController.Preview), "POST", "/api/v1/blocks/{id:int}/preview"); ShouldHaveActionRoute(nameof(BlockController.Copy), "POST", "/api/v1/blocks/{id:int}/copy"); } [Test] public async Task CreateGroup_Should_Return_201_With_Location_And_Body() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Right(new BlockGroupViewModel(5, "Prime Time"))); IActionResult result = await _controller.CreateGroup( new CreateBlockGroupRequest("Prime Time"), CancellationToken.None); var created = result.ShouldBeOfType(); created.Location.ShouldBe("/api/v1/blocks/groups/5"); created.Value.ShouldBeOfType().Name.ShouldBe("Prime Time"); await _mediator.Received(1).Send( Arg.Is(c => c.Name == "Prime Time"), Arg.Any()); } [Test] public async Task CreateGroup_Should_Return_422_On_Validation_Error() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Left(BaseError.New("bad"))); IActionResult result = await _controller.CreateGroup( new CreateBlockGroupRequest(string.Empty), CancellationToken.None); result.ShouldBeOfType(); } [Test] public async Task DeleteGroup_Should_Return_204_When_Exists() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List { new(3, "Prime Time") }); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.DeleteGroup(3, CancellationToken.None); result.ShouldBeOfType(); await _mediator.Received(1).Send( Arg.Is(c => c.BlockGroupId == 3), Arg.Any()); } [Test] public async Task DeleteGroup_Should_Return_404_When_Missing() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List()); IActionResult result = await _controller.DeleteGroup(99, CancellationToken.None); result.ShouldBeOfType(); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] public async Task GetAll_Should_Map_ViewModels_To_Response_Models() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List { MakeBlock(1, 2, "Morning") }); List result = await _controller.GetAll(CancellationToken.None); result.Count.ShouldBe(1); result[0].Id.ShouldBe(1); result[0].GroupId.ShouldBe(2); result[0].Name.ShouldBe("Morning"); } [Test] public async Task Create_Should_Return_201_And_Map_Request() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Right(MakeBlock(8, 2, "Morning"))); IActionResult result = await _controller.Create( new CreateBlockRequest(2, "Morning"), CancellationToken.None); var created = result.ShouldBeOfType(); created.Location.ShouldBe("/api/v1/blocks/8"); await _mediator.Received(1).Send( Arg.Is(c => c.BlockGroupId == 2 && c.Name == "Morning"), Arg.Any()); } [Test] public async Task Create_Should_Return_422_On_Validation_Error() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Left(BaseError.New("dupe"))); IActionResult result = await _controller.Create( new CreateBlockRequest(2, "Morning"), CancellationToken.None); result.ShouldBeOfType(); } [Test] public async Task GetById_Should_Return_200_For_Some() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 2, "Morning"))); IActionResult result = await _controller.GetById(4, CancellationToken.None); result.ShouldBeOfType().Value.ShouldBeOfType().Id.ShouldBe(4); } [Test] public async Task GetById_Should_Return_404_For_None() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.GetById(4, CancellationToken.None); result.ShouldBeOfType(); } [Test] public async Task Delete_Should_Return_204_When_Exists() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 2, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.Delete(4, CancellationToken.None); result.ShouldBeOfType(); } [Test] public async Task Delete_Should_Return_404_When_Missing() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.Delete(4, CancellationToken.None); result.ShouldBeOfType(); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] public async Task GetItems_Should_Return_200_Ordered_By_Index() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 2, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List { MakeItem(20, 1), MakeItem(10, 0) }); IActionResult result = await _controller.GetItems(4, CancellationToken.None); var items = result.ShouldBeOfType().Value.ShouldBeOfType>(); items.Count.ShouldBe(2); items[0].Index.ShouldBe(0); items[1].Index.ShouldBe(1); } [Test] public async Task GetItems_Should_Return_404_When_Block_Missing() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.GetItems(4, CancellationToken.None); result.ShouldBeOfType(); } [Test] public async Task Replace_Should_Return_200_With_Refreshed_Block_And_Assign_Index_And_GroupId() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 7, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Right(Unit.Default)); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List { MakeItem(10, 0), MakeItem(11, 1) }); IActionResult result = await _controller.Replace( 4, new ReplaceBlockRequest( "Morning", 60, BlockStopScheduling.BeforeDurationEnd, [MakeItemRequest(), MakeItemRequest()]), CancellationToken.None); var body = result.ShouldBeOfType().Value.ShouldBeOfType(); body.Id.ShouldBe(4); body.Items.Count.ShouldBe(2); await _mediator.Received(1).Send( Arg.Is(c => c.BlockId == 4 && c.BlockGroupId == 7 && c.Minutes == 60 && c.StopScheduling == BlockStopScheduling.BeforeDurationEnd && c.Items.Count == 2 && c.Items[0].Index == 0 && c.Items[1].Index == 1), Arg.Any()); } [Test] public async Task GetItems_Should_Set_ETag_From_Block_Version() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 2, "Morning", version: 9))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List()); await _controller.GetItems(4, CancellationToken.None); _controller.Response.Headers.ETag.ToString().ShouldBe("\"9\""); } [Test] public async Task Replace_Should_Return_400_On_Malformed_If_Match() { _controller.Request.Headers.IfMatch = "not-an-etag"; IActionResult result = await _controller.Replace( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); result.ShouldBeOfType(); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] public async Task Replace_Should_Thread_If_Match_Version_Into_Command() { _controller.Request.Headers.IfMatch = "\"3\""; _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 7, "Morning", version: 4))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Right(Unit.Default)); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List()); IActionResult result = await _controller.Replace( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); result.ShouldBeOfType(); // On success the response carries the refreshed block's ETag. _controller.Response.Headers.ETag.ToString().ShouldBe("\"4\""); await _mediator.Received(1).Send( Arg.Is(c => c.ExpectedVersions == Option>.Some(new[] { 3 }.ToSeq())), Arg.Any()); } [Test] public async Task Replace_Without_If_Match_Should_Force_Write() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 7, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Right(Unit.Default)); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List()); await _controller.Replace( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); await _mediator.Received(1).Send( Arg.Is(c => c.ExpectedVersions == Option>.None), Arg.Any()); } [Test] public async Task Replace_Should_Return_412_On_Precondition_Failed() { _controller.Request.Headers.IfMatch = "\"2\""; _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 7, "Morning", version: 5))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Left(new PreconditionFailedError("stale"))); IActionResult result = await _controller.Replace( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); var objectResult = result.ShouldBeOfType(); objectResult.StatusCode.ShouldBe(StatusCodes.Status412PreconditionFailed); } [Test] public async Task Replace_Should_Return_404_When_Block_Missing() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.Replace( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); result.ShouldBeOfType(); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] public async Task Replace_Should_Return_422_On_Validation_Error() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 7, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Left(BaseError.New("bad minutes"))); IActionResult result = await _controller.Replace( 4, new ReplaceBlockRequest("Morning", 7, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); result.ShouldBeOfType(); } [Test] public async Task Preview_Should_Return_200_With_Preview_Items() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 7, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(new List { new("Show", TimeSpan.Zero, TimeSpan.FromMinutes(30), "00:30:00") }); IActionResult result = await _controller.Preview( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, [MakeItemRequest()]), CancellationToken.None); var items = result.ShouldBeOfType().Value .ShouldBeOfType>(); items.Count.ShouldBe(1); items[0].Title.ShouldBe("Show"); await _mediator.Received(1).Send( Arg.Is(p => p.Data.BlockId == 4 && p.Data.BlockGroupId == 7), Arg.Any()); } [Test] public async Task Preview_Should_Return_404_When_Block_Missing() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.Preview( 4, new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []), CancellationToken.None); result.ShouldBeOfType(); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] public async Task Copy_Should_Return_201_And_Map_Request() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 2, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Right(MakeBlock(9, 3, "Morning Copy"))); IActionResult result = await _controller.Copy( 4, new CopyBlockRequest(3, "Morning Copy"), CancellationToken.None); var created = result.ShouldBeOfType(); created.Location.ShouldBe("/api/v1/blocks/9"); await _mediator.Received(1).Send( Arg.Is(c => c.BlockId == 4 && c.NewBlockGroupId == 3 && c.NewBlockName == "Morning Copy"), Arg.Any()); } [Test] public async Task Copy_Should_Return_404_When_Source_Missing() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.None); IActionResult result = await _controller.Copy( 4, new CopyBlockRequest(3, "Morning Copy"), CancellationToken.None); result.ShouldBeOfType(); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] public async Task Copy_Should_Return_422_On_Validation_Error() { _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Option.Some(MakeBlock(4, 2, "Morning"))); _mediator.Send(Arg.Any(), Arg.Any()) .Returns(Left(BaseError.New("dupe"))); IActionResult result = await _controller.Copy( 4, new CopyBlockRequest(3, "Morning"), CancellationToken.None); result.ShouldBeOfType(); } private static BlockViewModel MakeBlock(int id, int groupId, string name, int version = 1) => new(id, groupId, "Group", name, 30, BlockStopScheduling.AfterDurationEnd, version); private static BlockItemViewModel MakeItem(int id, int index) => new( id, index, CollectionType.SearchQuery, null!, null!, null!, null!, "News", "news", PlaybackOrder.Shuffle, IncludeInProgramGuide: true, DisableWatermarks: false, [], []); private static BlockItemRequest MakeItemRequest() => new( CollectionType.SearchQuery, CollectionId: null, MultiCollectionId: null, SmartCollectionId: null, MediaItemId: null, SearchTitle: "News", SearchQuery: "news", PlaybackOrder: PlaybackOrder.Shuffle, IncludeInProgramGuide: true, DisableWatermarks: false, WatermarkIds: [], GraphicsElementIds: []); private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route) { MethodInfo action = typeof(BlockController).GetMethod(actionName) ?? throw new AssertionException($"Missing action {actionName}"); HttpMethodAttribute attribute = action.GetCustomAttributes(inherit: true).Single(); attribute.HttpMethods.ShouldContain(httpMethod); attribute.Template.ShouldBe(route); } }