Cotton code
688 lines · 23.1 KB · RustRaw
//! `report.ts` ships NO test file in TypeScript — its guard was the CLI's own//! output, and the CLI is gone. So every case here is a Node GOLDEN: the//! TypeScript `formatReport` was run over the fixture (`npx tsx`, from//! `packages/import-core`) and its output pasted in verbatim. Twenty-one whole//! reports, chosen for the lines that could drift — the singular/plural//! switch on every counted noun, the day-span rounding, an unparseable//! instant, the media block's four branches, and the two grammar bugs the port//! keeps on purpose.//!//! Every fixture is SYNTHETIC.use super::*;use crate::import::normalize::ReportParticipant;fn chat() -> ChatReport {    ChatReport {        kind: None,        title: None,        participants: None,        system_imported: None,        phone: Some("919000000001".to_string()),        display_name: Some("Asha".to_string()),        messages: 3,        inbound: 2,        outbound: 1,        first_sent_at: Some("2024-03-01T04:00:00.000Z".to_string()),        last_sent_at: Some("2024-03-11T04:00:00.000Z".to_string()),        reply_refs: 0,        unresolved_reply_refs: 0,        reactions: 0,        attachments: 0,        omitted_media: 0,        system_skipped: 0,        album_containers_dropped: 0,        warnings: Vec::new(),    }}fn report(chats: Vec<ChatReport>) -> ImportReport {    ImportReport {        source: ReportSource {            kind: SourceKind::ChatZip,            path: "/tmp/export.zip".to_string(),        },        target: ReportTarget {            cell: "cell-a".to_string(),            workspace_id: "ws-1".to_string(),            endpoint: "https://api.example.test/v1/import".to_string(),        },        chats,        skipped_chats: Vec::new(),        empty_chats: 0,        dropped_messages: 0,        limitations: Vec::new(),        warnings: Vec::new(),        media_manifest_path: None,        media_files: 0,        media_plan: None,        media_uploaded: None,        media_upload_failed: None,    }}/// The three-line header every golden opens with, for the `chat-zip` fixture.const ZIP_HEADER: &str = "Source   /tmp/export.zip  (chat-zip)\n\     Target   cell cell-a · workspace ws-1\n\     \x20        https://api.example.test/v1/import\n";/// The same header for the `chat-txt` fixture the edge-case goldens use.const TXT_HEADER: &str = "Source   /tmp/_chat.txt  (chat-txt)\n\     Target   cell cell-a · workspace ws-1\n\     \x20        https://api.example.test/v1/import\n";fn txt_report(chats: Vec<ChatReport>) -> ImportReport {    let mut value = report(chats);    value.source = ReportSource {        kind: SourceKind::ChatTxt,        path: "/tmp/_chat.txt".to_string(),    };    value}/* ── the two smallest reports ───────────────────────────────────────────── *//// No conversations: the "none found" line is pushed INSIDE the same block the/// chat loop would have written, so there is no blank line before TOTAL.#[test]fn empty_matches_node() {    assert_eq!(        format_report(&report(Vec::new())),        format!(            "{ZIP_HEADER}\n\             No importable conversations were found.\n\             TOTAL    0 messages across 0 conversations"        )    );}/// One plain dm — name, number, the counts and the span.#[test]fn simple_matches_node() {    assert_eq!(        format_report(&report(vec![chat()])),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/* ── every noun in its singular ─────────────────────────────────────────── *//// One of everything. Every counted noun takes its singular, the two grammar/// bugs show (`1 message were unusable`, and a five-hour span reading/// `(0 days)`), and the section order is the renderer's.#[test]fn singular_everything_matches_node() {    let mut single = chat();    single.messages = 1;    single.inbound = 1;    single.outbound = 0;    single.first_sent_at = Some("2024-03-01T04:00:00.000Z".to_string());    single.last_sent_at = Some("2024-03-01T09:00:00.000Z".to_string());    single.reply_refs = 1;    single.unresolved_reply_refs = 1;    single.reactions = 1;    single.attachments = 1;    single.omitted_media = 1;    single.system_skipped = 1;    single.album_containers_dropped = 1;    single.warnings = vec!["one number could not be identified".to_string()];    let mut value = report(vec![single]);    value.empty_chats = 1;    value.dropped_messages = 1;    value.media_files = 1;    value.limitations = vec!["reactions".to_string(), "call logs".to_string()];    value.warnings = vec!["the export may be truncated".to_string()];    assert_eq!(        format_report(&value),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   1 message   1 in / 0 out\n\             \x20   2024-03-01 → 2024-03-01   (0 days)\n\             \x20   1 reply   (1 quoting a message outside this import)\n\             \x20   1 reaction\n\             \x20   1 attachment   (1 not present in the export)\n\             \x20   1 system line skipped\n\             \x20   1 album — the export's blank line before each one was dropped\n\             \x20   ! one number could not be identified\n\             \n\             1 address-book entry with no messages (the exporter creates one per saved contact). Ignored.\n\             1 message were unusable and dropped.\n\             \n\             1 media file referenced. Pass --media manifest to write the manifest, or --media upload to upload.\n\             \n\             This source cannot carry:\n\             \x20   · reactions\n\             \x20   · call logs\n\             \n\             Warnings:\n\             \x20   ! the export may be truncated\n\             \n\             TOTAL    1 message across 1 conversation"        )    );}/* ── a group ────────────────────────────────────────────────────────────── *//// A group with a roster, skipped chats beside it, and every plural.#[test]fn group_matches_node() {    let mut group = chat();    group.kind = Some("group".to_string());    group.title = Some("Trip".to_string());    group.display_name = Some("Trip".to_string());    group.phone = None;    group.participants = Some(vec![        ReportParticipant {            display_name: "Asha".to_string(),            phone: Some("919000000001".to_string()),            identified: true,        },        ReportParticipant {            display_name: "Dev".to_string(),            phone: None,            identified: false,        },    ]);    group.system_imported = Some(2);    group.messages = 12;    group.inbound = 9;    group.outbound = 3;    group.reply_refs = 4;    group.unresolved_reply_refs = 2;    group.reactions = 5;    group.attachments = 3;    group.omitted_media = 1;    group.system_skipped = 2;    group.album_containers_dropped = 2;    group.warnings = vec!["two participants are unidentified".to_string()];    let mut value = report(vec![group]);    value.skipped_chats = vec![        SkippedChatReport {            label: "status@broadcast".to_string(),            messages: 40,            reason: "status — a 24-hour post".to_string(),        },        SkippedChatReport {            label: "A Broadcast".to_string(),            messages: 1,            reason: "broadcast list — one-way".to_string(),        },    ];    value.empty_chats = 4;    value.dropped_messages = 7;    value.media_files = 9;    value.media_manifest_path = Some("/tmp/media.json".to_string());    assert_eq!(        format_report(&value),        format!(            "{ZIP_HEADER}\n\             Group \"Trip\"\n\             \x20   Asha  +919000000001\n\             \x20   Dev  (to identify)\n\             \x20   12 messages   9 in / 3 out / 2 group events\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \x20   4 replies   (2 quoting a message outside this import)\n\             \x20   5 reactions\n\             \x20   3 attachments   (1 not present in the export)\n\             \x20   2 system lines skipped\n\             \x20   2 albums — the export's blank line before each one was dropped\n\             \x20   ! two participants are unidentified\n\             \n\             Skipped (2):\n\             \x20   status@broadcast   40 messages   — status — a 24-hour post\n\             \x20   A Broadcast   1 message   — broadcast list — one-way\n\             \n\             4 address-book entries with no messages (the exporter creates one per saved contact). Ignored.\n\             7 messages were unusable and dropped.\n\             \n\             9 media files referenced — manifest written to /tmp/media.json\n\             \n\             TOTAL    12 messages across 1 conversation"        )    );}/* ── the media block's branches ─────────────────────────────────────────── *//// A planned upload with something wrong in every column, and a run that/// partly failed.#[test]fn media_planned_matches_node() {    let mut value = report(vec![chat()]);    value.media_files = 12;    value.media_plan = Some(MediaUploadCounts {        uploadable: 5,        unsupported_type: 2,        oversize: 1,        missing: 3,        omitted: 1,    });    value.media_uploaded = Some(5.0);    value.media_upload_failed = Some(2.0);    assert_eq!(        format_report(&value),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             12 media files referenced — 5 uploadable · 2 unsupported type · 1 over the Worker's size cap · 3 referenced but not in the archive · 1 omitted by the export\n\             \x20   5 files uploaded · 2 FAILED\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// A clean run: only the `uploadable` part is printed, and a ZERO failure/// count stays silent — the TypeScript's test is truthiness, not `> 0`.#[test]fn media_planned_clean_upload_matches_node() {    let mut value = report(vec![chat()]);    value.media_files = 6;    value.media_plan = Some(MediaUploadCounts {        uploadable: 6,        ..MediaUploadCounts::default()    });    value.media_uploaded = Some(6.0);    value.media_upload_failed = Some(0.0);    assert_eq!(        format_report(&value),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             6 media files referenced — 6 uploadable\n\             \x20   6 files uploaded\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// Planned but not executed: no uploaded line at all.#[test]fn media_planned_no_upload_matches_node() {    let mut value = report(vec![chat()]);    value.media_files = 6;    value.media_plan = Some(MediaUploadCounts {        uploadable: 6,        ..MediaUploadCounts::default()    });    assert_eq!(        format_report(&value),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             6 media files referenced — 6 uploadable\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// Zero uploaded is still a KNOWN zero and prints — the gate is/// `typeof mediaUploaded === "number"`, and the failure count beside it is/// falsy so it stays away. Node golden.#[test]fn media_zero_uploaded_still_prints() {    let mut value = txt_report(vec![chat()]);    value.media_files = 3;    value.media_plan = Some(MediaUploadCounts {        uploadable: 3,        ..MediaUploadCounts::default()    });    value.media_uploaded = Some(0.0);    value.media_upload_failed = Some(0.0);    assert_eq!(        format_report(&value),        format!(            "{TXT_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             3 media files referenced — 3 uploadable\n\             \x20   0 files uploaded\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// An explicitly NULL plan reads exactly as an absent one — which is why the/// port needs only one `None`. Node golden.#[test]fn an_explicitly_null_plan_reads_as_an_absent_one() {    let mut value = txt_report(vec![chat()]);    value.media_files = 2;    assert_eq!(        format_report(&value),        format!(            "{TXT_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             2 media files referenced. Pass --media manifest to write the manifest, or --media upload to upload.\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/* ── who a conversation is with ─────────────────────────────────────────── *//// Neither a name nor a number: the line the report writes rather than an/// empty one.#[test]fn no_dates_and_no_identity_matches_node() {    let mut anonymous = chat();    anonymous.first_sent_at = None;    anonymous.last_sent_at = None;    anonymous.phone = None;    anonymous.display_name = None;    assert_eq!(        format_report(&report(vec![anonymous])),        format!(            "{ZIP_HEADER}\n\             (unidentified contact)\n\             \x20   3 messages   2 in / 1 out\n\             \x20   — → —\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// An EMPTY display name is falsy in JavaScript and drops out of the join, so/// the number stands alone. Node golden.#[test]fn an_empty_display_name_drops_out_of_the_join() {    let mut anonymous = chat();    anonymous.display_name = Some(String::new());    assert_eq!(        format_report(&txt_report(vec![anonymous])),        format!(            "{TXT_HEADER}\n\             +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// Both halves falsy — an empty string is not a name either. Node golden.#[test]fn an_empty_name_and_no_number_is_an_unidentified_contact() {    let mut anonymous = chat();    anonymous.display_name = Some(String::new());    anonymous.phone = None;    assert_eq!(        format_report(&txt_report(vec![anonymous])),        format!(            "{TXT_HEADER}\n\             (unidentified contact)\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// A name with no number. Node golden.#[test]fn a_name_with_no_number_matches_node() {    let mut named = chat();    named.phone = None;    assert_eq!(        format_report(&txt_report(vec![named])),        format!(            "{TXT_HEADER}\n\             Asha\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// A group with no title falls back to its display name, and the whole thing/// goes through `JSON.stringify` — so an inner quote is escaped. Node golden.#[test]fn a_group_title_is_json_stringified() {    let mut group = chat();    group.kind = Some("group".to_string());    group.title = None;    group.display_name = Some("Trip \"Two\"".to_string());    group.phone = None;    group.participants = Some(Vec::new());    assert_eq!(        format_report(&txt_report(vec![group])),        format!(            "{TXT_HEADER}\n\             Group \"Trip \\\"Two\\\"\"\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// Neither a title nor a display name: `(untitled)`, quoted like any other.#[test]fn an_untitled_group_matches_node() {    let mut group = chat();    group.kind = Some("group".to_string());    group.title = None;    group.display_name = None;    group.phone = None;    group.participants = Some(Vec::new());    assert_eq!(        format_report(&report(vec![group])),        format!(            "{ZIP_HEADER}\n\             Group \"(untitled)\"\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// A group event count of ZERO writes no `/ 0 group events` half. Node golden.#[test]fn a_zero_group_event_count_writes_nothing() {    let mut group = chat();    group.kind = Some("group".to_string());    group.title = Some("T".to_string());    group.system_imported = Some(0);    group.participants = Some(Vec::new());    assert_eq!(        format_report(&txt_report(vec![group])),        format!(            "{TXT_HEADER}\n\             Group \"T\"\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-11   (10 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/* ── the day span ───────────────────────────────────────────────────────── *//// Sixteen hours rounds UP to a day — `Math.round(0.667)`. A same-day chat/// therefore reads `(1 day)`, which is wrong and is what the TypeScript says.#[test]fn a_same_day_span_rounds_up_to_one_day() {    let mut same_day = chat();    same_day.first_sent_at = Some("2024-03-01T04:00:00.000Z".to_string());    same_day.last_sent_at = Some("2024-03-01T20:00:00.000Z".to_string());    assert_eq!(        format_report(&report(vec![same_day])),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-01   (1 day)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// Thirty-seven hours rounds to two days, not one — the ties-toward-+∞ rule.#[test]fn a_thirty_seven_hour_span_rounds_to_two_days() {    let mut span = chat();    span.first_sent_at = Some("2024-03-01T00:00:00.000Z".to_string());    span.last_sent_at = Some("2024-03-02T13:00:00.000Z".to_string());    assert_eq!(        format_report(&report(vec![span])),        format!(            "{ZIP_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-01 → 2024-03-02   (2 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// A LAST instant older than the first clamps at zero rather than going/// negative — `Math.max(0, …)`. Node golden.#[test]fn a_reversed_span_clamps_to_zero() {    let mut reversed = chat();    reversed.first_sent_at = Some("2024-03-11T04:00:00.000Z".to_string());    reversed.last_sent_at = Some("2024-03-01T04:00:00.000Z".to_string());    assert_eq!(        format_report(&txt_report(vec![reversed])),        format!(            "{TXT_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   2024-03-11 → 2024-03-01   (0 days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/// An instant that will not parse gives `NaN` on both sides, and the report/// SAYS so rather than hiding it behind a zero. Node golden.#[test]fn an_unparseable_instant_reads_nan_days() {    let mut broken = chat();    broken.first_sent_at = Some("not a date".to_string());    assert_eq!(        format_report(&txt_report(vec![broken])),        format!(            "{TXT_HEADER}\n\             Asha  +919000000001\n\             \x20   3 messages   2 in / 1 out\n\             \x20   not a date → 2024-03-11   (NaN days)\n\             \n\             TOTAL    3 messages across 1 conversation"        )    );}/* ── the WCE shape ──────────────────────────────────────────────────────── *//// The exporter creates one address-book shell per saved contact, so a WCE/// file with nothing importable still has a number worth stating. Node golden.#[test]fn wce_with_only_address_book_entries_matches_node() {    let mut value = report(Vec::new());    value.source = ReportSource {        kind: SourceKind::WceJson,        path: "/tmp/wce.json".to_string(),    };    value.empty_chats = 120;    assert_eq!(        format_report(&value),        "Source   /tmp/wce.json  (wce-json)\n\         Target   cell cell-a · workspace ws-1\n\         \x20        https://api.example.test/v1/import\n\         \n\         No importable conversations were found.\n\         120 address-book entries with no messages (the exporter creates one per saved contact). Ignored.\n\         \n\         TOTAL    0 messages across 0 conversations"    );}/* ── totalMessages, and the vocabulary ──────────────────────────────────── *//// The total is the sum of every chat's own count, whatever else the report/// holds.#[test]fn total_messages_sums_every_chat() {    assert_eq!(total_messages(&report(Vec::new())), 0);    assert_eq!(total_messages(&report(vec![chat()])), 3);    let mut twelve = chat();    twelve.messages = 12;    assert_eq!(total_messages(&report(vec![chat(), twelve])), 15);}/// The four input shapes, in the union's declared order and with the wire/// strings the CLI and the app both speak.#[test]fn source_kind_keeps_the_typescript_spelling() {    assert_eq!(        SourceKind::ALL.map(SourceKind::as_str),        ["wce-json", "chat-txt", "chat-zip", "chat-dir"]    );    assert_eq!(SourceKind::parse("chat-dir"), Some(SourceKind::ChatDir));    assert_eq!(SourceKind::parse("chat-rar"), None);    assert_eq!(        serde_json::to_string(&SourceKind::WceJson).unwrap(),        r#""wce-json""#    );}