thing-testkit: builders, bless door and pinned store move out of the contract tests (thing2 cut 2)

The contract tests' builders (tests/common), golden_bytes/blessing and the
pinned-clock store helpers become thing_testkit::{build, golden, store}; the
contract tests link them as a dev-dependency. No golden byte changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 20:33:41 +01:00
commit 52ad110e1a
10 changed files with 125 additions and 74 deletions

9
Cargo.lock generated
View file

@ -378,6 +378,15 @@ dependencies = [
"rmp-serde",
"serde",
"serde_bytes",
"thing-testkit",
]
[[package]]
name = "thing-testkit"
version = "0.1.0"
dependencies = [
"cultcache-rs",
"thing-contract",
]
[[package]]

View file

@ -12,4 +12,5 @@ serde = { workspace = true }
serde_bytes = "0.11"
[dev-dependencies]
thing-testkit = { path = "../thing-testkit" }
rmp-serde = { workspace = true }

View file

@ -2,23 +2,24 @@
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes
//! one. `THING_BLESS=1` rewrites them; any other run compares.
mod common;
use std::collections::BTreeSet;
use std::fmt::Debug;
use std::path::PathBuf;
use common::*;
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
use thing_testkit::{build::*, golden, store};
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
use thing_contract::*;
const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
// A value that must never appear in a refusal.
const CANARY: &str = "CANARY-7f3a91c2";
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
let produced = rmp_serde::to_vec(value).unwrap();
let committed = golden_bytes(&format!("{name}.bin"), &produced);
let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
@ -416,26 +417,17 @@ fn asset_catalog() -> AssetCatalog {
/// A store with one record of each kind, written by cultcache-rs under a pinned clock.
fn write_store(path: &std::path::Path) {
let _ = std::fs::remove_file(path);
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
let mut cache = store::create(path);
let surface = full_surface();
let composition = full_composition();
let invocation = invocation();
let result = CommandResult::pending(&invocation, seq(1), "working");
let catalog = asset_catalog();
put(&mut cache, &surface.record_key(), &surface);
put(&mut cache, &composition.record_key(), &composition);
put(&mut cache, &invocation.record_key(), &invocation);
put(&mut cache, &result.record_key(), &result);
put(&mut cache, &catalog.record_key(), &catalog);
}
fn put<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
envelope.stored_at = PINNED_CLOCK.into();
cache.put_envelope::<T>(envelope).unwrap();
store::put_pinned(&mut cache, &surface.record_key(), &surface);
store::put_pinned(&mut cache, &composition.record_key(), &composition);
store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
store::put_pinned(&mut cache, &result.record_key(), &result);
store::put_pinned(&mut cache, &catalog.record_key(), &catalog);
}
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
@ -443,19 +435,11 @@ fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope
key: key.into(),
r#type: T::TYPE.into(),
payload,
stored_at: PINNED_CLOCK.into(),
stored_at: store::PINNED_CLOCK.into(),
schema_id: Some(T::TYPE.into()),
}
}
fn open_store(path: &std::path::Path) -> CultCache {
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache
}
#[test]
fn goldens_match() {
let mut names = BTreeSet::new();
@ -472,7 +456,7 @@ fn goldens_match() {
// that no case names is an orphan.
let refusals = refusal_payloads();
for (name, bytes) in &refusals {
golden_bytes(&format!("{name}.bin"), bytes);
golden::check(&goldens_dir(), &format!("{name}.bin"), bytes);
names.insert((*name).to_string());
}
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
@ -485,10 +469,10 @@ fn goldens_match() {
// The store: one record of each kind, written under a pinned clock, byte for byte.
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
write_store(&scratch);
let committed = golden_bytes("surface.cc", &std::fs::read(&scratch).unwrap());
let committed = golden::check(&goldens_dir(), "surface.cc", &std::fs::read(&scratch).unwrap());
let reopened = goldens_dir().join("surface.cc");
assert_eq!(std::fs::read(&reopened).unwrap(), committed);
let cache = open_store(&scratch);
let cache = store::open(&scratch);
let surface = full_surface();
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
let composition = full_composition();
@ -572,7 +556,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
#[test]
fn refusal_cases() {
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
let committed = |name: &str| golden_bytes(&format!("{name}.bin"), &payloads[name]);
let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
// Stored under their key, each is refused naming the kind and the key, never a value.
let cases: [(&str, &str, &str); 7] = [
@ -679,15 +663,12 @@ fn deep_tree_body() {
};
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
let _ = std::fs::remove_file(&path);
{
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
put(&mut cache, &deep.record_key(), &deep);
put(&mut cache, &wide.record_key(), &wide);
let mut cache = store::create(&path);
store::put_pinned(&mut cache, &deep.record_key(), &deep);
store::put_pinned(&mut cache, &wide.record_key(), &wide);
}
let cache = open_store(&path);
let cache = store::open(&path);
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
}

View file

@ -4,14 +4,13 @@
//! TypeScript packages hold no list of their own and are held to every row.
//! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares.
mod common;
use std::fmt::Debug;
use std::path::PathBuf;
use common::*;
use serde::Serialize;
use serde::de::DeserializeOwned;
use thing_contract::*;
use thing_testkit::golden;
/// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked).
struct Span {
@ -79,7 +78,7 @@ fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) {
/// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant
/// must re-encode to the spliced bytes.
fn rows<T: DeserializeOwned + Serialize + Debug>(file: &str, out: &mut String) -> (usize, usize) {
let bytes = std::fs::read(goldens_dir().join(format!("{file}.bin"))).unwrap();
let bytes = golden::read(&goldens_dir(), &format!("{file}.bin"));
let mut found = Vec::new();
elements(&item(&bytes, 0), "", &mut found);
let (mut accepted, mut refused) = (0, 0);
@ -125,5 +124,9 @@ fn nil_positions_match() {
for (file, (accepted, refused)) in &totals {
println!("NILTOTAL {file} accept={accepted} refuse={refused}");
}
golden_bytes("nil-positions.tsv", table.as_bytes());
golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes());
}
fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}

View file

@ -1,6 +1,4 @@
mod common;
use common::*;
use thing_testkit::build::*;
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
use serde::Deserialize;
use serde::de::IntoDeserializer;

View file

@ -0,0 +1,10 @@
[package]
name = "thing-testkit"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[dependencies]
thing-contract = { path = "../thing-contract" }
cultcache-rs = { workspace = true }

View file

@ -1,31 +1,8 @@
//! Constructors for the values the goldens and the other tests share. Every value is built
//! through the crate's public types; no bytes are spelled here.
#![allow(dead_code)]
use std::path::PathBuf;
//! Constructors for the values the contract goldens, the fixtures and the other tests share.
//! Every value is built through the crate's public types; no bytes are spelled here.
use thing_contract::*;
pub fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
pub fn blessing() -> bool {
std::env::var("THING_BLESS").as_deref() == Ok("1")
}
/// Bless the file or compare against it. Returns the committed bytes.
pub fn golden_bytes(file: &str, produced: &[u8]) -> Vec<u8> {
let path = goldens_dir().join(file);
if blessing() {
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
}
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
committed
}
pub fn seq(value: i32) -> Seq {
Seq::new(value).unwrap()
}

View file

@ -0,0 +1,32 @@
//! The one bless door. `THING_BLESS=1` writes; any other run compares and never writes.
use std::path::Path;
fn blessing() -> bool {
std::env::var("THING_BLESS").as_deref() == Ok("1")
}
/// Bless the file or compare against it. Returns the committed bytes. A mismatch panics naming
/// the file and leaves it unchanged.
pub fn check(dir: &Path, file: &str, produced: &[u8]) -> Vec<u8> {
let path = dir.join(file);
if blessing() {
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
}
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
committed
}
/// Bless or compare `stem.bin` and `stem.txt` together: the binary is the oracle, the text is
/// compared too so it cannot rot. Returns the committed binary.
pub fn check_with_text(dir: &Path, stem: &str, bytes: &[u8], text: &str) -> Vec<u8> {
let committed = check(dir, &format!("{stem}.bin"), bytes);
check(dir, &format!("{stem}.txt"), text.as_bytes());
committed
}
/// Read a committed file. Never writes: backends read core's goldens through this.
pub fn read(dir: &Path, file: &str) -> Vec<u8> {
std::fs::read(dir.join(file)).unwrap_or_else(|error| panic!("{file}: {error}"))
}

View file

@ -0,0 +1,6 @@
//! The fakes, builders and the one bless door the Thing crates test with. A test crate
//! depends on this; no shipped crate does.
pub mod build;
pub mod golden;
pub mod store;

View file

@ -0,0 +1,34 @@
//! CultCache single-file stores of contract documents, written under a pinned clock so the
//! bytes are reproducible.
use std::path::Path;
use cultcache_rs::{CultCache, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
use thing_contract::ThingContract;
pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
/// An empty cache with the contract registered over a fresh single-file store at `path`.
pub fn create(path: &Path) -> CultCache {
let _ = std::fs::remove_file(path);
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
cache
}
/// Store `value` under `key` with `stored_at` pinned.
pub fn put_pinned<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
envelope.stored_at = PINNED_CLOCK.into();
cache.put_envelope::<T>(envelope).unwrap();
}
/// A cache with the contract registered, pulled from the store at `path`.
pub fn open(path: &Path) -> CultCache {
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache
}