Cotton code
433 lines · 13.4 KB · RustRaw
//! Every case of `packages/core/__tests__/engine/emailState.test.ts`.//!//! Every function here is pure and every one of them has two callers who must//! agree — the import and the push; the server's list and the app's.use super::*;const NOW: &str = "2026-09-04T10:00:00.000Z";fn labels(values: &[&str]) -> Vec<String> {    values.iter().map(|v| (*v).to_string()).collect()}fn desired(unread: bool, starred: bool, in_inbox: bool) -> DesiredLabels {    DesiredLabels {        unread,        starred,        in_inbox,    }}// ── email_state_from_labels ──────────────────────────────────────────────────/// RULE: Whether an email is unread, starred, in the inbox or in the bin is read from its labels in exactly one place.#[test]fn reads_the_four_labels_cotton_keeps_a_column_for() {    assert_eq!(        email_state_from_labels(&labels(&["INBOX", "UNREAD"])),        EmailState {            unread: true,            starred: false,            in_inbox: true,            trashed: false        }    );    assert_eq!(        email_state_from_labels(&labels(&["STARRED", "TRASH"])),        EmailState {            unread: false,            starred: true,            in_inbox: false,            trashed: true        }    );}#[test]fn is_false_all_round_for_a_message_with_no_labels_at_all() {    assert_eq!(email_state_from_labels(&[]), EmailState::default());}#[test]fn ignores_labels_it_has_no_column_for_rather_than_choking_on_them() {    assert!(        email_state_from_labels(&labels(&["CATEGORY_PROMOTIONS", "Label_42", "INBOX"])).in_inbox    );}// ── label_ops_for ────────────────────────────────────────────────────────────#[test]fn adds_only_what_is_missing_and_removes_only_what_is_there() {    assert_eq!(        label_ops_for(&labels(&["INBOX", "UNREAD"]), desired(false, true, true)),        LabelOps {            add: labels(&["STARRED"]),            remove: labels(&["UNREAD"]),        }    );}#[test]fn is_empty_when_the_labels_already_say_what_the_columns_do() {    assert_eq!(        label_ops_for(&labels(&["INBOX", "STARRED"]), desired(false, true, true)),        LabelOps::default()    );}/// RULE: Binning an email is never done by adding a label; the mail provider has its own action for that.#[test]fn never_names_trash_gmail_bins_through_its_own_verb_not_a_label() {    let ops = label_ops_for(&labels(&["TRASH"]), desired(false, false, false));    assert!(!ops        .add        .iter()        .chain(ops.remove.iter())        .any(|l| l == "TRASH"));}#[test]fn archives_by_removing_inbox() {    assert_eq!(        label_ops_for(&labels(&["INBOX"]), desired(false, false, false)),        LabelOps {            add: Vec::new(),            remove: labels(&["INBOX"]),        }    );}/// The emission order is UNREAD, STARRED, INBOX — the declaration order of the/// `want` calls, which a Gmail modify request carries verbatim.#[test]fn emits_the_three_labels_in_declaration_order() {    assert_eq!(        label_ops_for(&[], desired(true, true, true)),        LabelOps {            add: labels(&["UNREAD", "STARRED", "INBOX"]),            remove: Vec::new(),        }    );    assert_eq!(        label_ops_for(            &labels(&["INBOX", "STARRED", "UNREAD"]),            desired(false, false, false)        ),        LabelOps {            add: Vec::new(),            remove: labels(&["UNREAD", "STARRED", "INBOX"]),        }    );}// ── labels_after ─────────────────────────────────────────────────────────────#[test]fn keeps_every_label_cotton_has_no_column_for_in_order() {    assert_eq!(        labels_after(            &labels(&["CATEGORY_UPDATES", "INBOX", "UNREAD", "Label_7"]),            desired(false, true, true)        ),        labels(&["CATEGORY_UPDATES", "INBOX", "Label_7", "STARRED"])    );}#[test]fn round_trips_what_it_writes_is_what_the_state_says() {    let want = desired(true, false, false);    let after = labels_after(&labels(&["INBOX", "STARRED"]), want);    let read = email_state_from_labels(&after);    assert_eq!(        (read.unread, read.starred, read.in_inbox),        (want.unread, want.starred, want.in_inbox)    );}/// RULE: Writing an email's read, starred and inbox state and reading it back always gives the same answer, and never touches the bin./// The round trip over EVERY desired combination, from every starting shape/// that matters — the property the two callers actually depend on.#[test]fn every_desired_state_round_trips_from_every_starting_label_set() {    let starts: [Vec<String>; 5] = [        Vec::new(),        labels(&["INBOX"]),        labels(&["INBOX", "UNREAD", "STARRED"]),        labels(&["TRASH", "Label_1"]),        labels(&["CATEGORY_UPDATES", "STARRED"]),    ];    for start in &starts {        for unread in [false, true] {            for starred in [false, true] {                for in_inbox in [false, true] {                    let want = desired(unread, starred, in_inbox);                    let after = labels_after(start, want);                    let read = email_state_from_labels(&after);                    assert_eq!(                        (read.unread, read.starred, read.in_inbox),                        (unread, starred, in_inbox),                        "{start:?} → {want:?}"                    );                    // TRASH is never touched, in either direction.                    assert_eq!(                        start.iter().any(|l| l == "TRASH"),                        after.iter().any(|l| l == "TRASH"),                        "{start:?} → {want:?}"                    );                }            }        }    }}// ── email_row_patch ──────────────────────────────────────────────────────────fn patch_json(row: serde_json::Map<String, serde_json::Value>) -> String {    cotton_store::protocol::js::json_stringify(&serde_json::Value::Object(row))}#[test]fn says_unread_when_the_owner_says_not_read_and_stamps_the_bin_with_the_clock() {    let row = email_row_patch(        EmailStatePatch {            read: Some(false),            bin: Some(true),            ..EmailStatePatch::default()        },        NOW,        true,    );    assert_eq!(        patch_json(row),        r#"{"unread":true,"trashed_at":"2026-09-04T10:00:00.000Z","sync_state":"pending"}"#    );}#[test]fn clears_the_bin_with_null_not_with_a_second_instant() {    let row = email_row_patch(        EmailStatePatch {            bin: Some(false),            ..EmailStatePatch::default()        },        NOW,        true,    );    assert_eq!(        patch_json(row),        r#"{"trashed_at":null,"sync_state":"pending"}"#    );}#[test]fn leaves_sync_state_alone_for_mail_gmail_does_not_own() {    let row = email_row_patch(        EmailStatePatch {            starred: Some(true),            ..EmailStatePatch::default()        },        NOW,        false,    );    assert_eq!(patch_json(row), r#"{"starred":true}"#);}#[test]fn is_empty_for_an_empty_patch_so_nothing_is_queued_for_nothing() {    let row = email_row_patch(EmailStatePatch::default(), NOW, true);    assert!(row.is_empty());    assert_eq!(patch_json(row), "{}");}/// BOOLEANS, never 0/1 — the columns carry the `bool` codec and a number would/// be written silently wrong.#[test]fn writes_booleans_never_numbers() {    let row = email_row_patch(        EmailStatePatch {            read: Some(true),            starred: Some(false),            inbox: Some(true),            bin: None,        },        NOW,        false,    );    assert_eq!(        patch_json(row),        r#"{"unread":false,"starred":false,"in_inbox":true}"#    );}// ── folders ──────────────────────────────────────────────────────────────────#[test]fn names_four_folders_and_no_more() {    assert_eq!(        EmailFolder::ALL.map(|f| f.as_str()),        ["inbox", "archived", "bin", "all"]    );    for folder in EmailFolder::ALL {        assert_eq!(EmailFolder::parse(folder.as_str()), Some(folder));    }    assert_eq!(EmailFolder::parse("spam"), None);}#[test]fn keeps_the_bin_out_of_every_folder_but_the_bin() {    assert_eq!(        email_folder_filter(EmailFolder::Inbox),        EmailFolderFilter {            in_inbox: Some(true),            binned: false        }    );    assert_eq!(        email_folder_filter(EmailFolder::Archived),        EmailFolderFilter {            in_inbox: Some(false),            binned: false        }    );    assert_eq!(        email_folder_filter(EmailFolder::Bin),        EmailFolderFilter {            in_inbox: None,            binned: true        }    );    // "All" is Gmail's own All Mail: everything except what was thrown away.    assert_eq!(        email_folder_filter(EmailFolder::All),        EmailFolderFilter {            in_inbox: None,            binned: false        }    );}#[test]fn writes_the_same_answer_as_sql() {    assert_eq!(        email_folder_sql(EmailFolder::Inbox, "e"),        "e.trashed_at IS NULL AND e.in_inbox = 1"    );    assert_eq!(        email_folder_sql(EmailFolder::Archived, "e"),        "e.trashed_at IS NULL AND e.in_inbox = 0"    );    assert_eq!(        email_folder_sql(EmailFolder::Bin, "e"),        "e.trashed_at IS NOT NULL"    );    assert_eq!(        email_folder_sql(EmailFolder::All, "e"),        "e.trashed_at IS NULL"    );}// ── fold_thread_state ────────────────────────────────────────────────────────fn member(    unread: bool,    starred: bool,    in_inbox: bool,    trashed_at: Option<&str>,) -> EmailThreadMemberState {    EmailThreadMemberState {        unread,        starred,        in_inbox,        trashed_at: trashed_at.map(str::to_string),    }}#[test]fn is_the_or_over_its_messages() {    assert_eq!(        fold_thread_state(&[            member(true, false, false, None),            member(false, true, true, None)        ]),        EmailThreadState {            unread: true,            starred: true,            in_inbox: true,            trashed_at: None        }    );}/// RULE: An email conversation counts as binned only once every message in it has been binned.#[test]fn is_in_the_bin_only_when_nothing_of_it_is_left_outside() {    assert_eq!(        fold_thread_state(&[            member(false, false, false, Some(NOW)),            member(false, false, false, None)        ])        .trashed_at,        None    );    // The LATEST instant: the conversation went in when its last message did.    assert_eq!(        fold_thread_state(&[            member(false, false, false, Some("2026-09-01T00:00:00.000Z")),            member(false, false, false, Some(NOW))        ])        .trashed_at        .as_deref(),        Some(NOW)    );}#[test]fn answers_false_all_round_for_a_thread_with_no_messages() {    assert_eq!(fold_thread_state(&[]), EmailThreadState::default());}/// The latest instant regardless of the order the members arrive in — the/// comparison is a string comparison on both sides, which is chronological/// because every value is an ISO instant in one shape.#[test]fn takes_the_latest_bin_instant_whatever_order_the_members_come_in() {    let early = "2026-09-01T00:00:00.000Z";    let late = "2026-09-04T10:00:00.000Z";    for members in [        vec![            member(false, false, false, Some(early)),            member(false, false, false, Some(late)),        ],        vec![            member(false, false, false, Some(late)),            member(false, false, false, Some(early)),        ],    ] {        assert_eq!(            fold_thread_state(&members).trashed_at.as_deref(),            Some(late)        );    }}// RULE: an email conversation's state is said as marks (Unread, Starred, Archived, In the bin), and a read conversation in the inbox says nothing — never a row per switch.#[test]fn a_conversations_state_is_its_marks() {    let said = |unread, starred, in_inbox, binned| say_marks(&thread_marks(unread, starred, in_inbox, binned), &[]);    assert_eq!(said(false, false, true, false), None);    assert_eq!(said(true, true, true, false).as_deref(), Some("Unread \u{b7} Starred"));    assert_eq!(said(false, false, false, false).as_deref(), Some("Archived"));    assert_eq!(said(false, true, false, true).as_deref(), Some("Starred \u{b7} In the bin"));}/// RULE: a conversation's marks are said in the database's `email` lines —/// a rewording is a row, never a build.#[test]fn marks_are_said_in_the_databases_words() {    use crate::rules::shell_lines::LineRow;    let row = |line: &str, words: &str| LineRow { set: "email".into(), line: line.into(), words: words.into() };    let rows = [row("marks.unread", "New"), row("marks.join", "{a}, {b}")];    assert_eq!(say_marks(&thread_marks(true, true, true, false), &rows).as_deref(), Some("New, Starred"));}