Cotton code
105 lines · 4.5 KB · RustRaw
//! `keep.rules`, `keep.set`, `keep.clear` on the one synthetic paired phone://! the phone's screen writes through the same handler an assistant reaches,//! into the outbox, and reads back what it wrote at once. Every name is//! invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).use serde_json::{json, Value};use super::answer;use crate::fixture::SELF_DEVICE_ID;use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;const ALBUM: &str = "album-invented-trip";const AT: &str = "2026-10-01T09:00:00.000Z";fn exec(client: &ClientController, sql: &str, params: &[&str]) {    client        .with_writer(|replica| {            let bound: Vec<rusqlite::types::Value> =                params.iter().map(|value| rusqlite::types::Value::Text((*value).to_string())).collect();            replica.driver.run(sql, &bound).map_err(|error| error.to_string())?;            crate::fixture::receipted(replica.driver, sql);            Ok(())        })        .expect("the seed");}fn count(client: &ClientController, sql: &str) -> i64 {    client        .with_file(|replica| {            Ok(replica.driver.get(sql, &[]).map_err(|error| error.to_string())?.and_then(|row| row.int("n")))        })        .expect("the read runs")        .unwrap_or(-1)}/// This phone, said to be an iPhone, holding an album.fn phone() -> (tempfile::TempDir, std::sync::Arc<ClientController>) {    let (dir, client) = attached();    exec(&client, "UPDATE cotton_devices SET platform = 'ios' WHERE device_id = ?", &[SELF_DEVICE_ID]);    client.with_writer(|replica| {        crate::fixture::a_mac_behind(replica.driver);        Ok(())    }).expect("the Mac behind it");    exec(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, created_at, updated_at) \         VALUES (?, ?, 'trip', 'Drama Valley', ?, ?, ?, ?)",        &[ALBUM, crate::fixture::WORKSPACE, AT, AT, AT, AT],    );    (dir, client)}fn line<'a>(list: &'a Value, target: &str) -> Option<&'a Value> {    list["rules"].as_array().and_then(|lines| lines.iter().find(|line| line["target"] == target))}/// RULE: "Keep on this phone" writes a GROUP rule for THIS device — no/// device named — through the outbox, and the device row's list shows it the/// moment it is written; "Stop keeping" takes it away again.#[test]fn keep_on_this_phone_writes_this_devices_rule_and_the_list_shows_it_at_once() {    let (_dir, client) = phone();    let before = answer(&client, "keep.rules", &json!({})).expect("the list");    assert_eq!(before["phone"], json!(true));    assert_eq!(before["device"], json!(SELF_DEVICE_ID));    assert_eq!(line(&before, "cotton_email_threads").expect("mail's line")["says"], json!("Mail: 6 months"), "a phone keeps six months of mail by default");    assert!(line(&before, ALBUM).is_none());    answer(&client, "keep.set", &json!({ "kind": "group", "target": ALBUM, "rule": "always" })).expect("kept");    let after = answer(&client, "keep.rules", &json!({})).expect("the list");    assert_eq!(line(&after, ALBUM).expect("the album's line")["says"], json!("Album Drama Valley: always"));    assert_eq!(        count(&client, "SELECT count(*) AS n FROM _outbox WHERE tbl = 'cotton_device_keep'"),        1,        "the rule is queued to travel like every other write"    );    // The envelope `write` answers names the table, which is the `data`    // event the device row redraws on.    let envelope = client        .write("clear_keep_rule", &serde_json::Map::from_iter([            ("device".to_string(), json!(SELF_DEVICE_ID)),            ("kind".to_string(), json!("group")),            ("target".to_string(), json!(ALBUM)),        ]))        .expect("Stop keeping");    assert_eq!(envelope["tables"], json!(["cotton_device_keep"]));    let cleared = answer(&client, "keep.rules", &json!({})).expect("the list");    assert!(line(&cleared, ALBUM).is_none());}/// RULE: the phone's own screen cannot narrow it while keep's guard is off.#[test]fn the_phone_cannot_narrow_itself_while_the_guard_is_off() {    let (_dir, client) = phone();    let written = answer(&client, "keep.set", &json!({ "kind": "table", "target": "cotton_stories", "rule": "none" }));    if cotton_store::keep::NARROWING_GUARDED {        written.expect("keep's guard is on");        return;    }    let refused = written.expect_err("nothing narrows a phone yet");    assert!(refused.message.contains("after the next update"), "{}", refused.message);    assert_eq!(count(&client, "SELECT count(*) AS n FROM cotton_device_keep"), 0);}