Cotton code
225 lines · 13.5 KB · RustRaw
use super::*;use serde_json::json;fn board(raw: Value) -> BoardDefinition {    serde_json::from_value(raw).expect("decodes")}/// RULE: Every built-in board is authored: it parses, validates and names only the part kinds, settings and values this build draws.#[test]fn every_builtin_board_is_strict_and_named_by_its_file() {    for (id, json) in BUILTIN_BOARD_FILES {        let raw: Value = serde_json::from_str(json).unwrap();        let board = BoardDefinition::strict(&raw).unwrap_or_else(|error| panic!("{id}.json: {error}"));        assert_eq!(&board.id, id, "{id}.json declares another id");        assert_eq!(serde_json::to_value(&board).unwrap(), raw, "{id}.json round-trips");    }}/// RULE: The board's part kinds are a closed set, each drawn once; a setting table entry exists for every kind and no other.#[test]fn the_part_kinds_are_the_whole_closed_set() {    for kind in BOARD_PART_KINDS {        assert!(settings_of(kind).is_some(), "{kind} has its settings");    }    assert!(settings_of("carousel").is_none());}#[test]fn a_newer_builds_part_is_kept_whole_and_refused_only_when_authored() {    let raw = json!({"id": "home", "parts": [        {"kind": "carousel", "speed": 3},        {"kind": "tools", "face": "shelf", "tilt": 2}    ], "accent": "x"});    let read = board(raw.clone());    read.validate().expect("a newer build's row is well formed here");    assert_eq!(serde_json::to_value(&read).unwrap(), raw, "relayed whole");    assert!(matches!(BoardDefinition::strict(&raw), Err(DefinitionError::UnknownKeys(_))));}/// RULE: A board naming a removed part kind (`sections`) is refused with the sentence that says why, on the tolerant read as on an authored write — it is never relayed as a newer build's part (owner, 12 Oct 2026: Home is tiles and the notices line; removed means removed).#[test]fn a_board_with_a_sections_part_is_refused_with_a_sentence() {    let raw = json!({"id": "home", "parts": [{"kind": "head"}, {"kind": "sections", "source": "current"}]});    let read = board(raw.clone()).validate().expect_err("refused on read");    let written = BoardDefinition::strict(&raw).expect_err("refused on write");    for error in [read, written] {        assert!(matches!(error, DefinitionError::RemovedPart { kind: "sections", .. }), "{error}");    }    let variant = json!({"id": "home", "parts": [{"kind": "head"}], "variants": [{"when": {"size": "mac"}, "parts": [{"kind": "sections"}]}]});    assert!(board(variant).validate().is_err(), "a size's parts are held to the same set");    assert!(!BOARD_PART_KINDS.contains(&"sections"));}#[test]fn a_malformed_board_is_refused() {    for bad in [        json!({"id": "Home", "parts": [{"kind": "head"}]}),        json!({"id": "home", "parts": []}),        json!({"id": "home", "parts": [{"kind": "tools", "columns": "four"}]}),        json!({"id": "home", "parts": [{"kind": "tools", "columns": 0}]}),        json!({"id": "home", "parts": [{"kind": "head", "tags": "yes"}]}),        json!({"id": "home", "parts": [{"kind": "list"}]}),        json!({"id": "home", "parts": [{"kind": "facts", "source": "Not An Id"}]}),    ] {        assert!(board(bad.clone()).validate().is_err(), "{bad}");    }    assert!(serde_json::from_value::<BoardDefinition>(json!({"id": "home", "parts": [{"face": "row"}]})).is_err(), "a part names its kind");}/// RULE: The board parity fixture names every part kind and every setting value this build draws, and is strict here; the Swift decoder reads the same file (BoardDefinitionTests).#[test]fn the_parity_fixture_is_strict_and_covers_every_kind() {    let raw: Value = serde_json::from_str(include_str!("../../tests/fixtures/board-parity/every-part.json")).unwrap();    let board = BoardDefinition::strict(&raw).expect("strict");    for kind in BOARD_PART_KINDS {        assert!(board.parts.iter().any(|part| part.kind == *kind), "{kind} is in the fixture");    }}/// RULE: Capability gates use field presence, so an absent required source is refused and unknown future parts survive without a numeric revision gate.#[test]fn capabilities_are_checked_by_field_presence() {    let absent = board(json!({"id":"home", "parts":[{"kind":"facts"}]}));    assert!(absent.validate().is_err());    let present = board(json!({"id":"home", "parts":[{"kind":"facts", "source":"database"}]}));    present.validate().unwrap();    let future = board(json!({"id":"home", "parts":[{"kind":"future", "feature":"new"}]}));    future.validate().unwrap();    assert_eq!(serde_json::to_value(future).unwrap()["parts"][0]["feature"], "new");}/// RULE: What an `asked` or `done` part can show is exactly what the crate counts and reads — the board's words are the engine's wire names, so a board can never name a row no read answers, and every row the read answers can be named.#[test]fn the_bands_words_are_the_engines() {    use crate::rules::asked_of_you::ASKED_KEYS;    use crate::rules::done_for_you::DoneKind;    let asked: Vec<&str> = ASKED_KEYS.iter().map(|key| key.as_str()).collect();    let named: Vec<&str> = ASKED_SHOWS.iter().copied().filter(|show| !RETIRED_ASKED_SHOWS.contains(show)).collect();    assert_eq!(asked, named);    let done: Vec<&str> = [DoneKind::Filed, DoneKind::Remembered, DoneKind::CouldNotRead, DoneKind::CityFilled, DoneKind::JunkFiled, DoneKind::RemovedFrom]        .iter()        .map(|kind| kind.as_str())        .collect();    assert_eq!(done, DONE_SHOWS);}/// RULE: A band's `shows` names only what this build draws when authored, and a newer build's word is relayed on the tolerant read — Home's bands are declared in the board, never refused for a word a newer phone knows.#[test]fn a_bands_shows_is_held_to_its_vocabulary_when_authored() {    let newer = json!({"id": "home", "parts": [{"kind": "notices", "shows": ["update", "weather"]}]});    board(newer.clone()).validate().expect("relayed");    assert!(BoardDefinition::strict(&newer).is_err(), "authored here, refused");    for bad in [        json!({"id": "home", "parts": [{"kind": "asked", "shows": "invites"}]}),        json!({"id": "home", "parts": [{"kind": "done", "shows": [3]}]}),        json!({"id": "home", "parts": [{"kind": "done", "place": 1}]}),    ] {        assert!(board(bad.clone()).validate().is_err(), "{bad}");    }    BoardDefinition::strict(&json!({"id": "home", "parts": [        {"kind": "asked", "place": "head", "shows": ["invites"]},        {"kind": "about", "source": "build"}    ]}))    .expect("authored");}/// RULE: A setting word this build cannot draw (a newer device's tools face) never skips the part — skipping Home's tools would blank Home — it draws as its kind's default (`default_of`), a list keeps the words it can draw, and the resolved board names each setting that fell back in `fallbacks`.#[test]fn an_unknown_setting_word_draws_the_kinds_default_and_is_named() {    let raw = json!({"id": "home", "parts": [        {"kind": "head"},        {"kind": "tools", "face": "zzz", "size": "huge"},        {"kind": "notices", "shows": ["update", "weather"]}    ], "variants": [{"when": {"size": "mac"}, "parts": [{"kind": "tools", "face": "grid"}]}]});    let read = board(raw.clone());    read.validate().expect("a newer build's row is well formed here");    let resolved = read.resolved();    assert_eq!(resolved.parts[1].settings["face"], default_of("tools", "face").unwrap());    assert_eq!(resolved.parts[1].settings["size"], default_of("tools", "size").unwrap());    assert_eq!(resolved.parts[2].settings["shows"], json!(["update"]));    assert_eq!(resolved.fallbacks, vec!["parts.1.face", "parts.1.size", "parts.2.shows"]);    assert_eq!(resolved.variants[0].parts[0].settings["face"], json!("grid"));    assert!(BoardDefinition::strict(&raw).is_err(), "an authored board names only what this build draws");    assert!(BoardDefinition::builtins().iter().all(|board| board.resolved().fallbacks.is_empty()), "the shipped boards fall back on nothing");}/// RULE: a `list` or `figure` part's words are the figure's own — its periods are `FigurePeriod`'s wire names and its ops `SummaryOp`'s — so a Home can never name a stretch or a total no read keeps (19 Oct 2026, a business's Home).#[test]fn a_parts_periods_and_ops_are_the_figures() {    use crate::definitions::{FigurePeriod, SummaryOp};    for period in PART_PERIODS {        serde_json::from_value::<FigurePeriod>(json!(period)).unwrap_or_else(|_| panic!("{period} is a FigurePeriod"));    }    for op in FIGURE_OPS {        serde_json::from_value::<SummaryOp>(json!(op)).unwrap_or_else(|_| panic!("{op} is a SummaryOp"));    }    for period in [FigurePeriod::ThisMonth, FigurePeriod::Today, FigurePeriod::Tomorrow, FigurePeriod::Next7Days, FigurePeriod::NextDay] {        assert!(PART_PERIODS.contains(&serde_json::to_value(period).unwrap().as_str().unwrap()), "{period:?} can be named");    }}/// RULE: a figure part says what it totals and in which words (`heading`, `table`, `op`, `many`), a `where` names at least one column, and a period or an op outside the figure's own is refused when authored.#[test]fn a_figure_part_says_what_it_totals_and_how() {    let good = json!({"format_version": 1, "id": "home", "parts": [        {"kind": "list", "heading": "Today's sessions", "table": "yoga_session", "period": "today", "where": {"cancelled": false}},        {"kind": "figure", "heading": "Cash taken today", "table": "yoga_payment", "op": "sum", "column": "amount", "where": {"method": "cash"}, "period": "today", "many": "{n} in cash"}    ]});    BoardDefinition::strict(&good).expect("a business Home is a board this build draws");    for (at, key, value) in [        (1, "many", Value::Null),        (1, "op", json!("average")),        (1, "period", json!("this_year")),        (0, "where", json!({})),        (0, "period", json!("yesterday")),    ] {        let mut bad = good.clone();        if value.is_null() { bad["parts"][at].as_object_mut().unwrap().remove(key); } else { bad["parts"][at][key] = value.clone(); }        assert!(BoardDefinition::strict(&bad).is_err(), "{key}: {value}");    }}/// RULE: every business app's manifest (`apps/cotton/App/Flavours/<flavour>/flavour.json`) whose dial holds a Home carries one this build draws — a strict board with the id `home` and at least one part — or the core refuses it at open and the app never starts (owner, 19 Oct 2026).#[test]fn every_business_manifests_home_is_a_board_this_build_draws() {    let root = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours");    // The manifests kept as fixtures since their apps retired (Cotton Project's carries a Home, 22 Nov 2026).    let kept = cotton_store::manifest_dir().join("../../apps/cotton/Tests/Fixtures/Flavours");    let shipped = std::fs::read_dir(&root).expect("the flavours folder").map(|entry| entry.unwrap().path().join("flavour.json"));    let fixtures = std::fs::read_dir(&kept).expect("the kept manifests").map(|entry| entry.unwrap().path());    let mut seen = 0;    for path in shipped.chain(fixtures) {        if !path.exists() { continue; }        let manifest: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();        // Rigby carries Cotton's own manifest under its own identity (22 Oct        // 2026): a personal genesis and no Home of its own, so it draws the        // shipped Home (`cotton-ffi` handle.rs `business_home`, its flavour in        // `COTTONS_OWN_FLAVOURS`). Only a business app names its Home.        if manifest.get("home").is_none() && manifest["genesis"] == "personal" { continue; }        // A dial with no Home card (`fan.home` false: Sharmila opens on her        // studio, 4fb48a9ec) names no Home board; the core never opens one.        if manifest.get("home").is_none() && manifest["fan"]["home"] == false { continue; }        let home = BoardDefinition::strict(&manifest["home"]).unwrap_or_else(|error| panic!("{}: {error}", path.display()));        assert_eq!(home.id, "home", "{}", path.display());        assert!(!home.parts.is_empty(), "{}", path.display());        seen += 1;    }    assert!(seen > 0, "the project builds at least one business app");}/// RULE: Home's first part is this device's card, the sync card (owner, 2 Nov 2026: the card left Home for Settings' Backup card on 1 Nov, and the phone's deck never draws the one-line `sync` part, so Home showed no sync at all); the `device` part is the serving catalogue's to name (`THIS_DEVICE_KEY`), so a board that authors one is refused and a served one reads.#[test]fn homes_first_part_is_this_devices_card_and_a_served_device_part_reads() {    let home = BoardDefinition::builtin("home").expect("home ships");    assert_eq!(home.parts.first().map(|part| part.kind.as_str()), Some("device"), "the shipped Home leads with this device's card: {:?}", home.parts.iter().map(|part| &part.kind).collect::<Vec<_>>());    // Home is the sync card and nothing else for now (owner, 2 Nov 2026): the    // tools part stays, for the fan the cards stand on.    assert_eq!(home.parts.iter().map(|part| part.kind.as_str()).collect::<Vec<_>>(), ["device", "tools"]);    assert!(home.resolved().fallbacks.is_empty());    let authored = json!({"id": "home", "parts": [{"kind": "device", THIS_DEVICE_KEY: "invented-device"}]});    assert!(matches!(BoardDefinition::strict(&authored), Err(DefinitionError::UnknownKeys(_))), "never authored");    let served = board(authored.clone());    served.validate().expect("the served part, with its device named, reads");    assert_eq!(served.resolved().parts[0].settings[THIS_DEVICE_KEY], "invented-device", "resolving keeps the device the catalogue named");}