Cotton code
111 lines · 5.7 KB · RustRaw
//! The `form` key (transforms contract 6). Every table is invented.use serde_json::json;use super::*;fn ledger(slip: serde_json::Value) -> TableDefinition {    serde_json::from_value(json!({        "id": "invented_ledger", "name": "Ledger", "plural": "Ledgers", "picture": null, "builtin": false, "engine": null,        "title": "title", "date": null, "project": null, "order": null,        "slip": slip,        "tile": { "face": "slip-list" }, "page": [], "instructions": "Invented.",        "columns": [            {"key": "title", "type": "text"},            {"key": "currency", "type": "text"},            {"key": "due_at", "type": "date"},            {"key": "born_on", "type": "date", "yearly": true},            {"key": "balance", "type": "amount", "currency": "currency"},            {"key": "visits", "type": "number"}        ]    }))    .unwrap()}fn slip_with(extra: serde_json::Value) -> serde_json::Value {    let mut slip = json!({ "title": "title", "subtitle": null, "trailing": null, "photo": null, "toggle": null });    slip.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());    slip}/// GUARD: a definition naming a form on a column of the wrong type is/// refused when it is saved. A form is a promise about what the column/// holds — money reads minor units and a currency, a date form reads a day —/// and the app never throws on a definition, so the only place a mismatch can/// be caught is the save: let one through and a slip says a date as money,/// or nothing, on every device that syncs it.#[test]fn a_form_on_the_wrong_column_type_is_refused() {    let refused = |slip: serde_json::Value| ledger(slip_with(slip)).validate().is_err();    let fine = |slip: serde_json::Value| ledger(slip_with(slip)).validate();    // The slip's forms, by column.    fine(json!({"forms": {"due_at": "late", "balance": "money_signed", "visits": "count", "born_on": "next_occurrence"}})).unwrap();    assert!(refused(json!({"forms": {"due_at": "money"}})), "money on a date");    assert!(refused(json!({"forms": {"balance": "relative"}})), "a date form on an amount");    assert!(refused(json!({"forms": {"title": "count"}})), "count on text");    assert!(refused(json!({"forms": {"due_at": "turns"}})), "turns on a date that is not yearly");    assert!(refused(json!({"forms": {"nowhere": "count"}})), "a column the table lacks");    // The caption's leading date.    fine(json!({"caption": {"dates": ["due_at"], "form": "weekday_date"}})).unwrap();    assert!(refused(json!({"caption": {"dates": ["due_at"], "form": "money"}})), "money on the leading date");    assert!(refused(json!({"caption": {"dates": ["due_at"], "form": "relative", "date_form": "relative"}})), "one name, not both");    // A field card.    let card = |column: &str, form: Form| {        let mut table = ledger(slip_with(json!({})));        let mut parts = table.resolved_parts();        parts.cards = Some(vec![parts::PartsCard { column: Some(column.into()), form: Some(form), ..Default::default() }]);        parts.strip = None;        table.parts = Some(parts);        table.validate()    };    card("balance", Form::Money).unwrap();    assert!(card("visits", Form::Money).is_err(), "money on a number card");    assert!(card("balance", Form::Duration).is_err(), "duration on an amount card");}/// `date_form` is the caption form's older name and means the same.#[test]fn date_form_is_the_forms_older_name() {    let older: SlipCaption = serde_json::from_value(json!({"dates": ["due_at"], "date_form": "age"})).unwrap();    let newer: SlipCaption = serde_json::from_value(json!({"dates": ["due_at"], "form": "age"})).unwrap();    assert_eq!(older.leading_form(), Some(Form::Age));    assert_eq!(newer.leading_form(), Some(Form::Age));}/// A definition refusal names its pieces by key and says them as the/// `refusal.definition` lines: the assistant reads words, never a key, and a/// rewording is a line. A piece not yet moved to a line is said as written.#[test]fn a_refusal_says_its_pieces_as_lines() {    let refused = DefinitionError::Requires { slot: "tool.tables".into(), needs: "each_table_once" };    assert_eq!(refused.to_string(), "tool.tables needs each table once");    let refused = DefinitionError::Conflict { slot: "slip.caption.form".into(), other: "slip_caption_date_form_its_older_name" };    assert_eq!(refused.to_string(), "slip.caption.form cannot sit beside slip.caption.date_form, its older name");    assert_eq!(refusal_words("still words in another file"), "still words in another file");    let kit: serde_json::Value = serde_json::from_str(include_str!("../../kits/shell/lines/refusal.json")).unwrap();    // Every file of definitions/ names its own pieces (mod.rs, commands.rs, …),    // and so do the rules cotton-rules reads for them (visibility).    let mut source = String::new();    for dir in [cotton_store::manifest_dir().join("src/definitions"), cotton_store::manifest_dir().join("../cotton-rules/src")] {        for entry in walkdir(&dir) {            source.push_str(&std::fs::read_to_string(entry).unwrap());        }    }    for key in kit["definition"].as_object().unwrap().keys() {        assert!(source.contains(&format!("\"{key}\"")), "refusal.definition.{key} is said by nothing in definitions/ or cotton-rules");    }}/// Every `.rs` file under `dir`, nested folders too.fn walkdir(dir: &std::path::Path) -> Vec<std::path::PathBuf> {    let mut files = Vec::new();    for entry in std::fs::read_dir(dir).unwrap() {        let path = entry.unwrap().path();        if path.is_dir() {            files.extend(walkdir(&path));        } else if path.extension().is_some_and(|ext| ext == "rs") {            files.push(path);        }    }    files}