Thing 2.0: the remaining fixtures (testkit-fixtures) #8

Merged
eureka merged 6 commits from hands/thing2-testkit-fixtures into main 2026-11-27 20:52:52 +00:00
15 changed files with 837 additions and 31 deletions

View file

@ -10,6 +10,5 @@ thing-contract = { path = "../thing-contract" }
cultcache-rs = { workspace = true }
thing-core = { path = "../thing-core" }
anyhow = { workspace = true }
[dev-dependencies]
rmp-serde = { workspace = true }

View file

@ -8,11 +8,21 @@ frozen, and a normal test run only compares and reads them. The rows are the fix
| File | Holds | Map rules |
|---|---|---|
| `f01-swarm-dashboard.surface.cc` | One surface: a Grid Box root, a Text bound with a Number Format, a Repeat over a RecordsSource prefix whose template binds Item members, and a Button whose CommandRef is declared | 6, 9 |
| `f02-login-effect.surface.cc` | One surface (a Text TextInput and a Button whose command captures it, plus the declared resume command), the CommandInvocation of it, and its two results: Pending, then Completed with an `OpenExternal` effect whose `resume` names the declared command | 1, 2 |
| `f03-input-target.surface.cc` | One surface (an Image over a position: absolute Box with insets, holding a bound label) and the AssetCatalog the Image names | - |
| `f04-form.surface.cc` | One surface (Toggle, Slider, Select with literal options, TextInput of Number kind) and one command capturing all four, its invocation, and a Completed result declaring `clear_drafts` | 1 |
| `f05-modal-overlay.surface.cc` | One surface with a modal Overlay anchored to the viewport, a dismiss CommandRef and two Buttons inside | - |
| `f06-scroll-list.surface.cc` | One surface: a Box with `overflow: scroll` holding a Repeat over a RecordsSource prefix, template keyed by the item's `id` (the 1,000 items are provider state, not here) | - |
| `f07-plot.surface.cc` | One surface with a Plot of each mark (Line, Bar, Area) over a bound series, with and without axis bounds | - |
| `f08-embed-viewport.surface.cc` | One surface: an Embed of declared fixed size as a leaf between two Texts | - |
| `f09-composition-stack.surface.cc` | One surface whose Use passes one argument of each ArgValue arm and a Slot holding a second Use (two levels), and the publisher CompositionDocument both name | 5 |
| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion, an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 |
| `f11-deep.surface.cc` | One surface: the deepest Box chain whose payload CultCache's `check_payload_depth` accepts, found by the builder | - |
| `f11-deep-refused.bin` | The payload of the same chain one Box level deeper, raw: `check_payload_depth` refuses it at depth 257 and so does CultCache. No store can hold it | - |
| `f12-text-edge.surface.cc` | One surface of five Text nodes: bidi (Hebrew and Arabic in Latin), CJK wide characters, combining marks, emoji ZWJ sequences, and a paragraph long enough to wrap | - |
A surface whose bytes the contract refuses (an unknown union arm) cannot live in a store: that
case is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to
A payload the contract refuses cannot live in a store: f11's refused payload is a raw file here, and an
unknown union arm is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to
`MemState::put_raw`.
## Regenerate

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -1,10 +1,10 @@
//! The frozen fixture stores: typed contract documents built here, encoded through CultCache
//! under a pinned clock, committed under `fixtures/`, and loaded back through the same door
//! every consumer uses. `THING_BLESS=1` through `golden::check` is the only writer.
//! every consumer uses. The bless switch is read in `golden::check` alone.
use std::path::PathBuf;
use cultcache_rs::CultCache;
use cultcache_rs::{CultCache, check_payload_depth};
use thing_contract::*;
use crate::build::*;
@ -13,39 +13,79 @@ use crate::{golden, store};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fixture {
F01SwarmDashboard,
F02LoginEffect,
F03InputTarget,
F04Form,
F05ModalOverlay,
F06ScrollList,
F07Plot,
F08EmbedViewport,
F09CompositionStack,
F10Hostile,
F11Deep,
F12TextEdge,
}
/// The documents of one fixture, each kind in record-key order.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FixtureSet {
pub surfaces: Vec<SurfaceDocument>,
pub compositions: Vec<CompositionDocument>,
pub catalogs: Vec<AssetCatalog>,
pub invocations: Vec<CommandInvocation>,
pub results: Vec<CommandResult>,
}
impl FixtureSet {
fn new(
mut surfaces: Vec<SurfaceDocument>,
mut compositions: Vec<CompositionDocument>,
mut catalogs: Vec<AssetCatalog>,
) -> Self {
surfaces.sort_by_key(SurfaceDocument::record_key);
compositions.sort_by_key(CompositionDocument::record_key);
catalogs.sort_by_key(AssetCatalog::record_key);
Self { surfaces, compositions, catalogs }
fn sorted(mut self) -> Self {
self.surfaces.sort_by_key(SurfaceDocument::record_key);
self.compositions.sort_by_key(CompositionDocument::record_key);
self.catalogs.sort_by_key(AssetCatalog::record_key);
self.invocations.sort_by_key(CommandInvocation::record_key);
self.results.sort_by_key(CommandResult::record_key);
self
}
fn surfaces(surfaces: Vec<SurfaceDocument>) -> Self {
Self { surfaces, ..Self::default() }.sorted()
}
/// Every document in the set, counted.
pub fn document_count(&self) -> usize {
self.surfaces.len() + self.compositions.len() + self.catalogs.len() + self.invocations.len() + self.results.len()
}
}
impl Fixture {
pub const ALL: [Fixture; 3] = [Fixture::F01SwarmDashboard, Fixture::F09CompositionStack, Fixture::F10Hostile];
pub const ALL: [Fixture; 12] = [
Fixture::F01SwarmDashboard,
Fixture::F02LoginEffect,
Fixture::F03InputTarget,
Fixture::F04Form,
Fixture::F05ModalOverlay,
Fixture::F06ScrollList,
Fixture::F07Plot,
Fixture::F08EmbedViewport,
Fixture::F09CompositionStack,
Fixture::F10Hostile,
Fixture::F11Deep,
Fixture::F12TextEdge,
];
pub fn file_name(self) -> &'static str {
match self {
Fixture::F01SwarmDashboard => "f01-swarm-dashboard.surface.cc",
Fixture::F02LoginEffect => "f02-login-effect.surface.cc",
Fixture::F03InputTarget => "f03-input-target.surface.cc",
Fixture::F04Form => "f04-form.surface.cc",
Fixture::F05ModalOverlay => "f05-modal-overlay.surface.cc",
Fixture::F06ScrollList => "f06-scroll-list.surface.cc",
Fixture::F07Plot => "f07-plot.surface.cc",
Fixture::F08EmbedViewport => "f08-embed-viewport.surface.cc",
Fixture::F09CompositionStack => "f09-composition-stack.surface.cc",
Fixture::F10Hostile => "f10-hostile.surface.cc",
Fixture::F11Deep => "f11-deep.surface.cc",
Fixture::F12TextEdge => "f12-text-edge.surface.cc",
}
}
@ -56,16 +96,45 @@ impl Fixture {
/// The documents the builders produce.
pub fn build(self) -> FixtureSet {
match self {
Fixture::F01SwarmDashboard => FixtureSet::new(vec![swarm_dashboard()], vec![], vec![]),
Fixture::F09CompositionStack => FixtureSet::new(vec![composition_stack()], vec![stack_card()], vec![]),
Fixture::F10Hostile => FixtureSet::new(hostile(), vec![hostile_dup()], vec![]),
Fixture::F01SwarmDashboard => FixtureSet::surfaces(vec![swarm_dashboard()]),
Fixture::F02LoginEffect => login_effect(),
Fixture::F03InputTarget => input_target(),
Fixture::F04Form => form(),
Fixture::F05ModalOverlay => FixtureSet::surfaces(vec![modal_overlay()]),
Fixture::F06ScrollList => FixtureSet::surfaces(vec![scroll_list()]),
Fixture::F07Plot => FixtureSet::surfaces(vec![plot()]),
Fixture::F08EmbedViewport => FixtureSet::surfaces(vec![embed_viewport()]),
Fixture::F09CompositionStack => {
FixtureSet { surfaces: vec![composition_stack()], compositions: vec![stack_card()], ..FixtureSet::default() }
.sorted()
}
Fixture::F10Hostile => {
FixtureSet { surfaces: hostile(), compositions: vec![hostile_dup()], ..FixtureSet::default() }.sorted()
}
Fixture::F11Deep => FixtureSet::surfaces(vec![deep_surface(deepest_accepted())]),
Fixture::F12TextEdge => FixtureSet::surfaces(vec![text_edge()]),
}
}
/// The file holding the payload one Box level deeper than f11, which the contract refuses.
pub const DEEP_REFUSED: &'static str = "f11-deep-refused.bin";
/// The payload of f11's surface with one more Box level than the bound admits: raw bytes,
/// since no store can hold them.
pub fn deep_refused_payload() -> Vec<u8> {
rmp_serde::to_vec(&deep_surface(deepest_accepted() + 1)).unwrap()
}
/// Bless or compare the committed file of the refused payload; returns the committed bytes.
pub fn write_deep_refused() -> Vec<u8> {
golden::check(&Self::dir(), Self::DEEP_REFUSED, &Self::deep_refused_payload())
}
/// Encode the built documents into a store and bless or compare the committed file; returns
/// the committed bytes.
pub fn write(self) -> Vec<u8> {
let scratch = std::env::temp_dir().join(format!("thing-testkit-{}-{}", std::process::id(), self.file_name()));
let work = scratch_dir("write");
let scratch = work.join(self.file_name());
let mut cache = store::create(&scratch);
let set = self.build();
for surface in &set.surfaces {
@ -77,20 +146,23 @@ impl Fixture {
for catalog in &set.catalogs {
store::put_pinned(&mut cache, &catalog.record_key(), catalog);
}
for invocation in &set.invocations {
store::put_pinned(&mut cache, &invocation.record_key(), invocation);
}
for result in &set.results {
store::put_pinned(&mut cache, &result.record_key(), result);
}
drop(cache);
let bytes = std::fs::read(&scratch).unwrap();
let _ = std::fs::remove_file(&scratch);
let _ = std::fs::remove_dir_all(&work);
golden::check(&Self::dir(), self.file_name(), &bytes)
}
/// The committed store, opened through the contract. Opening creates a lock file beside the
/// store, so this opens a copy in a directory of its own (process id and a serial), removed
/// once the store is read: the fixtures directory is never written.
/// store, so this opens a copy in a directory of its own, removed once the store is read:
/// the fixtures directory is never written.
pub fn open(self) -> CultCache {
static OPENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let serial = OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let work = std::env::temp_dir().join(format!("thing-testkit-open-{}-{serial}", std::process::id()));
std::fs::create_dir_all(&work).unwrap();
let work = scratch_dir("open");
let copy = work.join(self.file_name());
std::fs::copy(Self::dir().join(self.file_name()), &copy).unwrap();
let cache = store::open(&copy);
@ -101,10 +173,27 @@ impl Fixture {
/// The committed store, decoded through the contract.
pub fn load(self) -> FixtureSet {
let cache = self.open();
FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap())
FixtureSet {
surfaces: cache.get_all().unwrap(),
compositions: cache.get_all().unwrap(),
catalogs: cache.get_all().unwrap(),
invocations: cache.get_all().unwrap(),
results: cache.get_all().unwrap(),
}
.sorted()
}
}
/// A fresh directory of its own under the temp directory (process id and a serial), so the lock
/// file a store creates beside its file goes when the directory does.
fn scratch_dir(purpose: &str) -> PathBuf {
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let work = std::env::temp_dir().join(format!("thing-testkit-{purpose}-{}-{serial}", std::process::id()));
std::fs::create_dir_all(&work).unwrap();
work
}
const SWARM: &str = "provider.swarm";
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
@ -339,3 +428,387 @@ fn hostile_dup() -> CompositionDocument {
body: boxed("dup-root", vec![text("shared-id", "from the composition")]),
}
}
// The nine fixtures below bind to test schemas only; the state scripts that fill them belong to
// the bind cut, so no provider state record lives in a fixture.
const TEST_SCHEMA_ROOT: &str = "gamecult.thing.test";
fn decl(id: &str, captures: &[&str], confirm: Option<&str>) -> CommandDecl {
CommandDecl {
id: CommandId::new(id),
payload_schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.{id}.v1")),
captures: captures.iter().map(|node| nid(node)).collect(),
confirm: confirm.map(Into::into),
}
}
fn record_member(provider: &str, schema: &str, key: &str, member: &[&str]) -> Bind {
Bind {
source: StateSource::Record(StateRef {
provider: Some(ProviderId::new(provider)),
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.{schema}.v1")),
key: RecordKey::new(key),
}),
member: path(member),
format: None,
}
}
fn surface(provider: &str, label: &str, root: Node, commands: Vec<CommandDecl>) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(provider),
label: seg(label),
version: ver(1),
title: label.into(),
root,
commands,
}
}
/// An invocation of `command` on `surface`, issued at the pinned clock.
fn invoke(surface: &SurfaceDocument, id: &str, command: &str, captured: Vec<CapturedInput>) -> CommandInvocation {
CommandInvocation {
invocation_id: id.into(),
surface_key: surface.record_key(),
surface_version: surface.version.clone(),
command: CommandId::new(command),
payload: RecordPayload {
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.{command}.v1")),
// An empty MessagePack array: the payload record has no slots to fill.
bytes: vec![0x90],
},
captured,
client: "renderer.web".into(),
issued_at: store::PINNED_CLOCK.into(),
delegation: None,
}
}
fn captured(node: &str, value: InputValue) -> CapturedInput {
CapturedInput { node: nid(node), value }
}
fn text_input(id: &str, kind: InputKind, initial: &str, submit: CommandRef) -> Node {
Node::TextInput(TextInputNode {
common: common(id),
multiline: false,
input_kind: kind,
placeholder: lit_text(id),
initial: lit_text(initial),
submit,
})
}
fn button(id: &str, label: &str, on_activate: CommandRef) -> Node {
Node::Button(ButtonNode {
common: common(id),
content: vec![text(&format!("{id}-label"), label)],
on_activate,
enabled: lit_bool(true),
})
}
fn login_effect() -> FixtureSet {
let root = boxed(
"root",
vec![
text_input("username", InputKind::Text, "", command("sign-in")),
button("sign-in-button", "Sign in", command("sign-in")),
],
);
let login = surface(
"provider.login",
"login",
root,
vec![decl("sign-in", &["username"], None), decl("login-resume", &[], None)],
);
let invocation = invoke(
&login,
"6d1c0f52-7a0e-4b53-8f3d-2a9e4c7b1d10",
"sign-in",
vec![captured("username", InputValue::Text(TextValue { value: "ada".into() }))],
);
// The answer arrives in two steps: Pending, then Completed, whose effect sends the user to
// an external page and names the command that runs when they return.
let results = vec![
CommandResult::pending(&invocation, seq(1), "waiting for the identity provider"),
CommandResult::completed(
&invocation,
seq(2),
None,
false,
Some(Effect::OpenExternal(OpenExternalEffect {
url: "https://login.example.test/authorize".into(),
resume: command("login-resume"),
})),
),
];
FixtureSet { surfaces: vec![login], invocations: vec![invocation], results, ..FixtureSet::default() }.sorted()
}
fn input_target() -> FixtureSet {
let provider = "provider.muninn";
let board = Node::Image(ImageNode {
common: common("board"),
catalog: "targets".into(),
asset: "board".into(),
fit: ImageFit::Contain,
alt: lit_text("The board the target sits on"),
});
let label = Node::Text(TextNode {
common: common("target-label"),
content: TextSource::Bound(record_member(provider, "target", "cursor", &["label"])),
style_token: "body".into(),
wrap: false,
max_lines: Some(count(1)),
selectable: false,
});
// An absolute Box over the Image: insets from the root's top and left edges, a fixed size.
let mut over = style();
over.position = Position::Absolute;
over.inset = Edges { top: px(120.0), right: Dimension::Auto, bottom: Dimension::Auto, left: px(200.0) };
over.size = size2(px(48.0), px(48.0));
let target = Node::Box(BoxNode {
common: common("target"),
style: over,
paint: plain_paint(),
role: Role::Group,
children: vec![label],
});
let mut frame = style();
frame.size = size2(px(640.0), px(360.0));
let root = Node::Box(BoxNode {
common: common("root"),
style: frame,
paint: plain_paint(),
role: Role::Group,
children: vec![board, target],
});
let catalog = AssetCatalog {
provider_id: ProviderId::new(provider),
catalog_id: seg("targets"),
version: ver(1),
assets: vec![AssetEntry {
id: "board".into(),
media_type: "image/png".into(),
uri: "asset://provider.muninn/board.png".into(),
width: count(640),
height: count(360),
}],
};
FixtureSet {
surfaces: vec![surface(provider, "input-target", root, vec![])],
catalogs: vec![catalog],
..FixtureSet::default()
}
.sorted()
}
fn form() -> FixtureSet {
let provider = "provider.settings";
let toggle = Node::Toggle(ToggleNode {
common: common("enabled"),
checked: BoolSource::Bound(record_member(provider, "settings", "current", &["enabled"])),
on_change: command("save"),
});
let slider = Node::Slider(SliderNode {
common: common("volume"),
min: 0.0,
max: 1.0,
step: 0.05,
value: NumberSource::Bound(record_member(provider, "settings", "current", &["volume"])),
commit: command("save"),
});
let select = Node::Select(SelectNode {
common: common("theme"),
options: OptionList::Literal(LiteralOptions {
options: vec![
SelectOption { value: "dark".into(), label: "Dark".into() },
SelectOption { value: "light".into(), label: "Light".into() },
],
}),
value: record_member(provider, "settings", "current", &["theme"]),
on_change: command("save"),
});
let port = text_input("port", InputKind::Number, "8080", command("save"));
let root = boxed("root", vec![toggle, slider, select, port]);
let form = surface(provider, "form", root, vec![decl("save", &["enabled", "volume", "theme", "port"], None)]);
let invocation = invoke(
&form,
"0b7e44aa-31c9-4e0d-a6f2-95d8c3e1b277",
"save",
vec![
captured("enabled", InputValue::Bool(BoolValue { value: true })),
captured("volume", InputValue::Number(NumberValue { value: 0.75 })),
captured("theme", InputValue::Choice(ChoiceValue { value: "dark".into() })),
captured("port", InputValue::Number(NumberValue { value: 8080.0 })),
],
);
// The save succeeds and clears the drafts the invocation captured.
let result = CommandResult::completed(&invocation, seq(1), Some(ver(2)), true, None);
FixtureSet { surfaces: vec![form], invocations: vec![invocation], results: vec![result], ..FixtureSet::default() }
.sorted()
}
fn modal_overlay() -> SurfaceDocument {
let dialog = Node::Box(BoxNode {
common: common("dialog"),
style: style(),
paint: plain_paint(),
role: Role::Dialog,
children: vec![
text("dialog-title", "Delete the archive?"),
button("confirm", "Delete", command("confirm")),
button("cancel", "Cancel", command("dismiss")),
],
});
let overlay = Node::Overlay(OverlayNode {
common: common("confirm-overlay"),
anchor: Anchor::Viewport,
modal: true,
dismiss: command("dismiss"),
children: vec![dialog],
});
surface(
"provider.dialog",
"modal",
boxed("root", vec![text("page-text", "The archive holds 12 items."), overlay]),
vec![decl("confirm", &[], Some("Delete the archive?")), decl("dismiss", &[], None)],
)
}
fn scroll_list() -> SurfaceDocument {
let provider = "provider.feed";
let row = Node::Box(BoxNode {
common: common("item-row"),
style: style(),
paint: plain_paint(),
role: Role::ListItem,
children: vec![Node::Text(TextNode {
common: common("item-title"),
content: TextSource::Bound(item_bind(path(&["title"]))),
style_token: "body".into(),
wrap: false,
max_lines: Some(count(1)),
selectable: false,
})],
});
let items = Node::Repeat(RepeatNode {
common: common("items"),
collection: CollectionSource::Records(RecordsSource {
provider: Some(ProviderId::new(provider)),
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.item.v1")),
key_prefix: "item-".into(),
}),
key_member: path(&["id"]),
template: std::boxed::Box::new(row),
});
let mut list = style();
list.overflow = Overflow::Scroll;
list.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(400.0));
let root = Node::Box(BoxNode {
common: common("root"),
style: list,
paint: plain_paint(),
role: Role::List,
children: vec![items],
});
surface(provider, "scroll-list", root, vec![])
}
fn plot() -> SurfaceDocument {
let provider = "provider.market";
let series = || record_member(provider, "series", "prices", &["values"]);
let mark = |id: &str, mark: PlotMark, x: (Option<f64>, Option<f64>), y: (Option<f64>, Option<f64>)| {
Node::Plot(PlotNode {
common: common(id),
series: series(),
mark,
x_min: x.0,
x_max: x.1,
y_min: y.0,
y_max: y.1,
})
};
let root = boxed(
"root",
vec![
mark("line", PlotMark::Line, (None, None), (None, None)),
mark("bar", PlotMark::Bar, (None, None), (Some(0.0), None)),
mark("area", PlotMark::Area, (Some(0.0), Some(99.0)), (Some(-1.0), Some(1.0))),
],
);
surface(provider, "plot", root, vec![])
}
fn embed_viewport() -> SurfaceDocument {
let embed = Node::Embed(EmbedNode {
common: common("viewport"),
slot_kind: "viewport.world".into(),
slot_id: "main".into(),
width: 320.0,
height: 180.0,
});
let mut row = style();
row.direction = Direction::Row;
let root = Node::Box(BoxNode {
common: common("root"),
style: row,
paint: plain_paint(),
role: Role::Group,
children: vec![text("before", "before"), embed, text("after", "after")],
});
surface("provider.viewport", "embed-viewport", root, vec![])
}
/// A chain of `levels` Boxes, each the only child of the last, the innermost empty.
fn deep_surface(levels: usize) -> SurfaceDocument {
let mut chain = boxed(&format!("deep-{}", levels - 1), vec![]);
for level in (0..levels - 1).rev() {
chain = boxed(&format!("deep-{level}"), vec![chain]);
}
surface("provider.deep", "deep", chain, vec![])
}
/// The most Box levels whose surface payload CultCache's depth check accepts, found by trying
/// one more level until the check refuses. The bound is CultCache's, never restated here.
fn deepest_accepted() -> usize {
let mut levels = 1;
while check_payload_depth(&rmp_serde::to_vec(&deep_surface(levels + 1)).unwrap()).is_ok() {
levels += 1;
}
levels
}
fn text_edge() -> SurfaceDocument {
let paragraph = "The quick brown fox jumps over the lazy dog while the evening light slides across the \
valley, and the long paragraph keeps going so that any reasonable column must break it \
across several lines. "
.repeat(4);
let samples = [
// Hebrew and Arabic runs inside a Latin sentence.
("bidi", "Hello \u{5e9}\u{5dc}\u{5d5}\u{5dd} \u{5e2}\u{5d5}\u{5dc}\u{5dd} and \u{645}\u{631}\u{62d}\u{628}\u{627} \u{628}\u{627}\u{644}\u{639}\u{627}\u{644}\u{645} then 123 end."),
// Han, kana, hangul and fullwidth Latin: two columns each.
("cjk", "\u{65e5}\u{672c}\u{8a9e}\u{30c6}\u{30b9}\u{30c8} \u{4f60}\u{597d}\u{4e16}\u{754c} \u{d55c}\u{ad6d}\u{c5b4} \u{ff21}\u{ff22}\u{ff23}\u{ff11}\u{ff12}\u{ff13}"),
// Marks that attach to the letter before them.
("combining", "e\u{301} a\u{308} n\u{303} o\u{302}\u{323} z\u{35b}\u{34f}\u{300}"),
// A family, a skin-toned technologist and a flag, each one cluster of joined scalars.
("emoji-zwj", "\u{1f469}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} \u{1f468}\u{1f3fd}\u{200d}\u{1f4bb} \u{1f3f3}\u{fe0f}\u{200d}\u{1f308}"),
("long-wrap", paragraph.as_str()),
];
let nodes = samples
.iter()
.map(|(id, content)| {
Node::Text(TextNode {
common: common(id),
content: lit_text(content),
style_token: "body".into(),
wrap: true,
max_lines: None,
selectable: true,
})
})
.collect();
surface("provider.text", "text-edge", boxed("root", nodes), vec![])
}

View file

@ -2,9 +2,12 @@
//! byte for byte, and each holds the shapes its row of the fixture table names.
//! `THING_BLESS=1` on this test rewrites them; any other run compares.
use cultcache_rs::{CultCacheEnvelope, PayloadTooDeep, check_payload_depth};
use thing_contract::*;
use thing_testkit::fixture::{Fixture, FixtureSet};
use thing_testkit::golden;
use thing_testkit::mem_state::MemState;
use thing_testkit::store;
use thing_core::port::{Address, Lookup, StatePort};
/// Decoding runs on a 16 MiB thread until the workspace pin of cultcache-rs carries
@ -42,13 +45,25 @@ fn every_fixture_round_trips_through_the_contract() {
let key = composition.record_key();
assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key));
}
for catalog in &loaded.catalogs {
assert_eq!(rmp_serde::to_vec(catalog).unwrap(), payload("gamecult.thing.asset_catalog", catalog.record_key()));
}
for invocation in &loaded.invocations {
let key = invocation.record_key();
assert_eq!(rmp_serde::to_vec(invocation).unwrap(), payload("gamecult.thing.command_invocation", key));
}
for result in &loaded.results {
assert_eq!(rmp_serde::to_vec(result).unwrap(), payload("gamecult.thing.command_result", result.record_key()));
}
assert_eq!(
stored.len(),
loaded.surfaces.len() + loaded.compositions.len() + loaded.catalogs.len(),
loaded.document_count(),
"{}: the store holds the documents and nothing else",
fixture.file_name()
);
}
// The payload one Box level past f11's chain is a raw file, not a store.
assert_eq!(Fixture::write_deep_refused(), Fixture::deep_refused_payload());
});
}
@ -191,3 +206,281 @@ fn loading_a_fixture_writes_nothing_in_the_fixtures_directory() {
}
assert_eq!(listing(), before);
}
fn arm(node: &Node) -> &'static str {
match node {
Node::Box(_) => "Box",
Node::Text(_) => "Text",
Node::Image(_) => "Image",
Node::Button(_) => "Button",
Node::Toggle(_) => "Toggle",
Node::Slider(_) => "Slider",
Node::TextInput(_) => "TextInput",
Node::Select(_) => "Select",
Node::Repeat(_) => "Repeat",
Node::Overlay(_) => "Overlay",
Node::Plot(_) => "Plot",
Node::Embed(_) => "Embed",
Node::Use(_) => "Use",
}
}
const ALL_ARMS: [&str; 13] = [
"Box", "Button", "Embed", "Image", "Overlay", "Plot", "Repeat", "Select", "Slider", "Text", "TextInput", "Toggle",
"Use",
];
/// Every node under `node`, itself first, through every child position the union has.
fn walk<'a>(node: &'a Node, out: &mut Vec<&'a Node>) {
out.push(node);
match node {
Node::Box(node) => node.children.iter().for_each(|child| walk(child, out)),
Node::Button(node) => node.content.iter().for_each(|child| walk(child, out)),
Node::Repeat(node) => walk(&node.template, out),
Node::Overlay(node) => node.children.iter().for_each(|child| walk(child, out)),
Node::Use(node) => {
for arg in &node.args {
if let ArgValue::Slot(slot) = &arg.value {
slot.nodes.iter().for_each(|child| walk(child, out));
}
}
}
_ => {}
}
}
fn nodes(set: &FixtureSet) -> Vec<&Node> {
let mut out = Vec::new();
set.surfaces.iter().for_each(|surface| walk(&surface.root, &mut out));
set.compositions.iter().for_each(|composition| walk(&composition.body, &mut out));
out
}
fn arms_of(fixture: Fixture) -> std::collections::BTreeSet<&'static str> {
nodes(&load(fixture)).into_iter().map(arm).collect()
}
fn holds(fixture: Fixture, wanted: &[&str]) {
let arms = arms_of(fixture);
for name in wanted {
assert!(arms.contains(name), "{}: no {name} node", fixture.file_name());
}
}
#[test]
fn the_twelve_fixtures_cover_all_thirteen_node_arms() {
let mut covered = std::collections::BTreeSet::new();
for fixture in Fixture::ALL {
covered.extend(arms_of(fixture));
}
assert_eq!(covered.into_iter().collect::<Vec<_>>(), ALL_ARMS);
holds(Fixture::F02LoginEffect, &["TextInput", "Button"]);
holds(Fixture::F03InputTarget, &["Image", "Box", "Text"]);
holds(Fixture::F04Form, &["Toggle", "Slider", "Select", "TextInput"]);
holds(Fixture::F05ModalOverlay, &["Overlay", "Button"]);
holds(Fixture::F06ScrollList, &["Box", "Repeat"]);
holds(Fixture::F07Plot, &["Plot"]);
holds(Fixture::F08EmbedViewport, &["Embed", "Text"]);
holds(Fixture::F11Deep, &["Box"]);
holds(Fixture::F12TextEdge, &["Text"]);
}
fn single_surface(fixture: Fixture) -> (FixtureSet, SurfaceDocument) {
let set = load(fixture);
assert_eq!(set.surfaces.len(), 1, "{}", fixture.file_name());
let surface = set.surfaces[0].clone();
(set, surface)
}
#[test]
fn f02_completes_with_an_external_step_whose_resume_command_the_surface_declares() {
let (set, surface) = single_surface(Fixture::F02LoginEffect);
let [invocation] = &set.invocations[..] else { panic!("one invocation expected") };
assert_eq!(invocation.surface_key, surface.record_key());
assert!(commands_declared(&surface).contains(&invocation.command.as_str()));
let decl = surface.commands.iter().find(|decl| decl.id == invocation.command).unwrap();
assert_eq!(decl.captures.len(), 1);
assert_eq!(invocation.captured.len(), 1);
assert_eq!(invocation.captured[0].node, decl.captures[0]);
let [pending, completed] = &set.results[..] else { panic!("two results expected") };
assert!(pending.seq().get() < completed.seq().get(), "Pending precedes Completed in seq");
assert!(matches!(pending.outcome(), Outcome::Pending(_)));
let Outcome::Completed(done) = completed.outcome() else { panic!("not Completed") };
let Some(Effect::OpenExternal(external)) = &done.effect else { panic!("not OpenExternal") };
let CommandRef::Id(resume) = &external.resume else { panic!("resume is not a command id") };
assert!(commands_declared(&surface).contains(&resume.id.as_str()), "the resume command is declared");
for result in &set.results {
assert_eq!(result.invocation_id(), invocation.invocation_id);
}
}
#[test]
fn f03_places_an_absolute_target_over_an_image_from_its_catalog() {
let (set, surface) = single_surface(Fixture::F03InputTarget);
let root_children = box_children(&surface.root);
let Node::Image(image) = &root_children[0] else { panic!("the Image comes first") };
let [catalog] = &set.catalogs[..] else { panic!("one catalog expected") };
assert_eq!(catalog.catalog_id.as_str(), image.catalog);
assert!(catalog.assets.iter().any(|asset| asset.id == image.asset), "the catalog holds the asset");
let Node::Box(target) = &root_children[1] else { panic!("the target Box follows the Image") };
assert_eq!(target.style.position, Position::Absolute);
assert_ne!(target.style.inset.top, Dimension::Auto);
assert_ne!(target.style.inset.left, Dimension::Auto);
let Node::Text(label) = &target.children[0] else { panic!("not a Text") };
assert!(matches!(label.content, TextSource::Bound(_)), "the label is bound");
}
#[test]
fn f04_one_command_captures_all_four_inputs_and_clears_drafts() {
let (set, surface) = single_surface(Fixture::F04Form);
let [save] = &surface.commands[..] else { panic!("one command expected") };
let inputs: Vec<&str> = nodes(&set)
.into_iter()
.filter(|node| matches!(node, Node::Toggle(_) | Node::Slider(_) | Node::Select(_) | Node::TextInput(_)))
.map(|node| match node {
Node::Toggle(node) => node.common.id.as_str(),
Node::Slider(node) => node.common.id.as_str(),
Node::Select(node) => node.common.id.as_str(),
Node::TextInput(node) => node.common.id.as_str(),
_ => unreachable!(),
})
.collect();
let captures: Vec<&str> = save.captures.iter().map(NodeId::as_str).collect();
assert_eq!(captures, inputs);
let [invocation] = &set.invocations[..] else { panic!("one invocation expected") };
let carried: Vec<&str> = invocation.captured.iter().map(|input| input.node.as_str()).collect();
assert_eq!(carried, captures);
let [result] = &set.results[..] else { panic!("one result expected") };
assert!(matches!(result.outcome(), Outcome::Completed(done) if done.clear_drafts));
let kinds: Vec<&InputKind> = nodes(&set)
.into_iter()
.filter_map(|node| if let Node::TextInput(input) = node { Some(&input.input_kind) } else { None })
.collect();
assert_eq!(kinds, [&InputKind::Number]);
let options = nodes(&set).into_iter().find_map(|node| if let Node::Select(select) = node { Some(select) } else { None });
assert!(matches!(&options.unwrap().options, OptionList::Literal(literal) if literal.options.len() == 2));
}
#[test]
fn f05_is_a_modal_viewport_overlay_with_two_focusable_controls_and_a_declared_dismiss() {
let (set, surface) = single_surface(Fixture::F05ModalOverlay);
let all = nodes(&set);
let Some(Node::Overlay(overlay)) = all.iter().copied().find(|node| matches!(node, Node::Overlay(_))) else {
panic!("no Overlay")
};
assert_eq!(overlay.anchor, Anchor::Viewport);
assert!(overlay.modal);
let CommandRef::Id(dismiss) = &overlay.dismiss else { panic!("dismiss is not a command id") };
assert!(commands_declared(&surface).contains(&dismiss.id.as_str()));
let mut inside = Vec::new();
overlay.children.iter().for_each(|child| walk(child, &mut inside));
assert_eq!(inside.iter().filter(|node| matches!(node, Node::Button(_))).count(), 2);
}
#[test]
fn f06_scrolls_a_repeat_over_a_records_prefix() {
let (_, surface) = single_surface(Fixture::F06ScrollList);
let Node::Box(root) = &surface.root else { panic!("root is not a Box") };
assert_eq!(root.style.overflow, Overflow::Scroll);
let [Node::Repeat(items)] = &root.children[..] else { panic!("one Repeat expected") };
assert!(matches!(&items.collection, CollectionSource::Records(records) if !records.key_prefix.is_empty()));
assert_eq!(items.key_member, thing_testkit::build::path(&["id"]));
}
#[test]
fn f07_plots_each_mark_over_a_bound_series() {
let (set, _) = single_surface(Fixture::F07Plot);
let marks: Vec<&PlotMark> = nodes(&set)
.into_iter()
.filter_map(|node| if let Node::Plot(plot) = node { Some(&plot.mark) } else { None })
.collect();
assert_eq!(marks, [&PlotMark::Line, &PlotMark::Bar, &PlotMark::Area]);
for node in nodes(&set) {
if let Node::Plot(plot) = node {
assert!(matches!(plot.series.source, StateSource::Record(_)));
}
}
}
#[test]
fn f08_embeds_a_fixed_size_leaf_among_siblings() {
let (_, surface) = single_surface(Fixture::F08EmbedViewport);
let children = box_children(&surface.root);
assert!(children.len() >= 3);
let embeds: Vec<&EmbedNode> = children.iter().filter_map(|node| if let Node::Embed(e) = node { Some(e) } else { None }).collect();
let [embed] = &embeds[..] else { panic!("one Embed expected") };
assert!(embed.width > 0.0 && embed.height > 0.0);
assert!(children.iter().any(|node| matches!(node, Node::Text(_))), "siblings around the Embed");
}
#[test]
fn f11_is_the_deepest_chain_the_bound_admits_and_one_more_level_is_refused() {
on_big_stack(|| {
let (set, surface) = single_surface(Fixture::F11Deep);
let cache = Fixture::F11Deep.open();
let stored = cache.snapshot_envelopes();
assert_eq!(stored.len(), 1);
// The committed surface passes CultCache's own check and decodes to the built chain.
assert_eq!(check_payload_depth(&stored[0].payload), Ok(()));
assert_eq!(rmp_serde::to_vec(&surface).unwrap(), stored[0].payload);
let levels = {
let mut levels = 0;
let mut node = &surface.root;
while let Node::Box(boxed) = node {
levels += 1;
match boxed.children.first() {
Some(child) => node = child,
None => break,
}
}
levels
};
assert!(levels > 1, "a chain, not one Box");
assert_eq!(set.surfaces.len(), 1);
// One Box level deeper is refused by the check, naming depth 257, and by CultCache.
let refused = golden::read(&Fixture::dir(), Fixture::DEEP_REFUSED);
assert_eq!(refused, Fixture::deep_refused_payload());
assert_eq!(check_payload_depth(&refused), Err(PayloadTooDeep { depth: 257, limit: 256 }));
let mut cache = store::memory();
let envelope = CultCacheEnvelope {
key: surface.record_key(),
r#type: "gamecult.thing.surface".into(),
payload: refused,
stored_at: store::PINNED_CLOCK.into(),
schema_id: Some("gamecult.thing.surface.v1".into()),
};
let error = cache.put_raw_envelope(envelope).unwrap_err();
assert!(error.downcast_ref::<PayloadTooDeep>().is_some(), "{error:#}");
assert!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap().is_none());
});
}
#[test]
fn f12_holds_each_text_edge_case_as_its_own_node() {
let (set, _) = single_surface(Fixture::F12TextEdge);
let texts: Vec<(&str, &str)> = nodes(&set)
.into_iter()
.filter_map(|node| match node {
Node::Text(text) => match &text.content {
TextSource::Literal(literal) => Some((text.common.id.as_str(), literal.value.as_str())),
_ => None,
},
_ => None,
})
.collect();
let ids: Vec<&str> = texts.iter().map(|(id, _)| *id).collect();
assert_eq!(ids, ["bidi", "cjk", "combining", "emoji-zwj", "long-wrap"]);
let content = |id: &str| texts.iter().find(|(name, _)| *name == id).unwrap().1;
assert!(content("bidi").chars().any(|c| ('\u{590}'..='\u{6ff}').contains(&c)) && content("bidi").is_ascii() == false);
assert!(content("bidi").contains("Hello"));
assert!(content("cjk").chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)));
assert!(content("combining").chars().any(|c| ('\u{300}'..='\u{36f}').contains(&c)));
assert!(content("emoji-zwj").contains('\u{200d}'));
assert!(content("long-wrap").len() > 400);
}

View file

@ -0,0 +1,31 @@
//! Writing a fixture leaves nothing behind. This is the only test in its binary, so no other
//! thread creates scratch files while it counts.
use thing_testkit::fixture::Fixture;
fn scratch_entries() -> Vec<String> {
let prefix = "thing-testkit-";
let mut names: Vec<String> = std::fs::read_dir(std::env::temp_dir())
.unwrap()
.filter_map(|entry| entry.unwrap().file_name().into_string().ok())
.filter(|name| name.starts_with(prefix) && name.contains(&format!("-{}-", std::process::id())))
.collect();
names.sort();
names
}
#[test]
fn writing_a_fixture_leaves_no_scratch_file_or_lock_behind() {
let before = scratch_entries();
let stack = std::thread::Builder::new().stack_size(16 * 1024 * 1024);
stack
.spawn(|| {
for fixture in Fixture::ALL {
fixture.write();
}
})
.unwrap()
.join()
.unwrap();
assert_eq!(scratch_entries(), before);
}