Cotton code
247 lines · 7.5 KB · RustRaw
//! Every case is a SHAPE seen in a real export — the keywords are localized to//! the exporting phone's WhatsApp language, so the German, Spanish, Portuguese//! and Italian bodies below are what those exports literally write,//! transcribed with invented questions.//!//! The bodies are given already normalized (`normalize_export_text` has run)://! iOS writes a LEFT-TO-RIGHT MARK before `POLL:` and before every `OPTION:`,//! and German counts with a NARROW NO-BREAK SPACE inside the parentheses, and//! both are gone by the time a `TxtMessage` exists.use super::*;use serde::Deserialize;#[derive(Deserialize)]struct PollVector {    body: String,    poll: Option<TxtPoll>,}#[derive(Deserialize)]struct Vectors {    poll: Vec<PollVector>,}fn body(lines: &[&str]) -> String {    lines.join("\n")}const EN: [&str; 4] = [    "POLL:",    "Which day works for the site visit?",    "OPTION: Thursday (3 votes)",    "OPTION: Friday (1 vote)",];#[test]fn reads_the_question_the_options_and_the_counts() {    assert_eq!(        parse_poll_body(&body(&EN)),        Some(TxtPoll {            question: "Which day works for the site visit?".to_string(),            options: vec![                TxtPollOption {                    text: "Thursday".to_string(),                    votes: 3                },                TxtPollOption {                    text: "Friday".to_string(),                    votes: 1                },            ],        })    );}#[test]fn reads_zero_votes_as_zero_rather_than_as_no_answer() {    let poll = parse_poll_body(&body(&[        "POLL:",        "Tea or coffee?",        "OPTION: Tea (0 votes)",        "OPTION: Coffee (2 votes)",    ]))    .expect("a poll");    assert_eq!(        poll.options[0],        TxtPollOption {            text: "Tea".to_string(),            votes: 0        }    );}#[test]fn keeps_a_question_that_runs_over_several_lines_blank_lines_and_all() {    let poll = parse_poll_body(&body(&[        "POLL:",        "Hey everyone!",        "",        "Which size do you want for the crew shirts?",        "OPTION: Medium (4 votes)",        "OPTION: Large (7 votes)",    ]))    .expect("a poll");    assert_eq!(        poll.question,        "Hey everyone!\n\nWhich size do you want for the crew shirts?"    );    assert_eq!(poll.options.len(), 2);}#[test]fn takes_the_last_parenthesised_count_so_an_option_may_contain_brackets() {    let poll = parse_poll_body(&body(&[        "POLL:",        "Where to?",        "OPTION: Out (the far gate) (5 votes)",        "OPTION: In (0 votes)",    ]))    .expect("a poll");    assert_eq!(        poll.options[0],        TxtPollOption {            text: "Out (the far gate)".to_string(),            votes: 5        }    );}#[test]fn takes_an_option_whose_text_contains_a_colon() {    let poll = parse_poll_body(&body(&[        "POLL:",        "Which slot?",        "OPTION: Morning: 9 to 11 (2 votes)",        "OPTION: Evening (1 vote)",    ]))    .expect("a poll");    assert_eq!(poll.options[0].text, "Morning: 9 to 11");}/// The keywords follow the exporting PHONE's language, so matching the English/// word would import every non-English owner's polls as prose.#[test]fn reads_a_german_spanish_portuguese_and_italian_export_the_same_way() {    let cases: [[&str; 3]; 4] = [        [            "UMFRAGE:",            "OPTION: Donnerstag (1 Stimme)",            "OPTION: Freitag (2 Stimmen)",        ],        [            "ENCUESTA:",            "OPCIÓN: Jueves (1 voto)",            "OPCIÓN: Viernes (4 votos)",        ],        [            "ENQUETE:",            "OPÇÃO: Quinta (0 voto)",            "OPÇÃO: Sexta (3 votos)",        ],        [            "SONDAGGIO:",            "OPZIONE: Giovedì (1 voto)",            "OPZIONE: Venerdì (2 voti)",        ],    ];    for [header, first, second] in cases {        let poll = parse_poll_body(&body(&[header, "Welcher Tag?", first, second]))            .unwrap_or_else(|| panic!("{header} should read as a poll"));        assert_eq!(poll.options.len(), 2, "{header}");        assert!(poll.options[1].votes > 0, "{header}");    }}#[test]fn refuses_a_message_that_merely_opens_with_a_word_and_a_colon() {    assert_eq!(        parse_poll_body(&body(&["TOMORROW:", "bring the drawings", "and the tape"])),        None    );}#[test]fn refuses_a_body_with_only_one_option_whatsapp_cannot_make_that_poll() {    assert_eq!(        parse_poll_body(&body(&["POLL:", "Coming?", "OPTION: Yes (3 votes)"])),        None    );}#[test]fn refuses_a_poll_with_no_question_at_all() {    assert_eq!(        parse_poll_body(&body(&[            "POLL:",            "OPTION: Yes (3 votes)",            "OPTION: No (1 vote)"        ])),        None    );}#[test]fn refuses_option_lines_whose_keyword_changes_halfway() {    assert_eq!(        parse_poll_body(&body(&[            "POLL:",            "Coming?",            "OPTION: Yes (3 votes)",            "CHOICE: No (1 vote)"        ])),        None    );}#[test]fn answers_none_for_an_ordinary_message() {    assert_eq!(parse_poll_body("are we still on for tomorrow?"), None);    assert_eq!(parse_poll_body(""), None);}// ── the Node vector table ────────────────────────────────────────────────────#[test]fn every_body_reads_the_way_the_typescript_read_it() {    let parsed: Vectors =        serde_json::from_str(include_str!("../../../cotton-rules/vectors/import.json"))            .expect("cotton-rules/vectors/import.json");    assert!(parsed.poll.len() >= 16, "the table should not shrink");    for case in &parsed.poll {        assert_eq!(parse_poll_body(&case.body), case.poll, "{:?}", case.body);    }}/// An emoji question and emoji option texts. The keyword length is checked in/// UTF-16 code units, as `{3,24}` counts in JavaScript, so this reads as a/// poll on both sides rather than only on the one whose quantifier counts/// characters.#[test]fn an_emoji_poll_reads_the_same_on_both_sides() {    let poll = parse_poll_body(&body(&[        "POLL:",        "\u{1f44d}?",        "OPTION: \u{1f44d} (11 votes)",        "OPTION: \u{1f469}\u{200d}\u{1f4bb} (0 votes)",    ]))    .expect("a poll");    assert_eq!(poll.question, "\u{1f44d}?");    assert_eq!(poll.options[0].votes, 11);    assert_eq!(poll.options[1].text, "\u{1f469}\u{200d}\u{1f4bb}");}/// RULE (owner, FEEDBACK-3, 23 Nov 2026; CONTRACT "Polls shown"): a poll from the WhatsApp link lands with its options/// at no votes and how many one voter may pick, and a vote's picks (WhatsApp's SHA-256 of each option's words) are/// read as the options' indexes; a pick naming no option of this poll is left out.#[test]fn a_linked_poll_reads_a_votes_picks_as_its_options() {    let options = vec!["Thursday".to_string(), "Friday".to_string(), "Saturday".to_string()];    let poll = super::linked_poll("Which day?", &options, 1).as_object().cloned().unwrap();    assert_eq!(poll["options"], serde_json::json!([{ "text": "Thursday", "votes": 0 }, { "text": "Friday", "votes": 0 }, { "text": "Saturday", "votes": 0 }]));    assert_eq!(poll["selectable"], 1);    let h = |t: &str| super::option_hash(t);    assert_eq!(super::picked_options(&poll, &[h("Saturday"), h("Friday"), h("Not an option"), h("Friday")]), Some(vec![1, 2]));    assert_eq!(super::picked_options(&poll, &[]), Some(vec![]), "a vote that picks nothing takes the voter off");    assert_eq!(super::picked_options(&serde_json::Map::new(), &[h("Friday")]), None);}