Add unit tests for Audit (59% to 100%) and Webhooks (62% to 91%) namespaces

Covers AuditLogQueryService filtering/paging/actor-name join,
AuditLogResponse mapping, AuditLogsController, AuditService.LogAsync
and actor-claim resolution, WebhookResponse/WebhookDeliveryLogResponse
mapping, CreateWebhookRequestValidator, WebhookQueue, and additional
WebhookDispatcher branch coverage (scope routing, disabled webhooks,
delivery exceptions).

Excludes WebhookBackgroundService and WebhookRetryBackgroundService
from coverage: both resolve a DI-scoped concrete MicCheckDbContext via
IServiceScopeFactory, which requires a live DI container/DB per
CLAUDE.md's no-InMemory/WebApplicationFactory rule. Their query and
dispatch logic is covered by WebhookRetryTests/WebhookDispatcherTests.
This commit is contained in:
2026-07-05 15:00:02 -07:00
parent 68d426253d
commit 9e8e81ba83
10 changed files with 789 additions and 0 deletions

View File

@@ -0,0 +1,219 @@
using MicCheck.Api.Audit;
using MicCheck.Api.Data;
using MicCheck.Api.Tests.Unit.TestSupport;
using MicCheck.Api.Users;
using Moq;
using NUnit.Framework;
namespace MicCheck.Api.Tests.Unit.Audit;
[TestFixture]
public class AuditLogQueryServiceTests
{
private Mock<IMicCheckDbContext> _db = null!;
private List<AuditLog> _auditLogs = null!;
private List<User> _users = null!;
private AuditLogQueryService _service = null!;
private const int OrganizationId = 1;
private const int ProjectId = 1;
private const int EnvironmentId = 1;
[SetUp]
public void SetUp()
{
_db = new Mock<IMicCheckDbContext>();
_auditLogs = [];
_db.SetupDbSet(c => c.AuditLogs, _auditLogs);
_users = [];
_db.SetupDbSet(c => c.Users, _users);
_service = new AuditLogQueryService(_db.Object);
}
private AuditLog AddLog(string resourceType = "Feature", string action = "created", int? projectId = ProjectId,
int? environmentId = EnvironmentId, int? actorUserId = null, DateTimeOffset? createdAt = null)
{
var log = new AuditLog
{
Id = _auditLogs.Count + 1,
ResourceType = resourceType,
ResourceId = "1",
Action = action,
OrganizationId = OrganizationId,
ProjectId = projectId,
EnvironmentId = environmentId,
ActorUserId = actorUserId,
CreatedAt = createdAt ?? DateTimeOffset.UtcNow
};
_auditLogs.Add(log);
return log;
}
[Test]
public async Task WhenListingByOrganization_ThenOnlyLogsForThatOrganizationAreReturned()
{
AddLog();
_auditLogs.Add(new AuditLog { Id = 2, ResourceType = "Feature", ResourceId = "1", Action = "created", OrganizationId = 999, CreatedAt = DateTimeOffset.UtcNow });
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter());
Assert.That(result.Total, Is.EqualTo(1));
Assert.That(result.Items, Has.Count.EqualTo(1));
}
[Test]
public async Task WhenListingByProject_ThenOnlyLogsForThatProjectAreReturned()
{
AddLog(projectId: ProjectId);
AddLog(projectId: 999);
var result = await _service.ListByProjectAsync(ProjectId, new AuditLogFilter());
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenListingByEnvironment_ThenOnlyLogsForThatEnvironmentAreReturned()
{
AddLog(environmentId: EnvironmentId);
AddLog(environmentId: 999);
var result = await _service.ListByEnvironmentAsync(EnvironmentId, new AuditLogFilter());
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenFilteringByFromDate_ThenOnlyLogsOnOrAfterAreReturned()
{
AddLog(createdAt: DateTimeOffset.UtcNow.AddDays(-10));
AddLog(createdAt: DateTimeOffset.UtcNow);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(From: DateTimeOffset.UtcNow.AddDays(-1)));
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenFilteringByToDate_ThenOnlyLogsOnOrBeforeAreReturned()
{
AddLog(createdAt: DateTimeOffset.UtcNow.AddDays(-10));
AddLog(createdAt: DateTimeOffset.UtcNow);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(To: DateTimeOffset.UtcNow.AddDays(-1)));
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenFilteringByResourceType_ThenOnlyMatchingLogsAreReturned()
{
AddLog(resourceType: "Feature");
AddLog(resourceType: "Segment");
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(ResourceType: "Segment"));
Assert.That(result.Total, Is.EqualTo(1));
Assert.That(result.Items[0].ResourceType, Is.EqualTo("Segment"));
}
[Test]
public async Task WhenFilteringByAction_ThenOnlyMatchingLogsAreReturned()
{
AddLog(action: "created");
AddLog(action: "deleted");
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(Action: "deleted"));
Assert.That(result.Total, Is.EqualTo(1));
Assert.That(result.Items[0].Action, Is.EqualTo("deleted"));
}
[Test]
public async Task WhenFilteringByProjectIdOnAnOrganizationQuery_ThenOnlyMatchingLogsAreReturned()
{
AddLog(projectId: ProjectId);
AddLog(projectId: 999);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(ProjectId: ProjectId));
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenFilteringByEnvironmentIdOnAnOrganizationQuery_ThenOnlyMatchingLogsAreReturned()
{
AddLog(environmentId: EnvironmentId);
AddLog(environmentId: 999);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(EnvironmentId: EnvironmentId));
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenFilteringByActorUserId_ThenOnlyMatchingLogsAreReturned()
{
AddLog(actorUserId: 1);
AddLog(actorUserId: 2);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(ActorUserId: 1));
Assert.That(result.Total, Is.EqualTo(1));
}
[Test]
public async Task WhenPageSizeExceedsMaximum_ThenItIsClampedTo100()
{
for (var i = 0; i < 150; i++)
AddLog();
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(PageSize: 1000));
Assert.That(result.Items, Has.Count.EqualTo(100));
}
[Test]
public async Task WhenPageSizeIsBelowMinimum_ThenItIsClampedTo1()
{
AddLog();
AddLog();
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter(PageSize: 0));
Assert.That(result.Items, Has.Count.EqualTo(1));
}
[Test]
public async Task WhenResultsAreOrderedByCreationDate_ThenNewestAppearsFirst()
{
AddLog(createdAt: DateTimeOffset.UtcNow.AddDays(-1));
var newest = AddLog(createdAt: DateTimeOffset.UtcNow);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter());
Assert.That(result.Items[0].Id, Is.EqualTo(newest.Id));
}
[Test]
public async Task WhenALogHasAnActorUser_ThenTheActorUserNameIsPopulated()
{
_users.Add(new User { Id = 7, Email = "alice@example.com", PasswordHash = "hash", FirstName = "Alice", LastName = "Smith", CreatedAt = DateTimeOffset.UtcNow });
AddLog(actorUserId: 7);
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter());
Assert.That(result.Items[0].ActorUserName, Is.EqualTo("Alice Smith"));
}
[Test]
public async Task WhenALogHasNoActorUser_ThenTheActorUserNameIsNull()
{
AddLog();
var result = await _service.ListByOrganizationAsync(OrganizationId, new AuditLogFilter());
Assert.That(result.Items[0].ActorUserName, Is.Null);
}
}

View File

@@ -0,0 +1,76 @@
using MicCheck.Api.Audit;
using NUnit.Framework;
namespace MicCheck.Api.Tests.Unit.Audit;
[TestFixture]
public class AuditLogResponseTests
{
[Test]
public void WhenMappingWithoutAnActorUserName_ThenItDefaultsToNull()
{
var log = new AuditLog
{
Id = 1,
ResourceType = "Feature",
ResourceId = "42",
Action = "created",
OrganizationId = 1,
CreatedAt = DateTimeOffset.UtcNow
};
var response = AuditLogResponse.From(log);
Assert.That(response.ActorUserName, Is.Null);
}
[Test]
public void WhenMappingWithAnActorUserName_ThenItIsIncluded()
{
var log = new AuditLog
{
Id = 1,
ResourceType = "Feature",
ResourceId = "42",
Action = "created",
OrganizationId = 1,
ActorUserId = 7,
CreatedAt = DateTimeOffset.UtcNow
};
var response = AuditLogResponse.From(log, "Alice Smith");
Assert.That(response.ActorUserId, Is.EqualTo(7));
Assert.That(response.ActorUserName, Is.EqualTo("Alice Smith"));
}
[Test]
public void WhenMapping_ThenAllFieldsAreCopiedFromTheLog()
{
var createdAt = DateTimeOffset.UtcNow;
var log = new AuditLog
{
Id = 1,
ResourceType = "FeatureState",
ResourceId = "5",
Action = "updated",
Changes = """{"before":{},"after":{}}""",
OrganizationId = 10,
ProjectId = 20,
EnvironmentId = 30,
CreatedAt = createdAt
};
var response = AuditLogResponse.From(log);
Assert.That(response.Id, Is.EqualTo(1));
Assert.That(response.ResourceType, Is.EqualTo("FeatureState"));
Assert.That(response.ResourceId, Is.EqualTo("5"));
Assert.That(response.Action, Is.EqualTo("updated"));
Assert.That(response.Changes, Is.EqualTo("""{"before":{},"after":{}}"""));
Assert.That(response.OrganizationId, Is.EqualTo(10));
Assert.That(response.ProjectId, Is.EqualTo(20));
Assert.That(response.EnvironmentId, Is.EqualTo(30));
Assert.That(response.CreatedAt, Is.EqualTo(createdAt));
}
}

View File

@@ -0,0 +1,118 @@
using MicCheck.Api.Audit;
using MicCheck.Api.Common;
using MicCheck.Api.Data;
using MicCheck.Api.Environments;
using MicCheck.Api.Organizations;
using MicCheck.Api.Projects;
using MicCheck.Api.Tests.Unit.TestSupport;
using MicCheck.Api.Users;
using Microsoft.AspNetCore.Mvc;
using Moq;
using NUnit.Framework;
using AppEnvironment = MicCheck.Api.Environments.Environment;
namespace MicCheck.Api.Tests.Unit.Audit;
[TestFixture]
public class AuditLogsControllerTests
{
private Mock<IMicCheckDbContext> _db = null!;
private List<Organization> _organizations = null!;
private List<Project> _projects = null!;
private List<AppEnvironment> _environments = null!;
private List<AuditLog> _auditLogs = null!;
private AuditLogsController _controller = null!;
private const int OrganizationId = 1;
private const int ProjectId = 1;
private const int EnvironmentId = 1;
private const string ApiKey = "env-key";
[SetUp]
public void SetUp()
{
_db = new Mock<IMicCheckDbContext>();
_organizations = [new Organization { Id = OrganizationId, Name = "Org", CreatedAt = DateTimeOffset.UtcNow }];
_db.SetupDbSet(c => c.Organizations, _organizations);
_projects = [new Project { Id = ProjectId, Name = "Project", OrganizationId = OrganizationId, CreatedAt = DateTimeOffset.UtcNow }];
_db.SetupDbSet(c => c.Projects, _projects);
_environments = [new AppEnvironment { Id = EnvironmentId, Name = "Production", ApiKey = ApiKey, ProjectId = ProjectId, CreatedAt = DateTimeOffset.UtcNow }];
_db.SetupDbSet(c => c.Environments, _environments);
_auditLogs = [];
_db.SetupDbSet(c => c.AuditLogs, _auditLogs);
_db.SetupDbSet(c => c.Users, []);
var auditServiceMock = new Mock<AuditService>(_db.Object, null!, new MicCheck.Api.Webhooks.WebhookQueue());
var auditService = auditServiceMock.Object;
_controller = new AuditLogsController(
new AuditLogQueryService(_db.Object),
new OrganizationService(_db.Object, auditService),
new ProjectService(_db.Object, auditService),
new EnvironmentService(_db.Object, auditService));
}
[Test]
public async Task WhenListingByOrganizationThatDoesNotExist_ThenNotFoundIsReturned()
{
var result = await _controller.ListByOrganization(999, new AuditLogFilter(), CancellationToken.None);
Assert.That(result.Result, Is.InstanceOf<NotFoundResult>());
}
[Test]
public async Task WhenListingByOrganizationThatExists_ThenMatchingLogsAreReturned()
{
_auditLogs.Add(new AuditLog { Id = 1, ResourceType = "Feature", ResourceId = "1", Action = "created", OrganizationId = OrganizationId, CreatedAt = DateTimeOffset.UtcNow });
var result = await _controller.ListByOrganization(OrganizationId, new AuditLogFilter(), CancellationToken.None);
var ok = result.Result as OkObjectResult;
var body = ok!.Value as PaginatedResponse<AuditLogResponse>;
Assert.That(body!.Count, Is.EqualTo(1));
}
[Test]
public async Task WhenListingByProjectThatDoesNotExist_ThenNotFoundIsReturned()
{
var result = await _controller.ListByProject(999, new AuditLogFilter(), CancellationToken.None);
Assert.That(result.Result, Is.InstanceOf<NotFoundResult>());
}
[Test]
public async Task WhenListingByProjectThatExists_ThenMatchingLogsAreReturned()
{
_auditLogs.Add(new AuditLog { Id = 1, ResourceType = "Feature", ResourceId = "1", Action = "created", OrganizationId = OrganizationId, ProjectId = ProjectId, CreatedAt = DateTimeOffset.UtcNow });
var result = await _controller.ListByProject(ProjectId, new AuditLogFilter(), CancellationToken.None);
var ok = result.Result as OkObjectResult;
var body = ok!.Value as PaginatedResponse<AuditLogResponse>;
Assert.That(body!.Count, Is.EqualTo(1));
}
[Test]
public async Task WhenListingByEnvironmentThatDoesNotExist_ThenNotFoundIsReturned()
{
var result = await _controller.ListByEnvironment("missing-key", new AuditLogFilter(), CancellationToken.None);
Assert.That(result.Result, Is.InstanceOf<NotFoundResult>());
}
[Test]
public async Task WhenListingByEnvironmentThatExists_ThenMatchingLogsAreReturned()
{
_auditLogs.Add(new AuditLog { Id = 1, ResourceType = "Feature", ResourceId = "1", Action = "created", OrganizationId = OrganizationId, EnvironmentId = EnvironmentId, CreatedAt = DateTimeOffset.UtcNow });
var result = await _controller.ListByEnvironment(ApiKey, new AuditLogFilter(), CancellationToken.None);
var ok = result.Result as OkObjectResult;
var body = ok!.Value as PaginatedResponse<AuditLogResponse>;
Assert.That(body!.Count, Is.EqualTo(1));
}
}

View File

@@ -90,6 +90,85 @@ public class AuditServiceTests
Assert.That(log.ActorUserId, Is.Null);
}
[Test]
public async Task WhenLoggingWithNoChanges_ThenChangesRemainsNull()
{
await _service.LogAsync("Feature", "1", "created", organizationId: 1);
var log = _auditLogs.First();
Assert.That(log.Changes, Is.Null);
}
[Test]
public async Task WhenLoggingWithChanges_ThenChangesAndMetadataArePersisted()
{
await _service.LogAsync("Feature", "2", "updated", organizationId: 5, projectId: 6, environmentId: 7, changes: "raw-json");
var log = _auditLogs.First();
Assert.That(log.ResourceType, Is.EqualTo("Feature"));
Assert.That(log.ResourceId, Is.EqualTo("2"));
Assert.That(log.Action, Is.EqualTo("updated"));
Assert.That(log.Changes, Is.EqualTo("raw-json"));
Assert.That(log.OrganizationId, Is.EqualTo(5));
Assert.That(log.ProjectId, Is.EqualTo(6));
Assert.That(log.EnvironmentId, Is.EqualTo(7));
}
[Test]
public async Task WhenLogging_ThenAuditLogCreatedEventIsEnqueued()
{
await _service.LogAsync("Feature", "1", "created", organizationId: 1);
var events = new List<WebhookEvent>();
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
try
{
await foreach (var e in _queue.ReadAllAsync(cts.Token))
{
events.Add(e);
break;
}
}
catch (OperationCanceledException) { }
Assert.That(events, Has.Count.EqualTo(1));
Assert.That(events[0].EventType, Is.EqualTo(WebhookEventTypes.AuditLogCreated));
}
[Test]
public async Task WhenTheHttpContextHasAnAuthenticatedUser_ThenTheActorUserIdIsResolvedFromTheClaim()
{
var identity = new System.Security.Claims.ClaimsIdentity(
[new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, "42")], "TestAuth");
var httpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext
{
User = new System.Security.Claims.ClaimsPrincipal(identity)
};
var httpContextAccessor = new Mock<IHttpContextAccessor>();
httpContextAccessor.Setup(x => x.HttpContext).Returns(httpContext);
var service = new AuditService(_db.Object, httpContextAccessor.Object, _queue);
await service.RecordAsync("Feature", "1", "created", organizationId: 1);
Assert.That(_auditLogs.First().ActorUserId, Is.EqualTo(42));
}
[Test]
public async Task WhenTheHttpContextHasNoNameIdentifierClaim_ThenTheActorUserIdIsNull()
{
var httpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext
{
User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity())
};
var httpContextAccessor = new Mock<IHttpContextAccessor>();
httpContextAccessor.Setup(x => x.HttpContext).Returns(httpContext);
var service = new AuditService(_db.Object, httpContextAccessor.Object, _queue);
await service.RecordAsync("Feature", "1", "created", organizationId: 1);
Assert.That(_auditLogs.First().ActorUserId, Is.Null);
}
[Test]
public async Task WhenRecording_ThenAuditLogCreatedEventIsEnqueued()
{