Thing/crates/thing-core/tests/bind.rs
Eureka 72d93006d0
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
Thing 2.0: images measure from their bound asset entry (#18)
2026-11-28 06:33:58 +00:00

1089 lines
50 KiB
Rust

//! Bind: the values of every site, keyed Repeat instances, typed faults, the interests a bound tree
//! holds and the dirty set of a change. `THING_BLESS=1` on `f01_by_name_store` and `f04_form`
//! rewrites their goldens through `golden::check`.
use std::path::PathBuf;
use thing_contract::*;
use thing_core::bind::{Applied, Binder, Bound, BoundTree, Field};
use thing_core::diagnostic::Code;
use thing_core::port::{Address, Change, Interest, Ledger, Prefix, StatePort, StateValue};
use thing_core::resolve::{Limits, resolve};
use thing_testkit::build::*;
use thing_testkit::fixture::Fixture;
use thing_testkit::golden;
use thing_testkit::mem_state::{Call, MemState};
use thing_testkit::state::{self, Inner, Item, Mixed, Series, Swarm, SwarmRenamed};
const SWARM: &str = "provider.swarm";
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
struct Rig {
state: MemState,
binder: Binder,
ledger: Ledger,
}
fn merge(into: &mut Applied, from: Applied) {
for (surface, ids) in from.dirty {
let held = into.dirty.entry(surface).or_default();
for id in ids {
if !held.contains(&id) {
held.push(id);
}
}
}
into.diagnostics.extend(from.diagnostics);
}
impl Rig {
fn new(state: MemState) -> Self {
Self { state, binder: Binder::new(Limits::default()), ledger: Ledger::new() }
}
fn fixture(fixture: Fixture) -> (Self, SurfaceDocument) {
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
(Self::new(state), fixture.load().surfaces.remove(0))
}
fn bind(&mut self, document: &SurfaceDocument) -> Applied {
let resolution = resolve(document, &self.state, &Limits::default());
let tree = resolution.tree.unwrap_or_else(|| panic!("not resolved: {:?}", resolution.diagnostics));
self.binder.bind(tree, &mut self.state, &mut self.ledger)
}
/// Drain the port and apply each change, as the frame owner does.
fn settle(&mut self) -> Applied {
let mut applied = Applied::default();
for change in self.state.drain() {
merge(&mut applied, self.binder.apply(&change, &mut self.state, &mut self.ledger));
}
applied
}
fn tree(&self, document: &SurfaceDocument) -> &BoundTree {
self.binder.tree(&document.record_key()).expect("bound")
}
}
fn nodes(applied: &Applied, document: &SurfaceDocument) -> Vec<String> {
applied.dirty.get(&document.record_key()).map(|ids| ids.iter().map(|id| id.as_str().to_string()).collect()).unwrap_or_default()
}
fn show(bound: &Bound) -> String {
match bound {
Bound::Text(text) => format!("text {text:?}"),
Bound::Number(n) => format!("number {n}"),
Bound::Bool(b) => format!("bool {b}"),
Bound::Series(series) => format!("series {series:?}"),
Bound::Options(options) => {
format!("options [{}]", options.iter().map(|o| format!("{}={}", o.value, o.label)).collect::<Vec<_>>().join(", "))
}
Bound::Asset(entry) => format!("asset {} {}x{}", entry.id, entry.width.get(), entry.height.get()),
Bound::Absent => "absent".to_string(),
Bound::Error(error) => format!("error {:?}", error.code),
}
}
/// The sorted (node id, field, value) listing the goldens hold: bind output has no wire form.
fn listing(tree: &BoundTree) -> String {
tree.sites().into_iter().map(|(node, field, bound)| format!("{} {} {}\n", node.as_str(), field.name(), show(bound))).collect()
}
fn goldens() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
fn value<'t>(tree: &'t BoundTree, node: &str, field: Field) -> &'t Bound {
tree.value(&nid(node), field).unwrap_or_else(|| panic!("no value at {node} {field:?}"))
}
fn code(bound: &Bound) -> Code {
match bound {
Bound::Error(error) => error.code,
other => panic!("not an error: {other:?}"),
}
}
fn address(key: &str) -> Address {
Address { provider: ProviderId::new(SWARM), schema: SchemaId::new(SWARM_SCHEMA), key: RecordKey::new(key) }
}
fn swarm_bind(key: &str, steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
bind_at(SWARM_SCHEMA, key, steps, format)
}
fn prices_bind(steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
bind_at("gamecult.thing.test.series.v1", "prices", steps, format)
}
fn bind_at(schema: &str, key: &str, steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
Bind {
source: StateSource::Record(StateRef {
provider: Some(ProviderId::new(SWARM)),
schema: SchemaId::new(schema),
key: RecordKey::new(key),
}),
member: MemberPath { steps },
format,
}
}
fn name(member: &str) -> MemberStep {
MemberStep::Name(MemberName { name: member.into() })
}
fn index(at: i32) -> MemberStep {
MemberStep::Index(MemberIndex { index: count(at) })
}
fn bound_text(id: &str, bind: Bind) -> Node {
Node::Text(TextNode {
common: common(id),
content: TextSource::Bound(bind),
style_token: "body".into(),
wrap: false,
max_lines: None,
selectable: false,
})
}
fn page(label: &str, children: Vec<Node>) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(SWARM),
label: seg(label),
version: ver(1),
title: label.into(),
root: boxed("root", children),
commands: vec![],
}
}
fn swarm_state() -> MemState {
let mut state = MemState::new();
state::script(Fixture::F01SwarmDashboard, &mut state);
state
}
fn count_calls(state: &MemState, wanted: impl Fn(&Call) -> bool) -> usize {
state.calls().iter().filter(|call| wanted(call)).count()
}
fn swarm(id: &str, name: &str, load: f64) -> Swarm {
Swarm { id: id.into(), name: name.into(), load }
}
#[test]
fn f01_by_name_store() {
let mut state = MemState::new();
state.load_store(&ProviderId::new(SWARM), &Fixture::dir().join(state::SWARM_STORE));
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
assert_eq!(applied.diagnostics, vec![]);
let tree = rig.tree(&document);
assert_eq!(value(tree, "load", Field::Content), &Bound::Text("42.0%".into()));
let instances = tree.instances(&nid("minds"));
assert_eq!(instances.iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["mind-1", "mind-2", "mind-3"]);
for (instance, name) in instances.iter().zip(["Eureka", "Libby", "Kiko"]) {
let id = format!("minds#6:{}/mind-name", instance.key);
assert_eq!(value(tree, &id, Field::Content), &Bound::Text(name.into()));
}
golden::check(&goldens(), "bind-f01-swarm-dashboard.txt", listing(tree).as_bytes());
}
#[test]
fn members_empty_store_refuses_every_record() {
let mut state = MemState::new();
state.load_store(&ProviderId::new(SWARM), &Fixture::dir().join(state::SWARM_STORE_MEMBERS_EMPTY));
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(code(value(tree, "load", Field::Content)), Code::DecodeRefused);
let instances = tree.instances(&nid("minds"));
assert_eq!(instances.iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["!mind-1", "!mind-2", "!mind-3"]);
for instance in instances {
let id = format!("minds!{}:{}/mind-name", instance.key.len() - 1, &instance.key[1..]);
assert_eq!(code(value(tree, &id, Field::Content)), Code::DecodeRefused);
}
assert_eq!(applied.diagnostics.len(), 4);
assert!(applied.diagnostics.iter().all(|d| d.code == Code::DecodeRefused));
assert!(!listing(tree).contains("Eureka") && !listing(tree).contains("0.42"));
}
#[test]
fn schema_mismatch_missing_member_and_absence() {
// f10's schema-mismatch surface asks nowhere.v1 of a key that holds a swarm.
let hostile = Fixture::F10Hostile.load();
let surface = hostile.surfaces.iter().find(|s| s.label.as_str() == "schema-mismatch").unwrap();
let (mut rig, _) = Rig::fixture(Fixture::F10Hostile);
let applied = rig.bind(surface);
assert_eq!(code(value(rig.tree(surface), "mismatch", Field::Content)), Code::BindSchemaMismatch);
assert_eq!(applied.diagnostics.len(), 1);
assert_eq!(applied.diagnostics[0].code, Code::BindSchemaMismatch);
// Without the record: absent, and nothing to say.
let mut bare = Rig::new(MemState::from_fixture(Fixture::F10Hostile));
let applied = bare.bind(surface);
assert_eq!(value(bare.tree(surface), "mismatch", Field::Content), &Bound::Absent);
assert_eq!(applied.diagnostics, vec![]);
// f01 with Load renamed in the record: a member that is not there is loud.
let mut state = MemState::new();
state.put_state(&ProviderId::new(SWARM), "summary", &SwarmRenamed { id: "summary".into(), name: "Swarm".into(), burden: 0.42 });
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
assert_eq!(code(value(rig.tree(&document), "load", Field::Content)), Code::BindMemberMissing);
assert_eq!(applied.diagnostics.iter().filter(|d| d.code == Code::BindMemberMissing).count(), 1);
}
#[test]
fn no_value_is_coerced() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "prices", &Series { values: vec![3.0, 5.5] });
let mut rig = Rig::new(state);
let document = page(
"coerce",
vec![
bound_text("number-as-text", swarm_bind("summary", vec![name("Load")], None)),
bound_text("text-as-number", swarm_bind("summary", vec![name("Name")], Some(Format::Number(NumberFormat { precision: count(1), percent: false, unit: None })))),
bound_text("index-on-record", swarm_bind("summary", vec![index(0)], None)),
bound_text("name-on-list", prices_bind(vec![name("Values"), name("x")], None)),
bound_text("affix-on-number", swarm_bind("summary", vec![name("Load")], Some(Format::Affix(AffixFormat { prefix: "<".into(), suffix: ">".into() })))),
Node::Toggle(ToggleNode {
common: common("number-as-bool"),
checked: BoolSource::Bound(swarm_bind("summary", vec![name("Load")], None)),
on_change: command("x"),
}),
Node::Slider(SliderNode {
common: common("text-as-slider"),
min: 0.0,
max: 1.0,
step: 0.1,
value: NumberSource::Bound(swarm_bind("summary", vec![name("Name")], None)),
commit: command("x"),
}),
Node::Slider(SliderNode {
common: common("formatted-slider"),
min: 0.0,
max: 1.0,
step: 0.1,
value: NumberSource::Bound(swarm_bind("summary", vec![name("Load")], Some(Format::Duration))),
commit: command("x"),
}),
],
);
let mut document = document;
document.commands = ["x"]
.iter()
.map(|id| CommandDecl { id: CommandId::new(*id), payload_schema: SchemaId::new("gamecult.thing.test.x.v1"), captures: vec![], confirm: None })
.collect();
rig.bind(&document);
let tree = rig.tree(&document);
for (id, field) in [
("number-as-text", Field::Content),
("text-as-number", Field::Content),
("index-on-record", Field::Content),
("name-on-list", Field::Content),
("affix-on-number", Field::Content),
("number-as-bool", Field::Checked),
("text-as-slider", Field::Value),
("formatted-slider", Field::Value),
] {
assert_eq!(code(value(tree, id, field)), Code::BindTypeMismatch, "{id}");
}
}
#[test]
fn formats_and_indexes_through_the_walk() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "prices", &Series { values: vec![3.0, 5.5, 3_605.0] });
let mut rig = Rig::new(state);
let document = page(
"formats",
vec![
bound_text("index", prices_bind(vec![name("Values"), index(1)], Some(Format::Number(NumberFormat { precision: count(2), percent: false, unit: Some("pt".into()) })))),
bound_text("duration", prices_bind(vec![name("Values"), index(2)], Some(Format::Duration))),
bound_text("timestamp", prices_bind(vec![name("Values"), index(0)], Some(Format::Timestamp))),
bound_text("affix", swarm_bind("summary", vec![name("Name")], Some(Format::Affix(AffixFormat { prefix: "[".into(), suffix: "]".into() })))),
bound_text("past-the-end", prices_bind(vec![name("Values"), index(9)], None)),
],
);
rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(value(tree, "index", Field::Content), &Bound::Text("5.50 pt".into()));
assert_eq!(value(tree, "duration", Field::Content), &Bound::Text("1h 00m 05s".into()));
assert_eq!(value(tree, "timestamp", Field::Content), &Bound::Text("1970-01-01T00:00:03Z".into()));
assert_eq!(value(tree, "affix", Field::Content), &Bound::Text("[Swarm]".into()));
assert_eq!(code(value(tree, "past-the-end", Field::Content)), Code::BindMemberMissing);
}
#[test]
fn f04_form() {
let (mut rig, document) = Rig::fixture(Fixture::F04Form);
let applied = rig.bind(&document);
assert_eq!(applied.diagnostics, vec![]);
let tree = rig.tree(&document);
assert_eq!(value(tree, "enabled", Field::Checked), &Bound::Bool(true));
assert_eq!(value(tree, "volume", Field::Value), &Bound::Number(40.0));
assert_eq!(value(tree, "theme", Field::Selected), &Bound::Text("dark".into()));
golden::check(&goldens(), "bind-f04-form.txt", listing(tree).as_bytes());
}
#[test]
fn f07_series_and_f06_options() {
let (mut rig, document) = Rig::fixture(Fixture::F07Plot);
rig.bind(&document);
assert_eq!(value(rig.tree(&document), "line", Field::Series), &Bound::Series(vec![3.0, 5.5, 4.25, 8.0, 6.5]));
// A select whose options are the records of a collection.
let mut state = MemState::new();
state::script(Fixture::F06ScrollList, &mut state);
let select = Node::Select(SelectNode {
common: common("pick"),
options: OptionList::Bound(BoundOptions {
collection: CollectionSource::Records(RecordsSource {
provider: Some(ProviderId::new("provider.feed")),
schema: SchemaId::new("gamecult.thing.test.item.v1"),
key_prefix: "item-000".into(),
}),
value_member: path(&["Id"]),
label_member: path(&["Title"]),
}),
value: swarm_bind("none", vec![name("Id")], None),
on_change: command("x"),
});
let mut document = page("options", vec![select]);
document.commands = vec![CommandDecl { id: CommandId::new("x"), payload_schema: SchemaId::new("gamecult.thing.test.x.v1"), captures: vec![], confirm: None }];
let mut rig = Rig::new(state);
rig.bind(&document);
let Bound::Options(options) = value(rig.tree(&document), "pick", Field::Options) else { panic!("not options") };
assert_eq!(options.len(), 10);
assert_eq!((options[3].value.as_str(), options[3].label.as_str()), ("item-0003", "Item 3"));
assert_eq!(value(rig.tree(&document), "pick", Field::Selected), &Bound::Absent);
}
#[test]
fn repeat_identity_follows_the_key() {
let (mut rig, document) = Rig::fixture(Fixture::F06ScrollList);
rig.bind(&document);
let feed = ProviderId::new("provider.feed");
let ids = |rig: &Rig| -> Vec<String> {
let mut ids: Vec<String> = rig.tree(&document).instances(&nid("items")).iter().map(|i| format!("{:?}", i.root)).collect();
ids.sort();
ids
};
let keys = |rig: &Rig| -> Vec<String> { rig.tree(&document).instances(&nid("items")).iter().map(|i| i.key.clone()).collect() };
let before_ids = ids(&rig);
let before_keys = keys(&rig);
assert_eq!(before_keys.len(), 1000);
let id_of = |key: &str| format!("items#{}:{key}/item-row", key.len());
assert!(rig.tree(&document).value(&nid(&id_of("item-0042")), Field::Visible).is_some());
assert!(rig.tree(&document).value(&nid(&"items#9:item-0042/item-title".to_string()), Field::Content).is_some());
// Reorder: two records swap which Id they hold. The instance id set is the same.
rig.state.put_state(&feed, "item-0000", &Item { id: "item-0001".into(), title: "Item 1".into() });
rig.state.put_state(&feed, "item-0001", &Item { id: "item-0000".into(), title: "Item 0".into() });
let applied = rig.settle();
assert_eq!(ids(&rig), before_ids);
let after = keys(&rig);
assert_eq!(&after[..2], ["item-0001", "item-0000"]);
assert!(nodes(&applied, &document).contains(&"items".to_string()));
// Insert one.
rig.state.put_state(&feed, "item-0500a", &Item { id: "extra".into(), title: "Extra".into() });
let applied = rig.settle();
assert_eq!(keys(&rig).len(), 1001);
assert!(nodes(&applied, &document).contains(&"items".to_string()));
assert!(rig.tree(&document).value(&nid(&id_of("extra")), Field::Visible).is_some());
// Remove one.
rig.state.delete(&Address { provider: feed, schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new("item-0500a") });
let applied = rig.settle();
assert_eq!(keys(&rig).len(), 1000);
assert!(nodes(&applied, &document).contains(&"items".to_string()));
assert!(rig.tree(&document).value(&nid(&id_of("extra")), Field::Visible).is_none());
}
#[test]
fn a_duplicate_key_is_local_to_its_repeat() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "mind-2", &swarm("mind-1", "Twin", 0.0));
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(tree.repeat_error(&nid("minds")).map(|e| e.code), Some(Code::RepeatKeyDuplicate));
assert!(tree.instances(&nid("minds")).is_empty());
assert_eq!(value(tree, "load", Field::Content), &Bound::Text("42.0%".into()));
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::RepeatKeyDuplicate]);
}
#[test]
fn an_instance_id_that_is_already_an_id_refuses_that_repeat() {
// The authored id is exactly the id the first instance would derive.
let items = Node::Repeat(RepeatNode {
common: common("rows"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(text("t", "row")),
});
let document = page("clash", vec![items, text("rows#6:mind-1/t", "taken")]);
let mut rig = Rig::new(swarm_state());
let applied = rig.bind(&document);
assert_eq!(rig.tree(&document).repeat_error(&nid("rows")).map(|e| e.code), Some(Code::DuplicateNodeId));
assert_eq!(applied.diagnostics.len(), 1);
// And past the node limit.
let resolution = resolve(&document, &rig.state, &Limits::default());
let mut small = Binder::new(Limits { max_nodes: 2, ..Limits::default() });
let mut ledger = Ledger::new();
let roomy = page("limit", vec![Node::Repeat(RepeatNode {
common: common("rows"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(text("t", "row")),
})]);
drop(resolution);
let tree = resolve(&roomy, &rig.state, &Limits::default()).tree.unwrap();
small.bind(tree, &mut rig.state, &mut ledger);
assert_eq!(small.tree(&roomy.record_key()).unwrap().repeat_error(&nid("rows")).map(|e| e.code), Some(Code::ExpansionLimit));
}
#[test]
fn nested_repeats_derive_ids_from_ids() {
// Rows of swarm records, and under each a Repeat over the same records.
let inner = Node::Repeat(RepeatNode {
common: common("inner"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-1".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(Node::Text(TextNode {
common: common("cell"),
content: TextSource::Bound(item_bind(path(&["Name"]))),
style_token: "body".into(),
wrap: false,
max_lines: None,
selectable: false,
})),
});
let outer = Node::Repeat(RepeatNode {
common: common("outer"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(boxed("row", vec![inner])),
});
let document = page("nested", vec![outer]);
let mut rig = Rig::new(swarm_state());
let applied = rig.bind(&document);
assert_eq!(applied.diagnostics, vec![]);
let tree = rig.tree(&document);
assert_eq!(tree.instances(&nid("outer")).len(), 3);
let inner_id = "outer#6:mind-2/inner";
let cells = tree.instances(&nid(inner_id));
assert_eq!(cells.len(), 1);
assert_eq!(value(tree, &format!("{inner_id}#6:mind-1/outer#6:mind-2/cell"), Field::Content), &Bound::Text("Eureka".into()));
}
#[test]
fn dirty_is_only_what_changed() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
rig.bind(&document);
let before = rig.state.calls().len();
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.5));
let applied = rig.settle();
assert_eq!(nodes(&applied, &document), ["load"]);
assert_eq!(value(rig.tree(&document), "load", Field::Content), &Bound::Text("50.0%".into()));
let calls: Vec<Call> = rig.state.calls()[before..].iter().filter(|call| **call != Call::Drain).cloned().collect();
assert_eq!(calls, [Call::Read(address("summary"))]);
// A record nothing holds an interest in is never queued, and a change handed over anyway reads nothing.
rig.state.put_state(&ProviderId::new(SWARM), "zzz", &swarm("zzz", "Nobody", 0.0));
assert!(rig.state.drain().is_empty());
let calls_before = rig.state.calls().len();
let applied = rig.binder.apply(&Change::Delete(address("zzz")), &mut rig.state, &mut rig.ledger);
assert_eq!(applied, Applied::default());
assert_eq!(rig.state.calls().len(), calls_before);
// A mind changing re-lists its Repeat only.
rig.state.put_state(&ProviderId::new(SWARM), "mind-3", &swarm("mind-3", "Renamed", 0.0));
let applied = rig.settle();
assert_eq!(nodes(&applied, &document), ["minds#6:mind-3/mind-name"]);
}
#[test]
fn a_fault_is_said_once() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "summary", &SwarmRenamed { id: "summary".into(), name: "Swarm".into(), burden: 0.4 });
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
assert_eq!(rig.bind(&document).diagnostics.len(), 1);
rig.state.put_state(&ProviderId::new(SWARM), "summary", &SwarmRenamed { id: "summary".into(), name: "Swarm".into(), burden: 0.5 });
assert_eq!(rig.settle().diagnostics, vec![]);
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.5));
let applied = rig.settle();
assert_eq!(applied.diagnostics, vec![]);
assert_eq!(value(rig.tree(&document), "load", Field::Content), &Bound::Text("50.0%".into()));
}
#[test]
fn interests_follow_the_tree() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
let subscribes = |rig: &Rig| count_calls(&rig.state, |call| matches!(call, Call::Subscribe(_)));
let unsubscribes = |rig: &Rig| count_calls(&rig.state, |call| matches!(call, Call::Unsubscribe(_)));
rig.bind(&document);
assert_eq!(subscribes(&rig), 2);
let summary = Interest::Record(address("summary"));
let minds = Interest::Prefix(Prefix { provider: ProviderId::new(SWARM), schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() });
assert_eq!((rig.ledger.readers(&summary), rig.ledger.readers(&minds)), (1, 1));
// Applies do not resubscribe.
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.1));
rig.settle();
rig.state.put_state(&ProviderId::new(SWARM), "mind-1", &swarm("mind-1", "Eureka", 0.1));
rig.settle();
assert_eq!((subscribes(&rig), unsubscribes(&rig)), (2, 0));
// A rebind on a tree that drops the Repeat releases its prefix, and nothing else.
let mut slimmer = document.clone();
let Node::Box(root) = &mut slimmer.root else { panic!("root is a Box") };
root.children.retain(|child| !matches!(child, Node::Repeat(_)));
rig.bind(&slimmer);
assert_eq!((subscribes(&rig), unsubscribes(&rig)), (2, 1));
assert_eq!((rig.ledger.readers(&summary), rig.ledger.readers(&minds)), (1, 0));
// An unsubscribed record's arrival changes nothing.
rig.state.put_state(&ProviderId::new(SWARM), "mind-9", &swarm("mind-9", "Late", 0.0));
assert_eq!(rig.settle(), Applied::default());
}
#[test]
fn two_surfaces_share_one_subscription() {
let mut rig = Rig::new(swarm_state());
let one = page("one", vec![bound_text("a", swarm_bind("summary", vec![name("Name")], None))]);
let two = page("two", vec![bound_text("b", swarm_bind("summary", vec![name("Name")], None))]);
rig.bind(&one);
rig.bind(&two);
let summary = Interest::Record(address("summary"));
assert_eq!(count_calls(&rig.state, |call| matches!(call, Call::Subscribe(_))), 1);
assert_eq!(rig.ledger.readers(&summary), 2);
rig.binder.forget(&one.record_key(), &mut rig.state, &mut rig.ledger);
assert_eq!(count_calls(&rig.state, |call| matches!(call, Call::Unsubscribe(_))), 0);
rig.binder.forget(&two.record_key(), &mut rig.state, &mut rig.ledger);
assert_eq!(count_calls(&rig.state, |call| matches!(call, Call::Unsubscribe(_))), 1);
assert_eq!(rig.ledger.readers(&summary), 0);
// A change reaches both holders through the one subscription.
let mut rig = Rig::new(swarm_state());
rig.bind(&one);
rig.bind(&two);
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Moved", 0.0));
let applied = rig.settle();
assert_eq!(nodes(&applied, &one), ["a"]);
assert_eq!(nodes(&applied, &two), ["b"]);
}
#[test]
fn binding_twice_is_the_same() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
rig.bind(&document);
let first = rig.tree(&document).clone();
let calls = rig.state.calls().len();
let applied = rig.bind(&document);
assert_eq!(rig.tree(&document), &first);
assert_eq!(applied, Applied::default());
let new: Vec<Call> = rig.state.calls()[calls..].to_vec();
assert!(new.iter().all(|call| matches!(call, Call::Read(_) | Call::List(_))), "{new:?}");
}
#[test]
fn pipeline_smoke_f09() {
let mut state = MemState::from_fixture(Fixture::F09CompositionStack);
state::script(Fixture::F01SwarmDashboard, &mut state);
// The card's rows are the surface provider's records.
for (key, record) in state::swarm_records() {
state.put_state(&ProviderId::new("provider.stack"), key, &record);
}
let mut rig = Rig::new(state);
let document = Fixture::F09CompositionStack.load().surfaces.remove(0);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
let rows = tree.instances(&nid("outer-card/card-rows"));
assert_eq!(rows.len(), 3);
assert_eq!(value(tree, "outer-card/card-rows#6:mind-2/outer-card/card-row", Field::Content), &Bound::Text("Libby".into()));
// The std stat's Bind argument is bound at its expanded id: Load is a number and the stat
// gives it no Format, so the site says so rather than coercing.
assert_eq!(code(value(tree, "std-stat/stat-value", Field::Content)), Code::BindTypeMismatch);
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::BindTypeMismatch]);
}
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
const MIXED: &str = "gamecult.thing.test.mixed.v1";
fn mixed(id: &str, count: i64, maybe: Option<&str>) -> Mixed {
Mixed {
id: id.into(),
count,
flag: true,
maybe: maybe.map(Into::into),
inner: Inner { label: "L".into(), weight: 2.5 },
tags: vec!["a".into(), "b".into()],
when: "2026-01-01T00:00:00Z".into(),
}
}
/// A state whose `Mixed` records came through a real store file and `load_store`, so every value is
/// what the port decodes by the store's own member rows.
fn mixed_state(records: &[(&str, Mixed)]) -> MemState {
let dir = std::env::temp_dir().join(format!("thing-bind-mixed-{}-{}", std::process::id(), SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("mixed.cc");
std::fs::write(&path, state::mixed_store(records)).unwrap();
let mut state = MemState::new();
state.load_store(&ProviderId::new(SWARM), &path);
let _ = std::fs::remove_dir_all(&dir);
state
}
fn mixed_bind(key: &str, steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
bind_at(MIXED, key, steps, format)
}
fn mixed_records(prefix: &str) -> CollectionSource {
CollectionSource::Records(RecordsSource { provider: Some(ProviderId::new(SWARM)), schema: SchemaId::new(MIXED), key_prefix: prefix.into() })
}
fn repeat_over(id: &str, collection: CollectionSource, key: &[&str], template: Node) -> Node {
Node::Repeat(RepeatNode { common: common(id), collection, key_member: path(key), template: std::boxed::Box::new(template) })
}
fn with_x(mut document: SurfaceDocument) -> SurfaceDocument {
document.commands = vec![CommandDecl { id: CommandId::new("x"), payload_schema: SchemaId::new("gamecult.thing.test.x.v1"), captures: vec![], confirm: None }];
document
}
fn site_of(kind: &str, bind: Bind) -> Node {
match kind {
"text" => bound_text(kind, bind),
"number" => Node::Slider(SliderNode { common: common(kind), min: 0.0, max: 1.0, step: 0.1, value: NumberSource::Bound(bind), commit: command("x") }),
"bool" => Node::Toggle(ToggleNode { common: common(kind), checked: BoolSource::Bound(bind), on_change: command("x") }),
"series" => Node::Plot(PlotNode { common: common(kind), series: bind, mark: PlotMark::Line, x_min: None, x_max: None, y_min: None, y_max: None }),
_ => unreachable!(),
}
}
fn kind_field(kind: &str) -> Field {
match kind {
"text" => Field::Content,
"number" => Field::Value,
"bool" => Field::Checked,
_ => Field::Series,
}
}
#[test]
fn every_member_kind_against_every_site_kind() {
use Bound::*;
// (member, [text, number, bool, series]); None is BindTypeMismatch.
let rows: [(&str, [Option<Bound>; 4]); 6] = [
("Id", [Some(Text("m1".into())), None, None, None]),
("Count", [None, Some(Number(7.0)), None, None]),
("Flag", [None, None, Some(Bool(true)), None]),
("Inner", [None, None, None, None]),
("Tags", [None, None, None, None]),
("Maybe", [Some(Absent), Some(Absent), Some(Absent), Some(Absent)]),
];
let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))]));
for (member, expected) in rows {
for (kind, want) in ["text", "number", "bool", "series"].into_iter().zip(expected) {
let document = with_x(page(&format!("pair-{member}-{kind}"), vec![site_of(kind, mixed_bind("m1", vec![name(member)], None))]));
rig.bind(&document);
let got = value(rig.tree(&document), kind, kind_field(kind));
match want {
Some(bound) => assert_eq!(got, &bound, "{member} at a {kind} site"),
None => assert_eq!(code(got), Code::BindTypeMismatch, "{member} at a {kind} site"),
}
}
}
}
#[test]
fn a_series_with_a_non_number_is_refused_whole() {
// The nested record decodes as [Text, Float]: filtering would bind [2.5].
let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))]));
let document = with_x(page("series", vec![site_of("series", mixed_bind("m1", vec![name("Inner")], None))]));
rig.bind(&document);
assert_eq!(code(value(rig.tree(&document), "series", Field::Series)), Code::BindTypeMismatch);
}
#[test]
fn nested_records_are_positional_and_a_name_step_into_one_is_loud() {
let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))]));
let one = Some(Format::Number(NumberFormat { precision: count(1), percent: false, unit: None }));
let document = page(
"nested",
vec![
bound_text("by-name", mixed_bind("m1", vec![name("Inner"), name("Label")], None)),
bound_text("by-index", mixed_bind("m1", vec![name("Inner"), index(0)], None)),
bound_text("weight", mixed_bind("m1", vec![name("Inner"), index(1)], one)),
bound_text("past", mixed_bind("m1", vec![name("Inner"), index(2)], None)),
],
);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(code(value(tree, "by-name", Field::Content)), Code::BindTypeMismatch);
assert_eq!(value(tree, "by-index", Field::Content), &Bound::Text("L".into()));
assert_eq!(value(tree, "weight", Field::Content), &Bound::Text("2.5".into()));
assert_eq!(code(value(tree, "past", Field::Content)), Code::BindMemberMissing);
assert_eq!(applied.diagnostics.len(), 2);
}
#[test]
fn timestamp_text_is_validated_and_shown_as_written() {
let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None))]));
let document = page(
"stamps",
vec![
bound_text("stamp", mixed_bind("m1", vec![name("When")], Some(Format::Timestamp))),
bound_text("not-a-stamp", mixed_bind("m1", vec![name("Id")], Some(Format::Timestamp))),
bound_text("text-as-duration", mixed_bind("m1", vec![name("Id")], Some(Format::Duration))),
],
);
rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(value(tree, "stamp", Field::Content), &Bound::Text("2026-01-01T00:00:00Z".into()));
assert_eq!(code(value(tree, "not-a-stamp", Field::Content)), Code::BindTypeMismatch);
assert_eq!(code(value(tree, "text-as-duration", Field::Content)), Code::BindTypeMismatch);
}
#[test]
fn nil_is_absence_at_the_end_and_in_the_middle_but_an_error_as_an_option() {
let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None)), ("m2", mixed("m2", 8, Some("two")))]));
let select = Node::Select(SelectNode {
common: common("pick"),
options: OptionList::Bound(BoundOptions { collection: mixed_records("m"), value_member: path(&["Id"]), label_member: path(&["Maybe"]) }),
value: mixed_bind("m1", vec![name("Maybe"), name("deeper")], None),
on_change: command("x"),
});
let document = with_x(page(
"nil",
vec![bound_text("end", mixed_bind("m1", vec![name("Maybe")], None)), bound_text("middle", mixed_bind("m1", vec![name("Maybe"), name("x")], None)), select],
));
let applied = rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(value(tree, "end", Field::Content), &Bound::Absent);
assert_eq!(value(tree, "middle", Field::Content), &Bound::Absent);
assert_eq!(value(tree, "pick", Field::Selected), &Bound::Absent);
assert_eq!(code(value(tree, "pick", Field::Options)), Code::BindTypeMismatch);
assert_eq!(applied.diagnostics.len(), 1);
}
#[test]
fn collections_and_keys_take_their_own_kinds() {
let mut rig = Rig::new(mixed_state(&[("m1", mixed("m1", 7, None)), ("m2", mixed("m2", 8, None))]));
let tag = |id: &str| bound_text(id, item_bind(path(&[])));
let document = page(
"collections",
vec![
// A list member of a record: the items are its elements, keyed by themselves.
repeat_over("tags", CollectionSource::Member(mixed_bind("m1", vec![name("Tags")], None)), &[], tag("tag")),
// A member that is not a list is the Repeat's error, not an empty Repeat.
repeat_over("not-a-list", CollectionSource::Member(mixed_bind("m1", vec![name("Count")], None)), &[], tag("tag2")),
// An Int key is its decimal text.
repeat_over("by-count", mixed_records("m"), &["Count"], bound_text("c", item_bind(path(&["Id"])))),
// A key that is neither Text nor Int is the Repeat's error.
repeat_over("by-flag", mixed_records("m"), &["Flag"], bound_text("f", item_bind(path(&["Id"])))),
// A record that is not there is an empty Repeat, not an error.
repeat_over("absent", CollectionSource::Member(mixed_bind("nobody", vec![name("Tags")], None)), &[], tag("tag3")),
],
);
rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(tree.instances(&nid("tags")).iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(value(tree, "tags#1:a/tag", Field::Content), &Bound::Text("a".into()));
assert_eq!(tree.repeat_error(&nid("not-a-list")).map(|e| e.code), Some(Code::BindTypeMismatch));
assert_eq!(tree.instances(&nid("by-count")).iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["7", "8"]);
assert_eq!(value(tree, "by-count#1:7/c", Field::Content), &Bound::Text("m1".into()));
assert_eq!(tree.repeat_error(&nid("by-flag")).map(|e| e.code), Some(Code::BindTypeMismatch));
assert!(tree.instances(&nid("absent")).is_empty() && tree.repeat_error(&nid("absent")).is_none());
}
#[test]
fn a_refusal_reaches_the_site_and_marks_it_dirty() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
rig.bind(&document);
rig.state.put_state_raw(address("summary"), vec![0xc1], &Swarm::schema_members());
let applied = rig.settle();
assert_eq!(code(value(rig.tree(&document), "load", Field::Content)), Code::DecodeRefused);
assert_eq!(nodes(&applied, &document), ["load"]);
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::DecodeRefused]);
// A refused item of the collection becomes a refused instance in place.
rig.state.put_state_raw(address("mind-2"), vec![0xc1], &Swarm::schema_members());
let applied = rig.settle();
let keys: Vec<String> = rig.tree(&document).instances(&nid("minds")).iter().map(|i| i.key.clone()).collect();
assert_eq!(keys, ["mind-1", "!mind-2", "mind-3"]);
assert!(nodes(&applied, &document).contains(&"minds".to_string()));
assert_eq!(code(value(rig.tree(&document), "minds!6:mind-2/mind-name", Field::Content)), Code::DecodeRefused);
// The record coming back replaces the refusal.
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.1));
let applied = rig.settle();
assert_eq!(value(rig.tree(&document), "load", Field::Content), &Bound::Text("10.0%".into()));
assert_eq!(nodes(&applied, &document), ["load"]);
}
#[test]
fn what_a_rebind_drops_is_dirty() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
rig.bind(&document);
// The Repeat becomes a Box (only a Visible site) with its id (so the id is not a vanished site) and the button goes.
let mut next = document.clone();
let Node::Box(root) = &mut next.root else { panic!("root is a Box") };
root.children = vec![root.children[0].clone(), boxed("minds", vec![])];
next.commands.clear();
let applied = rig.bind(&next);
let dirty = nodes(&applied, &next);
for gone in ["restart", "restart-label", "minds#6:mind-1/mind-name"] {
assert!(dirty.contains(&gone.to_string()), "{gone} vanished and is not dirty: {dirty:?}");
}
// `minds` keeps a visible site equal to before: only its instance set vanished.
assert!(dirty.contains(&"minds".to_string()));
assert!(!dirty.contains(&"load".to_string()));
assert!(rig.tree(&next).instances(&nid("minds")).is_empty());
}
#[test]
fn instance_budget_edge_and_the_ids_of_other_templates() {
let source = || CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() });
let document = page("budget", vec![repeat_over("rows", source(), &["Id"], text("t", "row"))]);
let tree = resolve(&document, &swarm_state(), &Limits::default()).tree.unwrap();
for (max_nodes, fine) in [(3, true), (2, false)] {
let mut state = swarm_state();
let mut binder = Binder::new(Limits { max_nodes, ..Limits::default() });
binder.bind(tree.clone(), &mut state, &mut Ledger::new());
let bound = binder.tree(&document.record_key()).unwrap();
assert_eq!(bound.repeat_error(&nid("rows")).is_none(), fine, "max_nodes {max_nodes}");
}
// An id inside another Repeat's template is an id of the tree too.
let hidden = repeat_over(
"other",
CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "zzz".into() }),
&["Id"],
text("rows#6:mind-1/t", "taken"),
);
let document = page("hidden", vec![repeat_over("rows", source(), &["Id"], text("t", "row")), hidden]);
let mut rig = Rig::new(swarm_state());
rig.bind(&document);
assert_eq!(rig.tree(&document).repeat_error(&nid("rows")).map(|e| e.code), Some(Code::DuplicateNodeId));
}
const RAW: &str = "gamecult.thing.test.raw.v1";
fn raw_address(key: &str) -> Address {
Address { provider: ProviderId::new(SWARM), schema: SchemaId::new(RAW), key: RecordKey::new(key) }
}
fn raw_record(members: Vec<(&str, StateValue)>) -> StateValue {
StateValue::Record(members.into_iter().map(|(name, value)| (name.to_string(), value)).collect())
}
/// One record holding a value of every kind a reader could be tempted to convert: numeric,
/// boolean and stamp text, bytes, a float and an int, a list of numeric text and a list of numbers.
fn raw_state() -> MemState {
use StateValue::*;
let mut state = MemState::new();
let members = vec![
("Num", Text("42".into())),
("Truth", Text("true".into())),
("Stamp", Text("2026-01-01T00:00:00Z".into())),
("Blob", Bytes(vec![0x34, 0x32])),
("Float", Float(1.5)),
("Int", Int(3)),
("NumTexts", List(vec![Text("1".into()), Text("2".into())])),
("Numbers", List(vec![Int(1), Float(2.5)])),
("Bools", List(vec![Bool(true)])),
];
state.put_value(raw_address("r1"), raw_record(members));
state
}
#[test]
fn no_value_kind_is_read_as_another() {
use Bound::*;
// (member, [text, number, bool, series]); None is BindTypeMismatch.
let rows: [(&str, [Option<Bound>; 4]); 9] = [
("Num", [Some(Text("42".into())), None, None, None]),
("Truth", [Some(Text("true".into())), None, None, None]),
("Stamp", [Some(Text("2026-01-01T00:00:00Z".into())), None, None, None]),
("Blob", [None, None, None, None]),
("Float", [None, Some(Number(1.5)), None, None]),
("Int", [None, Some(Number(3.0)), None, None]),
("NumTexts", [None, None, None, None]),
("Numbers", [None, None, None, Some(Series(vec![1.0, 2.5]))]),
("Bools", [None, None, None, None]),
];
let mut rig = Rig::new(raw_state());
for (member, expected) in rows {
for (kind, want) in ["text", "number", "bool", "series"].into_iter().zip(expected) {
let document = with_x(page(&format!("raw-{member}-{kind}"), vec![site_of(kind, bind_at(RAW, "r1", vec![name(member)], None))]));
rig.bind(&document);
let got = value(rig.tree(&document), kind, kind_field(kind));
match want {
Some(bound) => assert_eq!(got, &bound, "{member} at a {kind} site"),
None => assert_eq!(code(got), Code::BindTypeMismatch, "{member} at a {kind} site"),
}
}
}
}
#[test]
fn options_and_keys_take_text_and_int_only() {
use StateValue::*;
let mut state = MemState::new();
for (key, text, int, float, blob, flag) in [("r1", "a", 1, 1.5, vec![1u8], true), ("r2", "b", 2, 2.5, vec![2u8], false)] {
let members = vec![
("Id", Text(text.into())),
("Int", Int(int)),
("Float", Float(float)),
("Blob", Bytes(blob)),
("Flag", Bool(flag)),
];
state.put_value(raw_address(key), raw_record(members));
}
let records = || CollectionSource::Records(RecordsSource { provider: Some(ProviderId::new(SWARM)), schema: SchemaId::new(RAW), key_prefix: "r".into() });
let select = |id: &str, value_member: &str, label_member: &str| {
Node::Select(SelectNode {
common: common(id),
options: OptionList::Bound(BoundOptions { collection: records(), value_member: path(&[value_member]), label_member: path(&[label_member]) }),
value: bind_at(RAW, "none", vec![name("Id")], None),
on_change: command("x"),
})
};
let mut nodes_ = vec![select("opt-text", "Id", "Id")];
for member in ["Int", "Float", "Blob", "Flag"] {
nodes_.push(select(&format!("opt-value-{member}"), member, "Id"));
nodes_.push(select(&format!("opt-label-{member}"), "Id", member));
}
for (n, member) in ["Id", "Int", "Float", "Blob", "Flag"].into_iter().enumerate() {
nodes_.push(repeat_over(&format!("key-{member}"), records(), &[member], text(&format!("cell{n}"), "x")));
}
let document = with_x(page("raw-options", nodes_));
let mut rig = Rig::new(state);
rig.bind(&document);
let tree = rig.tree(&document);
let Bound::Options(options) = value(tree, "opt-text", Field::Options) else { panic!("not options") };
assert_eq!(options.len(), 2);
for member in ["Int", "Float", "Blob", "Flag"] {
assert_eq!(code(value(tree, &format!("opt-value-{member}"), Field::Options)), Code::BindTypeMismatch, "{member} as an option value");
assert_eq!(code(value(tree, &format!("opt-label-{member}"), Field::Options)), Code::BindTypeMismatch, "{member} as an option label");
}
assert_eq!(tree.instances(&nid("key-Id")).iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(tree.instances(&nid("key-Int")).iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["1", "2"]);
for member in ["Float", "Blob", "Flag"] {
assert_eq!(tree.repeat_error(&nid(&format!("key-{member}"))).map(|e| e.code), Some(Code::BindTypeMismatch), "{member} as a key");
}
}
/// A port whose `list` also serves a state record of another schema than the prefix names: a port
/// fault (the contract is one lookup per record of the prefix's schema), which the Binder must
/// refuse rather than bind.
struct Odd(MemState);
impl StatePort for Odd {
fn read(&self, address: &Address) -> thing_core::port::Lookup {
self.0.read(address)
}
fn list(&self, prefix: &Prefix) -> Vec<thing_core::port::Lookup> {
let mut found = self.0.list(prefix);
found.push(thing_core::port::Lookup::Present(thing_core::port::Entry {
address: Address { provider: prefix.provider.clone(), schema: prefix.schema.clone(), key: RecordKey::new("mind-9") },
record: thing_core::port::Record::State {
schema: SchemaId::new("gamecult.thing.test.other.v1"),
value: StateValue::Record(vec![("Name".into(), StateValue::Text("Intruder".into()))]),
},
}));
found
}
fn subscribe(&mut self, interest: Interest) -> thing_core::port::SubscriptionId {
self.0.subscribe(interest)
}
fn unsubscribe(&mut self, id: thing_core::port::SubscriptionId) {
self.0.unsubscribe(id)
}
fn drain(&mut self) -> Vec<Change> {
self.0.drain()
}
}
#[test]
fn a_listed_record_of_another_schema_is_refused_in_place() {
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let mut port = Odd(swarm_state());
let tree = resolve(&document, &port, &Limits::default()).tree.unwrap();
let mut binder = Binder::new(Limits::default());
let applied = binder.bind(tree, &mut port, &mut Ledger::new());
let bound = binder.tree(&document.record_key()).unwrap();
let keys: Vec<&str> = bound.instances(&nid("minds")).iter().map(|i| i.key.as_str()).collect();
assert_eq!(keys, ["mind-1", "mind-2", "mind-3", "!mind-9"]);
assert_eq!(code(value(bound, "minds!6:mind-9/mind-name", Field::Content)), Code::BindSchemaMismatch);
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::BindSchemaMismatch]);
}
fn picture(catalog: &str, asset: &str) -> Node {
Node::Image(ImageNode { common: common("pic"), catalog: catalog.into(), asset: asset.into(), fit: ImageFit::Contain, alt: lit_text("alt") })
}
fn icons(width: i32, assets: &[&str]) -> AssetCatalog {
let entry = |id: &str| AssetEntry {
id: id.into(),
media_type: "image/png".into(),
uri: format!("asset://{id}"),
width: count(width),
height: count(width / 2),
};
AssetCatalog { provider_id: ProviderId::new(SWARM), catalog_id: seg("icons"), version: ver(1), assets: assets.iter().map(|id| entry(id)).collect() }
}
#[test]
fn an_image_binds_its_catalog_entry_and_a_republish_dirties_it() {
let mut state = MemState::new();
state.put(&ProviderId::new(SWARM), &icons(64, &["logo"]));
let mut rig = Rig::new(state);
let document = page("pictures", vec![picture("icons", "logo")]);
assert_eq!(rig.bind(&document).diagnostics, vec![]);
assert_eq!(show(value(rig.tree(&document), "pic", Field::Asset)), "asset logo 64x32");
rig.settle();
rig.state.put(&ProviderId::new(SWARM), &icons(128, &["logo"]));
let applied = rig.settle();
assert_eq!(nodes(&applied, &document), ["pic"]);
assert_eq!(show(value(rig.tree(&document), "pic", Field::Asset)), "asset logo 128x64");
}
#[test]
fn an_image_whose_catalog_is_not_published_is_absent_until_it_is() {
let mut rig = Rig::new(MemState::new());
let document = page("pictures", vec![picture("icons", "logo")]);
assert_eq!(rig.bind(&document).diagnostics, vec![]);
assert_eq!(value(rig.tree(&document), "pic", Field::Asset), &Bound::Absent);
rig.settle();
rig.state.put(&ProviderId::new(SWARM), &icons(64, &["logo"]));
assert_eq!(nodes(&rig.settle(), &document), ["pic"]);
assert_eq!(show(value(rig.tree(&document), "pic", Field::Asset)), "asset logo 64x32");
}
#[test]
fn an_image_naming_what_the_catalog_lacks_or_a_bad_catalog_id_is_asset_missing() {
let mut state = MemState::new();
state.put(&ProviderId::new(SWARM), &icons(64, &["logo"]));
let mut rig = Rig::new(state);
let document = page("pictures", vec![picture("icons", "other")]);
rig.bind(&document);
assert_eq!(code(value(rig.tree(&document), "pic", Field::Asset)), Code::AssetMissing);
let bad = page("bad", vec![picture("a.b", "logo")]);
rig.bind(&bad);
assert_eq!(code(value(rig.tree(&bad), "pic", Field::Asset)), Code::AssetMissing);
}