//! `packages/core/__tests__/messages/groupEvent.test.ts`, case for case.//!//! The neutral half of a group event: the sentence that goes in the BODY and is//! read in N files, none of which may be told "you". The per-viewer half lives in//! the app (`lib/messages/groupEventLine.ts`) and is tested there.//!//! Every number below is invented [nothing-real-ever-goes-in-cotton-s-public-tree].use serde_json::{json, Map, Value};usesuper::*;const ME: &str = "919876500001";const PRIYA: &str = "919876500002";const ASHA: &str = "919876500003";/// Named as the actor's own file would: `None` is the owner.fn name_for(phone: Option<&str>) -> Option<String> {match phone {None => Some("Meera".to_string()),Some(value) if value == ME => Some("Meera".to_string()),Some(value) if value == PRIYA => Some("Priya".to_string()),Some(value) if value == ASHA => Some("Asha".to_string()),Some(_) => None, }}fn nobody(_phone: Option<&str>) -> Option<String> {None}fn event(kind: GroupEventKind, actor: Option<&str>) -> GroupEvent {GroupEvent { kind, actor: actor.map(str::to_string), subjects: None, title: None, }}fn with_subjects(mut event: GroupEvent, subjects: &[&str]) -> GroupEvent { event.subjects = Some(subjects.iter().map(|s| s.to_string()).collect()); event}fn sentence(event: &GroupEvent) -> String { group_event_sentence(event, &name_for)}fn names(values: &[&str]) -> Vec<String> { values.iter().map(|value| value.to_string()).collect()}fn meta_with(system: MessageSystem) -> MessageMeta {MessageMeta { system: Some(system), ..MessageMeta::default() }}fn object(value: Value) -> Map<String, Value> {match value {Value::Object(map) => map, other => panic!("a test fixture must be an object, got {other}"), }}// ── isGroupEvent / groupEventOf ──────────────────────────────────────────────#[test]fn tells_the_structured_form_from_the_bare_flag() { assert!(!is_group_event(Some(&MessageSystem::Flag(true)))); assert!(!is_group_event(Some(&MessageSystem::Flag(false)))); assert!(!is_group_event(None)); assert!(is_group_event(Some(&MessageSystem::Event(event(GroupEventKind::Created,Some(ME) )))));}/// An imported WhatsApp archive is full of `system: true` rows and always will be/// — `None` means "fall back to the body", never "drift".#[test]fn reads_the_event_off_a_meta_and_answers_none_for_everything_else() {let meta = meta_with(MessageSystem::Event(event(GroupEventKind::Left, Some(ME)))); assert_eq!( group_event_of(Some(&meta)),Some(&event(GroupEventKind::Left, Some(ME))) ); assert_eq!( group_event_of(Some(&meta_with(MessageSystem::Flag(true)))),None ); assert_eq!(group_event_of(Some(&MessageMeta::default())), None); assert_eq!(group_event_of(None), None);}// ── joinNames ────────────────────────────────────────────────────────────────#[test]fn reads_as_a_list_a_person_would_say_out_loud() { assert_eq!(join_names(&[]), ""); assert_eq!(join_names(&names(&["Priya"])), "Priya"); assert_eq!(join_names(&names(&["Priya", "Asha"])), "Priya and Asha"); assert_eq!( join_names(&names(&["Priya", "Asha", "Dev"])),"Priya, Asha and Dev" );}// ── groupEventSentence ───────────────────────────────────────────────────────#[test]fn says_every_kind_in_the_third_person() { assert_eq!( sentence(&event(GroupEventKind::Created, Some(ME))),"Meera created the group" ); assert_eq!( sentence(&with_subjects( event(GroupEventKind::Added, Some(ME)), &[PRIYA] )),"Meera added Priya" ); assert_eq!( sentence(&with_subjects( event(GroupEventKind::Removed, Some(ME)), &[PRIYA] )),"Meera removed Priya" ); assert_eq!( sentence(&event(GroupEventKind::Left, Some(PRIYA))),"Priya left" );letmut renamed = event(GroupEventKind::Renamed, Some(ME)); renamed.title = Some("Ship it".to_string()); assert_eq!( sentence(&renamed),"Meera changed the group name to \u{201c}Ship it\u{201d}" ); assert_eq!( sentence(&event(GroupEventKind::Photo, Some(ME))),"Meera changed the group photo" ); assert_eq!( sentence(&event(GroupEventKind::Description, Some(ME))),"Meera changed the group description" );}/// The `match` is exhaustive by type; this catches a kind added to the list/// without a sentence, which would otherwise be an empty timeline row.#[test]fn has_a_sentence_for_every_kind_there_is() {for kind inGroupEventKind::ALL {letmut one = with_subjects(event(kind, Some(ME)), &[PRIYA]); one.title = Some("X".to_string()); assert!( sentence(&one).chars().any(|ch| !ch.is_whitespace()),"{kind}" ); }}/// RULE: A line describing what happened in a group is written in the third person, so the same sentence reads correctly in everybody's copy./// The row is mirrored verbatim; "you" would be true in one file and a lie in/// every other. This is the bug the whole change exists for.#[test]fn never_says_you_not_even_about_the_actors_own_file() {let word = regex::Regex::new(r"(?i-u:\byou\b)").expect("compiles");for kind inGroupEventKind::ALL {letmut one = with_subjects(event(kind, None), &[PRIYA]); one.title = Some("X".to_string()); assert!(!word.is_match(&sentence(&one)), "{kind}"); }}#[test]fn names_the_owner_for_a_null_actor_their_file_knows_who_they_are() { assert_eq!( sentence(&event(GroupEventKind::Created, None)),"Meera created the group" );}#[test]fn joins_several_subjects() { assert_eq!( sentence(&with_subjects( event(GroupEventKind::Added, Some(ME)), &[PRIYA, ASHA] )),"Meera added Priya and Asha" );}#[test]fn falls_back_to_the_number_when_nobody_knows_the_name() {let stranger = "919876509999"; assert_eq!( sentence(&with_subjects( event(GroupEventKind::Added, Some(stranger)), &[stranger] )), format!("{stranger} added {stranger}") );}#[test]fn says_someone_only_when_there_is_no_phone_at_all_to_fall_back_to() { assert_eq!( group_event_sentence(&event(GroupEventKind::Created, None), &nobody),"Someone created the group" ); assert_eq!( sentence(&with_subjects(event(GroupEventKind::Added, Some(ME)), &[])),"Meera added someone" );}#[test]fn renames_to_an_empty_title_rather_than_dropping_the_quotes() { assert_eq!( sentence(&event(GroupEventKind::Renamed, Some(ME))),"Meera changed the group name to \u{201c}\u{201d}" );}// ── parseGroupEvent ──────────────────────────────────────────────────────────#[test]fn reads_a_well_formed_event_ignoring_extra_keys() { assert_eq!( parse_group_event(&object( json!({ "kind": "added", "actor": ME, "subjects": [PRIYA], "mystery": 1 }) )),Ok(with_subjects( event(GroupEventKind::Added, Some(ME)), &[PRIYA] )) );}#[test]fn keeps_a_null_actor_as_null_and_reads_a_blank_one_as_null_too() { assert_eq!( parse_group_event(&object(json!({ "kind": "created", "actor": null }))),Ok(event(GroupEventKind::Created, None)) ); assert_eq!( parse_group_event(&object(json!({ "kind": "created" }))),Ok(event(GroupEventKind::Created, None)) ); assert_eq!( parse_group_event(&object(json!({ "kind": "created", "actor": "" }))),Ok(event(GroupEventKind::Created, None)) );}#[test]fn keeps_the_title_only_when_it_is_a_string() { assert_eq!( parse_group_event(&object( json!({ "kind": "renamed", "actor": ME, "title": "Ship it" }) )) .expect("parses") .title .as_deref(),Some("Ship it") ); assert_eq!( parse_group_event(&object( json!({ "kind": "renamed", "actor": ME, "title": 7 }) )) .expect("parses") .title,None );}#[test]fn refuses_an_unknown_kind_a_row_nobody_can_render_is_worse_than_a_loud_failure() {for value in [ json!({ "kind": "exploded", "actor": ME }), json!({ "actor": ME }), ] {let refusal = parse_group_event(&object(value)).unwrap_err().to_string(); assert!(refusal.contains("meta.system.kind"), "{refusal}"); }}#[test]fn refuses_an_actor_or_subjects_of_the_wrong_shape() {let refusal = parse_group_event(&object(json!({ "kind": "created", "actor": 91 }))) .unwrap_err() .to_string(); assert!(refusal.contains("meta.system.actor"), "{refusal}");for value in [ json!({ "kind": "added", "actor": ME, "subjects": "priya" }), json!({ "kind": "added", "actor": ME, "subjects": [1] }), ] {let refusal = parse_group_event(&object(value)).unwrap_err().to_string(); assert!(refusal.contains("meta.system.subjects"), "{refusal}"); }}// ── isOwnerActor — the two spellings of "this file's owner" ──────────────────/// A live row leaves the actor blank, because the file has no number of its own/// to sign it with and the server fills it from the envelope on the way out. An/// IMPORTED row never travels, so the Mac's importer writes the literal instead./// One predicate knows both, and every reader asks it rather than comparing by/// hand.#[test]fn answers_yes_to_absent_and_the_literal_and_no_to_a_number() { assert!(is_owner_actor(None)); assert!(is_owner_actor(Some(OWNER_ACTOR))); assert!(!is_owner_actor(Some(ME))); assert!(!is_owner_actor(Some(""))); assert!(!is_owner_actor(Some("Owner")));}#[test]fn keeps_the_literal_out_of_the_neutral_sentence_it_is_not_a_number() {// Unnamed, the owner is "Someone" — never the word "owner" printed where a// reader would take it for a name or a number. assert_eq!( group_event_sentence(&event(GroupEventKind::Created, Some(OWNER_ACTOR)), &nobody),"Someone created the group" ); assert_eq!( group_event_sentence(&event(GroupEventKind::Created, None), &nobody),"Someone created the group" );// Named, it is the owner's own name — the same answer a blank actor gets.let named = |phone: Option<&str>| {if is_owner_actor(phone) {Some("Meera".to_string()) } else {None } }; assert_eq!( group_event_sentence(&event(GroupEventKind::Left, Some(OWNER_ACTOR)), &named),"Meera left" );}// ── Node vectors ─────────────────────────────────────────────────────────────/// Printed by running the TypeScript (`vec_groupevent.ts`), pasted verbatim.////// Sentences first, because they are the bytes that land in the body column of/// every member's file — the curly quotes around a renamed title especially,/// which are U+201C/U+201D and not `"` on either side.#[test]fn node_vectors_for_the_sentences() {let by_number = |phone: Option<&str>| phone.map(str::to_string);letmut renamed = event(GroupEventKind::Renamed, Some("919000000001")); renamed.title = Some("Weekend plans \u{1f3d6}".to_string()); assert_eq!( group_event_sentence(&renamed, &by_number),"919000000001 changed the group name to \u{201c}Weekend plans \u{1f3d6}\u{201d}" ); assert_eq!( group_event_sentence( &with_subjects( event(GroupEventKind::Removed, Some("919000000001")), &["919000000002", "919000000003", "919000000004"] ), &by_number ),"919000000001 removed 919000000002, 919000000003 and 919000000004" );// The namer's answer is TRIMMED, and a name that is only whitespace is no// name at all — so this falls through to the number.let padded = |phone: Option<&str>| phone.map(|_| " ".to_string()); assert_eq!( group_event_sentence(&event(GroupEventKind::Left, Some("919000000009")), &padded),"919000000009 left" );let spaced = |phone: Option<&str>| phone.map(|_| " Meera ".to_string()); assert_eq!( group_event_sentence(&event(GroupEventKind::Photo, Some("919000000009")), &spaced),"Meera changed the group photo" );}/// And the refusal sentences, which carry `JSON.stringify` of whatever was in the/// column — the reason a log line can say what actually landed.#[test]fn node_vectors_for_the_refusals() { assert_eq!( parse_group_event(&object(json!({ "kind": "exploded", "actor": ME }))) .unwrap_err() .to_string(),"Unexpected value for cotton_msg_messages.meta.system.kind: \"exploded\". Expected one of created, added, removed, left, renamed, photo, description." ); assert_eq!( parse_group_event(&object(json!({ "actor": ME }))) .unwrap_err() .to_string(),"Unexpected value for cotton_msg_messages.meta.system.kind: undefined. Expected one of created, added, removed, left, renamed, photo, description." ); assert_eq!( parse_group_event(&object(json!({ "kind": "created", "actor": 91 }))) .unwrap_err() .to_string(),"Unexpected value for cotton_msg_messages.meta.system.actor: 91. Expected a phone or null." ); assert_eq!( parse_group_event(&object( json!({ "kind": "added", "actor": ME, "subjects": "priya" }) )) .unwrap_err() .to_string(),"Unexpected value for cotton_msg_messages.meta.system.subjects: \"priya\". Expected an array of phones." ); assert_eq!( parse_group_event(&object(json!({ "kind": "added", "actor": ME, "subjects": [1] }))) .unwrap_err() .to_string(),"Unexpected value for cotton_msg_messages.meta.system.subjects: [1]. Expected an array of phones." );}// RULE: the importer's rows name their source with a word ("whatsapp-chat-txt"), not the provenance object; the meta// still reads (its `system` with it) and the word comes back verbatim when written again.#[test]fn an_imported_rows_source_word_does_not_fail_its_meta() {let raw = json!({ "source": "whatsapp-chat-txt", "system": true });let meta: MessageMeta = serde_json::from_value(raw.clone()).expect("the importer's meta reads"); assert!(meta.system.as_ref().is_some_and(MessageSystem::is_truthy)); assert!(meta.source.is_none()); assert_eq!(serde_json::to_value(&meta).unwrap(), raw);// The provenance object still reads as itself.let live: MessageMeta = serde_json::from_value(json!({ "source": { "site": "instagram" } })).unwrap(); assert_eq!(live.source.and_then(|s| s.site).as_deref(), Some("instagram"));}