thing-contract parity: the C# reader of the TypeScript store and the writer of the C# one; written-by-ts.cc
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c74bee925e
commit
6d90581fda
3 changed files with 252 additions and 0 deletions
117
packages/thing-contract/test/parity.test.ts
Normal file
117
packages/thing-contract/test/parity.test.ts
Normal file
|
|
@ -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<void> {
|
||||
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<string, string[]>();
|
||||
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);
|
||||
});
|
||||
135
tests/GameCult.Thing.Contract.Tests/ParityTests.cs
Normal file
135
tests/GameCult.Thing.Contract.Tests/ParityTests.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using static GameCult.Thing.Contract.Tests.Builders;
|
||||
|
||||
namespace GameCult.Thing.Contract.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<SurfaceDocument>().Single(), "surface-all-arms", "thing:surface:provider.a.main"),
|
||||
(cache.GetAll<CompositionDocument>().Single(), "composition-all-params", "thing:composition:provider.a.panel.v3"),
|
||||
(cache.GetAll<CommandInvocation>().Single(), "invocation-all-inputs", "thing:invocation:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b"),
|
||||
(cache.GetAll<CommandResult>().Single(), "result-pending", "thing:result:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b.1"),
|
||||
(cache.GetAll<AssetCatalog>().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<SurfaceDocument>().Count() + cache.GetAll<CompositionDocument>().Count() + cache.GetAll<CommandInvocation>().Count()
|
||||
+ cache.GetAll<CommandResult>().Count() + cache.GetAll<AssetCatalog>().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<AssetCatalog>().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);
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
tests/thing-contract-parity/written-by-ts.cc
Normal file
BIN
tests/thing-contract-parity/written-by-ts.cc
Normal file
Binary file not shown.
Loading…
Reference in a new issue