Files
KArtSell.Aegis/tests/KArtSell.Integration.Tests/TradeExecution/TradeExecutionTests.cs
T
kjh2064 b1e38ac374 feat: Phase 3 J/K/L (Sell Decision, Trade Execution, Portfolio Reconciliation) + fix pre-existing build/boot breakage
Completes VS-10/VS-12/VS-14 and makes the solution and Host actually
build and boot for the first time on this branch (main did not build
before this commit).

Root-cause fixes required to reach a green build/boot (not scoped to
J/K/L but blocking any verification of it):
- Restore Polly PackageVersion accidentally deleted from
  Directory.Packages.props (broke KArtSell.Host).
- Remove MediatR dependency from Compliance/VS-04 (package was never
  installed; ICommand/ICommandHandler/IMediator never existed) and
  wire Endpoint -> Handler directly per this repo's convention.
- Migrate FastEndpoints v5 API calls (SendOkAsync/SendAsync/
  SendCreatedAtAsync/SendNotFoundAsync, Description().WithName()) to
  the v7 Send.* fluent API across ~10 endpoint files.
- Fix migrations 0036/0038/0039/0040: rewritten from invalid T-SQL
  (`IF NOT EXISTS ... BEGIN ... END`) to idiomatic Postgres
  (`CREATE TABLE/INDEX IF NOT EXISTS`) — these could not apply to any
  fresh database before this fix.
- Collapse 3 duplicate cross-cutting abstractions that shadowed the
  BuildingBlocks versions and caused type-mismatch compile errors:
  IKrxDataService, IOutboxWriter (ReconcileTradeHandler), IClock
  (ApprovalWorkflow/ApprovalPolicy).
- Inject IClock (BuildingBlocks.Time) in place of direct
  DateTime.Now/UtcNow across 19 files to satisfy the architecture
  test AGENTS.md#DateTime-abstraction rule (13/13 architecture tests
  now pass, was 12/13).
- Register all new and previously-unregistered slices in
  Program.cs DI (SellDecision, TradeExecution, PortfolioReconciliation,
  Compliance, Features/ApprovalWorkflow) — the Host had never
  successfully completed a boot with this code present.
- Disable ("[DontRegister]") the older, route-colliding
  ApprovalWorkflow/ (Workstream H) endpoint set in favor of
  Features/ApprovalWorkflow/ (Workstream G, matches the documented
  Features/<Slice>/ convention); kept for its existing test coverage.
  See TECH_DEBT-017 for the follow-up decision needed.

Verified: dotnet build 0 errors/0 warnings; architecture tests 13/13;
unit tests 54/54 + 18/18; integration tests 34/36 (2 failures are a
local test-DB migration-journal/schema mismatch, not a code defect);
Host boots cleanly and registers all 34 endpoints.

New tech debt recorded: DEBT-017 (duplicate VS-03 implementation),
DEBT-018 (outbox write not co-transactional with entity write in
TradeExecution/PortfolioReconciliation), DEBT-019 (duplicate
BuildingBlocks-shadowing abstractions, partially resolved).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 19:53:38 +09:00

253 lines
8.4 KiB
C#

using System.Text.Json;
using KArtSell.Modules.ModelOperations.TradeExecution;
using Microsoft.Extensions.Logging;
using Npgsql;
using Xunit;
namespace KArtSell.Integration.Tests.TradeExecution;
[Collection("Database")]
public class TradeExecutionTests : IAsyncLifetime
{
private readonly NpgsqlDataSource _dataSource;
private readonly ILogger<TradeSql> _logger;
public TradeExecutionTests()
{
var connectionString = Environment.GetEnvironmentVariable("KARTSELL_POSTGRES")
?? "Host=localhost;Port=5432;Database=kartselldb;Username=kartsell;Password=kartsell4321@!";
var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
_dataSource = dataSourceBuilder.Build();
_logger = new LoggerFactory().CreateLogger<TradeSql>();
}
public async Task InitializeAsync()
{
await using var connection = await _dataSource.OpenConnectionAsync();
}
public async Task DisposeAsync()
{
await _dataSource.DisposeAsync();
}
[Fact]
public async Task CreateTrade_WithValidData_ShouldInsertSuccessfully()
{
var sql = new TradeSql(_dataSource, _logger);
var sellDecisionId = Guid.NewGuid();
var correlationId = Guid.NewGuid();
var trade = Trade.Create(sellDecisionId, 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(trade.Id, retrieved.Id);
Assert.Equal(TradeStatus.Pending, retrieved.Status);
Assert.Equal(1000, retrieved.Quantity);
}
[Fact]
public async Task MarkSubmitted_UpdatesTradeStatusCorrectly()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkSubmitted("KIS-ORDER-123", response);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Submitted, response, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.Submitted, retrieved.Status);
Assert.Equal("KIS-ORDER-123", retrieved.KisOrderId);
}
[Fact]
public async Task MarkFilled_CalculatesCorrectTotals()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkFilled(1000, 49.95m, response, DateTime.UtcNow);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.FullyFilled, response, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.FullyFilled, retrieved.Status);
Assert.Equal(1000, retrieved.ExecutedQuantity);
Assert.Equal(49.95m, retrieved.UnitPrice);
Assert.Equal(49950m, retrieved.TotalAmount);
}
[Fact]
public async Task GetTradesByStatus_ReturnsCorrectTrades()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade1 = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
var trade2 = Trade.Create(Guid.NewGuid(), 2000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade1);
await sql.InsertTradeAsync(trade2);
var trades = await sql.GetTradesByStatusAsync(TradeStatus.Pending, correlationId);
Assert.NotEmpty(trades);
Assert.Contains(trades, t => t.Id == trade1.Id);
Assert.Contains(trades, t => t.Id == trade2.Id);
}
[Fact]
public async Task MarkConfirmed_SetsSettlementTimestamp()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
trade.TotalAmount = 49950m;
trade.MarkConfirmed(DateTime.UtcNow, 50m);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Confirmed, null, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.Confirmed, retrieved.Status);
Assert.Equal(50m, retrieved.Commission);
Assert.Equal(49900m, retrieved.NetProceeds);
}
[Fact]
public async Task TradeStatusHistory_TracksAllTransitions()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Submitted, null, null, correlationId);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Accepted, null, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.Accepted, retrieved.Status);
}
[Fact]
public async Task CountTradesByStatus_ReturnsAccurateCount()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade1 = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
var trade2 = Trade.Create(Guid.NewGuid(), 2000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade1);
await sql.InsertTradeAsync(trade2);
var count = await sql.CountTradesByStatusAsync(TradeStatus.Pending);
Assert.True(count >= 2);
}
[Fact]
public void ErrorClassification_TransientErrors_Identified()
{
var ex = new KisTradeExecutionException(
"Timeout",
ErrorClassification.Transient
);
Assert.Equal(ErrorClassification.Transient, ex.Classification);
}
[Fact]
public void ErrorClassification_PermanentErrors_Identified()
{
var ex = new KisTradeExecutionException(
"Invalid order",
ErrorClassification.Permanent
);
Assert.Equal(ErrorClassification.Permanent, ex.Classification);
}
[Fact]
public void ErrorClassification_LiquidityErrors_Identified()
{
var ex = new KisTradeExecutionException(
"Insufficient liquidity",
ErrorClassification.Liquidity
);
Assert.Equal(ErrorClassification.Liquidity, ex.Classification);
}
[Fact]
public void Trade_StateTransitions_ValidSequence()
{
var trade = Trade.Create(Guid.NewGuid(), 1000, Guid.NewGuid(), DateTime.UtcNow);
Assert.Equal(TradeStatus.Pending, trade.Status);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkSubmitted("KIS-123", response);
Assert.Equal(TradeStatus.Submitted, trade.Status);
trade.MarkAccepted(response);
Assert.Equal(TradeStatus.Accepted, trade.Status);
trade.MarkFilled(1000, 49.95m, response, DateTime.UtcNow);
Assert.Equal(TradeStatus.FullyFilled, trade.Status);
trade.MarkConfirmed(DateTime.UtcNow, 50m);
Assert.Equal(TradeStatus.Confirmed, trade.Status);
trade.MarkReconciled();
Assert.Equal(TradeStatus.Reconciled, trade.Status);
}
[Fact]
public void Trade_PartialFill_StatusCorrect()
{
var trade = Trade.Create(Guid.NewGuid(), 1000, Guid.NewGuid(), DateTime.UtcNow);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkFilled(500, 49.95m, response, DateTime.UtcNow);
Assert.Equal(TradeStatus.PartiallyFilled, trade.Status);
Assert.Equal(500, trade.ExecutedQuantity);
}
[Fact]
public void Trade_RevisionIncrementsOnStateChange()
{
var trade = Trade.Create(Guid.NewGuid(), 1000, Guid.NewGuid(), DateTime.UtcNow);
var initialRevision = trade.Revision;
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkSubmitted("KIS-123", response);
Assert.Equal(initialRevision + 1, trade.Revision);
}
}