Files
Khaemhat/tests/Khaemhat.Core.Tests/Architecture/DependencyRulesTests.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

119 lines
4.9 KiB
C#

using System.Xml.Linq;
namespace Khaemhat.Core.Tests.Architecture;
/// <summary>
/// Project dependency rules of SPEC §3 and the package allowlist of SPEC §1.2 (ADR 0002). They read the project
/// files, so a forbidden reference fails here before anyone builds on it.
/// </summary>
[TestClass]
public sealed class DependencyRulesTests
{
// What each production project may reference: exactly SPEC §3.
private static readonly Dictionary<string, string[]> AllowedReferences = new(StringComparer.Ordinal)
{
["Khaemhat.Core"] = [],
["Khaemhat.Fiscal.Abstractions"] = ["Khaemhat.Core"],
["Khaemhat.Fiscal.Italy"] = ["Khaemhat.Core", "Khaemhat.Fiscal.Abstractions", "Khaemhat.Infrastructure"],
["Khaemhat.Data"] = ["Khaemhat.Core"],
["Khaemhat.Data.Sqlite"] = ["Khaemhat.Data"],
["Khaemhat.Data.PostgreSql"] = ["Khaemhat.Data"],
["Khaemhat.Infrastructure"] = ["Khaemhat.Core", "Khaemhat.Data"],
["Khaemhat.Application"] = ["Khaemhat.Core", "Khaemhat.Data", "Khaemhat.Infrastructure", "Khaemhat.Fiscal.Abstractions"],
["Khaemhat.Web"] = ["Khaemhat.Application", "Khaemhat.Data.Sqlite", "Khaemhat.Data.PostgreSql", "Khaemhat.Fiscal.Italy"],
["Khaemhat.LicenseTool"] = ["Khaemhat.Core", "Khaemhat.Infrastructure"],
["Khaemhat.DataModelTool"] = ["Khaemhat.Data"],
};
// The only packages, and where each may be referenced.
private static readonly Dictionary<string, Func<string, bool>> AllowedPackages = new(StringComparer.OrdinalIgnoreCase)
{
["Npgsql"] = file => Name(file) == "Khaemhat.Data.PostgreSql",
["Microsoft.Data.Sqlite"] = file => Name(file) == "Khaemhat.Data.Sqlite",
["Microsoft.NET.Test.Sdk"] = IsTestFile,
["MSTest"] = IsTestFile,
};
[TestMethod]
public void EveryProductionProject_HasDependencyRules()
{
var unknown = RepositoryLayout.Projects().Keys
.Where(name => !name.EndsWith(".Tests", StringComparison.Ordinal) && !AllowedReferences.ContainsKey(name))
.ToList();
Assert.IsEmpty(unknown, "Projects without dependency rules (add them to SPEC §3 and this test): " + string.Join(", ", unknown));
}
[TestMethod]
public void ProductionProjects_ReferenceOnlyWhatSpecSection3Allows()
{
var violations = new List<string>();
foreach (var (name, file) in RepositoryLayout.Projects())
{
if (!AllowedReferences.TryGetValue(name, out var allowed))
{
continue;
}
foreach (var reference in RepositoryLayout.ProjectReferences(file).Except(allowed, StringComparer.Ordinal))
{
violations.Add($"{name} -> {reference}");
}
}
Assert.IsEmpty(violations, "Forbidden project references: " + string.Join("; ", violations));
}
[TestMethod]
public void TestProjects_ReferenceOnlyKhaemhatProjects()
{
var violations = RepositoryLayout.Projects()
.Where(p => p.Key.EndsWith(".Tests", StringComparison.Ordinal))
.SelectMany(p => RepositoryLayout.ProjectReferences(p.Value)
.Where(r => !r.StartsWith("Khaemhat.", StringComparison.Ordinal))
.Select(r => $"{p.Key} -> {r}"))
.ToList();
Assert.IsEmpty(violations, string.Join("; ", violations));
}
[TestMethod]
public void Packages_AreOnTheAllowlistAndInTheirProjects()
{
var violations = new List<string>();
foreach (var file in RepositoryLayout.MsBuildFiles())
{
foreach (var package in RepositoryLayout.PackageReferences(file))
{
if (!AllowedPackages.TryGetValue(package, out var allowedIn))
{
violations.Add($"{RepositoryLayout.Relative(file)}: {package} is not on the allowlist (SPEC §1.2)");
}
else if (!allowedIn(file))
{
violations.Add($"{RepositoryLayout.Relative(file)}: {package} is not allowed in this project");
}
}
}
Assert.IsEmpty(violations, string.Join(Environment.NewLine, violations));
}
[TestMethod]
public void CentralPackageVersions_ListOnlyAllowedPackages()
{
var file = Path.Combine(RepositoryLayout.Root, "Directory.Packages.props");
var extra = XDocument.Load(file).Descendants()
.Where(e => e.Name.LocalName == "PackageVersion")
.Select(e => (string?)e.Attribute("Include") ?? string.Empty)
.Where(p => !AllowedPackages.ContainsKey(p))
.ToList();
Assert.IsEmpty(extra, "Directory.Packages.props declares packages outside the allowlist: " + string.Join(", ", extra));
}
private static string Name(string file) => Path.GetFileNameWithoutExtension(file);
private static bool IsTestFile(string file) => RepositoryLayout.Relative(file).StartsWith("tests/", StringComparison.Ordinal);
}