Cotton code
297 lines · 12.2 KB · RustRaw
//! The four rules of the merge, stated as arithmetic.//!//! Every fixture is invented — a slug nobody owns, a tool key no build has//! ([nothing-real-ever-goes-in-cotton-s-public-tree]). Nothing here reads a//! clock or a file: the whole module under test is a function of its arguments.use super::{    arrange_projects, home_views, installed_tools, mark_empty, merge_order, tool_view, view_tool, ArrangedProject,    HomeArrangement, HomeTile, EVERYTHING_VIEW,};/// A project row with nothing on it but the slug the arrangement names.#[derive(Debug, Clone, PartialEq, Eq)]struct Project(&'static str);impl ArrangedProject for Project {    fn slug(&self) -> &str {        self.0    }}fn said(entries: &[&str]) -> Vec<String> {    entries.iter().map(|entry| (*entry).to_string()).collect()}fn slugs(projects: &[Project]) -> Vec<&str> {    projects.iter().map(|project| project.0).collect()}// ── rule 1 — nothing stored is the default, verbatim ──────────────────────#[test]fn an_empty_manual_list_answers_the_default_order_verbatim() {    assert_eq!(merge_order(&["a", "b", "c"], &[]), said(&["a", "b", "c"]));}#[test]fn a_row_that_stored_no_order_is_the_same_answer_as_no_row() {    let empty = HomeArrangement::default();    let band = vec![Project("alpaca"), Project("beta")];    assert_eq!(        slugs(&arrange_projects(band.clone(), Some(&empty))),        slugs(&band)    );}// ── rule 2 — a stored entry counts once, and only if it still exists ──────#[test]fn a_stored_order_is_taken_entry_by_entry() {    assert_eq!(        merge_order(&["a", "b", "c"], &said(&["c", "a", "b"])),        said(&["c", "a", "b"])    );}#[test]fn an_entry_the_default_set_no_longer_holds_falls_out() {    // The archived project, and the tool key a later build renamed.    assert_eq!(        merge_order(&["a", "b"], &said(&["zeppelin", "b", "a"])),        said(&["b", "a"])    );}#[test]fn a_stored_entry_named_twice_keeps_its_first_position() {    assert_eq!(        merge_order(&["a", "b", "c"], &said(&["c", "a", "c"])),        said(&["c", "a", "b"])    );}// ── rule 3 — what the stored list never named is appended in default order ─#[test]fn everything_the_stored_list_did_not_name_appends_in_default_order() {    // `b` and `d` were born after the last drag: they arrive where the default    // order put them, after everything the person did arrange.    assert_eq!(        merge_order(&["a", "b", "c", "d"], &said(&["c", "a"])),        said(&["c", "a", "b", "d"])    );}#[test]fn a_stored_list_of_nothing_but_unknowns_answers_the_default() {    assert_eq!(        merge_order(&["a", "b"], &said(&["zeppelin", "yak"])),        said(&["a", "b"])    );}// ── rule 4 — the answer is a permutation, and running it again is a no-op ──#[test]fn the_answer_is_the_default_set_once_each_however_stale_the_stored_list() {    let default = ["a", "b", "c", "d"];    let merged = merge_order(&default, &said(&["d", "zeppelin", "d", "b"]));    assert_eq!(merged.len(), default.len());    let mut sorted = merged.clone();    sorted.sort();    assert_eq!(sorted, said(&["a", "b", "c", "d"]));    assert_eq!(merged, said(&["d", "b", "a", "c"]));}#[test]fn merging_an_order_that_is_already_arranged_changes_nothing() {    let default = ["a", "b", "c"];    let once = merge_order(&default, &said(&["c", "b", "a"]));    let twice = merge_order(&default, &once);    assert_eq!(once, twice);}// ── the tools, and what "put away" means ──────────────────────────────────// ── a database's tools and its Home ───────────────────────────────────────/// The alphabet's name of a key in these fixtures: the key itself.fn by_key(key: &str) -> String {    key.to_string()}/// The alphabet's name of a view in these fixtures: its tool's key, else the id.fn view_by_key(view: &str) -> String {    view_tool(view).unwrap_or(view).to_string()}/// RULE (owner's ruling, 12 Oct 2026): nothing is hidden. Home is a set of view ids; with no row it is every tool's list and, in the personal database, Everything; a tile the person took off stays off, and a tool that joined since the row was written arrives on Home.#[test]fn home_is_the_rows_views_and_a_tool_that_joined_since_arrives() {    let tools = said(&["notes", "todos", "people"]);    assert_eq!(home_views(None, &tools, false, &[], |_| false, view_by_key), said(&["tool/notes", "tool/people", "tool/todos"]));    assert_eq!(        home_views(None, &tools, true, &[], |_| false, view_by_key),        said(&["tool/notes", "tool/people", "ready/everything", "tool/todos"])    );    // Todos' tile taken off; People joined after the row was written; a group    // tile the file still holds and one it does not.    let row = HomeArrangement {        tools: said(&["notes", "todos"]),        view_ids: said(&["person/g1", "tool/notes", "tool/notes", "tool/zeppelin", "person/gone"]),        ..HomeArrangement::default()    };    assert_eq!(        home_views(Some(&row), &tools, true, &[], |view| view == "person/g1", view_by_key),        said(&["tool/notes", "tool/people", "person/g1"])    );    // A tool no longer in the database takes its tile with it.    assert_eq!(home_views(Some(&row), &said(&["people"]), true, &[], |_| false, view_by_key), said(&["tool/people"]));    assert_eq!(view_tool("tool/notes"), Some("notes"));    assert_eq!(view_tool(EVERYTHING_VIEW), None);    assert_eq!(view_tool("tool/"), None);}/// RULE (owner, 17 Oct 2026): a tile with nothing to show is drawn faint IN ITS PLACE — the alphabet's — and is never moved after the ones that have something.#[test]fn an_empty_tile_draws_faint_in_its_alphabetical_place() {    let home = said(&["tool/notes", "tool/people", "tool/todos"]);    let tiles = mark_empty(home, |view| view != "tool/notes");    let tile = |id: &str, empty: bool| HomeTile { id: id.to_string(), empty };    assert_eq!(tiles, vec![tile("tool/notes", true), tile("tool/people", false), tile("tool/todos", false)]);}/// RULE (owner, 17 Oct 2026): the fan's order is ALPHABETICAL in every database, always — that is how he finds tools. There is no kept or per-database order: whatever order the stored `tools` and `view_ids` hold, every database's Home membership answers sorted by name (case-insensitive collation), and reversing or shuffling the row changes nothing. Home's card is not special; it sits under H.#[test]fn every_databases_home_answers_alphabetically_whatever_the_stored_order() {    let names = |key: &str| match key {        "home" => "Home".to_string(),        "alarms" => "alarms".to_string(),        "zoo" => "Zoo".to_string(),        "bees" => "Bees".to_string(),        other => other.to_string(),    };    let view_name = |view: &str| view_tool(view).map(names).unwrap_or_else(|| "Everything".to_string());    let alphabetical = |list: &[String], name: &dyn Fn(&str) -> String| {        list.windows(2).all(|pair| crate::js_text::compare_names(&name(&pair[0]), &name(&pair[1])) != std::cmp::Ordering::Greater)    };    let tools = said(&["zoo", "notes", "home", "todos", "bees", "alarms", "members", "devices"]);    let mut shuffled = tools.clone();    shuffled.reverse();    for personal in [true, false] {        let mut answers = Vec::new();        for stored in [tools.clone(), shuffled.clone()] {            let row = HomeArrangement {                tools: stored.clone(),                view_ids: stored.iter().map(|key| tool_view(key)).chain([EVERYTHING_VIEW.to_string()]).collect(),                ..HomeArrangement::default()            };            let held = installed_tools(&stored, names);            assert!(alphabetical(&held, &names), "tools out of the alphabet: {held:?}");            let home = home_views(Some(&row), &held, personal, &[], |view| view == EVERYTHING_VIEW, view_name);            assert!(alphabetical(&home, &view_name), "Home out of the alphabet: {home:?}");            let home_card = home.iter().position(|view| view == "tool/home").expect("Home's card is on Home");            let members = home.iter().position(|view| view == "tool/members").expect("Members is on Home");            assert!(home_card < members, "Home sits under H, before Members: {home:?}");            answers.push((held, home));        }        assert_eq!(answers[0], answers[1], "the stored order is never read");    }}// ── the projects band ─────────────────────────────────────────────────────#[test]fn a_stored_slug_order_re_seats_the_band() {    let band = vec![Project("alpaca"), Project("beta"), Project("cedar")];    let row = HomeArrangement {        project_slugs: said(&["cedar", "alpaca"]),        ..HomeArrangement::default()    };    assert_eq!(        slugs(&arrange_projects(band, Some(&row))),        vec!["cedar", "alpaca", "beta"]    );}#[test]fn an_archived_slug_drops_out_and_a_newer_project_appends_in_activity_order() {    // `zeppelin` was archived since the drag; `dogwood` was born since it. The    // band arrives in activity order, so `dogwood` lands where activity put it.    let band = vec![Project("dogwood"), Project("alpaca"), Project("beta")];    let row = HomeArrangement {        project_slugs: said(&["beta", "zeppelin", "alpaca"]),        ..HomeArrangement::default()    };    assert_eq!(        slugs(&arrange_projects(band, Some(&row))),        vec!["beta", "alpaca", "dogwood"]    );}#[test]fn every_row_handed_in_comes_back_out_exactly_once() {    let band = vec![Project("alpaca"), Project("alpaca"), Project("beta")];    let row = HomeArrangement {        project_slugs: said(&["alpaca"]),        ..HomeArrangement::default()    };    let out = arrange_projects(band, Some(&row));    assert_eq!(out.len(), 3, "a duplicate slug may not swallow a row");    let mut seen = slugs(&out);    seen.sort_unstable();    assert_eq!(seen, vec!["alpaca", "alpaca", "beta"]);}#[test]fn an_empty_band_arranges_to_an_empty_band() {    let row = HomeArrangement {        project_slugs: said(&["alpaca"]),        ..HomeArrangement::default()    };    let out: Vec<Project> = arrange_projects(Vec::new(), Some(&row));    assert!(out.is_empty());}#[test]fn a_borrowed_row_arranges_the_same_way_an_owned_one_does() {    // A caller may sort `Vec<&ProjectRow>`, so the blanket impl over a    // reference is load-bearing rather than a convenience.    let band = [Project("alpaca"), Project("beta")];    let borrowed: Vec<&Project> = band.iter().collect();    let row = HomeArrangement {        project_slugs: said(&["beta"]),        ..HomeArrangement::default()    };    let out = arrange_projects(borrowed, Some(&row));    assert_eq!(        out.iter().map(|project| project.0).collect::<Vec<&str>>(),        vec!["beta", "alpaca"]    );}/// RULE: a project's section arrives on Home once — the row's `tools` names every view Home has shown — and a tile the person took off stays off.#[test]fn a_section_arrives_once_and_stays_off_when_taken_off() {    let tools = said(&["notes"]);    let memory = "project/memory/cotton".to_string();    let arriving = vec![memory.clone()];    // No row: in the alphabet, with the tools' lists.    assert_eq!(home_views(None, &tools, false, &arriving, |_| true, view_by_key), said(&["tool/notes", "project/memory/cotton"]));    // A row written before the section was shown: it arrives.    let before = HomeArrangement { project_slugs: vec![], tools: said(&["notes"]), view_ids: said(&["tool/notes"]) };    assert_eq!(home_views(Some(&before), &tools, false, &arriving, |_| true, view_by_key), said(&["tool/notes", "project/memory/cotton"]));    // Shown, then taken off: stays off.    let off = HomeArrangement { project_slugs: vec![], tools: vec!["notes".into(), memory.clone()], view_ids: said(&["tool/notes"]) };    assert_eq!(home_views(Some(&off), &tools, false, &arriving, |_| true, view_by_key), said(&["tool/notes"]));    // A section that no longer holds anything and is not on Home does not arrive.    assert_eq!(home_views(None, &tools, false, &arriving, |_| false, view_by_key), said(&["tool/notes"]));}