diff --git a/docs/superpowers/plans/2026-07-23-test-coverage-80pct.md b/docs/superpowers/plans/2026-07-23-test-coverage-80pct.md new file mode 100644 index 0000000..c263e8a --- /dev/null +++ b/docs/superpowers/plans/2026-07-23-test-coverage-80pct.md @@ -0,0 +1,227 @@ +# Test Coverage 80% Implementation Plan + +> **For agentic workers:** This plan covers 4 phases (~330 tests) across 6 source projects. +> Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Raise global test coverage from ~15% to 80%+ across all Heimdall projects + +**Architecture:** Layer-by-layer (Domain → Application → Infrastructure → Web) following Clean Architecture dependency order. Each phase is independently buildable and testable. + +**Tech Stack:** xUnit v3, NSubstitute, Shouldly, FluentValidation.TestHelper, coverlet + +--- + +## Global Constraints + +- All tests use xUnit `[Fact]` / `[Theory]` +- Assertions via Shouldly (`ShouldBe`, `ShouldNotBe`, `ShouldBeTrue`, etc.) +- Mocking via NSubstitute (`Substitute.For()`) +- Handler tests mock `IApplicationDbContext` with `NSubstitute` DbSet mocks +- All tests must pass before commit (`dotnet test`) +- One commit per logical unit within each phase +- Push only after all phases complete (+ learning-agent) + +--- + +## File Structure + +### Phase 1 — Domain Layer + +**New test files:** +- `tests/Heimdall.Domain.Tests/Primitives/EntityTests.cs` +- `tests/Heimdall.Domain.Tests/Primitives/ValueObjectTests.cs` +- `tests/Heimdall.Domain.Tests/Enums/EnumValuesTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/ApiKeyTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/AppSettingTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/AgentSettingTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/AuditLogTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/CameraAssignmentTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/CameraCredentialsTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/CameraEventTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/GroupTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/PersonTests.cs` +- `tests/Heimdall.Domain.Tests/Entities/RevokedRefreshTokenTests.cs` + +**Modified test files:** +- `tests/Heimdall.Domain.Tests/Entities/CameraTests.cs` (add methods) +- `tests/Heimdall.Domain.Tests/Entities/AgentTests.cs` (add methods) + +### Phase 2 — Application Layer + +**New test files:** +- `tests/Heimdall.Application.Tests/Services/ServiceResultTests.cs` +- `tests/Heimdall.Application.Tests/Behaviors/ValidationBehaviorTests.cs` +- `tests/Heimdall.Application.Tests/Behaviors/LoggingBehaviorTests.cs` +- `tests/Heimdall.Application.Tests/Mappings/MappingProfileTests.cs` +- `tests/Heimdall.Application.Tests/Handlers/Sites/CreateSiteHandlerTests.cs` +- `tests/Heimdall.Application.Tests/Handlers/Sites/UpdateSiteHandlerTests.cs` +- `tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs` +- `tests/Heimdall.Application.Tests/Handlers/Sites/GetSitesHandlerTests.cs` +- ...(one per handler) + +### Phase 3 — Infrastructure Layer + +**New test files:** +- `tests/Heimdall.Infrastructure.Tests/Security/JwtServiceTests.cs` +- `tests/Heimdall.Infrastructure.Tests/Security/CredentialProtectorTests.cs` +- `tests/Heimdall.Infrastructure.Tests/Security/RolePermissionServiceTests.cs` +- ...(one per service) + +### Phase 4 — Web Layer + +**New test files:** +- `tests/Heimdall.Web.Tests/Controllers/ControllerBaseExtensionsTests.cs` +- `tests/Heimdall.Web.Tests/Filters/ExceptionFilterTests.cs` +- New scenarios in `tests/Heimdall.IntegrationTests/Controllers/` + +--- + +## Phase 1 — Domain Layer + +### Task 1.1: Domain.Primitives tests + +**Files:** +- Create: `tests/Heimdall.Domain.Tests/Primitives/EntityTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Primitives/ValueObjectTests.cs` + +- [ ] **Step 1: Write EntityTests.cs** + +Entity tests: equality, GetHashCode, operator==, operator!=, same/different IDs, null comparisons, different entity types. + +- [ ] **Step 2: Write ValueObjectTests.cs** + +ValueObject tests: equality by components, GetHashCode, null handling, different components, derived types. + +- [ ] **Step 3: Build and run tests** + +- [ ] **Step 4: Commit** + +--- + +### Task 1.2: Enum values tests + +**Files:** +- Create: `tests/Heimdall.Domain.Tests/Enums/EnumValuesTests.cs` + +- [ ] **Step 1-2**: Write EnumValuesTests.cs — verify all enum types have expected values and counts + +- [ ] **Step 3-4**: Build, test, commit + +--- + +### Task 1.3: Entity tests — ApiKey, AppSetting, AgentSetting, AuditLog, RevokedRefreshToken + +**Files:** +- Create: `tests/Heimdall.Domain.Tests/Entities/ApiKeyTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/AppSettingTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/AgentSettingTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/AuditLogTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/RevokedRefreshTokenTests.cs` + +Simple entities with few methods — combine into one task for efficiency. + +--- + +### Task 1.4: Entity tests — CameraAssignment, CameraCredentials, CameraEvent + +- Create: `tests/Heimdall.Domain.Tests/Entities/CameraAssignmentTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/CameraCredentialsTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/CameraEventTests.cs` + +--- + +### Task 1.5: Entity tests — Group, Person + +- Create: `tests/Heimdall.Domain.Tests/Entities/GroupTests.cs` +- Create: `tests/Heimdall.Domain.Tests/Entities/PersonTests.cs` + +--- + +### Task 1.6: Augment CameraTests and AgentTests + +- Modify: `tests/Heimdall.Domain.Tests/Entities/CameraTests.cs` — add tests for SetCapabilities, SetDiscoveryInfo, SetPorts, SetCapabilityFlags, SetStreamTestResult, SetCredentials, SetDetectionProfile, SoftDelete, AssignAgent(null) +- Modify: `tests/Heimdall.Domain.Tests/Entities/AgentTests.cs` — add tests for Register, UpdateHeartbeat, MarkOffline, MarkError, UpdateCapabilities, SoftDelete + +--- + +## Phase 2 — Application Layer + +### Task 2.1: ServiceResult tests + +**Files:** +- Create: `tests/Heimdall.Application.Tests/Services/ServiceResultTests.cs` +- Test ALL factory methods, both generic and non-generic variants + +### Task 2.2: Pipeline Behaviors tests + +- Create: `tests/Heimdall.Application.Tests/Behaviors/ValidationBehaviorTests.cs` +- Create: `tests/Heimdall.Application.Tests/Behaviors/LoggingBehaviorTests.cs` + +### Task 2.3: AutoMapper profiles tests + +- Create: `tests/Heimdall.Application.Tests/Mappings/MappingProfileTests.cs` + +### Task 2.4-N: CQRS Handler tests (one task per ~3-5 handlers) + +Each handler test follows the same pattern: +1. Mock `IApplicationDbContext` with `NSubstitute` +2. Mock relevant `DbSet` with async query support +3. Create handler with mocked context +4. Assert ServiceResult properties + +Handlers grouped by feature: +- Sites (2.4): CreateSite, UpdateSite, DeleteSite, GetSite, GetSites +- Cameras (2.5): CreateCamera, DeleteCamera, SetCredentials, GetCamera, GetCamerasBySite +- Auth (2.6): Login, Register, RegisterAdmin, RefreshToken, ChangePassword +- Agents (2.7): RegisterAgent, Heartbeat, GetAgent, GetAgentsBySite, GetAllAgents +- Users (2.8): CreateUser, UpdateUser, DeleteUser, AssignRoles, AssignSites, LockUser, UnlockUser, ResetPassword, GetMe, GetUser, GetUsers +- Events (2.9): CreateEvent, DeleteEvent, AttachSnapshot, GetEvent, GetEvents, GetRecentByCamera +- Assignments (2.10): AssignCamera, ReleaseCamera, AssignSite, Failover, GetActiveAssignment, GetAgentAssignments, GetCameraHistory +- Discovery (2.11): ScanSubnet, ProbeIp, TestStreams, ConfirmDiscovery, BuildStreamUrls, CancelTestSession, CheckDuplicate, GetScreenshot, GetTestSession, SearchDatabase +- Groups (2.12): CreateGroup, UpdateGroup, DeleteGroup, AddUserToGroup, RemoveUserFromGroup, GetGroup, GetGroups, GetGroupMembers +- Persons (2.13): CreatePerson, UpdatePerson, DeletePerson, RegisterFace, DeleteFace, GetPerson, GetPersons, GetFaces +- Settings (2.14): CreateAppSetting, UpdateAppSetting, DeleteAppSetting, SetAgentSetting, RemoveAgentSetting, GetSettings, GetSettingByKey, GetAgentSettings, GetEffectiveAgentConfig +- Stats/Audit (2.15): GetStats, GetAgentStats, GetAuditLogs + +--- + +## Phase 3 — Infrastructure Layer + +### Task 3.1: Security services tests + +- Create: `tests/Heimdall.Infrastructure.Tests/Security/JwtServiceTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Security/CredentialProtectorTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Security/RolePermissionServiceTests.cs` + +### Task 3.2: Application services tests + +- Create: `tests/Heimdall.Infrastructure.Tests/Services/PersonServiceTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Services/CameraEventServiceTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Services/CameraAssignmentServiceTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Services/Discovery/HttpProbeServiceTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Services/Discovery/MdnsProbeServiceTests.cs` +- Create: `tests/Heimdall.Infrastructure.Tests/Services/Discovery/OnvifProbeServiceTests.cs` + +### Task 3.3: Background jobs and data layer tests + +- Add to `tests/Heimdall.Infrastructure.Tests/`: HeartbeatMonitorJobTests, AgentFailoverJobTests +- Add: Data/DbContextExtensionsTests, Persistence/UserRepositoryTests + +--- + +## Phase 4 — Web Layer + +### Task 4.1: Controller extensions and filters + +- Create: `tests/Heimdall.Web.Tests/Controllers/ControllerBaseExtensionsTests.cs` +- Create: `tests/Heimdall.Web.Tests/Filters/ExceptionFilterTests.cs` + +### Task 4.2: Integration test scenarios (new) + +- Add to existing `tests/Heimdall.IntegrationTests/Controllers/`: Groups, Persons, Stats, Audit, Permissions, Roles, Health + +### Task 4.3: SignalR hubs and web services + +- Create: `tests/Heimdall.Web.Tests/Hubs/ConfigHubTests.cs` +- Create: `tests/Heimdall.Web.Tests/Hubs/EventsHubTests.cs` +- Create: `tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs` diff --git a/docs/superpowers/specs/2026-07-23-test-coverage-80pct-design.md b/docs/superpowers/specs/2026-07-23-test-coverage-80pct-design.md new file mode 100644 index 0000000..3616c32 --- /dev/null +++ b/docs/superpowers/specs/2026-07-23-test-coverage-80pct-design.md @@ -0,0 +1,172 @@ +# Test Coverage 80% — Design Document + +**Date**: 2026-07-23 +**Project**: Heimdall — Camera management & surveillance platform +**Goal**: Minimum 80% global line/branch coverage across all projects + +--- + +## Current State + +| Metric | Value | +|---|---| +| Total tests | 226 (all passing) | +| Current coverage (line) | ~7-15% per project, ~52% integration | +| Target coverage (line) | 80%+ | +| Source projects | 6 (Domain.Primitives, Domain, Application, Infrastructure, Web, Agent) | +| Test projects | 7 (Domain.Tests, Application.Tests, Infrastructure.Tests, Agent.Tests, Api.Tests, Web.Tests, IntegrationTests) + TestCommon | + +--- + +## Strategy: Layer-by-Layer (Approved) + +Follow Clean Architecture dependency order: Domain → Application → Infrastructure → Web. +Each layer is fully tested before moving to the next. + +--- + +## Phase 1 — Domain Layer (~60 tests, +15-18% coverage) + +### 1a. Domain.Primitives +- `Entity`: Equals, GetHashCode, ==, !=, null handling, different types +- `ValueObject`: Equals, GetHashCode, same vs different values, null handling + +### 1b. Entities (14 untested files) +- `ApiKey`: MarkUsed, Disable, SetExpiry +- `AppSetting`: UpdateValue, UpdateMetadata (Description/Category/ValueType/AllowedValues null vs set) +- `AgentSetting`: UpdateValue +- `AppUser`: navigation collections initialized +- `AuditLog`: constructor with all parameters +- `Camera`: SetCapabilities, SetDiscoveryInfo, SetPorts, SetCapabilityFlags, SetStreamTestResult, SetCredentials, SetDetectionProfile, SoftDelete, AssignAgent(null) +- `CameraAssignment`: Release (idempotent), IsActive +- `CameraCredentials`: SetCredentials +- `CameraEvent`: SetSnapshot, SetMetadata, AssignAgent +- `Group`: SetName validation throws, Update, SoftDelete +- `Person`/`KnownFace`: Update, SetPhoto, AddFace, constructor +- `RevokedRefreshToken`: constructor validation +- `CameraDetectionProfile`: constructor/methods +- `CameraDiscoveryResult`: constructor/methods +- `DiscoveredStreamUrl`: constructor/methods +- `UserGroup`/`UserSite`: constructors + +### 1c. Enums +- AgentStatus, CameraCapability, CameraDiscoveryMethod, CameraStatus, DetectedCameraType, EventType, GpuAcceleration, StatType, StorageProvider, StreamProtocol, UserRole — verify defined values and counts + +--- + +## Phase 2 — Application Layer (~150 tests, +30-35% coverage) + +### 2a. ServiceResult +- ServiceResult and ServiceResult: Success, Failure, NotFound, Unauthorized, Conflict — IsSuccess, StatusCode, Data, Error + +### 2b. CQRS Handlers (~40 handlers) +Each handler tested with NSubstitute-mocked `IApplicationDbContext`. Pattern: Arrange DbSet mock → Act → Assert ServiceResult properties. + +- **Auth (7)**: Login, Register, RegisterAdmin, RefreshToken, ChangePassword, Enable2fa, Disable2fa, Verify2fa, Logout +- **Sites (4)**: CreateSite, UpdateSite, DeleteSite, GenerateSiteToken + GetSite, GetSites +- **Cameras (3)**: CreateCamera, DeleteCamera, SetCredentials + GetCamera, GetCamerasBySite +- **Agents (3)**: RegisterAgent, Heartbeat + GetAgent, GetAgentsBySite, GetAllAgents +- **Users (8)**: CreateUser, UpdateUser, DeleteUser, AssignRoles, AssignSites, LockUser, UnlockUser, ResetPassword + GetMe, GetUser, GetUsers +- **Events (4)**: CreateEvent, DeleteEvent, AttachSnapshot + GetEvent, GetEvents, GetRecentByCamera +- **Assignments (4)**: AssignCamera, ReleaseCamera, AssignSite, Failover + GetActiveAssignment, GetAgentAssignments, GetCameraHistory +- **Discovery (6)**: ScanSubnet, ProbeIp, TestStreams, ConfirmDiscovery, BuildStreamUrls, CancelTestSession + CheckDuplicate, GetScreenshot, GetTestSession, SearchDatabase +- **Groups (4)**: CreateGroup, UpdateGroup, DeleteGroup, AddUserToGroup, RemoveUserFromGroup + GetGroup, GetGroups, GetGroupMembers +- **Persons (4)**: CreatePerson, UpdatePerson, DeletePerson, RegisterFace, DeleteFace + GetPerson, GetPersons, GetFaces +- **Settings (5)**: CreateAppSetting, UpdateAppSetting, DeleteAppSetting, SetAgentSetting, RemoveAgentSetting + GetSettings, GetSettingByKey, GetAgentSettings, GetEffectiveAgentConfig +- **Stats (2)**: GetStats, GetAgentStats +- **Audit (1)**: GetAuditLogs + +### 2c. Pipeline Behaviors (2) +- `ValidationBehavior`: 0 validators, 1 validator (pass/fail), N validators (all fail, mixed), reflection Failure() fallback for invalid TResponse +- `LoggingBehavior`: success path logs, exception path logs error, stopwatch measurement + +### 2d. AutoMapper Profiles (12 profiles) +- Configuration validation for each profile (AssertConfigurationIsValid) +- Mapping round-trip tests for key DTO↔Entity pairs + +### 2e. Remaining Validators +- Complementary edge cases for already-tested validators + +### 2f. AuthHelper +- ComputeHash, GenerateToken, password validation + +--- + +## Phase 3 — Infrastructure Layer (~80 tests, +10-15% coverage) + +### 3a. Services +- `JwtService`: token generation, validation, refresh (with mocked IOptions) +- `CredentialProtector`: encrypt/decrypt round-trip +- `RolePermissionService`: permission checks +- `AuthDataService`: CRUD via mocked UserManager +- `AuthSignInService`: sign-in flows +- `PersonService`: CRUD via mocked IApplicationDbContext +- `CameraEventService`: event creation, snapshot attachment +- `CameraAssignmentService`: assignment/release/failover + +### 3b. Discovery Services (new tests) +- `HttpProbeServiceTests` +- `MdnsProbeServiceTests` +- `OnvifProbeServiceTests` + +### 3c. Background Jobs +- `HeartbeatMonitorJob`: timeout detection, status transitions +- `AgentFailoverJob`: failover logic, assignment handling + +### 3d. Data Layer +- `AppDbContext`: entity configurations, query filters, interceptor behavior +- `DbContextExtensions`: SaveChangesWithRetryAsync +- `UserRepository`: CRUD patterns + +--- + +## Phase 4 — Web / API Layer (~40 tests, +8-12% coverage) + +### 4a. Controller Extensions +- `ControllerBaseExtensions`: Ok, BadRequest, helpers + +### 4b. Integration Tests (new scenarios) +- Groups controller CRUD +- Persons controller CRUD +- Stats endpoints +- Audit logs endpoint +- Permissions/Roles endpoints +- Health endpoint + +### 4c. ExceptionFilter +- Catch and format exceptions as ProblemDetails + +### 4d. SignalR Hubs +- ConfigHub methods +- EventsHub methods + +### 4e. Web Services +- `HeimdallApiClient`: HTTP call patterns +- `HeimdallAuthStateProvider`: auth state lifecycle +- `TokenRefreshHandler`: refresh logic + +--- + +## Estimated Effort + +| Phase | Tests | Est. time | Coverage gain | +|---|---|---|---| +| Phase 1 — Domain | ~60 | ~2h | +15-18% | +| Phase 2 — Application | ~150 | ~6h | +30-35% | +| Phase 3 — Infrastructure | ~80 | ~4h | +10-15% | +| Phase 4 — Web | ~40 | ~2h | +8-12% | +| **Total** | **~330** | **~14h** | **Target 80%** | + +--- + +## Commit Strategy + +One commit per logical unit within each phase (e.g., "test(domain): add entity tests for ApiKey, AppSetting, Group"). +Push only after all phases complete. + +--- + +## Learning & Reflection + +At end of full process: invoke learning-agent for cross-project pattern analysis, +store findings as `heimdall/ref/learning-{date}`, then final push.