diff --git a/Cargo.lock b/Cargo.lock index 3898b9a..c4f3b61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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]] diff --git a/crates/thing-contract/Cargo.toml b/crates/thing-contract/Cargo.toml index f3ffd0f..b799adc 100644 --- a/crates/thing-contract/Cargo.toml +++ b/crates/thing-contract/Cargo.toml @@ -12,4 +12,5 @@ serde = { workspace = true } serde_bytes = "0.11" [dev-dependencies] +thing-testkit = { path = "../thing-testkit" } rmp-serde = { workspace = true } diff --git a/crates/thing-contract/tests/goldens.rs b/crates/thing-contract/tests/goldens.rs index e5c940d..d1891b7 100644 --- a/crates/thing-contract/tests/goldens.rs +++ b/crates/thing-contract/tests/goldens.rs @@ -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(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(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::(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(key: &str, payload: Vec) -> CultCacheEnvelope { @@ -443,19 +435,11 @@ fn envelope(key: &str, payload: Vec) -> 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 = 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::(&surface.record_key()).unwrap(), Some(surface)); let composition = full_composition(); @@ -572,7 +556,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec)> { #[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::(&deep.record_key()).unwrap(), Some(deep)); assert_eq!(cache.get::(&wide.record_key()).unwrap(), Some(wide)); } diff --git a/crates/thing-contract/tests/nil_positions.rs b/crates/thing-contract/tests/nil_positions.rs index 27ee98d..f39c22f 100644 --- a/crates/thing-contract/tests/nil_positions.rs +++ b/crates/thing-contract/tests/nil_positions.rs @@ -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(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") } diff --git a/crates/thing-contract/tests/result.rs b/crates/thing-contract/tests/result.rs index bed0312..49fd667 100644 --- a/crates/thing-contract/tests/result.rs +++ b/crates/thing-contract/tests/result.rs @@ -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; diff --git a/crates/thing-testkit/Cargo.toml b/crates/thing-testkit/Cargo.toml new file mode 100644 index 0000000..7886d45 --- /dev/null +++ b/crates/thing-testkit/Cargo.toml @@ -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 } diff --git a/crates/thing-contract/tests/common/mod.rs b/crates/thing-testkit/src/build.rs similarity index 82% rename from crates/thing-contract/tests/common/mod.rs rename to crates/thing-testkit/src/build.rs index 5696035..f042d9f 100644 --- a/crates/thing-contract/tests/common/mod.rs +++ b/crates/thing-testkit/src/build.rs @@ -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 { - 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() } diff --git a/crates/thing-testkit/src/golden.rs b/crates/thing-testkit/src/golden.rs new file mode 100644 index 0000000..728389a --- /dev/null +++ b/crates/thing-testkit/src/golden.rs @@ -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 { + 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 { + 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 { + std::fs::read(dir.join(file)).unwrap_or_else(|error| panic!("{file}: {error}")) +} diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs new file mode 100644 index 0000000..bab5b04 --- /dev/null +++ b/crates/thing-testkit/src/lib.rs @@ -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; diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs new file mode 100644 index 0000000..7889692 --- /dev/null +++ b/crates/thing-testkit/src/store.rs @@ -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(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::(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 +}