//! The WhatsApp `_chat.txt` fallback adapter, over synthetic fixtures. //! //! ## The fixtures are BUILT, not pasted //! //! The transcripts are assembled from code points here exactly as they are //! there, and for the same reason: the characters that actually break this //! parser are invisible. WhatsApp puts a LEFT-TO-RIGHT MARK in front of every //! iOS line, isolates around a bidi name, and a NARROW NO-BREAK SPACE before //! AM/PM in newer builds. Pasted into a file they would be unreviewable and //! would not survive a careless copy-paste; written like this each test says //! which invisible character it is exercising. //! //! Every conversation is invented. Nothing real goes in Cotton's public tree. //! //! ## The vector table //! //! `tests/fixtures/import_adapters.json` was produced by RUNNING the //! TypeScript adapter over these fixtures (`npx tsx`, from //! `packages/import-core`), and carries three things: the fixture TEXTS, the //! whole parse result for each, and per-function vector rows. So //! [`every_fixture_matches_the_typescripts_own_text`] proves the reconstruction //! above is byte-identical to the TypeScript's, and only then does //! [`every_fixture_parses_the_way_the_typescript_parsed_it`] mean anything. use std::collections::HashMap; use serde::Deserialize; use super::*; // ── the fixtures, built from code points ───────────────────────────────────── /// U+200E LEFT-TO-RIGHT MARK — prefixes every line of an iOS export. const LRM: &str = "\u{200e}"; /// U+200F RIGHT-TO-LEFT MARK. const RLM: &str = "\u{200f}"; /// U+2067 RIGHT-TO-LEFT ISOLATE / U+2069 POP DIRECTIONAL ISOLATE. const RLI: &str = "\u{2067}"; const PDI: &str = "\u{2069}"; /// U+202F NARROW NO-BREAK SPACE — sits before AM/PM in newer exports. const NNBSP: &str = "\u{202f}"; /// U+201C / U+201D — iOS quotes group names with curly quotes. const LDQ: &str = "\u{201c}"; const RDQ: &str = "\u{201d}"; const OWNER_NAME: &str = "Milo Example"; const CONTACT_NAME: &str = "Anita Rao"; const GROUP_MEMBER_2: &str = "Ravi Kumar"; const GROUP_MEMBER_3: &str = "Priya From Stores"; fn joined(lines: &[String]) -> String { lines.join("\n") } /// iOS `_chat.txt`. Exercises, in order: the encryption notice (a system line /// AND the not-truncated signal), a plain message, a multiline body, an /// attachment with the marker on its own line, an edited message, an /// omitted-media marker, a bidi-isolated body, and two identical messages in /// the same minute (which must still get distinct external ids). fn ios_chat_txt() -> String { joined(&[ format!("{LRM}[26/07/2025, 10:00:00 AM] Messages and calls are end-to-end encrypted. No one outside of this chat, not even WhatsApp, can read or listen to them."), format!("{LRM}[26/07/2025, 10:12:45 AM] {OWNER_NAME}: Hey, are we still on for tomorrow?"), format!("{LRM}[26/07/2025, 10:13:02 AM] {CONTACT_NAME}: yes!"), "Bringing the drive too.".to_string(), format!("{LRM}[26/07/2025, 10:15:00{NNBSP}AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[26/07/2025, 10:16:10 AM] {OWNER_NAME}: perfect "), format!("{LRM}[26/07/2025, 10:17:00 AM] {CONTACT_NAME}: image omitted"), format!("{LRM}[26/07/2025, 10:18:00 AM] {CONTACT_NAME}: {RLI}شكرا{PDI} {RLM}thanks"), format!("{LRM}[26/07/2025, 11:00:00 AM] {OWNER_NAME}: ok"), format!("{LRM}[26/07/2025, 11:00:30 AM] {OWNER_NAME}: ok"), String::new(), ]) } /// Android `_chat.txt`. Same conversation in the other dialect: no brackets, a /// ` - ` separator, 24-hour clock with no seconds, and Android's own attachment /// and omitted-media spellings. fn android_chat_txt() -> String { joined(&[ "26/07/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("26/07/2025, 10:12 - {OWNER_NAME}: Hey, are we still on for tomorrow?"), format!("26/07/2025, 10:13 - {CONTACT_NAME}: yes!"), "Bringing the drive too.".to_string(), format!("26/07/2025, 10:15 - {CONTACT_NAME}: IMG-20250726-WA0001.jpg (file attached)"), format!("26/07/2025, 10:16 - {OWNER_NAME}: perfect "), format!("26/07/2025, 10:17 - {CONTACT_NAME}: "), format!("26/07/2025, 10:18 - {CONTACT_NAME}'s security code changed. Tap to learn more."), format!("26/07/2025, 10:19 - {CONTACT_NAME}: This message was deleted"), String::new(), ]) } /// The counterparty is an UNSAVED contact, so the export writes their number. fn android_unsaved_contact_txt() -> String { joined(&[ "26/07/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("26/07/2025, 10:12 - {OWNER_NAME}: hello"), "26/07/2025, 10:13 - +91 98765 43210: hi".to_string(), String::new(), ]) } /// The adversarial case for [`classify_remainder`]: a system line that contains /// ": ", which a naive sender split reads as a message from a person called /// `Milo Example created group "Trip`. fn android_system_line_with_colon_txt() -> String { joined(&[ "26/07/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("26/07/2025, 10:01 - {OWNER_NAME} created group \"Trip: Goa\""), format!("26/07/2025, 10:12 - {OWNER_NAME}: hello"), format!("26/07/2025, 10:13 - {CONTACT_NAME}: hi"), String::new(), ]) } /// Three participants — a group, which the dm route skips. fn android_group_txt() -> String { joined(&[ "26/07/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("26/07/2025, 10:12 - {OWNER_NAME}: hello everyone"), format!("26/07/2025, 10:13 - {CONTACT_NAME}: hi"), "26/07/2025, 10:14 - Ravi Kumar: hello".to_string(), format!("26/07/2025, 10:15 - {CONTACT_NAME}: see you there"), "26/07/2025, 10:16 - Ravi Kumar: on my way".to_string(), String::new(), ]) } /// iOS GROUP export: the encryption notice attributed to the CURRENT group /// name; creation + rename events in both attributed disguises; member adds; /// disappearing messages toggled; a numbered document and photo; an edited /// message; a deleted-message tombstone; a multiline body; and two identical /// same-minute messages from one sender. fn ios_group_txt() -> String { joined(&[ format!("{LRM}[01/07/2026, 12:38:25 PM] Fixture Crew: {LRM}Messages and calls are end-to-end encrypted. Only people in this chat can read, listen to, or share them."), format!("{LRM}[01/07/2026, 12:38:25 PM] {CONTACT_NAME}: {LRM}{CONTACT_NAME} created group {LDQ}Delivery App For Fixtures{RDQ}"), format!("{LRM}[01/07/2026, 12:38:32 PM] {CONTACT_NAME}: {LRM}{LRM}{CONTACT_NAME} turned off disappearing messages. {LRM}Change timer"), format!("{LRM}[01/07/2026, 12:39:00 PM] Fixture Crew: {LRM}{CONTACT_NAME} added you"), format!("{LRM}[01/07/2026, 12:40:00 PM] Fixture Crew: {LRM}You added {GROUP_MEMBER_2} and {GROUP_MEMBER_3}"), format!("{LRM}[01/07/2026, 12:41:00 PM] Fixture Crew: {LRM}You changed the group name to {LDQ}Fixture Crew{RDQ}"), format!("{LRM}[01/07/2026, 5:32:09 PM] {GROUP_MEMBER_3}: Requirement.docx {LRM}"), format!("{LRM}[02/07/2026, 9:15:00 AM] {OWNER_NAME}: Got it, will review today"), format!("{LRM}[02/07/2026, 9:16:30 AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[02/07/2026, 9:20:00 AM] {GROUP_MEMBER_2}: Two points:"), "1. loading pattern looks off".to_string(), "2. need the trip sheet by Friday".to_string(), format!("{LRM}[02/07/2026, 9:25:00 AM] {OWNER_NAME}: I will get back with estimates before Friday. {LRM}"), format!("{LRM}[02/07/2026, 10:00:10 AM] {GROUP_MEMBER_3}: Okay"), format!("{LRM}[02/07/2026, 10:00:40 AM] {GROUP_MEMBER_3}: Okay"), format!("{LRM}[26/07/2026, 8:00:00 AM] {OWNER_NAME}: {LRM}You deleted this message."), String::new(), ]) } /// US locale: month first. Proven by `26` in the SECOND position. fn android_mdy_txt() -> String { joined(&[ "07/26/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("07/26/2025, 10:12 - {OWNER_NAME}: hello"), format!("07/26/2025, 10:13 - {CONTACT_NAME}: hi"), String::new(), ]) } /// No date above 12 anywhere — genuinely ambiguous, and the parser must say so. fn android_ambiguous_date_txt() -> String { joined(&[ "03/04/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("03/04/2025, 10:12 - {OWNER_NAME}: hello"), format!("03/04/2025, 10:13 - {CONTACT_NAME}: hi"), String::new(), ]) } /// Starts mid-conversation: no encryption notice. fn android_truncated_txt() -> String { joined(&[ format!("26/07/2025, 10:12 - {OWNER_NAME}: hello"), format!("26/07/2025, 10:13 - {CONTACT_NAME}: hi"), String::new(), ]) } /// iOS export with two ALBUMS and one genuinely blank line. /// /// The blank at 9:02 is NOT scaffolding: nothing with an attachment follows it, /// so it is one of the shapes the text export genuinely cannot carry (a /// sticker, a location pin, a view-once photo) and it must stay a message. fn ios_album_txt() -> String { joined(&[ format!("{LRM}[01/08/2026, 9:00:00 AM] Messages and calls are end-to-end encrypted. No one outside of this chat, not even WhatsApp, can read or listen to them."), format!("{LRM}[01/08/2026, 9:01:00 AM] {CONTACT_NAME}:"), format!("{LRM}[01/08/2026, 9:01:00 AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[01/08/2026, 9:01:01 AM] {CONTACT_NAME}: {LRM} both from the yard"), format!("{LRM}[01/08/2026, 9:02:00 AM] {OWNER_NAME}:"), format!("{LRM}[01/08/2026, 9:03:00 AM] {OWNER_NAME}: nice"), format!("{LRM}[01/08/2026, 9:05:00 AM] {CONTACT_NAME}:"), format!("{LRM}[01/08/2026, 9:05:00 AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[01/08/2026, 9:05:01{NNBSP}AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[01/08/2026, 9:05:02 AM] {CONTACT_NAME}: {LRM}"), String::new(), ]) } /// The same two albums in an iOS GROUP export — the group route builds its /// timeline separately, so the container rule has to hold on both. fn ios_group_album_txt() -> String { joined(&[ format!("{LRM}[01/08/2026, 9:00:00 AM] Fixture Crew: {LRM}{CONTACT_NAME} created group {LDQ}Fixture Crew{RDQ}"), format!("{LRM}[01/08/2026, 9:01:00 AM] {CONTACT_NAME}:"), format!("{LRM}[01/08/2026, 9:01:00 AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[01/08/2026, 9:01:01 AM] {CONTACT_NAME}: {LRM}"), format!("{LRM}[01/08/2026, 9:02:00 AM] {GROUP_MEMBER_2}:"), format!("{LRM}[01/08/2026, 9:03:00 AM] {GROUP_MEMBER_2}: nice"), format!("{LRM}[01/08/2026, 9:04:00 AM] {OWNER_NAME}: thanks"), String::new(), ]) } /// Android puts an attachment's caption on the line AFTER the marker. Until /// 2026-09-05 the caption took the whole message down with it: the pattern was /// anchored to a single line, so a captioned attachment matched nothing, kept /// `IMG-… (file attached)` in its body and never entered the media plan. fn android_captioned_attachment_txt() -> String { joined(&[ "26/07/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("26/07/2025, 10:12 - {CONTACT_NAME}: IMG-20250726-WA0002.jpg (file attached)"), "both from the yard".to_string(), format!("26/07/2025, 10:13 - {CONTACT_NAME}: IMG-20250726-WA0003.jpg (file attached)"), format!("26/07/2025, 10:14 - {OWNER_NAME}: got them"), String::new(), ]) } /// An Android album: three attachments in one minute from one sender, and NO /// container line — the Android exporter does not write one. The rule must be a /// no-op here, which is the only way to know it is reading a real signal rather /// than "a photo came after something". fn android_album_txt() -> String { joined(&[ "26/07/2025, 10:00 - Messages and calls are end-to-end encrypted. Tap to learn more." .to_string(), format!("26/07/2025, 10:12 - {CONTACT_NAME}: IMG-20250726-WA0004.jpg (file attached)"), format!("26/07/2025, 10:12 - {CONTACT_NAME}: IMG-20250726-WA0005.jpg (file attached)"), format!("26/07/2025, 10:12 - {CONTACT_NAME}: IMG-20250726-WA0006.jpg (file attached)"), format!("26/07/2025, 10:14 - {OWNER_NAME}: got them"), String::new(), ]) } /// A poll, as an iOS export renders one — the marker line, the question, and /// one line per option with its count, all inside a single message body. fn ios_poll_txt() -> String { joined(&[ format!("{LRM}[01/08/2026, 9:00:00 AM] Messages and calls are end-to-end encrypted. No one outside of this chat, not even WhatsApp, can read or listen to them."), format!("{LRM}[01/08/2026, 9:10:00 AM] {CONTACT_NAME}: {LRM}POLL:"), "Which day works for the site visit?".to_string(), format!("{LRM}OPTION: Thursday (3 votes)"), format!("{LRM}OPTION: Friday (1 vote)"), format!("{LRM}[01/08/2026, 9:11:00 AM] {OWNER_NAME}: Thursday for me"), String::new(), ]) } fn junk_txt() -> String { "this is not a whatsapp export\nat all\n".to_string() } fn album_far_txt() -> String { joined(&[ "26/07/2025, 10:12 - Anita Rao:".to_string(), "26/07/2025, 10:19 - Anita Rao: IMG-20250726-WA0009.jpg (file attached)".to_string(), String::new(), ]) } fn album_other_sender_txt() -> String { joined(&[ "26/07/2025, 10:12 - Anita Rao:".to_string(), "26/07/2025, 10:12 - Ravi Kumar: IMG-20250726-WA0009.jpg (file attached)".to_string(), String::new(), ]) } /// A year-first export written with dots — the separator class is `[/.-]` on /// both sides. fn ymd_dots_txt() -> String { joined(&[ "2025.07.26, 10:12 - Milo Example: hello".to_string(), "2025.07.27, 10:13 - Anita Rao: hi".to_string(), String::new(), ]) } /// The 12-hour clock at both of its hinges, plus the two spellings of the /// meridiem the pattern admits (`p.m.` and a spaced `P M`). fn meridiem_edges_txt() -> String { joined(&[ "[26/07/2025, 12:00:00 AM] Milo Example: midnight".to_string(), "[26/07/2025, 12:30:00 PM] Anita Rao: noon-ish".to_string(), "[26/07/2025, 1:05:00 p.m.] Milo Example: afternoon".to_string(), "[26/07/2025, 11:59:59 P M] Anita Rao: almost midnight".to_string(), String::new(), ]) } /// CRLF line endings, which `normalize_export_text` folds before the split. fn crlf_continuation_txt() -> String { [ "26/07/2025, 10:12 - Milo Example: first", "still first", "", "26/07/2025, 10:13 - Anita Rao: second", "", ] .join("\r\n") } /// The two exotic dashes Android writes instead of a hyphen. fn em_dash_separator_txt() -> String { joined(&[ "26/07/2025, 10:12 \u{2014} Milo Example: hello".to_string(), "26/07/2025, 10:13 \u{2013} Anita Rao: hi".to_string(), String::new(), ]) } /// Every fixture this file builds, by the name the vector table gave it. fn fixtures() -> Vec<(&'static str, String)> { vec![ ("ios", ios_chat_txt()), ("android", android_chat_txt()), ("android_unsaved", android_unsaved_contact_txt()), ("android_system_colon", android_system_line_with_colon_txt()), ("android_group", android_group_txt()), ("ios_group", ios_group_txt()), ("android_mdy", android_mdy_txt()), ("android_ambiguous", android_ambiguous_date_txt()), ("android_truncated", android_truncated_txt()), ("ios_album", ios_album_txt()), ("ios_group_album", ios_group_album_txt()), ("android_captioned", android_captioned_attachment_txt()), ("android_album", android_album_txt()), ("ios_poll", ios_poll_txt()), ("junk", junk_txt()), ("empty", String::new()), ("album_far", album_far_txt()), ("album_other_sender", album_other_sender_txt()), ("ymd_dots", ymd_dots_txt()), ("meridiem_edges", meridiem_edges_txt()), ("crlf_continuation", crlf_continuation_txt()), ("em_dash_separator", em_dash_separator_txt()), ] } /// `DEFAULT_CHAT_TXT_OPTIONS` — the IST default the TypeScript's tests use. fn ist() -> ChatTxtOptions { ChatTxtOptions::default() } fn parse(input: &str) -> ChatTxtParseResult { parse_chat_txt(input, &ist()).expect("a parse") } // ── parseChatTxt — iOS dialect ─────────────────────────────────────────────── #[test] fn reads_every_message_and_skips_the_system_lines() { // 9 message lines, 1 encryption notice. let result = parse(&ios_chat_txt()); assert_eq!(result.messages.len(), 8); assert_eq!(result.system_lines, 1); assert_eq!(result.unparsed_lines, 0); } #[test] fn survives_the_invisible_bidi_scaffolding_on_every_line() { let result = parse(&ios_chat_txt()); assert_eq!(result.messages[0].sender, OWNER_NAME); assert_eq!( result.messages[0].body, "Hey, are we still on for tomorrow?" ); } #[test] fn joins_a_multiline_body_instead_of_dropping_the_continuation() { let result = parse(&ios_chat_txt()); assert_eq!(result.messages[1].body, "yes!\nBringing the drive too."); } /// 10:15:00 AM IST → 04:45 UTC. A failure here means the line did not match the /// header regex and got swallowed as a continuation. #[test] fn reads_the_narrow_no_break_space_before_am_pm() { let result = parse(&ios_chat_txt()); assert_eq!(result.messages[2].sent_at, "2025-07-26T04:45:00.000Z"); } #[test] fn extracts_an_ios_attachment_marker() { let result = parse(&ios_chat_txt()); assert_eq!( result.messages[2].attachment, Some(TxtAttachment { filename: Some("00000042-PHOTO-2025-07-26-10-15-00.jpg".to_string()), omitted: false, label: "".to_string(), }) ); assert_eq!(result.messages[2].body, ""); } #[test] fn strips_the_edited_marker_and_records_the_flag() { let result = parse(&ios_chat_txt()); assert!(result.messages[3].edited); assert_eq!(result.messages[3].body, "perfect"); } #[test] fn records_omitted_media_as_an_attachment_that_is_not_present() { let result = parse(&ios_chat_txt()); let attachment = result.messages[4].attachment.as_ref().expect("an omission"); assert_eq!(attachment.filename, None); assert!(attachment.omitted); } #[test] fn keeps_rtl_content_while_dropping_its_isolate_marks() { let result = parse(&ios_chat_txt()); assert_eq!(result.messages[5].body, "شكرا thanks"); } #[test] fn applies_the_12_hour_clock_correctly() { let result = parse(&ios_chat_txt()); assert_eq!(result.messages[0].sent_at_local, "2025-07-26T10:12:45"); } #[test] fn sees_the_encryption_notice() { assert!(parse(&ios_chat_txt()).starts_with_encryption_notice); } #[test] fn infers_day_first_from_the_corpus() { let result = parse(&ios_chat_txt()); assert_eq!(result.date_order, DateOrder::Dmy); assert!(result.date_order_inferred); } // ── parseChatTxt — Android dialect ─────────────────────────────────────────── #[test] fn reads_the_dashed_header_with_a_24_hour_clock_and_no_seconds() { let result = parse(&android_chat_txt()); assert_eq!(result.messages[0].sender, OWNER_NAME); assert_eq!(result.messages[0].sent_at, "2025-07-26T04:42:00.000Z"); } #[test] fn extracts_an_android_attachment_marker() { let result = parse(&android_chat_txt()); let attached = result .messages .iter() .find(|message| { message .attachment .as_ref() .is_some_and(|attachment| attachment.filename.is_some()) }) .expect("an attachment"); let attachment = attached.attachment.as_ref().expect("an attachment"); assert_eq!( attachment.filename.as_deref(), Some("IMG-20250726-WA0001.jpg") ); assert!(!attachment.omitted); } #[test] fn treats_media_omitted_as_an_absent_file() { let result = parse(&android_chat_txt()); assert!(result.messages.iter().any(|message| message .attachment .as_ref() .is_some_and(|attachment| attachment.omitted))); } #[test] fn skips_the_security_code_system_line() { let result = parse(&android_chat_txt()); assert_eq!(result.system_lines, 2); assert!(result .messages .iter() .all(|message| !message.body.contains("security code"))); } #[test] fn marks_a_deleted_message_rather_than_importing_the_placeholder_as_text() { let result = parse(&android_chat_txt()); assert!(result.messages.last().expect("a message").deleted); } #[test] fn counts_both_participants() { let result = parse(&android_chat_txt()); let mut names: Vec<&str> = result .sender_counts .iter() .map(|entry| entry.name.as_str()) .collect(); names.sort_unstable(); assert_eq!(names, vec![CONTACT_NAME, OWNER_NAME]); } // ── classifyRemainder ──────────────────────────────────────────────────────── #[test] fn splits_a_normal_message_on_the_first_colon_space() { assert_eq!( classify_remainder("Anita Rao: hello"), Classified::Message { sender: "Anita Rao".to_string(), body: "hello".to_string() } ); } #[test] fn does_not_split_on_a_colon_inside_a_url() { assert_eq!( classify_remainder("Anita Rao: https://example.com/x"), Classified::Message { sender: "Anita Rao".to_string(), body: "https://example.com/x".to_string() } ); } #[test] fn treats_a_colon_free_line_as_a_system_line() { assert!(matches!( classify_remainder("Messages and calls are end-to-end encrypted."), Classified::System { .. } )); } #[test] fn refuses_to_invent_a_sender_out_of_a_group_event_line_containing_a_colon() { assert!(matches!( classify_remainder("Milo Example created group \"Trip: Goa\""), Classified::System { .. } )); } #[test] fn rejects_an_implausibly_long_sender() { assert!(matches!( classify_remainder(&format!("{}: body", "x".repeat(80))), Classified::System { .. } )); } #[test] fn handles_an_empty_body_after_the_colon() { assert_eq!( classify_remainder("Anita Rao:"), Classified::Message { sender: "Anita Rao".to_string(), body: String::new() } ); } // ── parseChatTxt — adversarial system lines ────────────────────────────────── #[test] fn does_not_turn_a_colon_bearing_group_event_into_a_message() { let result = parse(&android_system_line_with_colon_txt()); assert_eq!(result.messages.len(), 2); let mut names: Vec<&str> = result .sender_counts .iter() .map(|entry| entry.name.as_str()) .collect(); names.sort_unstable(); assert_eq!(names, vec![CONTACT_NAME, OWNER_NAME]); } // ── parseChatTxt — dates ───────────────────────────────────────────────────── #[test] fn infers_month_first_when_the_second_component_exceeds_12() { let result = parse(&android_mdy_txt()); assert_eq!(result.date_order, DateOrder::Mdy); assert_eq!(&result.messages[0].sent_at_local[..10], "2025-07-26"); } #[test] fn says_so_when_the_corpus_proves_nothing_and_falls_back_to_day_first() { let result = parse(&android_ambiguous_date_txt()); assert!(!result.date_order_inferred); assert_eq!(result.date_order, DateOrder::Dmy); assert!(result.warnings.join(" ").contains("could not be inferred")); } #[test] fn honours_an_explicit_date_order_over_inference() { let options = ChatTxtOptions { date_order: DateOrderSetting::Mdy, ..ChatTxtOptions::default() }; let result = parse_chat_txt(&android_ambiguous_date_txt(), &options).expect("a parse"); assert_eq!(&result.messages[0].sent_at_local[..10], "2025-03-04"); } #[test] fn applies_the_timezone_offset_the_operator_states() { let options = ChatTxtOptions { tz_offset: "Z".to_string(), ..ChatTxtOptions::default() }; let result = parse_chat_txt(&android_chat_txt(), &options).expect("a parse"); assert_eq!(result.messages[0].sent_at, "2025-07-26T10:12:00.000Z"); } // ── inferDateOrder ─────────────────────────────────────────────────────────── fn date(a: i64, b: i64, c: i64) -> HeaderDate { HeaderDate { a, b, c } } #[test] fn returns_none_when_every_date_fits_both_readings() { assert_eq!(infer_date_order(&[date(3, 4, 2025)]), None); } #[test] fn picks_ymd_when_the_leading_component_cannot_be_a_day() { assert_eq!(infer_date_order(&[date(2025, 7, 26)]), Some(DateOrder::Ymd)); } #[test] fn picks_dmy_on_a_day_above_12() { assert_eq!(infer_date_order(&[date(26, 7, 2025)]), Some(DateOrder::Dmy)); } #[test] fn picks_mdy_when_the_second_component_is_above_12() { assert_eq!(infer_date_order(&[date(7, 26, 2025)]), Some(DateOrder::Mdy)); } // ── localToInstant ─────────────────────────────────────────────────────────── fn parts(y: i64, m: i64, d: i64, hh: i64, mm: i64, ss: i64) -> LocalParts { LocalParts { y, m, d, hh, mm, ss, } } #[test] fn rejects_an_impossible_calendar_date_instead_of_rolling_it_into_next_month() { assert_eq!(local_to_instant(parts(2025, 2, 31, 10, 0, 0), 330), None); } #[test] fn converts_with_the_offset_applied() { assert_eq!( local_to_instant(parts(2025, 7, 26, 10, 12, 45), 330).as_deref(), Some("2025-07-26T04:42:45.000Z") ); } // ── offsetMinutes ──────────────────────────────────────────────────────────── #[test] fn parses_each_well_formed_offset() { assert_eq!(offset_minutes("+05:30"), Ok(330)); assert_eq!(offset_minutes("-08:00"), Ok(-480)); assert_eq!(offset_minutes("Z"), Ok(0)); } #[test] fn refuses_a_malformed_offset_rather_than_silently_using_utc() { let error = offset_minutes("+0530").expect_err("a refusal"); assert!(error.to_string().starts_with("Bad --tz-offset"), "{error}"); } // ── an export that does not start at the beginning ─────────────────────────── /// Ruling 2026-08-27: the missing notice is a FACT and nothing more. A chat /// that began on an old phone looks exactly like a trimmed export, and the /// user-facing warning read as an accusation on good imports. #[test] fn records_the_missing_notice_as_a_fact_and_warns_nobody() { let result = parse(&android_truncated_txt()); assert!(!result.starts_with_encryption_notice); assert!(!result.warnings.join(" ").contains("truncated")); } // ── unsaved contact ────────────────────────────────────────────────────────── #[test] fn keeps_the_counterpartys_number_as_the_sender_when_they_are_not_saved() { let result = parse(&android_unsaved_contact_txt()); assert!(result .sender_counts .iter() .any(|entry| entry.name == "+91 98765 43210")); } // ── junk input ─────────────────────────────────────────────────────────────── #[test] fn counts_unparsable_leading_lines_rather_than_crashing() { let result = parse(&junk_txt()); assert!(result.messages.is_empty()); assert_eq!(result.unparsed_lines, 2); assert!(result .warnings .join(" ") .contains("probably not a WhatsApp export")); } #[test] fn returns_an_empty_result_for_an_empty_file() { let result = parse(""); assert!(result.messages.is_empty()); assert!(result.warnings.is_empty()); } // ── attributed encryption notice (group exports) ───────────────────────────── /// Group exports attribute the notice to the group name, which classifies as a /// message — the not-truncated signal must fire anyway. #[test] fn an_attributed_notice_still_counts_as_starting_at_the_beginning_of_the_chat() { assert!(parse(&ios_group_txt()).starts_with_encryption_notice); } // ── album containers ───────────────────────────────────────────────────────── #[test] fn marks_the_blank_line_that_an_albums_attachments_follow() { let parsed = parse(&ios_album_txt()); assert_eq!(parsed.album_containers, 2); let containers: Vec<&TxtMessage> = parsed .messages .iter() .filter(|message| message.album_container) .collect(); assert_eq!( containers .iter() .map(|message| message.sent_at.as_str()) .collect::>(), vec!["2026-08-01T03:31:00.000Z", "2026-08-01T03:35:00.000Z"] ); for container in containers { assert_eq!(container.body, ""); assert_eq!(container.attachment, None); assert_eq!(container.sender, CONTACT_NAME); } } #[test] fn leaves_a_blank_line_that_no_attachment_follows_alone() { let parsed = parse(&ios_album_txt()); let lone = parsed .messages .iter() .find(|message| { message.sender == OWNER_NAME && message.body.is_empty() && message.attachment.is_none() }) .expect("the lone blank"); assert!(!lone.album_container); } #[test] fn keeps_a_caption_that_sits_beside_the_albums_marker() { let parsed = parse(&ios_album_txt()); let captioned: Vec<&TxtMessage> = parsed .messages .iter() .filter(|message| message.body == "both from the yard") .collect(); assert_eq!(captioned.len(), 1); assert_eq!( captioned[0] .attachment .as_ref() .and_then(|attachment| attachment.filename.as_deref()), Some("00000102-PHOTO-2026-08-01-09-01-01.jpg") ); } #[test] fn does_not_mark_a_blank_whose_attachment_is_minutes_away() { let parsed = parse(&album_far_txt()); assert_eq!(parsed.album_containers, 0); assert!(!parsed.messages[0].album_container); } #[test] fn does_not_mark_a_blank_whose_next_attachment_is_somebody_elses() { assert_eq!(parse(&album_other_sender_txt()).album_containers, 0); } #[test] fn is_a_no_op_on_an_android_album_which_writes_no_container_line() { let parsed = parse(&android_album_txt()); assert_eq!(parsed.album_containers, 0); assert_eq!( parsed .messages .iter() .filter(|message| message.attachment.is_some()) .count(), 3 ); } // ── Android attachment captions ────────────────────────────────────────────── #[test] fn keeps_the_caption_and_the_attachment() { let parsed = parse(&android_captioned_attachment_txt()); assert_eq!( parsed.messages[0].attachment, Some(TxtAttachment { filename: Some("IMG-20250726-WA0002.jpg".to_string()), omitted: false, label: "IMG-20250726-WA0002.jpg (file attached)".to_string(), }) ); assert_eq!(parsed.messages[0].body, "both from the yard"); } #[test] fn still_reads_a_caption_less_attachment_as_an_empty_body() { let parsed = parse(&android_captioned_attachment_txt()); assert_eq!(parsed.messages[1].body, ""); assert_eq!( parsed.messages[1] .attachment .as_ref() .and_then(|attachment| attachment.filename.as_deref()), Some("IMG-20250726-WA0003.jpg") ); } // ── the Node vector table ──────────────────────────────────────────────────── #[derive(Deserialize)] struct ClassifyVector { remainder: String, result: Classified, } #[derive(Deserialize)] struct DecorateVector { raw: String, result: DecoratedBody, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct InstantVector { parts: LocalParts, tz_offset_minutes: i64, result: Option, } #[derive(Deserialize)] struct WallClockVector { parts: LocalParts, result: String, } #[derive(Deserialize)] struct OffsetVector { input: String, minutes: Option, error: Option, } #[derive(Deserialize)] struct InferVector { headers: Vec, result: Option, } #[derive(Deserialize)] struct AlbumVector { messages: Vec, marked: i64, after: Vec, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct Vectors { chat_txt_inputs: HashMap, chat_txt_parses: HashMap, classify_remainder: Vec, decorate_body: Vec, local_to_instant: Vec, local_wall_clock: Vec, offset_minutes: Vec, infer_date_order: Vec, mark_album_containers: Vec, } fn vectors() -> Vectors { serde_json::from_str(include_str!("../../../tests/fixtures/import_adapters.json")) .expect("import_adapters.json") } /// The reconstruction guard. Every fixture above is rebuilt from code points; /// this compares each to the TypeScript's own text, so a mistyped invisible /// character fails HERE with the fixture's name rather than surfacing as an /// inexplicable parse difference twenty tests later. #[test] fn every_fixture_matches_the_typescripts_own_text() { let table = vectors().chat_txt_inputs; for (name, built) in fixtures() { let expected = table .get(name) .unwrap_or_else(|| panic!("the vector table has no fixture named {name}")); assert_eq!(&built, expected, "fixture {name}"); } } /// The whole parse result, field for field, for every fixture — including the /// three that are parsed with non-default options. #[test] fn every_fixture_parses_the_way_the_typescript_parsed_it() { let table = vectors(); let mut cases: Vec<(String, String, ChatTxtOptions)> = fixtures() .into_iter() .map(|(name, input)| (name.to_string(), input, ist())) .collect(); cases.push(( "android_utc".to_string(), android_chat_txt(), ChatTxtOptions { tz_offset: "Z".to_string(), ..ChatTxtOptions::default() }, )); cases.push(( "android_ambiguous_mdy".to_string(), android_ambiguous_date_txt(), ChatTxtOptions { date_order: DateOrderSetting::Mdy, ..ChatTxtOptions::default() }, )); // The one corpus that produces the impossible-date warning: an Android // day-first file read month-first, where `26` cannot be a month. cases.push(( "android_forced_mdy".to_string(), android_chat_txt(), ChatTxtOptions { date_order: DateOrderSetting::Mdy, ..ChatTxtOptions::default() }, )); assert!(cases.len() >= 25, "the table should not shrink"); for (name, input, options) in cases { let expected = table .chat_txt_parses .get(&name) .unwrap_or_else(|| panic!("no parse vector for {name}")); assert_eq!( &parse_chat_txt(&input, &options).expect("a parse"), expected, "parse of {name}" ); } } #[test] fn every_remainder_classifies_the_way_the_typescript_classified_it() { let table = vectors().classify_remainder; assert!(table.len() >= 16, "the table should not shrink"); for case in &table { assert_eq!( classify_remainder(&case.remainder), case.result, "{:?}", case.remainder ); } } #[test] fn every_body_decorates_the_way_the_typescript_decorated_it() { let table = vectors().decorate_body; assert!(table.len() >= 15, "the table should not shrink"); for case in &table { assert_eq!(decorate_body(&case.raw), case.result, "{:?}", case.raw); } } #[test] fn every_local_instant_matches_the_one_node_computed() { let table = vectors().local_to_instant; assert!(table.len() >= 14, "the table should not shrink"); for case in &table { assert_eq!( local_to_instant(case.parts, case.tz_offset_minutes), case.result, "{:?} @ {}", case.parts, case.tz_offset_minutes ); } } #[test] fn every_wall_clock_matches_the_one_node_printed() { let table = vectors().local_wall_clock; assert!(table.len() >= 5, "the table should not shrink"); for case in &table { assert_eq!( local_wall_clock(case.parts), case.result, "{:?}", case.parts ); } } /// Both halves: the minutes for a good offset, and the SENTENCE for a bad one — /// a handler prints that string, so it is API. #[test] fn every_offset_reads_or_refuses_the_way_the_typescript_did() { let table = vectors().offset_minutes; assert!(table.len() >= 13, "the table should not shrink"); for case in &table { match (&case.minutes, &case.error) { (Some(minutes), None) => { assert_eq!( offset_minutes(&case.input), Ok(*minutes), "{:?}", case.input ) } (None, Some(message)) => assert_eq!( offset_minutes(&case.input) .expect_err("a refusal") .to_string(), *message, "{:?}", case.input ), _ => panic!( "a vector row is neither a value nor an error: {:?}", case.input ), } } } #[test] fn every_corpus_infers_the_order_the_typescript_inferred() { let table = vectors().infer_date_order; assert!(table.len() >= 9, "the table should not shrink"); for case in &table { assert_eq!( infer_date_order(&case.headers), case.result, "{:?}", case.headers ); } } #[test] fn every_album_case_marks_what_the_typescript_marked() { let table = vectors().mark_album_containers; assert!(table.len() >= 7, "the table should not shrink"); for case in &table { let mut messages = case.messages.clone(); assert_eq!(mark_album_containers(&mut messages), case.marked); assert_eq!(messages, case.after); } }