shoc-backend/Api.SeaHavenIndustries.Tests/LocationControllerTests.cs

125 lines
5.1 KiB
C#
Raw Normal View History

refactor: enforce backend boundaries and optimize dispatch (#30) * refactor(api): enforce service and data-service boundaries * refactor(api): complete feature service boundaries * refactor(identity): enforce service and data boundaries * refactor(vendors): enforce service and data boundaries * refactor(workorders): enforce service and data boundaries * refactor(backend): enforce architecture and optimize dispatch * style(backend): format changed architecture files * fix(architecture): address backend review follow-ups * fix(backend): sanitize exception disclosure in changed API endpoints Replace raw exception-message disclosure (ex.Message) returned to API callers with a stable sanitized public message plus correlated structured internal logging, across the endpoints changed in this PR. - Add SanitizedErrors helper: logs the original exception at Error with a generated correlation id and returns a stable public message referencing it so support can trace without exposing internals. - Inject ILogger<T> into the 14 changed controllers and route every ex.Message/dbex.Message disclosure through the helper, preserving status codes, response shapes, and business data (e.g. OpenWorkOrders). - Leave FluentValidation (vex.Errors) and existing fixed-message catches untouched; out-of-scope controllers (Account/Contact/Employee/Asset/ PMSchedule) are unchanged. - Add focused tests proving internal exception text is not returned and that Error logging carrying the original exception is invoked. * fix(architecture): abstract job run state access * style: format board update service * test: use collection assertion idiom
2026-07-24 17:35:34 -03:00
using Api.SeaHavenIndustries.Controllers;
using Api.SeaHavenIndustries.DTOs;
using Data.SeaHavenIndustries;
using FluentAssertions;
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using SeaHaven.Services.DTOs;
using SeaHaven.Services.Interfaces;
using Xunit;
namespace Api.SeaHavenIndustries.Tests;
public class LocationControllerTests
{
private static LocationController NewController(Mock<ILocationService> service) =>
new(service.Object, Mock.Of<ILogger<LocationController>>());
private static object Prop(object source, string name) =>
source.GetType().GetProperty(name)!.GetValue(source)!;
[Fact]
public async Task GetLocationList_ReturnsPaginationEnvelopeWithServiceData()
{
var service = new Mock<ILocationService>();
service.Setup(s => s.GetLocationListPagedAsync(1, 10, "a", It.IsAny<CancellationToken>()))
.ReturnsAsync(new PagedResult<LocationDTO>
{
Items = new List<LocationDTO> { new() { Id = 1, Name = "Site" } },
TotalCount = 1,
Page = 1,
PageSize = 10
});
var result = await NewController(service).GetLocationList("a", 1, 10, CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
var envelope = ok.Value.Should().BeOfType<Pagination_DTO>().Subject;
envelope.PageNumber.Should().Be(1);
envelope.PageSize.Should().Be(10);
envelope.TotalCount.Should().Be(1);
envelope.TotalPages.Should().Be(1);
}
[Fact]
public async Task GetLocationById_WhenMissing_ReturnsNotFoundAndDoesNotLeakEntity()
{
var service = new Mock<ILocationService>();
service.Setup(s => s.GetLocationDetailAsync(5, It.IsAny<CancellationToken>()))
.ReturnsAsync((LocationDTO?)null);
var result = await NewController(service).GetLocationById(5, CancellationToken.None);
var notFound = result.Should().BeOfType<NotFoundObjectResult>().Subject;
var response = notFound.Value.Should().BeOfType<Response>().Subject;
response.Message.Should().Be("Location not found");
}
[Fact]
public async Task GetLocationById_WhenFound_MapsServiceDtoToAliasedShape()
{
var service = new Mock<ILocationService>();
service.Setup(s => s.GetLocationDetailAsync(7, It.IsAny<CancellationToken>()))
.ReturnsAsync(new LocationDTO { Id = 7, Name = "N", Address1 = "A", Zip = "Z", PhoneNumber = "P", Email = "E", Status = "Active" });
var result = await NewController(service).GetLocationById(7, CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
var body = ok.Value!;
Prop(body, "Id").Should().Be(7);
Prop(body, "Name").Should().Be("N");
Prop(body, "Address").Should().Be("A");
Prop(body, "ZipCode").Should().Be("Z");
Prop(body, "Phone").Should().Be("P");
Prop(body, "ContactEmail").Should().Be("E");
Prop(body, "Status").Should().Be("Active");
}
[Fact]
public async Task AddLocation_WhenServiceSucceeds_ReturnsCreatedResponse()
{
var service = new Mock<ILocationService>();
var result = await NewController(service).AddLocation(new Location_DTO { Name = "X" }, CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
var response = ok.Value.Should().BeOfType<DataResponse>().Subject;
response.Status.Should().Be("200");
response.Message.Should().Be("Location Created Successfully");
service.Verify(s => s.CreateLocationFromRequestAsync(It.IsAny<LocationCreateRequestDTO>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task AddLocation_MapsAccountIdFromBodyString()
{
var service = new Mock<ILocationService>();
LocationCreateRequestDTO? captured = null;
service
.Setup(s => s.CreateLocationFromRequestAsync(It.IsAny<LocationCreateRequestDTO>(), It.IsAny<CancellationToken>()))
.Callback<LocationCreateRequestDTO, CancellationToken>((dto, _) => captured = dto)
.Returns(Task.CompletedTask);
var result = await NewController(service).AddLocation(
new Location_DTO { Name = "X", AccountId = "1" },
CancellationToken.None);
result.Should().BeOfType<OkObjectResult>();
captured.Should().NotBeNull();
captured!.AccountId.Should().Be(1);
}
refactor: enforce backend boundaries and optimize dispatch (#30) * refactor(api): enforce service and data-service boundaries * refactor(api): complete feature service boundaries * refactor(identity): enforce service and data boundaries * refactor(vendors): enforce service and data boundaries * refactor(workorders): enforce service and data boundaries * refactor(backend): enforce architecture and optimize dispatch * style(backend): format changed architecture files * fix(architecture): address backend review follow-ups * fix(backend): sanitize exception disclosure in changed API endpoints Replace raw exception-message disclosure (ex.Message) returned to API callers with a stable sanitized public message plus correlated structured internal logging, across the endpoints changed in this PR. - Add SanitizedErrors helper: logs the original exception at Error with a generated correlation id and returns a stable public message referencing it so support can trace without exposing internals. - Inject ILogger<T> into the 14 changed controllers and route every ex.Message/dbex.Message disclosure through the helper, preserving status codes, response shapes, and business data (e.g. OpenWorkOrders). - Leave FluentValidation (vex.Errors) and existing fixed-message catches untouched; out-of-scope controllers (Account/Contact/Employee/Asset/ PMSchedule) are unchanged. - Add focused tests proving internal exception text is not returned and that Error logging carrying the original exception is invoked. * fix(architecture): abstract job run state access * style: format board update service * test: use collection assertion idiom
2026-07-24 17:35:34 -03:00
[Fact]
public async Task EditLocation_WhenMissing_ReturnsNotFound()
{
var service = new Mock<ILocationService>();
service.Setup(s => s.UpdateLocationFromRequestAsync(99, It.IsAny<LocationUpdateRequestDTO>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new KeyNotFoundException());
var result = await NewController(service).EditLocation(99, new EditLocation_DTO { Name = "X" }, CancellationToken.None);
var notFound = result.Should().BeOfType<NotFoundObjectResult>().Subject;
notFound.Value.Should().BeOfType<Response>().Subject.Message.Should().Be("Location not found");
}
}