1172 lines · 37.0 KB · RustRaw
//! ## Where the inputs and the expected values come from//!//! Every case in the TypeScript begins `parseChatTxt(FIXTURE, IST)` or//! `parseWceJson(WCE_SAMPLE)`, and neither adapter is ported yet. So the//! synthetic fixtures were parsed by the RUNNING TypeScript and their parse//! results captured into `tests/fixtures/import_parse.json`; the whole//! `NormalizeResult` of every invocation the test file makes was captured into//! `tests/fixtures/import_normalize.json`. The Rust reads the first as input//! and compares against the second.//!//! That is the strongest pinning available for this module: the goldens carry//! the real `txt2:` fingerprints, so a divergence in the occurrence counter,//! in whitespace collapsing, or in which line is dropped shows up as a//! different id rather than as a passing test. Every case below ALSO makes the//! TypeScript test's own assertion, because a whole-document comparison says//! "something moved" where the case says WHAT the rule is.//!//! Every fixture is SYNTHETIC — invented people, invented numbers, invented//! chat text.use super::*;use serde::Deserialize;use std::collections::BTreeMap;const OWNER_NAME: &str = "Milo Example";const CONTACT_NAME: &str = "Anita Rao";const CONTACT_PHONE: &str = "919876543210";const INCOMING_KEY_ID: &str = "3EB0A1B2C3D4E5F60718";const REPLY_KEY_ID: &str = "3EB0F9E8D7C6B5A43210";const THUMBS_UP: &str = "\u{1f44d}";const HEART: &str = "\u{2764}";// ── the fixtures ─────────────────────────────────────────────────────────────#[derive(Deserialize)]struct Parses { #[serde(rename = "chatTxt")] chat_txt: BTreeMap<String, ChatTxtParseResult>, wce: BTreeMap<String, WceParseResult>,}fn parses() -> Parses { serde_json::from_str(include_str!("../../tests/fixtures/import_parse.json")) .expect("import_parse.json")}fn txt_parse(name: &str) -> ChatTxtParseResult { parses() .chat_txt .remove(name) .unwrap_or_else(|| panic!("no chat-txt parse fixture named {name}"))}fn wce_parse(name: &str) -> WceParseResult { parses() .wce .remove(name) .unwrap_or_else(|| panic!("no wce parse fixture named {name}"))}#[derive(Deserialize, Default, Clone)]#[serde(rename_all = "camelCase")]struct CaseOptions { #[serde(default)] country_code: Option<String>, #[serde(default)] owner_name: Option<String>, #[serde(default)] owner_may_silent: Option<bool>, #[serde(default)] contact_phone: Option<String>, #[serde(default)] contact_person_id: Option<String>, #[serde(default)] display_name: Option<String>, /// A JSON object, and `serde_json`'s `preserve_order` keeps it in the /// order the TypeScript wrote it — which is the order that decides which /// of two labels sharing a `name_key` wins. #[serde(default)] participants: Option<Map<String, Value>>, #[serde(default)] group_title: Option<String>, #[serde(default)] group_key: Option<String>,}impl CaseOptions { fn build(&self) -> NormalizeOptions { NormalizeOptions { country_code: self.country_code.clone(), owner_name: self.owner_name.clone(), owner_may_silent: self.owner_may_silent.unwrap_or(false), contact_phone: self.contact_phone.clone(), contact_person_id: self.contact_person_id.clone(), display_name: self.display_name.clone(), participants: self .participants .iter() .flat_map(|map| map.iter()) .map(|(label, value)| { ( label.clone(), serde_json::from_value::<ParticipantHintValue>(value.clone()) .expect("a phone string or a hint object"), ) }) .collect(), group_title: self.group_title.clone(), group_key: self.group_key.clone(), } }}#[derive(Deserialize)]struct ErrorGolden { name: String, message: String,}#[derive(Deserialize)]struct Outcome { #[serde(default)] ok: Option<Value>, #[serde(default)] error: Option<ErrorGolden>,}#[derive(Deserialize)]struct TxtCase { name: String, source: String, options: CaseOptions, outcome: Outcome,}#[derive(Deserialize)]struct WceCase { name: String, outcome: Outcome,}#[derive(Deserialize)]struct ClassifyCase { name: String, source: String, owner: String, shape: ExportShape,}#[derive(Deserialize)]struct NormalizeGoldens { #[serde(rename = "chatTxt")] chat_txt: Vec<TxtCase>, wce: Vec<WceCase>, classify: Vec<ClassifyCase>,}fn goldens() -> NormalizeGoldens { serde_json::from_str(include_str!("../../tests/fixtures/import_normalize.json")) .expect("import_normalize.json")}fn txt_case(name: &str) -> (ChatTxtParseResult, NormalizeOptions) { let case = goldens() .chat_txt .into_iter() .find(|case| case.name == name) .unwrap_or_else(|| panic!("no normalize case named {name}")); (txt_parse(&case.source), case.options.build())}/// Run a captured case and hand back what the TypeScript's own test would hold.fn run_txt(name: &str) -> NormalizeResult { let (parsed, options) = txt_case(name); normalize_chat_txt(&parsed, &options) .unwrap_or_else(|err| panic!("{name} should not refuse: {err}"))}fn run_txt_err(name: &str) -> NormalizeError { let (parsed, options) = txt_case(name); normalize_chat_txt(&parsed, &options).expect_err("should refuse")}fn run_wce(name: &str) -> NormalizeResult { normalize_wce(&wce_parse(name), &NormalizeOptions::default()).expect("should normalize")}// ── the whole-document goldens ───────────────────────────────────────────────/// Every invocation the TypeScript test file makes, compared as a WHOLE/// document: chats, messages (fingerprints included), the report, the media/// manifest, the warnings and the limitations.#[test]fn every_captured_normalization_matches_the_typescript_byte_for_byte() { let goldens = goldens(); assert!(goldens.chat_txt.len() >= 23, "the table should not shrink"); for case in &goldens.chat_txt { let parsed = txt_parse(&case.source); let result = normalize_chat_txt(&parsed, &case.options.build()); match (&case.outcome.ok, &case.outcome.error) { (Some(expected), None) => { let actual = serde_json::to_value(result.expect("should normalize")).expect("serialises"); assert_eq!(&actual, expected, "{}", case.name); } (None, Some(expected)) => { let error = result.expect_err("should refuse"); assert_eq!(error.to_string(), expected.message, "{}", case.name); assert_eq!( error_name(&error), expected.name, "{} — the refusal's class", case.name ); } _ => panic!("{}: a case is one outcome or the other", case.name), } }}/// The TypeScript's `Error` subclass names, so a handler that branches on them/// keeps branching. Rust spells them as variants; this is the bridge.fn error_name(error: &NormalizeError) -> &'static str { match error { NormalizeError::OwnerNameNotFound { .. } => "OwnerNameNotFoundError", NormalizeError::OwnerNameRequired => "OwnerNameRequiredError", NormalizeError::GroupTitleRequired => "GroupTitleRequiredError", NormalizeError::Fingerprint(_) => "Error", }}#[test]fn every_captured_wce_normalization_matches_the_typescript_byte_for_byte() { for case in &goldens().wce { let parsed = wce_parse(&case.name); let actual = serde_json::to_value( normalize_wce(&parsed, &NormalizeOptions::default()).expect("should normalize"), ) .expect("serialises"); assert_eq!( &actual, case.outcome.ok.as_ref().expect("wce never refuses"), "{}", case.name ); }}#[test]fn every_captured_classification_matches_the_typescript() { for case in &goldens().classify { let parsed = txt_parse(&case.source); assert_eq!( classify_export(&parsed, &case.owner), case.shape, "{}", case.name ); }}// ── normalizeWce ─────────────────────────────────────────────────────────────fn wce_chat() -> NormalizedChat { run_wce("sample").chats.into_iter().next().expect("a chat")}#[test]fn wce_produces_a_section_eight_conformant_envelope() { let chat = wce_chat(); assert_eq!( crate::import::envelope::validate_import_batch(&serde_json::json!({ "workspaceId": "3f2504e0-4f89-11d3-9a0c-0305e82c3301", "channel": "whatsapp", "messages": serde_json::to_value(&chat.messages).expect("serialises"), })), Vec::<String>::new() );}#[test]fn wce_carries_the_contact_phone_and_display_name() { let chat = wce_chat(); assert_eq!(chat.phone.as_deref(), Some(CONTACT_PHONE)); assert_eq!(chat.messages[0].phone.as_deref(), Some(CONTACT_PHONE)); assert_eq!(chat.messages[0].display_name.as_deref(), Some("Anita Rao"));}#[test]fn wce_drops_system_rows_from_the_envelope_but_counts_them() { let chat = wce_chat(); assert_eq!(chat.messages.len(), 4); assert_eq!(chat.report.system_skipped, 1);}#[test]fn wce_uses_the_whatsapp_key_id_as_external_id_not_a_row_id() { let chat = wce_chat(); assert!(chat .messages .iter() .any(|message| message.external_id == INCOMING_KEY_ID)); assert!(chat .messages .iter() .all(|message| !message.external_id.starts_with("txt2:")));}#[test]fn wce_maps_direction_from_from_me() { let chat = wce_chat(); assert_eq!(chat.report.inbound, 2); assert_eq!(chat.report.outbound, 2);}#[test]fn wce_carries_reply_to_external_id_straight_through() { let chat = wce_chat(); let reply = chat .messages .iter() .find(|message| message.external_id == REPLY_KEY_ID) .expect("the reply"); assert_eq!(reply.reply_to_external_id.as_deref(), Some(INCOMING_KEY_ID));}#[test]fn wce_counts_a_reply_whose_quoted_message_is_not_in_this_import() { let chat = wce_chat(); assert_eq!(chat.report.reply_refs, 2); assert_eq!(chat.report.unresolved_reply_refs, 1);}#[test]fn wce_resolves_the_owners_own_reaction_to_owner_and_the_contacts_to_their_phone() { let chat = wce_chat(); let incoming = chat .messages .iter() .find(|message| message.external_id == INCOMING_KEY_ID) .expect("the incoming message"); assert_eq!( incoming.reactions.as_deref(), Some( [crate::import::envelope::EnvelopeReaction { emoji: THUMBS_UP.to_string(), actor: "owner".to_string(), at: None, }] .as_slice() ) ); let reply = chat .messages .iter() .find(|message| message.external_id == REPLY_KEY_ID) .expect("the reply"); assert_eq!( reply.reactions.as_deref(), Some( [crate::import::envelope::EnvelopeReaction { emoji: HEART.to_string(), actor: CONTACT_PHONE.to_string(), at: None, }] .as_slice() ) ); assert_eq!(chat.report.reactions, 2);}#[test]fn wce_describes_an_attachment_in_meta_and_never_populates_media() { let chat = wce_chat(); let media = chat .messages .iter() .find(|message| { message .meta .as_ref() .is_some_and(|meta| meta.contains_key("attachment")) }) .expect("the media message"); assert!(media.media.is_none()); assert_eq!( media.meta.as_ref().expect("meta")["attachment"], serde_json::json!({ "omitted": false, "name": "WhatsApp/Media/WhatsApp Images/IMG-20260814-WA0001.jpg", "mime": "image/jpeg", }) ); assert_eq!(media.body, "the drive");}#[test]fn wce_stamps_provenance_into_meta() { let chat = wce_chat(); assert_eq!( chat.messages[0].meta.as_ref().expect("meta")["source"], Value::String(WCE_SOURCE.to_string()) );}#[test]fn wce_collects_a_media_manifest_entry_per_attachment() { let result = run_wce("sample"); assert_eq!(result.media.len(), 1); assert_eq!(result.media[0].phone.as_deref(), Some(CONTACT_PHONE)); assert!(!result.media[0].omitted);}#[test]fn wce_reports_the_date_span() { let chat = wce_chat(); assert_eq!( chat.report.first_sent_at.as_deref(), Some("2025-08-14T12:00:00.000Z") ); assert_eq!( chat.report.last_sent_at.as_deref(), Some("2025-08-14T12:15:00.000Z") );}#[test]fn wce_names_what_this_source_cannot_carry() { assert!(run_wce("sample") .limitations .join(" ") .contains("iOS backup"));}#[test]fn wce_passes_the_group_and_lid_skips_through_to_the_report() { let result = run_wce("sample"); let reasons: String = result .skipped_chats .iter() .map(|skipped| skipped.reason.clone()) .collect::<Vec<_>>() .join(" "); assert!(reasons.contains("group"), "{reasons}"); assert!(reasons.contains("no phone number"), "{reasons}");}#[test]fn wce_warns_when_a_message_had_no_key_id_and_had_to_be_hashed() { let hashed = run_wce("hashed"); assert!(hashed.chats[0].messages[0].external_id.starts_with("txt2:")); assert!(hashed.warnings.join(" ").contains("no key_id"));}/// The counter answers "which of the identical same-minute texts is this", and/// only a message with no id of its own ever asks. A backup carries real ids/// for most rows and none for a few, so advancing the sequence for an/// id-carrying row would quietly re-hash the id-less ones beside it — the same/// message, a new id, a second copy on the next import.#[test]fn a_message_that_has_a_key_id_leaves_the_occurrence_counter_alone() { let with_keyed = run_wce("with_keyed"); let without_keyed = run_wce("without_keyed"); let with: Vec<&str> = with_keyed.chats[0] .messages .iter() .skip(1) .map(|message| message.external_id.as_str()) .collect(); let without: Vec<&str> = without_keyed.chats[0] .messages .iter() .map(|message| message.external_id.as_str()) .collect(); assert_eq!(with, without);}// ── normalizeChatTxt — direction and identity ────────────────────────────────#[test]fn requires_owner_name_because_the_export_names_senders_instead_of_sides() { assert_eq!(run_txt_err("no_owner"), NormalizeError::OwnerNameRequired);}#[test]fn names_the_senders_it_did_find_when_owner_name_matches_nobody() { let error = run_txt_err("wrong_owner"); assert!(matches!(error, NormalizeError::OwnerNameNotFound { .. })); let message = error.to_string(); assert!(message.contains(OWNER_NAME), "{message}"); assert!(message.contains(CONTACT_NAME), "{message}");}#[test]fn marks_the_owners_messages_outgoing_and_everything_else_incoming() { let result = run_txt("owner_phone"); assert_eq!(result.chats[0].report.outbound, 2); assert_eq!(result.chats[0].report.inbound, 4);}#[test]fn matches_owner_name_case_and_whitespace_insensitively() { assert_eq!(run_txt("owner_sloppy").chats[0].report.outbound, 2);}#[test]fn takes_the_number_from_the_export_when_the_contact_was_not_saved() { assert_eq!( run_txt("unsaved").chats[0].phone.as_deref(), Some("919876543210") );}#[test]fn imports_against_a_saved_name_with_no_number_the_person_is_identified_later() { let result = run_txt("name_only"); let chat = &result.chats[0]; assert_eq!(chat.phone, None); assert_eq!( chat.counterpart, Some(crate::import::envelope::EnvelopeCounterpart { label: CONTACT_NAME.to_string(), email: None, phone: None, person_id: None, handle: None, }) ); assert_eq!(chat.messages.len(), 6); assert!(chat.messages.iter().all(|message| message.phone.is_none())); assert!(chat .messages .iter() .all(|message| message.display_name.as_deref() == Some(CONTACT_NAME))); assert!(!result.warnings.join(" ").contains("--phone"));}#[test]fn carries_a_known_person_through_to_the_counterpart() { assert_eq!( run_txt("known_person").chats[0].counterpart, Some(crate::import::envelope::EnvelopeCounterpart { label: CONTACT_NAME.to_string(), email: None, phone: Some("919876543210".to_string()), person_id: Some("person-1".to_string()), handle: None, }) );}#[test]fn accepts_an_owner_who_never_spoke_when_told_the_name_came_from_memory() { let silent = run_txt("silent_owner"); assert_eq!(silent.chats[0].kind, "group"); assert_eq!(silent.chats[0].report.outbound, 0); assert_eq!( silent.chats[0] .participants .iter() .map(|p| p.label.as_str()) .collect::<Vec<_>>(), [OWNER_NAME, CONTACT_NAME, "Ravi Kumar"] ); assert!(matches!( run_txt_err("silent_owner_refused"), NormalizeError::OwnerNameNotFound { .. } ));}#[test]fn drops_the_encryption_notice_ios_attributes_to_the_other_person() { let result = run_txt("attributed_notice"); assert_eq!( result.chats[0] .messages .iter() .map(|message| message.body.as_str()) .collect::<Vec<_>>(), ["hello", "hi"] ); assert_eq!(result.chats[0].report.system_skipped, 1);}// ── normalizeChatTxt — envelope ──────────────────────────────────────────────#[test]fn txt_hashes_every_external_id_since_the_format_has_none() { assert!(run_txt("ios_full").chats[0] .messages .iter() .all(|message| message.external_id.starts_with("txt2:")));}#[test]fn gives_two_identical_same_minute_messages_distinct_ids() { let result = run_txt("ios_full"); let ids: Vec<&str> = result.chats[0] .messages .iter() .map(|message| message.external_id.as_str()) .collect(); let distinct: std::collections::HashSet<&&str> = ids.iter().collect(); assert_eq!(distinct.len(), ids.len());}#[test]fn is_deterministic_across_runs() { let first = run_txt("ios_full"); let again = run_txt("ios_full"); assert_eq!( first.chats[0] .messages .iter() .map(|m| m.external_id.clone()) .collect::<Vec<_>>(), again.chats[0] .messages .iter() .map(|m| m.external_id.clone()) .collect::<Vec<_>>() );}#[test]fn carries_edited_and_deleted_as_descriptive_meta() { let result = run_txt("ios_full"); assert!(result.chats[0].messages.iter().any(|message| { message .meta .as_ref() .is_some_and(|meta| meta.get("edited") == Some(&Value::Bool(true))) })); assert_eq!( result.chats[0].messages[0].meta.as_ref().expect("meta")["source"], Value::String(TXT_SOURCE.to_string()) );}#[test]fn never_sets_reply_refs_or_reactions_the_format_has_neither() { let result = run_txt("ios_full"); assert_eq!(result.chats[0].report.reply_refs, 0); assert_eq!(result.chats[0].report.reactions, 0); assert!(result.limitations.join(" ").contains("reply relations")); assert!(result.limitations.join(" ").contains("reactions"));}#[test]fn counts_attachments_including_the_one_whose_file_is_absent() { let result = run_txt("ios_full"); assert_eq!(result.chats[0].report.attachments, 2); assert_eq!(result.chats[0].report.omitted_media, 1);}/// `{name: null, …}` was the shape that blanked a chat screen: the reader/// refused it until 2026-08-27, and every such row already written is forever./// New rows carry keys only where there is a value.#[test]fn an_omitted_attachment_writes_only_the_flag_never_a_null_name_or_mime() { let result = run_txt("ios_full"); let omitted = result.chats[0] .messages .iter() .find(|message| { message.meta.as_ref().is_some_and(|meta| { meta.get("attachment") .and_then(Value::as_object) .is_some_and(|attachment| attachment.get("omitted") == Some(&Value::Bool(true))) }) }) .expect("the omitted attachment"); assert_eq!( omitted.meta.as_ref().expect("meta")["attachment"], serde_json::json!({ "omitted": true }) );}// ── country codes ────────────────────────────────────────────────────────────#[test]fn warns_when_a_number_will_not_match_an_app_sign_in() { let result = run_txt("national"); assert_eq!(result.chats[0].phone.as_deref(), Some("09876543210")); assert!(result.chats[0] .report .warnings .join(" ") .contains("no country code"));}#[test]fn promotes_the_number_when_the_operator_states_the_country() { let result = run_txt("promoted"); assert_eq!(result.chats[0].phone.as_deref(), Some("919876543210")); assert!(!result.chats[0] .report .warnings .join(" ") .contains("no country code"));}// ── groups ───────────────────────────────────────────────────────────────────fn participant( label: &str, phone: Option<&str>, person: Option<&str>,) -> EnvelopeThreadParticipant { EnvelopeThreadParticipant { label: label.to_string(), email: None, phone: phone.map(str::to_string), person_id: person.map(str::to_string), handle: None, }}#[test]fn imports_a_group_with_no_mapping_at_all_every_sender_seated_none_identified() { let result = run_txt("group_unmapped"); let chat = &result.chats[0]; assert_eq!(chat.kind, "group"); assert_eq!( chat.participants, vec![ participant(CONTACT_NAME, None, None), participant("Ravi Kumar", None, None), ] ); assert_eq!( chat.report.participants.as_ref().expect("a roster"), &vec![ ReportParticipant { display_name: CONTACT_NAME.to_string(), phone: None, identified: false, }, ReportParticipant { display_name: "Ravi Kumar".to_string(), phone: None, identified: false, }, ] ); let inbound: Vec<Option<&str>> = chat .messages .iter() .filter(|message| message.direction == Direction::In) .map(|message| message.sender_label.as_deref()) .collect(); assert_eq!( inbound, [ Some(CONTACT_NAME), Some("Ravi Kumar"), Some(CONTACT_NAME), Some("Ravi Kumar") ] ); expect_valid_group_envelope(chat);}fn expect_valid_group_envelope(chat: &NormalizedChat) { let batch = serde_json::json!({ "workspaceId": "3f2504e0-4f89-11d3-9a0c-0305e82c3301", "channel": "whatsapp", "thread": { "kind": "group", "title": chat.title, "externalKey": chat.external_key, "participants": serde_json::to_value(&chat.participants).expect("serialises"), }, "messages": serde_json::to_value(&chat.messages).expect("serialises"), }); assert_eq!( crate::import::envelope::validate_import_batch(&batch), Vec::<String>::new() );}#[test]fn imports_a_mapped_group_thread_block_sender_labels_txt2_ids() { let result = run_txt("group_mapped"); assert_eq!(result.chats.len(), 1); let chat = &result.chats[0]; assert_eq!(chat.title.as_deref(), Some("Trip Planning")); assert_eq!(chat.external_key.as_deref(), Some("wa:group:trip-planning")); assert_eq!( chat.participants, vec![ participant(CONTACT_NAME, Some("919876543210"), None), participant("Ravi Kumar", Some("919999999999"), Some("person-ravi")), ] ); assert!(chat .messages .iter() .filter(|message| message.direction == Direction::In) .all(|message| message.sender_label.is_some())); assert!(chat .messages .iter() .all(|message| message.external_id.starts_with("txt2:"))); assert!(chat.messages.iter().all(|message| message.phone.is_none())); assert!(chat .messages .iter() .filter(|message| message.direction == Direction::Out) .all(|message| message.sender_label.is_none())); expect_valid_group_envelope(chat);}#[test]fn a_sender_missing_from_the_mapping_imports_unidentified_beside_the_identified() { assert_eq!( run_txt("group_partial").chats[0].participants, vec![ participant(CONTACT_NAME, Some("919876543210"), None), participant("Ravi Kumar", None, None), ] );}#[test]fn an_unusable_number_leaves_the_sender_unidentified_and_says_so() { let result = run_txt("group_unusable_number"); assert_eq!( result.chats[0].participants, vec![ participant(CONTACT_NAME, None, None), participant("Ravi Kumar", None, None), ] ); assert!(result.warnings.join(" ").contains("\"Ravi Kumar\""));}/// The whole point of a content fingerprint: identity is not in the material,/// so naming somebody moves no id.#[test]fn the_fingerprint_does_not_move_when_a_sender_is_identified() { let anonymous = run_txt("group_unmapped"); let mapped = run_txt("group_mapped_both"); assert_eq!( mapped.chats[0] .messages .iter() .map(|m| m.external_id.clone()) .collect::<Vec<_>>(), anonymous.chats[0] .messages .iter() .map(|m| m.external_id.clone()) .collect::<Vec<_>>() );}#[test]fn refuses_a_titleless_group_without_group_title() { assert_eq!( run_txt_err("group_no_title"), NormalizeError::GroupTitleRequired );}// ── classifyExport ───────────────────────────────────────────────────────────#[test]fn names_the_counterpart_of_a_dm() { assert_eq!( classify_export(&txt_parse("android"), OWNER_NAME), ExportShape::Dm { counterpart: Some(CONTACT_NAME.to_string()), strays: Vec::new(), } );}#[test]fn calls_an_export_with_two_real_others_a_group_senders_in_order_of_first_appearance() { match classify_export(&txt_parse("android_group"), OWNER_NAME) { ExportShape::Group { senders, .. } => { assert_eq!(senders, [CONTACT_NAME, "Ravi Kumar"]); } other => panic!("expected a group, got {other:?}"), }}#[test]fn calls_an_export_that_names_itself_a_group_even_with_one_other_speaker() { match classify_export(&txt_parse("named_two"), OWNER_NAME) { ExportShape::Group { senders, .. } => assert_eq!(senders, [CONTACT_NAME]), other => panic!("expected a group, got {other:?}"), }}// ── albums — the container line never becomes a message ──────────────────────#[test]fn drops_the_scaffolding_and_keeps_every_photo_dm_route() { let result = run_txt("album_dm"); let chat = &result.chats[0]; assert_eq!(chat.report.album_containers_dropped, 2); // 5 attachments + the lone blank + "nice". assert_eq!(chat.messages.len(), 7); assert_eq!( chat.messages .iter() .filter(|message| message .meta .as_ref() .is_some_and(|meta| meta.contains_key("attachment"))) .count(), 5 );}#[test]fn leaves_exactly_one_placeholder_the_blank_nothing_followed() { let result = run_txt("album_dm"); let placeholders: Vec<&EnvelopeMessage> = result.chats[0] .messages .iter() .filter(|message| message.body == UNSUPPORTED_MESSAGE_BODY) .collect(); assert_eq!(placeholders.len(), 1); assert_eq!(placeholders[0].direction, Direction::Out); assert_eq!(placeholders[0].sent_at, "2026-08-01T03:32:00.000Z");}/// The container is dropped but still walks the occurrence counter, so the/// first caption-less photo of the 09:01 album is occurrence 1 and not 0 —/// exactly the id a build that kept the container gave it. Without the ghost/// slot every already-imported album duplicates on the next import.#[test]fn keeps_the_albums_photos_on_the_ids_the_containers_slot_leaves_them() { use cotton_store::protocol::fingerprint::message::{ content_fingerprint, ContentFingerprintInput, }; let result = run_txt("album_dm"); let first = result.chats[0] .messages .iter() .find(|message| message.sent_at == "2026-08-01T03:31:00.000Z") .expect("the first album photo"); assert_eq!( first.external_id, content_fingerprint(&ContentFingerprintInput { sent_at: "2026-08-01T03:31:00.000Z", body: "", occurrence: 1, }) .expect("a fingerprint") ); // …and the three-photo album at 09:05, whose container also sits in the // same minute bucket as its photos. let album: Vec<&str> = result.chats[0] .messages .iter() .filter(|message| message.sent_at.starts_with("2026-08-01T03:35")) .map(|message| message.external_id.as_str()) .collect(); let expected: Vec<String> = [ ("2026-08-01T03:35:00.000Z", 1), ("2026-08-01T03:35:01.000Z", 2), ("2026-08-01T03:35:02.000Z", 3), ] .into_iter() .map(|(sent_at, occurrence)| { content_fingerprint(&ContentFingerprintInput { sent_at, body: "", occurrence, }) .expect("a fingerprint") }) .collect(); assert_eq!(album, expected);}#[test]fn drops_the_scaffolding_on_the_group_route_too() { let result = run_txt("album_group"); let chat = &result.chats[0]; assert_eq!(chat.kind, "group"); assert_eq!(chat.report.album_containers_dropped, 1); assert_eq!( chat.messages .iter() .filter(|message| message.body == UNSUPPORTED_MESSAGE_BODY) .count(), 1 ); assert_eq!( chat.messages .iter() .filter(|message| message .meta .as_ref() .is_some_and(|meta| meta.contains_key("attachment"))) .count(), 2 ); expect_valid_group_envelope(chat);}// ── Android captions on attachments ──────────────────────────────────────────#[test]fn imports_the_caption_as_the_body_and_the_file_as_the_attachment() { let result = run_txt("captioned"); let chat = &result.chats[0]; assert_eq!(chat.report.attachments, 2); assert_eq!(chat.messages[0].body, "both from the yard"); assert_eq!( chat.messages[0].meta.as_ref().expect("meta")["attachment"], serde_json::json!({ "omitted": false, "name": "IMG-20250726-WA0002.jpg" }) ); // The caption-less one still gets the placeholder body. assert_eq!( chat.messages[1].body, "[attachment: IMG-20250726-WA0003.jpg]" ); assert_eq!( result .media .iter() .map(|entry| entry.filename.as_deref()) .collect::<Vec<_>>(), [ Some("IMG-20250726-WA0002.jpg"), Some("IMG-20250726-WA0003.jpg") ] );}// ── polls — the reading beside the export's own words ────────────────────────#[test]fn puts_the_question_the_options_and_the_counts_on_meta_poll() { let result = run_txt("poll"); let poll = &result.chats[0].messages[0]; let reply = &result.chats[0].messages[1]; assert_eq!( poll.meta.as_ref().expect("meta")["poll"], serde_json::json!({ "question": "Which day works for the site visit?", "options": [ { "text": "Thursday", "votes": 3 }, { "text": "Friday", "votes": 1 }, ], }) ); assert!(!reply.meta.as_ref().expect("meta").contains_key("poll"));}/// The body is what the content fingerprint hashes. Re-wording a poll would/// give it a new identity and import every already-imported poll again.#[test]fn leaves_the_body_exactly_as_the_export_wrote_it() { use cotton_store::protocol::fingerprint::message::{ content_fingerprint, ContentFingerprintInput, }; let result = run_txt("poll"); let poll = &result.chats[0].messages[0]; assert_eq!( poll.body, [ "POLL:", "Which day works for the site visit?", "OPTION: Thursday (3 votes)", "OPTION: Friday (1 vote)", ] .join("\n") ); assert_eq!( poll.external_id, content_fingerprint(&ContentFingerprintInput { sent_at: &poll.sent_at, body: &poll.body, occurrence: 0, }) .expect("a fingerprint") );}// ── the small builders, pinned by Node vector ────────────────────────────────#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct PlaceholderAttachment { omitted: bool, filename: Option<String>, mime: Option<String>, #[serde(default)] label: Option<String>,}#[derive(Deserialize)]struct PlaceholderVector { attachment: PlaceholderAttachment, body: String, meta: Value,}#[derive(Deserialize)]struct Vectors { placeholders: Vec<PlaceholderVector>,}#[test]fn every_placeholder_body_and_attachment_meta_matches_the_typescript() { let vectors: Vectors = serde_json::from_str(include_str!("../../../cotton-rules/vectors/import.json")) .expect("cotton-rules/vectors/import.json"); assert!( vectors.placeholders.len() >= 8, "the table should not shrink" ); for case in &vectors.placeholders { let attachment = PreparedAttachment { filename: case.attachment.filename.clone(), mime: case.attachment.mime.clone(), omitted: case.attachment.omitted, label: case.attachment.label.clone(), }; assert_eq!( media_placeholder_body(&attachment), case.body, "{:?}", case.attachment.filename ); assert_eq!( Value::Object(attachment_meta(&attachment)), case.meta, "{:?}", case.attachment.filename ); }}/// The staging prefix a placeholder strips is `^\d+-`, which eats the FIRST/// digit run only — `12-34-56-file.pdf` reads as `34-56-file.pdf`. Read out of/// Node, not reasoned about.#[test]fn a_placeholder_strips_one_leading_number_run_not_every_one() { let attachment = PreparedAttachment { filename: Some("12-34-56-file.pdf".to_string()), ..PreparedAttachment::default() }; assert_eq!( media_placeholder_body(&attachment), "[attachment: 34-56-file.pdf]" );}// ── the constant this crate could not read from the store ───────────────────//// It can now, and there is nothing left to read it from.//// `UNSUPPORTED_MESSAGE_BODY` was declared in `packages/store`'s migration// ladder, and a test here read that file by path — its own note said to move// the constant into `cotton-store` the day the file was ported, and to move// the guard with it. Step 5i deleted the package instead, and the Rust ladder// has no phantom-row deletion to disagree with, so `normalize.rs`'s constant// is the declaration.//// ONE SECOND COPY SURVIVES AND NOTHING PINS IT: `cotton-server`'s// `messages/preview.rs` declares the same letters privately. Teaching the// server to read core's is a one-line change to product code, which is not// what a file move gets to decide — so it is written down here instead.