Files
Khaemhat/tests/Khaemhat.Data.Tests/RepositoryTests.cs
T
Alby96andClaude Opus 5.5 738c43ba0a
CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe
by construction:

- Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every
  interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and
  optimistic concurrency on row_version, retries on transient errors.
- SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE,
  serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database
  creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never
  appears in messages.
- C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration
  under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings.
- CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key,
  purpose as associated data), so a copied row cannot be read for another company.
- tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of
  docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale.
- C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion.
- Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts
  differ from SPEC 5.1. Docs, wiki, changelog and status updated.

Closes #7, #8, #9, #10, #11, #12, #13, #14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:11:34 +01:00

191 lines
8.2 KiB
C#

using Khaemhat.Core.Common;
using Khaemhat.Data.Querying;
using Khaemhat.Data.Tests.Support;
namespace Khaemhat.Data.Tests;
[TestClass]
public sealed class RepositoryTests
{
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Crud_WithAuditColumns(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
await using var unitOfWork = await db.OpenAsync();
var items = unitOfWork.Repository<TestItem, long>();
var item = new TestItem { Code = "C1", Name = "First", Amount = 10.5m };
var id = await items.InsertAsync(item);
Assert.IsGreaterThan(0L, id);
Assert.AreEqual(id, item.Id);
Assert.AreEqual(1L, item.RowVersion);
Assert.IsNull(item.UpdatedAt);
item.Name = "Changed";
await items.UpdateAsync(item);
Assert.AreEqual(2L, item.RowVersion);
Assert.IsNotNull(item.UpdatedAt);
var read = await items.GetAsync(id);
Assert.AreEqual("Changed", read!.Name);
Assert.AreEqual(2L, read.RowVersion);
Assert.AreEqual(item.CreatedAt, read.CreatedAt);
Assert.AreEqual(item.UpdatedAt, read.UpdatedAt);
Assert.AreEqual(TestDatabase.TestUser, read.UpdatedBy);
Assert.IsTrue(await items.DeleteAsync(id));
Assert.IsFalse(await items.DeleteAsync(id));
Assert.IsNull(await items.GetAsync(id));
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Update_OfAStaleCopy_ThrowsConcurrencyException(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
long id;
await using (var setup = await db.OpenAsync())
{
id = await setup.Repository<TestItem, long>().InsertAsync(new TestItem { Code = "CC", Name = "v1" });
}
await using var first = await db.OpenAsync();
await using var second = await db.OpenAsync();
var copyA = await first.Repository<TestItem, long>().GetAsync(id);
var copyB = await second.Repository<TestItem, long>().GetAsync(id);
copyA!.Name = "by A";
await first.Repository<TestItem, long>().UpdateAsync(copyA);
copyB!.Name = "by B";
var conflict = await Assert.ThrowsExactlyAsync<ConcurrencyException>(() => second.Repository<TestItem, long>().UpdateAsync(copyB));
Assert.AreEqual("test_items", conflict.Table);
Assert.AreEqual(1L, conflict.ExpectedVersion);
Assert.AreEqual("by A", (await second.Repository<TestItem, long>().GetAsync(id))!.Name);
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Update_OfADeletedRow_ThrowsConcurrencyException(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
await using var unitOfWork = await db.OpenAsync();
var items = unitOfWork.Repository<TestItem, long>();
var item = new TestItem { Code = "GONE" };
await items.InsertAsync(item);
await items.DeleteAsync(item.Id);
await Assert.ThrowsExactlyAsync<ConcurrencyException>(() => items.UpdateAsync(item));
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Transactions_CommitAndRollback(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
await using var unitOfWork = await db.OpenAsync();
var items = unitOfWork.Repository<TestItem, long>();
await unitOfWork.BeginAsync();
await items.InsertAsync(new TestItem { Code = "ROLLED" });
await unitOfWork.RollbackAsync();
await Assert.ThrowsExactlyAsync<InvalidOperationException>(
() => unitOfWork.InTransactionAsync(async ct =>
{
await items.InsertAsync(new TestItem { Code = "FAILED" }, ct);
throw new InvalidOperationException("business rule");
}));
await unitOfWork.InTransactionAsync(async ct =>
{
await unitOfWork.AcquireLockAsync("numerator:FV:2026", ct);
await items.InsertAsync(new TestItem { Code = "KEPT" }, ct);
});
var codes = (await items.ListAsync(Query.For<TestItem>())).Items.Select(x => x.Code).ToArray();
CollectionAssert.AreEqual(new[] { "KEPT" }, codes);
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task HostileInput_IsStoredAndFound_AsData(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
await using var unitOfWork = await db.OpenAsync();
var items = unitOfWork.Repository<TestItem, long>();
const string hostile = "x'); DROP TABLE test_items; --";
await items.InsertAsync(new TestItem { Code = "H1", Name = hostile });
var found = await items.FindAsync(Query.For<TestItem>().Where(x => x.Name == hostile));
var like = await items.CountAsync(Query.For<TestItem>().Where(x => x.Name!.Contains("'); DROP")));
var raw = await unitOfWork.QueryAsync<string>(SqlFragment.Of($"SELECT code FROM test_items WHERE name = {hostile}"));
Assert.AreEqual("H1", found?.Code);
Assert.AreEqual(1, like);
CollectionAssert.AreEqual(new[] { "H1" }, raw.ToArray());
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Queries_MapToRecordsClassesAndScalars(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
await using var unitOfWork = await db.OpenAsync();
var items = unitOfWork.Repository<TestItem, long>();
await items.InsertAsync(new TestItem { Code = "R1", Amount = 1.25m, Kind = TestKind.Service });
await items.InsertAsync(new TestItem { Code = "R2", Amount = 2.5m, Kind = TestKind.Service });
await items.InsertAsync(new TestItem { Code = "R3", Amount = 4m, Kind = TestKind.Goods });
var totals = await unitOfWork.QueryAsync<KindTotal>(
SqlFragment.Literal("SELECT kind, SUM(amount) AS total_amount, COUNT(*) AS item_count FROM test_items GROUP BY kind ORDER BY kind"));
var rows = await unitOfWork.QueryAsync<CodeRow>(SqlFragment.Literal("SELECT code, amount FROM test_items ORDER BY code"));
var kinds = await unitOfWork.QueryAsync<TestKind>(SqlFragment.Literal("SELECT DISTINCT kind FROM test_items ORDER BY kind"));
var ids = await unitOfWork.QueryAsync<long>(SqlFragment.Literal("SELECT id FROM test_items ORDER BY id"));
var inList = await items.CountAsync(Query.For<TestItem>().Where(x => ids.Contains(x.Id) && x.Kind == TestKind.Service));
CollectionAssert.AreEqual(
new[] { new KindTotal(TestKind.Goods, 4m, 1), new KindTotal(TestKind.Service, 3.75m, 2) }, totals.ToArray());
Assert.AreEqual(2.5m, rows[1].Amount);
CollectionAssert.AreEqual(new[] { TestKind.Goods, TestKind.Service }, kinds.ToArray());
Assert.AreEqual(2, inList);
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Stream_ReadsWithoutMapping(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
await db.CreateTestTableAsync();
await using var unitOfWork = await db.OpenAsync();
await unitOfWork.Repository<TestItem, long>().InsertAsync(new TestItem { Code = "S1", Amount = 7.000001m });
await using var reader = await unitOfWork.StreamAsync(SqlFragment.Literal("SELECT amount FROM test_items"));
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(7.000001m, db.Dialect.FromDbValue(reader.GetValue(0), Schema.ColumnType.Decimal));
}
private sealed record KindTotal(TestKind Kind, decimal TotalAmount, long ItemCount);
private sealed class CodeRow
{
public string Code { get; set; } = string.Empty;
public decimal Amount { get; set; }
}
}