shoc-backend/Api.SeaHavenIndustries.Tests/CalendarControllerTests.cs
Alexandre Brandizzi 7d245eb717
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

206 lines
8.6 KiB
C#

using System.Collections;
using Api.SeaHavenIndustries.Controllers;
using Api.SeaHavenIndustries.DTOs;
using Data.SeaHavenIndustries;
using FluentAssertions;
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 CalendarControllerTests
{
private static EditEvent_DTO ValidDto(int? id = null, string title = "Standup") => new()
{
Id = id,
Title = title,
ReminderMinutes = 15,
EventColor = "primary",
StartDate = new DateTime(2026, 6, 1),
StartTime = "08:00 AM",
EndDate = new DateTime(2026, 6, 1),
EndTime = "08:30 AM"
};
private static CalendarController NewController(Mock<ICalendarService> service) =>
new(service.Object, Mock.Of<ILogger<CalendarController>>());
private static object Prop(object source, string name) =>
source.GetType().GetProperty(name)!.GetValue(source)!;
[Fact]
public async Task AddEvent_WhenServiceSucceeds_ReturnsOkWithCreatedMessage()
{
var service = new Mock<ICalendarService>();
var result = await NewController(service).AddEvent(ValidDto(), 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("Event Created Successfully");
service.Verify(s => s.CreateEventAsync(It.IsAny<EditEventInput>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task AddEvent_WhenServiceThrows_ReturnsSanitizedMessageAndLogsInternally()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.CreateEventAsync(It.IsAny<EditEventInput>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("SECRET-internal-db-connection-leak"));
var logger = new Mock<ILogger<CalendarController>>();
logger.Setup(x => x.IsEnabled(It.IsAny<LogLevel>())).Returns(true);
var controller = new CalendarController(service.Object, logger.Object);
var result = await controller.AddEvent(ValidDto(), CancellationToken.None);
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
var response = bad.Value.Should().BeOfType<Response>().Subject;
response.Status.Should().Be("Error");
response.Message.Should().NotContain("SECRET");
response.Message.Should().NotContain("internal-db-connection-leak");
response.Message.Should().Contain("reference");
logger.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.IsAny<It.IsAnyType>(),
It.Is<Exception>(ex => ex.Message.Contains("SECRET")),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
}
[Fact]
public async Task EditEvent_WhenIdMissing_ReturnsBadRequestWithoutCallingService()
{
var service = new Mock<ICalendarService>();
var result = await NewController(service).EditEvent(ValidDto(id: null), CancellationToken.None);
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
var response = bad.Value.Should().BeOfType<Response>().Subject;
response.Message.Should().Be("Event ID is required for editing");
service.Verify(s => s.UpdateEventAsync(It.IsAny<EditEventInput>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task EditEvent_WhenServiceReturnsFalse_ReturnsNotFound()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.UpdateEventAsync(It.IsAny<EditEventInput>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
var result = await NewController(service).EditEvent(ValidDto(id: 5), CancellationToken.None);
var nf = result.Should().BeOfType<NotFoundObjectResult>().Subject;
var response = nf.Value.Should().BeOfType<Response>().Subject;
response.Message.Should().Be("Event not found");
}
[Fact]
public async Task EditEvent_WhenServiceReturnsTrue_ReturnsOkWithUpdatedMessage()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.UpdateEventAsync(It.IsAny<EditEventInput>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
var result = await NewController(service).EditEvent(ValidDto(id: 5, title: "New"), CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
ok.Value.Should().BeOfType<DataResponse>().Which.Message.Should().Be("Event Updated Successfully");
}
[Fact]
public async Task GetEventById_WhenServiceReturnsNull_ReturnsNotFound()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.GetEventByIdAsync(7, It.IsAny<CancellationToken>())).ReturnsAsync((EventDTO?)null);
var result = await NewController(service).GetEventById(7, CancellationToken.None);
result.Should().BeOfType<NotFoundObjectResult>();
}
[Fact]
public async Task GetEventById_WhenServiceReturnsDto_ReturnsOkWithEventDto()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.GetEventByIdAsync(7, It.IsAny<CancellationToken>()))
.ReturnsAsync(new EventDTO { Id = 7, Title = "Review", createdby = "abc" });
var result = await NewController(service).GetEventById(7, CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
var response = ok.Value.Should().BeOfType<DataResponse>().Subject;
var dto = response.Data as Event_DTO;
dto.Should().NotBeNull();
dto!.Title.Should().Be("Review");
dto!.createdby.Should().Be("abc");
}
[Fact]
public async Task DeleteEvent_WhenServiceReturnsFalse_ReturnsNotFound()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.DeleteEventAsync(9, It.IsAny<CancellationToken>())).ReturnsAsync(false);
var result = await NewController(service).DeleteEvent(9, CancellationToken.None);
result.Should().BeOfType<NotFoundObjectResult>();
}
[Fact]
public async Task DeleteEvent_WhenServiceReturnsTrue_ReturnsOkWithDeletedMessage()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.DeleteEventAsync(9, It.IsAny<CancellationToken>())).ReturnsAsync(true);
var result = await NewController(service).DeleteEvent(9, CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
ok.Value.Should().BeOfType<DataResponse>().Which.Message.Should().Be("Event Deleted Successfully");
}
[Fact]
public async Task GetEventList_ReturnsOkWithRowsAndTotalCount()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.GetEventListAsync("alpha", 1, 10, It.IsAny<CancellationToken>()))
.ReturnsAsync(new PagedEventsResult
{
TotalCount = 2,
Rows = new List<EventDTO>
{
new() { Id = 1, Title = "Alpha meeting" },
new() { Id = 2, Title = "Alpha review" }
}
});
var result = await NewController(service).GetEventList(search: "alpha", page: 1, pageSize: 10);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
var data = ok.Value.Should().BeOfType<DataResponse>().Subject.Data!;
((int)Prop(data, "totalCount")).Should().Be(2);
var rows = ((IEnumerable)Prop(data, "rows")).Cast<Event_DTO>().ToList();
rows.Should().HaveCount(2);
}
[Fact]
public async Task GetEventsForCalendar_ReturnsOkWithEvents()
{
var service = new Mock<ICalendarService>();
service.Setup(s => s.GetEventsForCalendarAsync(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<EventDTO> { new() { Id = 1, Title = "InRange" } });
var result = await NewController(service).GetEventsForCalendar(
start: new DateTime(2026, 6, 1), end: new DateTime(2026, 6, 30), CancellationToken.None);
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
var data = ok.Value.Should().BeOfType<DataResponse>().Subject.Data;
var events = ((IEnumerable)data!).Cast<Event_DTO>().ToList();
events.Single().Title.Should().Be("InRange");
}
}