Cotton code
254 lines · 12.5 KB · RustRaw
//! The device and member page acts' receipts and undo.use serde_json::{json, Map, Value};use super::{decorate, Before};use crate::methods::dispatch;fn args(value: Value) -> Map<String, Value> {    value.as_object().cloned().expect("an object")}fn decorated(method: &str, request: Value, name: Option<&str>, answer: Value) -> Value {    let mut answer = answer;    decorate(method, &args(request), &Before { name: name.map(str::to_string), source: None }, &mut answer);    answer}/// RULE: Renaming a device answers a receipt and the undo that renames it back to the name it had, and no undo when the name did not change or the old one is unknown.#[test]fn renaming_a_device_answers_the_undo_back_to_its_old_name() {    let done = decorated(        "devices.rename",        json!({ "deviceId": "d1", "name": "Studio Mac", "database": "ws-a" }),        Some("Asha's Mac"),        json!({ "ok": true }),    );    assert_eq!(done["receipt"], "Renamed to Studio Mac");    assert_eq!(done["undoable"], true);    assert_eq!(        done["undo"],        json!({ "method": "devices.rename", "args": { "deviceId": "d1", "name": "Asha's Mac", "database": "ws-a" } })    );    let same = decorated("devices.rename", json!({ "deviceId": "d1", "name": "Studio Mac" }), Some("Studio Mac"), json!({}));    assert_eq!(same["undo"], Value::Null);    let unknown = decorated("devices.rename", json!({ "deviceId": "d1", "name": "Studio Mac" }), None, json!({}));    assert_eq!(unknown["undoable"], false);}/// RULE: Removing a device, admitting or turning one away, removing a member and inviting answer a receipt in words and undo null: none is taken back from the page, a removed device asks to join again.#[test]fn acts_that_cannot_be_taken_back_say_so() {    let cases = [        ("devices.revoke", json!({ "deviceId": "d2" }), Some("Kitchen iPad"), json!({}), "Removed Kitchen iPad"),        (            "devices.revoke",            json!({ "deviceId": "d2", "erase": true }),            Some("Kitchen iPad"),            json!({}),            "Removed Kitchen iPad and asked it to erase itself",        ),        ("pairing.approve", json!({ "pairingId": "p1" }), None, json!({ "device": { "name": "iPhone 17 Pro" } }), "Admitted iPhone 17 Pro"),        ("devices.approvePending", json!({ "pairingId": "p1" }), Some("iPhone 17 Pro"), json!({}), "Admitted iPhone 17 Pro"),        ("devices.declinePending", json!({ "pairingId": "p1" }), Some("iPhone 17 Pro"), json!({}), "Turned away iPhone 17 Pro"),        ("databases.remove", json!({ "personKey": "k1" }), Some("Asha"), json!({}), "Removed Asha from this database"),        ("databases.invite", json!({}), None, json!({ "link": "x" }), "Invite ready to send"),    ];    for (method, request, name, answer, receipt) in cases {        let done = decorated(method, request, name, answer);        assert_eq!(done["receipt"], receipt, "{method}");        assert_eq!(done["undo"], Value::Null, "{method}");        assert_eq!(done["undoable"], false, "{method}");    }}/// RULE: Every page act is one allow-listed method this core answers, so the page never strings a sequence of calls together.#[test]fn every_page_act_is_an_allowlisted_method() {    for act in super::ACTS {        assert!(crate::methods::ALL_METHODS.contains(&act), "{act}");    }}/// RULE: A member's claim is admitted and turned away by the person's name, a device pairing by its device's.#[test]fn a_claim_is_named_by_its_person_and_a_pairing_by_its_device() {    let claim = json!({ "pairingId": "p1", "name": "Example Phone", "person": { "name": "Example Person", "key": "k1" } });    assert_eq!(super::pending_name(&claim).as_deref(), Some("Example Person"));    let pairing = json!({ "pairingId": "p2", "name": "Example Phone", "person": null });    assert_eq!(super::pending_name(&pairing).as_deref(), Some("Example Phone"));    let blank = json!({ "pairingId": "p3", "name": "Example Phone", "person": { "name": " " } });    assert_eq!(super::pending_name(&blank).as_deref(), Some("Example Phone"));}/// A phone with a replica and its own device row, opened the way a launch opens one.fn phone() -> (tempfile::TempDir, crate::handle::CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let layout = cotton_client::layout::Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&json!({            "mode": "remote",            "baseUrl": "https://server.invalid",            "workspaceId": crate::fixture::WORKSPACE,            "ownerId": crate::fixture::OWNER,            "connectedAt": "2026-10-07T10:00:00.000Z",        }))        .expect("json"),    )    .expect("the connection record");    let replica = layout.replica(crate::fixture::WORKSPACE);    std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");    drop(crate::fixture::seeded(&replica));    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: dir.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some({            use base64::Engine;            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9u8; 32])        }),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    // This device's row, so it may author a write.    let slot = handle.client().receipt_signer_slot();    let signer = slot.get().expect("a device key");    handle        .client()        .with_writer(|file| {            crate::fixture::device_row(file.driver, &signer.device_key());            Ok(())        })        .expect("the device row");    (dir, handle)}/// RULE: Adding a voice word answers the Undo that forgets it, and forgetting one answers the Undo that adds it back; each Undo, run as given, does exactly that through the same dispatch.#[test]fn a_voice_word_add_and_remove_are_each_others_undo() {    let (_dir, handle) = phone();    let terms = |handle: &crate::handle::CottonHandle| -> Vec<String> {        crate::methods::dispatch(handle, "read.voiceVocabulary", &json!({}))            .expect("the voice words")["terms"]            .as_array()            .expect("a list")            .iter()            .filter_map(|row| row["term"].as_str().map(str::to_string))            .collect()    };    let run = |undo: &Value| {        let method = undo["method"].as_str().expect("an undo method");        crate::methods::dispatch(&handle, method, &undo["args"]).expect("the undo runs")    };    let added = crate::methods::dispatch(&handle, "settings.voiceTerm", &json!({ "term": "Nilgiri" }))        .expect("added");    assert_eq!(added["receipt"], "Added Nilgiri to your voice words");    assert_eq!(added["undoable"], true);    assert_eq!(terms(&handle), vec!["Nilgiri".to_string()]);    let undone = run(&added["undo"]);    assert_eq!(undone["receipt"], "Removed Nilgiri from your voice words");    assert!(terms(&handle).is_empty(), "the add's Undo removed the word");    let restored = run(&undone["undo"]);    assert_eq!(restored["receipt"], "Added Nilgiri to your voice words");    assert_eq!(terms(&handle), vec!["Nilgiri".to_string()], "the remove's Undo restored it");    let again = crate::methods::dispatch(&handle, "settings.voiceTerm", &json!({ "term": "nilgiri" }))        .expect("the same word");    assert_eq!(again["undoable"], false, "a word already there is not added again");    assert_eq!(again["receipt"], "Nilgiri is already in your voice words");}/// RULE: A device removal waiting for its Mac is not a completed act and must never acquire a success receipt or an Undo action.#[test]fn device_removal_pending_has_no_success_receipt() {    let pending = decorated("devices.revoke", json!({"deviceId":"synthetic-phone"}), Some("Synthetic phone"), json!({"pending":true}));    assert_eq!(pending["pending"], true);    assert!(pending.get("receipt").is_none());    assert!(pending.get("undo").is_none());}/// RULE: a record before it exists (a blank page, a form) is said as a read/// says one (transforms contract 7, Swift draws): `records.resolve` answers its/// data with the core's date parts and column words through the dispatch's/// resolve step, writes nothing, and refuses a request with no data.#[test]fn a_record_before_it_exists_is_resolved_as_a_read_resolves_one() {    let (_dir, handle) = phone();    let said = dispatch(&handle, "records.resolve", &json!({ "table": "todo", "data": { "title": "Invented errand", "due_at": "2026-09-30" } }))        .expect("resolved");    assert_eq!(said["id"], "", "{said}");    let parts = &said["data"]["@day_parts"]["due_at"];    assert_eq!(parts["day"], "2026-09-30", "{said}");    assert!(parts["heading"].as_str().is_some_and(|heading| !heading.is_empty()), "{said}");    assert!(said["data"]["@column_words"]["due_at"].is_string(), "{said}");    assert!(dispatch(&handle, "records.resolve", &json!({ "table": "todo" })).is_err());}/// RULE: every todo a dispatched `records.list` answers carries its card/// under `@card`, whether the read names no view, a view with its section or/// a view alone: the deck draws only rows with a card, so a read path that/// skips `attach_cards` empties the deck while the strip still counts rows.#[test]fn every_dispatched_todo_list_carries_each_rows_card() {    let (_dir, handle) = phone();    crate::methods::dispatch(&handle, "records.create", &json!({ "table": "todo", "data": { "title": "Invented errand", "due_at": "2026-09-30T09:00:00+05:30" }, "timezone": "Asia/Kolkata" }))        .expect("a late todo");    for request in [        json!({ "table": "todo", "page": 0, "limit": 50 }),        json!({ "table": "todo", "page": 0, "limit": 50, "view": "todos/late", "section": "late", "timezone": "Asia/Kolkata", "today": "2026-10-22" }),        json!({ "table": "todo", "page": 0, "limit": 50, "view": "todos/all" }),    ] {        let answer = crate::methods::dispatch(&handle, "records.list", &request).expect("a list");        let rows = answer["records"].as_array().expect("records");        assert!(!rows.is_empty(), "{request} answers rows");        for row in rows {            assert_eq!(row["data"]["@card"]["face"], "todo.card", "{request}: {row}");        }        if request["section"] == "late" {            let late = &rows[0]["data"]["@card"];            assert_eq!((late["pace"].as_str(), late["pressing"].as_bool()), (Some("late"), Some(true)), "{late}");        }    }}/// RULE: a song Music's Songs chip reads carries its card as the deck draws/// it — the 7-inch single face, its title, its artist as tagged, its place on/// its album, its length, and `play` naming the recording's file key, never/// words. The song comes in as a song does, through `music.capture` (its file/// and length are the file's, never typed). Everything here is invented; the/// bytes are no real recording.#[test]fn a_dispatched_songs_read_carries_each_songs_single_card() {    let (dir, handle) = phone();    let staged = dir.path().join("02 Invented Tide.m4a");    std::fs::write(&staged, b"invented bytes, no real song").expect("the staged file");    let captured = crate::methods::dispatch(&handle, "music.capture", &json!({ "songs": [{        "path": staged.to_string_lossy(),        "sourcePath": "02 Invented Tide.m4a",        "tags": { "title": "Invented Tide", "artist": "The Synthetic Quartet", "album": "Made-Up Shores", "track": 2, "duration": 222.0 },    }] }))    .expect("the song comes in");    let key = captured["songs"][0]["key"].as_str().unwrap_or_else(|| panic!("its key: {captured}")).to_string();    let answer = crate::methods::dispatch(&handle, "records.list", &json!({ "table": "song", "page": 0, "limit": 50, "view": "music/songs" }))        .expect("the Songs chip reads");    let rows = answer["records"].as_array().expect("records");    assert_eq!(rows.len(), 1, "{answer}");    let card = &rows[0]["data"]["@card"];    assert_eq!(card["face"], "song.single", "{card}");    assert_eq!(card["fields"]["title"], "Invented Tide", "{card}");    assert_eq!(card["fields"]["subtitle"], "The Synthetic Quartet", "{card}");    assert_eq!(card["fields"]["number"], "Track 2", "{card}");    assert_eq!(card["fields"]["length"], "3:42", "{card}");    assert_eq!(card["fields"]["play"], json!(key), "{card}");}