Files
KArtSell.Aegis/tests/KArtSell.Integration.Tests/ApprovalWorkflow/ApprovalWorkflowTests.cs
T
kjh2064 2ccf74c410 fix: Release build breakage + Dapper mapping bugs in VS-03/VS-04/Phase3-K
- KArtSell.Host.csproj: FrontendFiles glob was evaluated at project-load
  time, before pnpm build ran, so it copied stale/missing Vite-hashed
  filenames every Release build. Move the glob inside the target, after
  the build Exec.
- ApprovalSql/AuditSql/TradeSql: fix live-DB integration failures never
  caught by unit tests: DateOnly and inet columns can't be bound/read
  directly through Dapper without conversion; kis_response (jsonb) read
  as JsonElement threw InvalidCastException; GdprRetention.RetentionEndsAt
  was typed DateTime against a DATE column.
- TradeSql: UpdateTradeStatusAsync only ever persisted status/kis_response
  /error_message, silently dropping kis_order_id, executed_quantity,
  unit_price, total_amount, commission, net_proceeds and the execution/
  settlement timestamps on every call. Changed it to take the Trade
  aggregate so the full state transition persists.
- TradeSql: add a static ctor setting Dapper.DefaultTypeMap.
  MatchNamesWithUnderscores = true. The repo's [ModuleInitializer] in
  KArtSell.BuildingBlocks only fires once that assembly is actually
  loaded; TradeSql/Trade never reference a BuildingBlocks type, so under
  test isolation (or any host that queries a trade before touching
  BuildingBlocks) every snake_case column silently mapped to null/default.
- Test fixes: seed the FK prerequisites (model_operations.models,
  sell_decisions) that ApprovalWorkflowTests/TradeExecutionTests were
  missing, correct a SellPriorityRanker test input to match the approved
  VS-10-SLICE_SPEC age-boost threshold, and fix a GDPR redaction
  assertion that called ToString() on a Dictionary instead of inspecting
  its values.

12 DbUpMigrationTests failures remain and are unrelated to this fix: the
kartsell DB user isn't the owner of kartsell_migration_test, so DbUp's
fresh-database rehearsal can't DROP/CREATE it. Needs a DBA grant.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-07 23:21:04 +09:00

211 lines
6.1 KiB
C#

namespace KArtSell.Integration.Tests.ApprovalWorkflow;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;
using Xunit;
using KArtSell.BuildingBlocks.Time;
using KArtSell.Modules.ModelOperations.ApprovalWorkflow;
public class ApprovalWorkflowTests : IAsyncLifetime
{
private readonly string _connectionString;
private readonly ApprovalSql _sql;
private readonly ApprovalPolicy _policy;
private readonly IOutbox _outbox;
public ApprovalWorkflowTests()
{
_connectionString = "Host=localhost;Port=5432;Database=kartselldb;Username=kartsell;Password=kartsell4321@!";
_sql = new ApprovalSql(_connectionString, new SystemClock());
_policy = new ApprovalPolicy(new SystemClock());
_outbox = new InMemoryOutbox();
}
public async Task InitializeAsync()
{
// Ensure database is ready
await Task.CompletedTask;
}
public async Task DisposeAsync()
{
await Task.CompletedTask;
}
[Fact]
public void CanCreateProposal_WithMakerRole_ReturnsTrue()
{
// Arrange
var makerEmail = "maker@company.com";
var makerRole = "Maker";
// Act
var result = _policy.CanCreateProposal(makerEmail, makerRole);
// Assert
Assert.True(result);
}
[Fact]
public void CanCreateProposal_WithoutMakerRole_ReturnsFalse()
{
// Arrange
var email = "user@company.com";
var role = "Viewer";
// Act
var result = _policy.CanCreateProposal(email, role);
// Assert
Assert.False(result);
}
[Fact]
public void CanApproveApproval_WithDifferentChecker_ReturnsTrue()
{
// Arrange
var maker = "maker@company.com";
var checker = "checker@company.com";
var proposal = new ApprovalProposal { CreatedBy = maker, Status = ApprovalStatus.Proposed };
// Act
var result = _policy.CanApproveApproval(proposal, checker, maker);
// Assert
Assert.True(result);
}
[Fact]
public void CanApproveApproval_WithSameMaker_ReturnsFalse()
{
// Arrange
var maker = "maker@company.com";
var proposal = new ApprovalProposal { CreatedBy = maker, Status = ApprovalStatus.Proposed };
// Act
var result = _policy.CanApproveApproval(proposal, maker, maker);
// Assert
Assert.False(result);
}
[Fact]
public void CreateProposal_SetsCorrectDefaults()
{
// Arrange
var modelId = Guid.NewGuid();
var maker = "maker@company.com";
var justification = "Model passed OOS testing";
var effectiveAt = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(7));
// Act
var proposal = _policy.CreateProposal(modelId, maker, justification, effectiveAt);
// Assert
Assert.Equal(modelId, proposal.ModelId);
Assert.Equal(maker, proposal.CreatedBy);
Assert.Equal(ApprovalStatus.Draft, proposal.Status);
Assert.Equal(justification, proposal.Justification);
Assert.Equal(effectiveAt, proposal.EffectiveAt);
}
[Fact]
public void ProposeApproval_TransitionsToProposed()
{
// Arrange
var proposal = new ApprovalProposal
{
Id = Guid.NewGuid(),
CreatedBy = "maker@company.com",
Status = ApprovalStatus.Draft,
Justification = "Test",
EffectiveAt = DateOnly.FromDateTime(DateTime.UtcNow)
};
// Act
var updated = _policy.ProposeApproval(proposal, "maker@company.com");
// Assert
Assert.Equal(ApprovalStatus.Proposed, updated.Status);
Assert.NotNull(updated.ProposedAt);
}
[Fact]
public void ApproveApproval_AddsEvidence()
{
// Arrange
var proposal = new ApprovalProposal
{
Id = Guid.NewGuid(),
CreatedBy = "maker@company.com",
Status = ApprovalStatus.Proposed,
Evidence = [],
CorrelationId = Guid.NewGuid()
};
var evidence = new List<EvidenceItem>
{
new() { Type = "PBO_SCORE", Url = "s3://pbo-0.95.json", Comment = "Verified" }
};
// Act
var updated = _policy.ApproveApproval(proposal, "checker@company.com", "Looks good", evidence);
// Assert
Assert.Equal(ApprovalStatus.Approved, updated.Status);
Assert.Equal("checker@company.com", updated.ApprovedBy);
Assert.Single(updated.Evidence);
Assert.Equal("PBO_SCORE", updated.Evidence[0].EvidenceType);
}
[Fact]
public async Task InsertAndRetrieveProposal_RoundTrips()
{
// Arrange
var id = Guid.NewGuid();
var modelId = Guid.NewGuid();
var correlationId = Guid.NewGuid();
await SeedModelAsync(modelId);
// Act
await _sql.InsertProposalAsync(
id,
modelId,
"Draft",
"maker@company.com",
"Test justification",
DateOnly.FromDateTime(DateTime.UtcNow),
DateTimeOffset.UtcNow,
correlationId);
var retrieved = await _sql.GetProposalByIdAsync(id, DateTimeOffset.UtcNow.AddDays(1));
// Assert
Assert.NotNull(retrieved);
Assert.Equal(id, retrieved.Id);
Assert.Equal(modelId, retrieved.ModelId);
Assert.Equal(correlationId, retrieved.CorrelationId);
}
private async Task SeedModelAsync(Guid modelId)
{
await using var conn = new Npgsql.NpgsqlConnection(_connectionString);
await conn.OpenAsync();
await conn.ExecuteAsync(
"INSERT INTO model_operations.models (id, ticker, correlation_id) VALUES (@Id, @Ticker, @CorrelationId)",
new { Id = modelId, Ticker = "TEST", CorrelationId = Guid.NewGuid() });
}
}
public class InMemoryOutbox : IOutbox
{
public List<(string EventType, Guid CorrelationId, object Data)> Events { get; } = [];
public Task PublishAsync(string eventType, Guid correlationId, object data)
{
Events.Add((eventType, correlationId, data));
return Task.CompletedTask;
}
}