Cotton code
271 lines · 8.7 KB · RustRaw
//! The group-import rules, with the vector tables in `vectors/import.json`//! (keys `slug`, `groupEvents`, `titleEvents`, `pseudoSender`).//!//! Every name here is invented. The two curly quotes are built from their code//! points, as the TypeScript's fixtures build them.use super::*;use serde::Deserialize;const LDQ: char = '\u{201c}';const RDQ: char = '\u{201d}';#[derive(Deserialize)]struct SlugVector {    title: String,    slug: String,    key: String,}#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct EventVector {    sender: String,    body: String,    is_group_event_body: bool,    is_encryption_boilerplate: bool,}#[derive(Deserialize)]struct TitleInput {    text: String,    #[serde(rename = "sentAt")]    sent_at: String,}#[derive(Deserialize)]struct TitleEvents {    input: Vec<TitleInput>,    titles: Vec<GroupTitleEvent>,    latest: Option<String>,}#[derive(Deserialize)]struct PseudoVector {    sender: String,    is: bool,}#[derive(Deserialize)]struct Vectors {    slug: Vec<SlugVector>,    #[serde(rename = "groupEvents")]    group_events: Vec<EventVector>,    #[serde(rename = "titleEvents")]    title_events: TitleEvents,    #[serde(rename = "pseudoSender")]    pseudo_sender: Vec<PseudoVector>,}fn vectors() -> Vectors {    serde_json::from_str(include_str!("../../vectors/import.json"))        .expect("vectors/import.json")}fn titles_of(events: &[(&str, &str)]) -> Vec<GroupTitleEvent> {    let candidates: Vec<TitleCandidate<'_>> = events        .iter()        .map(|(text, sent_at)| TitleCandidate { text, sent_at })        .collect();    extract_group_titles(&candidates)}// ── extractGroupTitles / latestTitle ─────────────────────────────────────────#[test]fn reads_creation_and_rename_events_curly_or_straight_quotes_latest_wins() {    let created = format!("Anita created group {LDQ}First Name{RDQ}");    let renamed = "You changed the group name to \"Second Name\"".to_string();    let subject =        format!("R changed the subject from {LDQ}Second Name{RDQ} to {LDQ}Third Name{RDQ}");    let titles = titles_of(&[        (&created, "2026-07-01T00:00:00.000Z"),        (&renamed, "2026-07-02T00:00:00.000Z"),        (&subject, "2026-07-03T00:00:00.000Z"),    ]);    assert_eq!(        titles.iter().map(|t| t.title.as_str()).collect::<Vec<_>>(),        ["First Name", "Second Name", "Third Name"]    );    assert_eq!(latest_title(&titles), Some("Third Name"));}#[test]fn returns_none_for_a_corpus_with_no_naming_events() {    let titles = titles_of(&[("hello", "2026-07-01T00:00:00.000Z")]);    assert_eq!(latest_title(&titles), None);}// ── isGroupEventBody ─────────────────────────────────────────────────────────#[test]fn catches_the_ios_x_colon_x_shape() {    assert!(is_group_event_body(        "Anita Rao",        "Anita Rao turned off disappearing messages. Change timer"    ));    assert!(is_group_event_body(        "Anita Rao",        &format!("Anita Rao created group {LDQ}Trip{RDQ}")    ));}#[test]fn catches_you_shapes_and_bare_boilerplate() {    assert!(is_group_event_body(        "Fixture Crew",        "You added Ravi Kumar and Priya From Stores"    ));    assert!(is_group_event_body("Fixture Crew", "You're now an admin"));    assert!(is_group_event_body(        "Fixture Crew",        "Disappearing messages were turned on. Change timer"    ));}#[test]fn does_not_catch_people_merely_talking_about_the_same_words() {    assert!(!is_group_event_body(        "Anita Rao",        "I added the new SKUs to the sheet"    ));    assert!(!is_group_event_body(        "Anita Rao",        "he left already, start without him"    ));    assert!(!is_group_event_body(        "Anita Rao",        "the security code on the lock is 4411"    ));}/// A body that opens with its sender and an event phrase but runs past 200/// UTF-16 code units is a PERSON writing a long sentence, not an event — and/// the 200 is counted in code units, which is what the TypeScript's `.length`/// counts.#[test]fn a_long_body_is_a_person_talking_however_it_opens() {    let long = format!("Anita Rao added {}", "x".repeat(220));    assert!(!is_group_event_body("Anita Rao", &long));}// ── isGroupPseudoSender ──────────────────────────────────────────────────────#[test]fn matches_a_sender_equal_to_a_known_title() {    let created = format!("A created group {LDQ}Fixture Crew{RDQ}");    let titles = titles_of(&[(&created, "2026-07-01T00:00:00.000Z")]);    assert!(is_group_pseudo_sender("Fixture Crew", &titles));    assert!(!is_group_pseudo_sender("Anita Rao", &titles));}// ── slug / external key ──────────────────────────────────────────────────────#[test]fn slugs_like_the_spec_freeze() {    assert_eq!(slugify_title("AQ <> TinFactory"), "aq-tinfactory");    assert_eq!(group_external_key("Fixture Crew"), "wa:group:fixture-crew");    assert_eq!(slugify_title("   "), "untitled");}// ── isEncryptionBoilerplate ──────────────────────────────────────────────────#[test]fn flags_only_the_encryption_notice() {    assert!(is_encryption_boilerplate(        "Messages and calls are end-to-end encrypted. Learn more"    ));    assert!(!is_encryption_boilerplate("You changed the group name"));}// ── the Node vector tables ───────────────────────────────────────────────────#[test]fn every_slug_matches_the_typescript() {    let vectors = vectors();    assert!(vectors.slug.len() >= 13, "the table should not shrink");    for case in &vectors.slug {        assert_eq!(slugify_title(&case.title), case.slug, "{:?}", case.title);        assert_eq!(            group_external_key(&case.title),            case.key,            "{:?}",            case.title        );    }}/// The three readings a reasoned port gets wrong: an `é` written as `e` plus a/// combining acute slugs as `e-cole` (the mark becomes a hyphen), a CJK title/// keeps NOTHING and falls back to `untitled`, and a title of only emoji and a/// word keeps the word. None of that is tidied, because the slug is a thread's/// stable identity.#[test]fn the_slug_does_not_normalise_and_that_is_deliberate() {    assert_eq!(slugify_title("e\u{0301}cole"), "e-cole");    assert_eq!(slugify_title("你好世界"), "untitled");    assert_eq!(slugify_title("\u{1f44d} Crew \u{1f44d}"), "crew");    assert_eq!(slugify_title(&"a".repeat(60)), "a".repeat(48));}#[test]fn every_event_reading_matches_the_typescript() {    let vectors = vectors();    assert!(        vectors.group_events.len() >= 14,        "the table should not shrink"    );    for case in &vectors.group_events {        assert_eq!(            is_group_event_body(&case.sender, &case.body),            case.is_group_event_body,            "isGroupEventBody({:?}, {:?})",            case.sender,            case.body        );        assert_eq!(            is_encryption_boilerplate(&case.body),            case.is_encryption_boilerplate,            "isEncryptionBoilerplate({:?})",            case.body        );    }}#[test]fn the_extracted_titles_and_their_order_match_the_typescript() {    let vectors = vectors();    let candidates: Vec<TitleCandidate<'_>> = vectors        .title_events        .input        .iter()        .map(|event| TitleCandidate {            text: &event.text,            sent_at: &event.sent_at,        })        .collect();    let titles = extract_group_titles(&candidates);    assert_eq!(titles, vectors.title_events.titles);    assert_eq!(        latest_title(&titles).map(str::to_string),        vectors.title_events.latest    );    // The sort is by instant, so a rename dated BEFORE the creation event    // lands first — the corpus order is not the answer.    assert_eq!(titles[0].title, "Straight Quotes");}#[test]fn the_pseudo_sender_readings_match_the_typescript() {    let vectors = vectors();    let created = format!("A created group {LDQ}Fixture Crew{RDQ}");    let titles = titles_of(&[(&created, "2026-07-01T00:00:00.000Z")]);    for case in &vectors.pseudo_sender {        assert_eq!(            is_group_pseudo_sender(&case.sender, &titles),            case.is,            "{:?}",            case.sender        );    }}