Cotton code
377 lines · 12.0 KB · RustRaw
use super::*;const SHA: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";fn attachment(    name: &str,    mime: Option<&str>,    size: Option<f64>,    key: Option<&str>,) -> EmailAttachmentLike {    EmailAttachmentLike {        name: name.to_string(),        mime: mime.map(str::to_string),        size,        key: key.map(str::to_string),    }}// ── emailPhotoCandidate ──────────────────────────────────────────────────────#[test]fn keeps_a_real_picture_with_bytes() {    assert_eq!(        email_photo_candidate(&attachment(            "IMG_0421.jpg",            Some("image/jpeg"),            Some(2_400_000.0),            Some("ws/documents/a/IMG_0421.jpg"),        )),        EmailPhotoDecision::Photo {            content_type: "image/jpeg".to_string()        }    );}#[test]fn skips_an_attachment_whose_bytes_are_not_in_the_store() {    assert_eq!(        email_photo_candidate(&attachment(            "IMG_0421.jpg",            Some("image/jpeg"),            Some(2_400_000.0),            None        )),        EmailPhotoDecision::Skip {            reason: EmailPhotoSkipReason::NoBytes        }    );}#[test]fn skips_what_is_not_a_photo_a_pdf_a_gif_an_unknown_type() {    for entry in [        attachment("contract.pdf", Some("application/pdf"), None, Some("k")),        attachment(            "reaction.gif",            Some("image/gif"),            Some(900_000.0),            Some("k"),        ),        attachment("blob", None, None, Some("k")),    ] {        assert_eq!(            email_photo_candidate(&entry).reason(),            Some(EmailPhotoSkipReason::NotAnImage),            "{entry:?}"        );    }}/// The floor is the whole point of the filter: a mailbox is full of 2 KB/// signature logos and 1-pixel tracking images, every one of them `image/png`.#[test]fn skips_the_signature_logo_and_the_tracking_pixel() {    assert_eq!(        email_photo_candidate(&attachment(            "logo.png",            Some("image/png"),            Some(2_048.0),            Some("k")        ))        .reason(),        Some(EmailPhotoSkipReason::TooSmall)    );    assert!(!email_photo_candidate(&attachment(        "pixel.gif",        Some("image/gif"),        Some(43.0),        Some("k")    ))    .is_photo());    // The floor itself is IN — `>=`, not `>`.    assert!(email_photo_candidate(&attachment(        "p.png",        Some("image/png"),        Some(EMAIL_PHOTO_MIN_BYTES),        Some("k")    ))    .is_photo());    assert!(!is_above_email_photo_floor(EMAIL_PHOTO_MIN_BYTES - 1.0));}#[test]fn lets_a_picture_with_no_stated_size_through_because_the_writer_measures_the_bytes() {    assert_eq!(        email_photo_candidate(&attachment("IMG_1.heic", None, None, Some("k"))),        EmailPhotoDecision::Photo {            content_type: "image/heic".to_string()        }    );}// ── emailPhotoFetchDecision — what the Gmail import pulls ────────────────────#[test]fn fetches_a_picture_needs_no_key_and_refuses_the_floor_and_the_ceiling() {    assert_eq!(        email_photo_fetch_decision(&attachment(            "IMG_1.jpg",            Some("image/jpeg"),            Some(2_000_000.0),            None        )),        EmailPhotoDecision::Photo {            content_type: "image/jpeg".to_string()        }    );    assert_eq!(        email_photo_fetch_decision(&attachment(            "logo.png",            Some("image/png"),            Some(1_024.0),            None        ))        .reason(),        Some(EmailPhotoSkipReason::TooSmall)    );    assert_eq!(        email_photo_fetch_decision(&attachment(            "huge.png",            Some("image/png"),            Some(EMAIL_PHOTO_MAX_BYTES + 1.0),            None        ))        .reason(),        Some(EmailPhotoSkipReason::TooLarge)    );    assert!(email_photo_fetch_decision(&attachment(        "edge.png",        Some("image/png"),        Some(EMAIL_PHOTO_MAX_BYTES),        None    ))    .is_photo());    assert_eq!(        email_photo_fetch_decision(&attachment(            "contract.pdf",            Some("application/pdf"),            Some(5_000.0),            None        ))        .reason(),        Some(EmailPhotoSkipReason::NotAnImage)    );    // No stated size: fetched, then measured.    assert!(email_photo_fetch_decision(&attachment("IMG_2.heic", None, None, None)).is_photo());}#[test]fn names_the_extension_a_photo_key_carries() {    assert_eq!(email_photo_extension("image/jpeg"), "jpg");    assert_eq!(email_photo_extension("image/heif"), "heif");    assert_eq!(email_photo_extension("image/gif"), "");}// ── emailPhotoContentType ────────────────────────────────────────────────────#[test]fn trusts_the_mime_parameters_stripped_and_falls_back_to_the_name() {    assert_eq!(        email_photo_content_type(&attachment("x.bin", Some("image/JPEG; name=x"), None, None))            .as_deref(),        Some("image/jpeg")    );    assert_eq!(        email_photo_content_type(&attachment("x.jpeg", None, None, None)).as_deref(),        Some("image/jpeg")    );    assert_eq!(        email_photo_content_type(&attachment("x.HEIF", None, None, None)).as_deref(),        Some("image/heif")    );    // A MIME that says "not an image" wins over a name that says otherwise.    assert_eq!(        email_photo_content_type(&attachment(            "x.jpg",            Some("application/octet-stream"),            None,            None        )),        None    );    assert_eq!(        email_photo_content_type(&attachment("x", None, None, None)),        None    );}/// Vectors read out of Node, not reasoned out. Two of them corrected a guess:/// a MIME that is only WHITESPACE falls through to the name (the TypeScript/// trims after splitting and then asks for `length > 0`), and a name that is/// nothing but an extension (`.jpg`) reads as one, because `lastIndexOf(".")`/// is 0 and the slice starts after it.#[test]fn email_photo_content_type_matches_the_typescript_on_every_odd_shape() {    let cases: &[(&str, Option<&str>, Option<&str>)] = &[        ("x.bin", Some("image/JPEG; name=x"), Some("image/jpeg")),        (            "x.bin",            Some("  IMAGE/PNG  ; charset=binary"),            Some("image/png"),        ),        ("x.jpg", Some("   "), Some("image/jpeg")),        ("x.jpg", Some(""), Some("image/jpeg")),        ("x.jpeg", None, Some("image/jpeg")),        ("x.HEIF", None, Some("image/heif")),        ("x.JPG", None, Some("image/jpeg")),        ("photo.tar.gz", None, None),        ("x.", None, None),        (".jpg", None, Some("image/jpeg")),        ("x", Some("image/heic"), Some("image/heic")),        ("x.jpg", Some("application/octet-stream"), None),        ("x", None, None),        ("x.webp", None, Some("image/webp")),        ("x.gif", Some("image/gif"), None),        ("IMG.jpg", Some("image/jpeg;"), Some("image/jpeg")),    ];    for (name, mime, expected) in cases {        assert_eq!(            email_photo_content_type(&attachment(name, *mime, None, None)).as_deref(),            *expected,            "email_photo_content_type({name:?}, {mime:?})"        );    }}/// Every type the module keeps, and three it does not — read out of Node. The/// lookup is case-SENSITIVE (`IMAGE/JPEG` answers the empty string), which is/// safe only because every caller passes what `email_photo_content_type`/// returned, and that is already lower-cased.#[test]fn email_photo_extension_matches_the_typescript() {    let cases: &[(&str, &str)] = &[        ("image/jpeg", "jpg"),        ("image/png", "png"),        ("image/webp", "webp"),        ("image/heic", "heic"),        ("image/heif", "heif"),        ("image/gif", ""),        ("", ""),        ("IMAGE/JPEG", ""),    ];    for (content_type, expected) in cases {        assert_eq!(            email_photo_extension(content_type),            *expected,            "{content_type}"        );    }}// ── emailPhotoRows ───────────────────────────────────────────────────────────#[test]fn builds_the_content_addressed_row_and_the_email_sighting_on_the_attachments_own_key() {    let rows = email_photo_rows(&EmailPhotoInput {        workspace_id: "ws".to_string(),        email_id: "email-1".to_string(),        sent_at: "2026-08-20T10:00:00.000Z".to_string(),        key: "ws/documents/att/IMG.jpg".to_string(),        content_type: "image/jpeg".to_string(),        sha256: SHA.to_string(),        size_bytes: 123_456,        now: "2026-09-05T12:00:00.000Z".to_string(),    });    let expected: serde_json::Value = serde_json::from_str(GOLDEN).expect("golden JSON parses");    assert_eq!(serde_json::to_value(&rows).unwrap(), expected);    // …and the sighting id is the DERIVED one, so re-walking the same email    // writes the same row rather than a sibling.    assert_eq!(rows.sighting.id, "a5739db7-9bde-b001-ea5a-dfc58e055cad");    assert_eq!(rows.photo.id, format!("photo:{SHA}"));    assert_eq!(rows.sighting.thread_id, None);}/// Printed by `JSON.stringify(emailPhotoRows(…))` in Node — the sighting id/// included, which is the part no reasoning could have supplied.const GOLDEN: &str = r#"{ "photo": {  "id": "photo:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",  "workspace_id": "ws",  "key": "ws/documents/att/IMG.jpg",  "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",  "content_type": "image/jpeg",  "size_bytes": 123456,  "width": null,  "height": null,  "taken_at": "2026-08-20T10:00:00.000Z",  "preview": null,  "created_at": "2026-09-05T12:00:00.000Z",  "updated_at": "2026-09-05T12:00:00.000Z" }, "sighting": {  "id": "a5739db7-9bde-b001-ea5a-dfc58e055cad",  "workspace_id": "ws",  "record_kind": "photo",  "record_id": "photo:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",  "source": "email",  "source_id": "email-1",  "thread_id": null,  "key": "ws/documents/att/IMG.jpg",  "seen_at": "2026-08-20T10:00:00.000Z",  "created_at": "2026-09-05T12:00:00.000Z",  "updated_at": "2026-09-05T12:00:00.000Z" }}"#;/// The three boundary decisions, read out of Node rather than reasoned about:/// one byte under the floor is `too_small`, a stated ZERO is `too_small`/// rather than "unknown", and one byte over the ceiling is `too_large`.#[test]fn the_boundary_decisions_match_the_typescript() {    assert_eq!(        email_photo_candidate(&attachment(            "x.jpg",            Some("image/jpeg"),            Some(EMAIL_PHOTO_MIN_BYTES - 1.0),            Some("k")        ))        .reason(),        Some(EmailPhotoSkipReason::TooSmall)    );    assert_eq!(        email_photo_candidate(&attachment(            "x.jpg",            Some("image/jpeg"),            Some(0.0),            Some("k")        ))        .reason(),        Some(EmailPhotoSkipReason::TooSmall)    );    assert_eq!(        email_photo_fetch_decision(&attachment(            "x.jpg",            Some("image/jpeg"),            Some(EMAIL_PHOTO_MAX_BYTES + 1.0),            None        ))        .reason(),        Some(EmailPhotoSkipReason::TooLarge)    );}/// The skip reasons keep the TypeScript's own spellings — they reach a/// caller's log and an importer's report.#[test]fn the_skip_reasons_are_the_typescripts_own_strings() {    assert_eq!(EmailPhotoSkipReason::NoBytes.as_str(), "no_bytes");    assert_eq!(EmailPhotoSkipReason::NotAnImage.as_str(), "not_an_image");    assert_eq!(EmailPhotoSkipReason::TooSmall.as_str(), "too_small");    assert_eq!(EmailPhotoSkipReason::TooLarge.as_str(), "too_large");    assert_eq!(        serde_json::to_string(&EmailPhotoSkipReason::NotAnImage).unwrap(),        "\"not_an_image\""    );}