Cotton code
477 lines · 15.5 KB · RustRaw
//! The fixture is an invented export, never real chat data — hand-built to//! match WhatsApp-Chat-Exporter's JSON at v0.13.0 and deliberately carrying the//! things a real export contains and a naive reader trips over: address-book//! shells with no messages, a group, a LID chat, the calls pseudo-chat,//! `meta: true` system rows, `<br>`-encoded newlines, a media row whose `data`//! is a PATH, a reply pointing at another message's `key_id` (not its row id),//! an Android-style flat reactions map, and one field this reader has never//! heard of.//!//! Unlike the `_chat.txt` fixtures, this one is not rebuilt from code points//! here: it is a JSON DOCUMENT, and `tests/fixtures/import_adapters.json` holds//! it verbatim (fully ASCII-escaped, so the two emoji are reviewable as their//! code points) beside the parse result the RUNNING TypeScript produced from//! it. Reading the input from the same file as the expectation is what keeps//! the pair honest.use serde::Deserialize;use serde_json::{json, Value};use super::*;const CONTACT_JID: &str = "919876543210@s.whatsapp.net";const CONTACT_PHONE: &str = "919876543210";const GROUP_JID: &str = "120363001234567890@g.us";const LID_JID: &str = "98765432109876@lid";/// The `key_id` an incoming message carries, quoted by the outgoing reply.const INCOMING_KEY_ID: &str = "3EB0A1B2C3D4E5F60718";const REPLY_KEY_ID: &str = "3EB0F9E8D7C6B5A43210";const THUMBS_UP: &str = "\u{1f44d}";const HEART: &str = "\u{2764}";// ── the vector table ─────────────────────────────────────────────────────────#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct JidVector {    jid: String,    kind: WceChatKind,    phone: Option<String>,}#[derive(Deserialize)]struct BrVector {    input: String,    result: String,}#[derive(Deserialize)]struct TimestampVector {    value: Value,    result: Option<String>,}#[derive(Deserialize)]struct ErrorVector {    label: String,    message: String,}#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct Vectors {    wce_jids: Vec<JidVector>,    wce_br: Vec<BrVector>,    wce_timestamps: Vec<TimestampVector>,    wce_inputs: std::collections::HashMap<String, Value>,    wce_parses: std::collections::HashMap<String, WceParseResult>,    wce_errors: Vec<ErrorVector>,}fn vectors() -> Vectors {    serde_json::from_str(include_str!("../../../tests/fixtures/import_adapters.json"))        .expect("import_adapters.json")}fn input(name: &str) -> Value {    vectors()        .wce_inputs        .get(name)        .unwrap_or_else(|| panic!("the vector table has no wce input named {name}"))        .clone()}fn sample() -> WceParseResult {    parse_wce_json(&input("sample")).expect("a parse")}// ── classifyJid ──────────────────────────────────────────────────────────────#[test]fn classifies_every_jid_shape_the_exporter_writes() {    assert_eq!(        classify_jid("919876543210@s.whatsapp.net"),        WceChatKind::Personal    );    assert_eq!(classify_jid("120363001234567890@g.us"), WceChatKind::Group);    assert_eq!(        classify_jid("status@broadcast"),        WceChatKind::StatusBroadcast    );    assert_eq!(        classify_jid("1234567@broadcast"),        WceChatKind::BroadcastChannel    );    assert_eq!(classify_jid("98765432109876@lid"), WceChatKind::Lid);    assert_eq!(classify_jid("000000000000000"), WceChatKind::Calls);    assert_eq!(classify_jid("ExportedChat"), WceChatKind::Exported);}// ── phoneFromJid ─────────────────────────────────────────────────────────────#[test]fn takes_the_user_part_and_normalizes_it() {    assert_eq!(        phone_from_jid("919876543210@s.whatsapp.net").as_deref(),        Some("919876543210")    );}#[test]fn drops_a_multi_device_suffix() {    assert_eq!(        phone_from_jid("919876543210:12@s.whatsapp.net").as_deref(),        Some("919876543210")    );}/// A LID user part IS all digits, so the guard that matters is the JID/// classification, not this — but a 14-digit LID must never be silently/// accepted as a phone by anything that calls `phone_from_jid` directly.#[test]fn a_lid_is_recognised_by_its_suffix_not_by_its_digits() {    assert_eq!(classify_jid(LID_JID), WceChatKind::Lid);    assert!(phone_from_jid(LID_JID).is_some());}// ── reverseBrSubstitution ────────────────────────────────────────────────────#[test]fn restores_newlines_the_exporter_encoded_as_br() {    assert_eq!(reverse_br_substitution("a<br>b<br/>c<br />d"), "a\nb\nc\nd");}// ── timestampToIso ───────────────────────────────────────────────────────────#[test]fn reads_unix_seconds() {    assert_eq!(        timestamp_to_iso(Some(&json!(1_755_172_800))).as_deref(),        Some("2025-08-14T12:00:00.000Z")    );}#[test]fn tolerates_fractional_seconds_which_the_exporter_emits() {    assert_eq!(        timestamp_to_iso(Some(&json!(1_755_172_800.571_629))).as_deref(),        Some("2025-08-14T12:00:00.571Z")    );}#[test]fn defends_against_raw_milliseconds_from_a_hand_merged_file() {    assert_eq!(        timestamp_to_iso(Some(&json!(1_755_172_800_000i64))).as_deref(),        Some("2025-08-14T12:00:00.000Z")    );}/// The TypeScript's `it.each([0, -1, "1755172800", null, undefined, NaN])`./// `undefined` arrives here as an absent key (`None`) and `NaN` cannot exist in/// a `serde_json::Number` at all, so both are covered by the same branch that/// rejects a string.#[test]fn rejects_a_value_that_is_not_a_usable_timestamp() {    assert_eq!(timestamp_to_iso(Some(&json!(0))), None);    assert_eq!(timestamp_to_iso(Some(&json!(-1))), None);    assert_eq!(timestamp_to_iso(Some(&json!("1755172800"))), None);    assert_eq!(timestamp_to_iso(Some(&Value::Null)), None);    assert_eq!(timestamp_to_iso(None), None);}#[test]fn rejects_a_timestamp_from_before_whatsapp_existed() {    assert_eq!(timestamp_to_iso(Some(&json!(1))), None);}// ── parseWceJson ─────────────────────────────────────────────────────────────#[test]fn keeps_only_the_one_to_one_conversation() {    let result = sample();    assert_eq!(result.chats.len(), 1);    assert_eq!(result.chats[0].jid, CONTACT_JID);    assert_eq!(result.chats[0].phone.as_deref(), Some(CONTACT_PHONE));    assert_eq!(result.chats[0].name.as_deref(), Some("Anita Rao"));}#[test]fn skips_the_group_with_a_counted_reason() {    let result = sample();    let group = result        .skipped        .iter()        .find(|chat| chat.jid == GROUP_JID)        .expect("the group");    assert_eq!(group.kind, "group");    assert_eq!(group.messages, 1);    assert!(group.reason.contains("group"));}#[test]fn skips_the_lid_chat_whose_jid_carries_no_phone_number() {    let result = sample();    let lid = result        .skipped        .iter()        .find(|chat| chat.jid == LID_JID)        .expect("the lid chat");    assert_eq!(lid.kind, "lid");    assert!(lid.reason.contains("no phone number"));}#[test]fn skips_the_calls_pseudo_chat() {    assert!(sample().skipped.iter().any(|chat| chat.kind == "calls"));}#[test]fn counts_address_book_shells_rather_than_reporting_each_one() {    let result = sample();    assert_eq!(result.empty_chats, 2);    assert!(!result.skipped.iter().any(|chat| chat.messages == 0));}#[test]fn keeps_system_rows_in_the_parse_so_the_normalizer_can_count_them() {    let result = sample();    assert_eq!(        result.chats[0]            .messages            .iter()            .filter(|message| message.is_system)            .count(),        1    );}fn by_key_id<'a>(chat: &'a WceChat, key_id: &str) -> &'a WceMessage {    chat.messages        .iter()        .find(|message| message.key_id.as_deref() == Some(key_id))        .expect("a message with that key id")}#[test]fn restores_newlines_in_message_text() {    let result = sample();    assert_eq!(        by_key_id(&result.chats[0], INCOMING_KEY_ID).text,        "Are we still on for tomorrow?\nI can bring the drive."    );}#[test]fn reads_direction_from_from_me() {    let result = sample();    assert!(by_key_id(&result.chats[0], REPLY_KEY_ID).from_me);}#[test]fn carries_the_reply_as_the_quoted_messages_key_id_not_a_row_id() {    let result = sample();    assert_eq!(        by_key_id(&result.chats[0], REPLY_KEY_ID)            .reply_to_key_id            .as_deref(),        Some(INCOMING_KEY_ID)    );}#[test]fn reads_the_flat_reactions_map_distinguishing_the_owners_own() {    let result = sample();    assert_eq!(        by_key_id(&result.chats[0], INCOMING_KEY_ID).reactions,        vec![WceReaction {            actor_name: "You".to_string(),            emoji: THUMBS_UP.to_string(),        }]    );    assert_eq!(        by_key_id(&result.chats[0], REPLY_KEY_ID).reactions,        vec![WceReaction {            actor_name: "Anita Rao".to_string(),            emoji: HEART.to_string(),        }]    );}#[test]fn takes_media_text_from_caption_and_the_path_from_data() {    let result = sample();    let media = result.chats[0]        .messages        .iter()        .find(|message| message.is_media)        .expect("the media row");    assert_eq!(media.text, "the drive");    assert_eq!(        media.media_path.as_deref(),        Some("WhatsApp/Media/WhatsApp Images/IMG-20260814-WA0001.jpg")    );    assert_eq!(media.mime.as_deref(), Some("image/jpeg"));}#[test]fn sorts_messages_chronologically() {    let result = sample();    let times: Vec<&str> = result.chats[0]        .messages        .iter()        .map(|message| message.sent_at.as_str())        .collect();    let mut sorted = times.clone();    sorted.sort_unstable();    assert_eq!(sorted, times);}#[test]fn reports_unknown_fields_once_instead_of_crashing_on_them() {    let result = sample();    assert_eq!(result.unknown_message_fields, vec!["some_future_field"]);    assert!(result.warnings.join(" ").contains("some_future_field"));}#[test]fn rejects_a_document_that_is_not_the_exporters_shape() {    for document in [json!([]), json!("nope"), json!(3), Value::Null] {        let error = parse_wce_json(&document).expect_err("a refusal");        assert!(error.to_string().contains("keyed by JID"), "{error}");    }}#[test]fn tolerates_a_chat_missing_every_optional_field() {    let minimal = parse_wce_json(&input("minimal")).expect("a parse");    assert_eq!(minimal.chats[0].messages[0].text, "hi");    assert_eq!(minimal.chats[0].name, None);    assert_eq!(minimal.chats[0].messages[0].key_id, None);}#[test]fn drops_a_message_with_no_usable_timestamp_and_counts_it() {    let broken = parse_wce_json(&input("broken")).expect("a parse");    assert_eq!(broken.chats[0].messages.len(), 1);    assert_eq!(broken.dropped_messages, 1);}#[test]fn treats_a_per_sender_name_in_a_supposed_one_to_one_as_a_group() {    let disguised = parse_wce_json(&input("disguised")).expect("a parse");    assert!(disguised.chats.is_empty());    assert!(disguised.skipped[0].reason.contains("group"));}/// JavaScript walks integer-like object keys in ASCENDING NUMERIC order before/// any other key, whatever the file's order — and `messages` is keyed by DB row/// id, so every key is integer-like. The fixture writes row 30 first; both/// readers must still see 9, 10, 30, and the stable sort by instant must leave/// 9 before 10 where the two share a timestamp.#[test]fn walks_row_ids_in_javascripts_own_key_order() {    let ordering = parse_wce_json(&input("ordering")).expect("a parse");    assert_eq!(        ordering.chats[0]            .messages            .iter()            .map(|message| message.row_key.as_str())            .collect::<Vec<_>>(),        vec!["9", "10", "30"]    );}// ── the Node vector tables ───────────────────────────────────────────────────#[test]fn every_jid_classifies_and_yields_the_phone_the_typescript_read() {    let table = vectors().wce_jids;    assert!(table.len() >= 10, "the table should not shrink");    for case in &table {        assert_eq!(classify_jid(&case.jid), case.kind, "{}", case.jid);        assert_eq!(phone_from_jid(&case.jid), case.phone, "{}", case.jid);    }}#[test]fn every_br_substitution_reverses_the_way_the_typescript_reversed_it() {    let table = vectors().wce_br;    assert!(table.len() >= 6, "the table should not shrink");    for case in &table {        assert_eq!(            reverse_br_substitution(&case.input),            case.result,            "{:?}",            case.input        );    }}#[test]fn every_timestamp_reads_the_way_the_typescript_read_it() {    let table = vectors().wce_timestamps;    assert!(table.len() >= 14, "the table should not shrink");    for case in &table {        // Two rows stand for values JSON cannot carry — `undefined` and `NaN`,        // which the generator marked with a sentinel string. Both reject on        // the same branch as any other non-number, and        // `rejects_a_value_that_is_not_a_usable_timestamp` covers them.        if matches!(case.value.as_str(), Some("__undefined__" | "__nan__")) {            assert_eq!(case.result, None);            continue;        }        assert_eq!(            timestamp_to_iso(Some(&case.value)),            case.result,            "{}",            case.value        );    }}/// The whole parse result, field for field, for every document the generator/// ran — the sample, the four minimal shapes, an out-of-order one, and a/// document full of the coercions the exporter's `__dict__` dump can produce/// (a numeric `name`, a numeric `key_id`, 0/1 in place of booleans, an empty/// reaction emoji, and a chat whose value is not an object at all).#[test]fn every_document_parses_the_way_the_typescript_parsed_it() {    let table = vectors();    assert!(table.wce_parses.len() >= 7, "the table should not shrink");    for (name, expected) in &table.wce_parses {        let document = table            .wce_inputs            .get(name)            .unwrap_or_else(|| panic!("no input for {name}"));        assert_eq!(            &parse_wce_json(document).expect("a parse"),            expected,            "parse of {name}"        );    }}/// The refusal SENTENCE, which a handler prints, for every non-object shape.#[test]fn every_bad_document_refuses_with_the_typescripts_own_sentence() {    let table = vectors().wce_errors;    assert!(table.len() >= 4, "the table should not shrink");    for case in &table {        let document = match case.label.as_str() {            "array" => json!([]),            "string" => json!("nope"),            "number" => json!(3),            "null" => Value::Null,            other => panic!("unknown error vector {other}"),        };        assert_eq!(            parse_wce_json(&document)                .expect_err("a refusal")                .to_string(),            case.message        );    }}