diff --git a/packages/thing-contract/test/parity.test.ts b/packages/thing-contract/test/parity.test.ts new file mode 100644 index 0000000..6e46e29 --- /dev/null +++ b/packages/thing-contract/test/parity.test.ts @@ -0,0 +1,117 @@ +// Parity with the C# package, both ways. written-by-cs.cc is a store the C# package's CultCache wrote from its own +// builders (ParityTests.cs writes it); each of its five records re-encodes here to its value golden under keys.ts's +// key. written-by-ts.cc is the store this test writes from the ported builders, and ParityTests.cs reads it the same +// way. THING_PARITY_WRITE=1 rewrites written-by-ts.cc; every other run only reads the committed fixtures and writes a +// temp store whose catalog must equal the C# package's catalog-members.tsv. +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +import { + CultCache, + SingleFileMessagePackBackingStore, + documentPayloadBytes, + inspectCultCacheBytes, +} from "@gamecult/cultcache-ts"; +import { + CommandResult, + assetCatalogDocument, + assetCatalogKey, + commandInvocationDocument, + commandResultDocument, + compositionDocument, + compositionKey, + invocationKey, + resultKey, + surfaceDocument, + surfaceKey, + thingContract, +} from "@gamecult/thing-contract"; + +import { assetCatalogValue, fullComposition, fullSurface, golden, invocation, nonEmptyLines, parityDir } from "./builders.js"; + +const surface = fullSurface(); +const composition = fullComposition(); +const answered = invocation(); +const result = CommandResult.pending(answered, 1, "working"); +const catalog = assetCatalogValue(); + +const records: [key: string, golden: string][] = [ + [surfaceKey(surface.providerId, surface.label), "surface-all-arms.bin"], + [compositionKey(composition.publisher, composition.name, composition.version), "composition-all-params.bin"], + [invocationKey(answered.invocationId), "invocation-all-inputs.bin"], + [resultKey(result.invocationId, result.seq), "result-pending.bin"], + [assetCatalogKey(catalog.providerId, catalog.catalogId), "asset-catalog.bin"], +]; + +function openCache(file: string) { + return CultCache.builder().withRegistry(thingContract).withGenericStore(new SingleFileMessagePackBackingStore(file)).build(); +} + +async function writeStore(file: string): Promise { + const cache = openCache(file); + await cache.pullAllBackingStores(); + await cache.put(surfaceDocument, records[0][0], surface); + await cache.put(compositionDocument, records[1][0], composition); + await cache.put(commandInvocationDocument, records[2][0], answered); + await cache.put(commandResultDocument, records[3][0], result); + await cache.put(assetCatalogDocument, records[4][0], catalog); +} + +/** The five records of an opened store each equal their golden's bytes under the package's own key. */ +function assertFiveRecords(cache: CultCache): void { + const snapshot = cache.snapshot(); + assert.deepEqual(snapshot.map((envelope) => envelope.key).sort(), records.map(([key]) => key).sort()); + for (const [key, file] of records) { + const envelope = snapshot.find((candidate) => candidate.key === key); + assert.ok(envelope !== undefined, key); + assert.deepEqual(documentPayloadBytes(envelope.payload), golden(file), key); + } +} + +/** A store's catalog as the C# members file prints it, one group per document in the file's order of slots. */ +function catalogGroups(rows: string[]): string[] { + const groups = new Map(); + for (const row of rows) { + const [schemaId, slot, member, typeName] = row.split("\t"); + groups.set(schemaId, [...(groups.get(schemaId) ?? []), [slot, member, typeName].join("\t")]); + } + return [...groups.values()].map((group) => group.join("\n")).sort(); +} + +test("a store the C# package wrote opens to five records that re-encode to the goldens", async () => { + const cache = openCache(join(parityDir, "written-by-cs.cc")); + await cache.pullAllBackingStores(); + assertFiveRecords(cache); + assert.deepEqual(cache.getRequired(surfaceDocument, records[0][0]), surface); + assert.deepEqual(cache.getRequired(commandResultDocument, records[3][0]), result); +}); + +test("the store this package writes opens to the same five records, and its catalog is the C# catalog", async () => { + const directory = mkdtempSync(join(tmpdir(), "thing-parity-")); + try { + const file = join(directory, "written-by-ts.cc"); + await writeStore(file); + const reopened = openCache(file); + await reopened.pullAllBackingStores(); + assertFiveRecords(reopened); + + const bytes = new Uint8Array(readFileSync(file)); + const mine = inspectCultCacheBytes(file, bytes).catalog.flatMap((entry) => + entry.members.map((member) => [entry.schemaId, member.slot, member.memberName, member.typeName].join("\t")), + ); + assert.deepEqual(catalogGroups(mine), catalogGroups(nonEmptyLines(join(parityDir, "catalog-members.tsv")))); + + if (process.env.THING_PARITY_WRITE === "1") writeFileSync(join(parityDir, "written-by-ts.cc"), bytes); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("the committed written-by-ts.cc opens to the five records", async () => { + const cache = openCache(join(parityDir, "written-by-ts.cc")); + await cache.pullAllBackingStores(); + assertFiveRecords(cache); +}); diff --git a/tests/GameCult.Thing.Contract.Tests/ParityTests.cs b/tests/GameCult.Thing.Contract.Tests/ParityTests.cs new file mode 100644 index 0000000..3cd5ce5 --- /dev/null +++ b/tests/GameCult.Thing.Contract.Tests/ParityTests.cs @@ -0,0 +1,135 @@ +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using static GameCult.Thing.Contract.Tests.Builders; + +namespace GameCult.Thing.Contract.Tests; + +/// +/// Parity with the TypeScript package, both ways. written-by-ts.cc is a store @gamecult/thing-contract's CultCache wrote +/// from its own builders: this reads it through CultCacheMessagePack, whose reader compares member type names, and each of +/// its five records re-encodes to its value golden under the package's own key. written-by-cs.cc is the store this test +/// writes from the C# builders and the TypeScript package's parity.test.ts reads. THING_PARITY_WRITE=1 rewrites +/// written-by-cs.cc in tests/thing-contract-parity; every other run writes only a temp store. +/// +public sealed class ParityTests +{ + private static string ParityPath(string file) => Path.Combine(AppContext.BaseDirectory, "parity", file); + + private static string SourceParityPath(string file) + { + for (var here = new DirectoryInfo(AppContext.BaseDirectory); here != null; here = here.Parent) + { + var candidate = Path.Combine(here.FullName, "tests", "thing-contract-parity"); + if (Directory.Exists(candidate)) return Path.Combine(candidate, file); + } + + throw new DirectoryNotFoundException("tests/thing-contract-parity is not above the test output"); + } + + private static (object Value, string Golden, string Key)[] Records(CultCache cache) => + new (object, string, string)[] + { + (cache.GetAll().Single(), "surface-all-arms", "thing:surface:provider.a.main"), + (cache.GetAll().Single(), "composition-all-params", "thing:composition:provider.a.panel.v3"), + (cache.GetAll().Single(), "invocation-all-inputs", "thing:invocation:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b"), + (cache.GetAll().Single(), "result-pending", "thing:result:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b.1"), + (cache.GetAll().Single(), "asset-catalog", "thing:asset_catalog:provider.a.icons"), + }; + + private static void AssertFiveRecords(CultCache cache) + { + foreach (var (value, golden, key) in Records(cache)) + { + Assert.That(Convert.ToHexString(Wire.Write(value)), Is.EqualTo(Convert.ToHexString(Wire.Golden($"{golden}.bin"))), golden); + Assert.That((string)value.GetType().GetProperty("RecordKey")!.GetValue(value)!, Is.EqualTo(key), golden); + } + + Assert.That(cache.GetAll().Count() + cache.GetAll().Count() + cache.GetAll().Count() + + cache.GetAll().Count() + cache.GetAll().Count(), Is.EqualTo(5)); + } + + private static CultCache OpenCopy(string source, out string scratch, byte[]? bytes = null) + { + scratch = Path.Combine(Path.GetTempPath(), $"thing-parity-{Guid.NewGuid():N}.cc"); + if (bytes == null) File.Copy(source, scratch); + else File.WriteAllBytes(scratch, bytes); + return CultCacheMessagePack.Create(scratch, new CultCacheOpenOptions { Registry = Wire.Registry, ReadOnly = true }); + } + + [Test] + public void TheStoreTypeScriptWroteOpensToFiveRecordsThatReEncodeToTheGoldens() + { + using var cache = OpenCopy(ParityPath("written-by-ts.cc"), out var scratch); + try + { + AssertFiveRecords(cache); + } + finally + { + cache.Dispose(); + File.Delete(scratch); + } + } + + [Test] + public void AStoreTypeScriptWroteWithOneDriftedTypeNameIsRefused() + { + var written = File.ReadAllBytes(ParityPath("written-by-ts.cc")); + var from = System.Text.Encoding.UTF8.GetBytes("System.Int64"); + var to = System.Text.Encoding.UTF8.GetBytes("System.Int32"); + var drifted = (byte[])written.Clone(); + var patched = 0; + for (var i = 0; i + from.Length <= drifted.Length; i++) + { + if (!drifted.AsSpan(i, from.Length).SequenceEqual(from)) continue; + to.CopyTo(drifted, i); + patched++; + } + + Assert.That(patched, Is.GreaterThan(0), "a member type name was recorded"); + var scratch = ""; + try + { + var error = Assert.Catch(() => + { + using var cache = OpenCopy("", out scratch, drifted); + cache.GetAll().ToList(); + })!; + Assert.That(Wire.Flatten(error), Does.Contain("changed type").And.Contain("System.Int32").And.Contain("System.Int64")); + } + finally + { + if (scratch != "") File.Delete(scratch); + } + } + + [Test] + public void TheStoreThisPackageWritesReopensToFiveRecordsAndIsTheFixtureTypeScriptReads() + { + var scratch = Path.Combine(Path.GetTempPath(), $"thing-parity-{Guid.NewGuid():N}.cc"); + try + { + using (var cache = CultCacheMessagePack.Create(scratch, new CultCacheOpenOptions { Registry = Wire.Registry })) + { + cache.Commit(b => b + .Upsert(FullSurface()) + .Upsert(FullComposition()) + .Upsert(Invocation()) + .Upsert(Results(Invocation()).Single(r => r.Name == "result-pending").Result) + .Upsert(FullAssetCatalog())); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + using (var reopened = CultCacheMessagePack.Create(scratch, new CultCacheOpenOptions { Registry = Wire.Registry, ReadOnly = true })) + { + AssertFiveRecords(reopened); + } + + if (Environment.GetEnvironmentVariable("THING_PARITY_WRITE") == "1") File.Copy(scratch, SourceParityPath("written-by-cs.cc"), overwrite: true); + } + finally + { + File.Delete(scratch); + } + } +} diff --git a/tests/thing-contract-parity/written-by-ts.cc b/tests/thing-contract-parity/written-by-ts.cc new file mode 100644 index 0000000..15231e3 Binary files /dev/null and b/tests/thing-contract-parity/written-by-ts.cc differ