SPB Git

Repository Public

NextComposeSupportTests.swift 25.8 KB 316 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/NextComposeSupportTests.swift3// Description: Unit tests of the composer rules: draft body load / store with the quoted block kept byte for byte, inline image parts,4// signature swapping, `;shortcut` snippet expansion, recipient entry and validation, send-later and reminder presets, idempotency keys,5// held-message reopening, and the outbox carrying inline parts (1.1.0 items still decodable).6import Foundation7import Testing8@testable import SPMailCore910private let me = EmailAddress(name: "Moi", email: "moi@stg.spboucher.ai")11private func sig(_ id: String, _ text: String, html: String = "") -> SignatureChoice { SignatureChoice(id: id, html: html, text: text) }12private func apply(_ edit: (range: NSRange, replacement: NSAttributedString)?, to text: NSAttributedString) -> NSAttributedString {13    guard let edit else { return text }14    let m = NSMutableAttributedString(attributedString: text)15    m.replaceCharacters(in: edit.range, with: edit.replacement)16    return m17}1819@Suite struct RichBodyTests {20    @Test func plainDraftStaysPlainAndRichDraftGetsHTML() {21        var m = OutgoingMessage(from: me, text: "Bonjour\n\n-- \nMoi")22        let doc = RichBody.load(&m)23        #expect(doc.string == "Bonjour\n\n-- \nMoi")24        RichBody.store(doc, in: &m, attachments: [])25        #expect(m.html == nil && m.text == "Bonjour\n\n-- \nMoi")26        let rich = NSMutableAttributedString(attributedString: doc)27        rich.addAttribute(RichKey.bold, value: true, range: NSRange(location: 0, length: 7))28        RichBody.store(rich, in: &m, attachments: [])29        #expect(m.html == "<div><b>Bonjour</b></div><div><br></div><div>--&nbsp;</div><div>Moi</div>" && m.text == "Bonjour\n\n-- \nMoi")30        var again = m31        #expect(RichHTML.html(from: RichBody.load(&again)) == m.html)32    }3334    @Test func quotedOriginalIsNeverTouched() {35        let quote = OutgoingMessage.quoteBlockOpen + "<p>Le 3 mai, A a écrit :</p><blockquote type=\"cite\" style=\"margin:0 0 0 .8ex\"><table width=\"100%\"><tr><td style=\"color:#f00\">Tableau &amp; <img src=\"cid:logo@x\"></td></tr></table></blockquote></div>"36        var m = OutgoingMessage(from: me, text: "")37        m.quotedHTML = quote38        m.quotedText = "Le 3 mai, A a écrit :\n> Tableau &"39        let logo = OutgoingAttachment(name: "logo.png", type: "image/png", size: 10, blobId: "B1", cid: "logo@x", inline: true)40        let doc = NSMutableAttributedString(attributedString: RichBody.load(&m))41        doc.append(NSAttributedString(string: "Merci !", attributes: [RichKey.block: "p", RichKey.italic: true]))42        RichBody.store(doc, in: &m, attachments: [logo])43        #expect(m.quotedHTML == quote)44        #expect(m.fullHTML == "<div><i>Merci !</i></div>" + quote)45        #expect(m.fullText == "Merci !\n\nLe 3 mai, A a écrit :\n> Tableau &")46        #expect(m.attachments == [logo]) // referenced by the quoted block only: it still travels47        // closed and reopened any number of times: the same bytes48        for _ in 0..<3 {49            var stored = m50            let reopened = RichBody.load(&stored)51            RichBody.store(reopened, in: &stored, attachments: stored.attachments)52            #expect(stored.fullHTML == m.fullHTML && stored.quotedHTML == quote && stored.fullText == m.fullText)53        }54        // removing the quote removes its inline part too55        RichBody.store(doc, in: &m, attachments: [logo], includeQuote: false)56        #expect(m.quotedHTML == nil && m.quotedText == nil && m.attachments.isEmpty && m.html == "<div><i>Merci !</i></div>")57    }5859    @Test func serverDraftAdoptedByThe110RulesBecomesEditableAgain() {60        // what `SyncEngine.fill` leaves when the stored HTML is richer than 1.1.0 could edit: everything in the untouched block61        let top = "<div>Liste :</div><ul><li><u>un</u></li><li>deux</li></ul>"62        let quote = OutgoingMessage.quoteBlockOpen + "<p>intro</p><blockquote type=\"cite\">original</blockquote></div>"63        var m = OutgoingMessage(from: me, text: "")64        m.html = ""65        m.quotedHTML = top + quote66        m.quotedText = "Liste :\n• un\n• deux\n\nintro\n> original"67        let before = m.fullHTML68        let doc = RichBody.load(&m)69        #expect(doc.string == "Liste :\nun\ndeux" && m.html == top && m.quotedHTML == quote && m.quotedText == "intro\n> original")70        #expect(m.fullHTML == before)71        // a webmail draft the composer cannot represent stays whole, with an empty editable part above it72        var table = OutgoingMessage(from: me, text: "")73        table.html = ""74        table.quotedHTML = "<table><tr><td>a</td></tr></table>"75        table.quotedText = "a"76        #expect(RichBody.load(&table).length == 0 && table.quotedHTML == "<table><tr><td>a</td></tr></table>" && table.html == "")77        // an editable part that turns out not to be representable is moved into the block rather than flattened78        var odd = OutgoingMessage(from: me, text: "a", html: "<div style=\"color:red\">a</div>")79        #expect(RichBody.load(&odd).length == 0 && odd.quotedHTML == "<div style=\"color:red\">a</div>" && odd.fullHTML == "<div></div><div style=\"color:red\">a</div>" || odd.fullHTML == "<div style=\"color:red\">a</div>")80    }8182    @Test func inlinePartsFollowTheText() {83        let a = OutgoingAttachment(id: "A", name: "a.png", type: "image/png", size: 1, cid: "a@spmail", inline: true)84        let b = OutgoingAttachment(id: "B", name: "b.png", type: "image/png", size: 1, cid: "<b@spmail>", inline: true)85        let file = OutgoingAttachment(id: "F", name: "f.pdf", type: "application/pdf", size: 1)86        let doc = NSMutableAttributedString(attributedString: RichText.attributed(fromPlain: "x"))87        doc.append(NSAttributedString(string: RichText.attachmentCharacter, attributes: [RichKey.block: "p", RichKey.image: RichImage(cid: "b@spmail", name: "b.png").rawValue]))88        var m = OutgoingMessage(from: me)89        RichBody.store(doc, in: &m, attachments: [a, b, file])90        #expect(m.attachments.map(\.id) == ["B", "F"]) // the removed image's part is dropped; the regular attachment stays91        #expect(m.html?.contains("<img src=\"cid:b@spmail\" alt=\"b.png\">") == true)92        #expect(m.jmapEmail(mailboxId: "d", draft: true)["attachments"].arrayValue == nil) // not uploaded yet: nothing to reference93        var uploaded = m94        uploaded.attachments[0].blobId = "BLOB"95        let part = uploaded.jmapEmail(mailboxId: "d", draft: true)["attachments"].arrayValue?.first96        #expect(part?["disposition"].stringValue == "inline" && part?["cid"].stringValue == "<b@spmail>" && part?["blobId"].stringValue == "BLOB")97        #expect(InlineParts.isInlineImageType("image/PNG") && !InlineParts.isInlineImageType("image/svg+xml") && !InlineParts.isInlineImageType("image/heic"))98    }99100    @Test func outboxItemsOfVersion110StillDecodeAndNewOnesRoundTrip() throws {101        // an item as 1.1.0 stored it: no failureKind, no syncedDigest, no messageId, attachments without cid102        let old = #"{"id":"I1","account":"A","state":"draft","attempts":0,"createdAt":700000000,"updatedAt":700000000,"needsDraftSync":true,"delivery":{},"message":{"from":{"email":"moi@stg.spboucher.ai"},"to":[],"cc":[],"bcc":[],"subject":"s","text":"t","html":"<div>t</div>","attachments":[{"id":"X","name":"f.txt","type":"text/plain","size":3,"inline":false}],"inReplyTo":[],"references":[]}}"#103        let item = try JSONDecoder().decode(OutboxItem.self, from: Data(old.utf8))104        var m = item.message105        #expect(RichBody.load(&m).string == "t" && m.attachments.first?.cid == nil)106        // a Next item with an inline part and rich HTML survives the store's encoding107        var next = OutboxItem(account: "A", message: OutgoingMessage(from: me, text: "x", html: "<div>x<img src=\"cid:c@spmail\" alt=\"c.png\" width=\"160\"></div>",108                                                                    attachments: [OutgoingAttachment(id: "C", name: "c.png", type: "image/png", size: 9, cid: "c@spmail", inline: true)]))109        next.message.quotedHTML = OutgoingMessage.quoteBlockOpen + "q</div>"110        let decoded = try JSONDecoder().decode(OutboxItem.self, from: try JSONEncoder().encode(next))111        #expect(decoded == next && decoded.message.contentDigest == next.message.contentDigest)112        var reopened = decoded.message113        let doc = RichBody.load(&reopened)114        #expect(RichText.cids(in: doc) == ["c@spmail"] && RichImage(rawValue: doc.attribute(RichKey.image, at: 1, effectiveRange: nil) as? String ?? "")?.width == 160)115    }116117    @Test func heldMessageReopensWithItsAttachments() throws {118        let json = try JSONValue.parse(Data(#"{"id":"msg_out_abcdefghij","status":"cancelled","draft":true,"mailbox_id":"mb","email_id":"e9","thread_id":"t","from":{"email":"moi@stg.spboucher.ai","name":"Moi"},"to":[{"email":"b@stg.spboucher.ai","name":"B"}],"cc":[],"bcc":[],"subject":"Sujet","html":"<div>Bonjour <b>B</b></div><div><img src=\"cid:c@spmail\" alt=\"c.png\"></div>","text":"Bonjour B","attachments":[{"blob_id":"blob-1","name":"c.png","type":"image/png","size":9,"cid":"c@spmail","inline":true},{"blob_id":"blob-2","name":"note.txt","type":"text/plain","size":4,"cid":null,"inline":false}],"in_reply_to":["m1@x"],"references":["m0@x","m1@x"],"send_at":"2026-11-20T10:00:10Z","undo_until":"2026-11-20T10:00:10Z"}"#.utf8))119        let held = try #require(HeldMessage(json: json))120        var m = OutgoingMessage(held: held, from: me, identityId: "id1")121        #expect(m.to.first?.email == "b@stg.spboucher.ai" && m.subject == "Sujet" && m.inReplyTo == ["m1@x"] && m.references.count == 2)122        #expect(m.attachments.map(\.blobId) == ["blob-1", "blob-2"] && m.attachments[0].inline && m.attachments[0].cid == "c@spmail" && !m.attachments[1].inline)123        let doc = RichBody.load(&m)124        #expect(doc.string == "Bonjour B\n\u{FFFC}" && doc.attribute(RichKey.bold, at: 8, effectiveRange: nil) != nil && RichText.cids(in: doc) == ["c@spmail"])125    }126}127128@Suite struct RichSignatureTests {129    let alice = sig("a", "Alice\nDirection"), bob = sig("b", "Bob", html: "<div><b>Bob</b></div><div><a href=\"https://b.example\">b.example</a></div>"), none = sig("none", "")130131    private func document(_ typed: String, _ s: SignatureChoice?) -> NSAttributedString {132        apply(RichSignature.swap(in: RichText.attributed(fromPlain: typed), old: nil, new: s), to: RichText.attributed(fromPlain: typed))133    }134135    @Test func insertedOnceAndSwappedInPlace() {136        var doc = document("Bonjour", alice)137        #expect(doc.string == "Bonjour\n\n-- \nAlice\nDirection")138        #expect(RichSignature.swap(in: doc, old: nil, new: alice) == nil) // never twice139        doc = apply(RichSignature.swap(in: doc, old: alice, new: bob), to: doc)140        #expect(doc.string == "Bonjour\n\n-- \nBob\nb.example")141        #expect(RichHTML.html(from: doc) == "<div>Bonjour</div><div><br></div><div class=\"spm-signature\"><div>--&nbsp;</div><div><b>Bob</b></div><div><a href=\"https://b.example\" rel=\"noopener noreferrer\">b.example</a></div></div>")142        // back and forth any number of times: one block, typed text intact143        for _ in 0..<3 {144            doc = apply(RichSignature.swap(in: doc, old: bob, new: alice), to: doc)145            doc = apply(RichSignature.swap(in: doc, old: alice, new: bob), to: doc)146        }147        #expect(doc.string == "Bonjour\n\n-- \nBob\nb.example" && doc.string.components(separatedBy: "-- \n").count == 2)148    }149150    @Test func senderWithoutSignatureRemovesTheBlockAndItsBlankLine() {151        var doc = document("Bonjour", alice)152        doc = apply(RichSignature.swap(in: doc, old: alice, new: none), to: doc)153        #expect(doc.string == "Bonjour")154        doc = apply(RichSignature.swap(in: doc, old: none, new: bob), to: doc)155        #expect(doc.string == "Bonjour\n\n-- \nBob\nb.example")156        doc = apply(RichSignature.swap(in: doc, old: bob, new: nil), to: doc)157        #expect(doc.string == "Bonjour")158        // an empty message: the legacy shape "\n\n-- \nsignature"159        #expect(document("", alice).string == "\n\n-- \nAlice\nDirection")160    }161162    @Test func anEditedSignatureIsNeverReplaced() {163        let doc = NSMutableAttributedString(attributedString: document("Bonjour", alice))164        doc.replaceCharacters(in: (doc.string as NSString).range(of: "Direction"), with: "Direction générale") // typed inside the block: the tag is inherited165        #expect(RichSignature.swap(in: doc, old: alice, new: bob) == nil)166        #expect(RichSignature.swap(in: doc, old: alice, new: none) == nil)167        // an explicit choice in the picker does replace it168        let forced = apply(RichSignature.swap(in: doc, old: alice, new: bob, force: true), to: doc)169        #expect(forced.string == "Bonjour\n\n-- \nBob\nb.example")170    }171172    @Test func aRemovedSignatureIsNotPutBack() {173        let typed = RichText.attributed(fromPlain: "Bonjour, sans signature")174        #expect(RichSignature.swap(in: typed, old: alice, new: bob) == nil) // Alice's was removed by hand175        #expect(apply(RichSignature.swap(in: typed, old: alice, new: bob, force: true), to: typed).string == "Bonjour, sans signature\n\n-- \nBob\nb.example")176        // text that already ends with the new signature, untagged (typed by hand): not doubled177        let manual = RichText.attributed(fromPlain: "Bonjour\n\n-- \nAlice\nDirection")178        #expect(RichSignature.swap(in: manual, old: none, new: alice) == nil)179    }180181    @Test func legacyBlockOfAPlainDraftIsRecognised() {182        let doc = NSMutableAttributedString(attributedString: RichText.attributed(fromPlain: "Texte tapé\n\n-- \nAlice\nDirection"))183        RichSignature.tagLegacy(in: doc, signatureText: "Alice\nDirection", id: "a")184        #expect(RichSignature.range(in: doc) == NSRange(location: 12, length: 19))185        #expect(apply(RichSignature.swap(in: doc, old: alice, new: bob), to: doc).string == "Texte tapé\n\n-- \nBob\nb.example")186        // not at the end, or not after a line break: left alone187        let middle = NSMutableAttributedString(attributedString: RichText.attributed(fromPlain: "-- \nAlice\nDirection\nsuite"))188        RichSignature.tagLegacy(in: middle, signatureText: "Alice\nDirection", id: "a")189        #expect(RichSignature.range(in: middle) == nil)190        // the block is recognised by `known` when the previous sender's signature is not what was inserted191        #expect(RichSignature.swap(in: doc, old: none, new: bob) == nil)192        #expect(RichSignature.swap(in: doc, old: none, new: bob, known: [alice]) != nil)193    }194195    @Test func managedSignatureDefaultsWinOverTheLegacyAddressEntry() throws {196        func s(_ json: String) throws -> Signature { try #require(Signature(json: try JSONValue.parse(Data(json.utf8)))) }197        let legacy = try s(#"{"id":"address:A1","name":"a@x","html":"","text":"Ancienne","default_for":["A1"],"default_for_replies":["A1"],"source":"address","read_only":true,"address_id":"A1"}"#)198        let work = try s(#"{"id":"s1","name":"Travail","html":"<div>Pro</div>","text":"Pro","default_for":["A1"],"default_for_replies":[]}"#)199        let short = try s(#"{"id":"s2","name":"Courte","html":"","text":"SP","default_for":[],"default_for_replies":["A1","A2"]}"#)200        #expect(Signature.defaultSignature(forAddress: "A1", isReply: false, in: [legacy, work, short])?.id == "s1")201        #expect(Signature.defaultSignature(forAddress: "A1", isReply: true, in: [legacy, work, short])?.id == "s2")202        #expect(Signature.defaultSignature(forAddress: "A1", isReply: true, in: [legacy, work])?.id == "s1")203        #expect(Signature.defaultSignature(forAddress: "A1", isReply: false, in: [legacy])?.id == "address:A1")204        #expect(Signature.defaultSignature(forAddress: "A2", isReply: false, in: [legacy, work, short]) == nil)205        #expect(SignatureChoice(work).html == "<div>Pro</div>" && !SignatureChoice(work).isEmpty && SignatureChoice(id: "x", html: "<div> </div>", text: " \n").isEmpty)206    }207}208209@Suite struct SnippetExpansionTests {210    private func snippet(_ shortcut: String?, _ text: String, html: String = "") throws -> Snippet {211        var o: JSONValue = ["id": .string(shortcut ?? "none"), "name": .string(shortcut ?? "none"), "html": .string(html), "text": .string(text)]212        if let shortcut { o["shortcut"] = .string(shortcut) }213        return try #require(Snippet(json: o))214    }215216    @Test func expandsWhenADelimiterFollowsTheShortcut() throws {217        let all = [try snippet("merci", "Merci beaucoup pour votre message."), try snippet("me", "moi"), try snippet(nil, "sans raccourci"), try snippet("rdv", "x", html: "<div>Rendez-vous <b>jeudi</b></div><ul><li>10 h</li></ul>")]218        #expect(SnippetExpander.completed(in: "Bonjour ;merci", snippets: all) == nil) // still typing: `;me` must not fire inside `;merci`219        let hit = try #require(SnippetExpander.completed(in: "Bonjour ;merci ", snippets: all))220        #expect(hit.snippet.shortcut == "merci" && hit.trigger == NSRange(location: 8, length: 6))221        #expect(SnippetExpander.completed(in: ";me\n", snippets: all)?.snippet.shortcut == "me")222        #expect(SnippetExpander.completed(in: "é ;MERCI.", snippets: all)?.trigger == NSRange(location: 2, length: 6))223        #expect(SnippetExpander.completed(in: "👩🏽‍💻 ;rdv ", snippets: all)?.trigger == NSRange(location: 8, length: 4)) // UTF-16 offsets224        for miss in ["mot;merci ", "a;b ", ";inconnu ", "; ", ";merci", "merci ", ";mer ci "] { #expect(SnippetExpander.completed(in: miss, snippets: all) == nil, "\(miss)") }225        let rich = SnippetExpander.content(of: all[3])226        #expect(rich.string == "Rendez-vous jeudi\n10 h" && RichHTML.html(from: rich) == "<div>Rendez-vous <b>jeudi</b></div><ul><li>10 h</li></ul>")227        #expect(SnippetExpander.content(of: all[0]).string == "Merci beaucoup pour votre message.")228    }229}230231@Suite struct RecipientRulesTests {232    @Test func typingCommitsAtSeparators() {233        #expect(RecipientInput.commit("a@b.co") == .init(entries: [], rest: "a@b.co"))234        #expect(RecipientInput.commit("a@b.co,") == .init(entries: [EmailAddress(email: "a@b.co")], rest: ""))235        #expect(RecipientInput.commit("a@b.co; c@d.co ; e") == .init(entries: [EmailAddress(email: "a@b.co"), EmailAddress(email: "c@d.co")], rest: " e"))236        #expect(RecipientInput.commit("a@b.co", force: true).entries == [EmailAddress(email: "a@b.co")])237        #expect(RecipientInput.commit("  ", force: true) == .init(entries: [], rest: ""))238        // a pasted list, names with commas, one address per line239        let pasted = RecipientInput.commit("\"Tremblay, Camille\" <camille@example.org>, Bob <bob@example.org>\ncarol@example.org;\tdave@example.org", force: true)240        #expect(pasted.entries.map(\.email) == ["camille@example.org", "bob@example.org", "carol@example.org", "dave@example.org"])241        #expect(pasted.entries[0].name == "Tremblay, Camille" && pasted.entries[1].name == "Bob")242        // a comma inside quotes or angle brackets does not split while typing243        #expect(RecipientInput.commit("\"Tremblay, Cam").entries.isEmpty)244        // what is not an address is kept as typed, to be shown as invalid — never silently dropped245        let bad = RecipientInput.commit("pas une adresse, x@, ok@example.org,")246        #expect(bad.entries.map(\.email) == ["pas une adresse", "x@", "ok@example.org"])247    }248249    @Test func validationFindsInvalidDuplicateAndMissingRecipients() {250        let a = EmailAddress(name: "A", email: "a@example.org"), b = EmailAddress(email: "B@example.org"), bad = EmailAddress(email: "pas une adresse")251        #expect(RecipientIssues.check(to: [], cc: [], bcc: []).none && RecipientIssues.check(to: [], cc: [], bcc: []).blocksSending)252        let issues = RecipientIssues.check(to: [a, bad], cc: [EmailAddress(email: "A@EXAMPLE.org"), b], bcc: [b, a])253        #expect(issues.invalid == [bad] && issues.duplicates.map(\.id) == ["a@example.org", "b@example.org"] && !issues.none && issues.blocksSending)254        let ok = RecipientIssues.check(to: [a], cc: [b], bcc: [])255        #expect(ok.isEmpty && !ok.blocksSending)256        #expect(!RecipientIssues.check(to: [a], cc: [a], bcc: []).blocksSending) // duplicates ask, they do not block257        let unique = RecipientIssues.deduplicated(to: [a, a], cc: [EmailAddress(email: "A@example.org"), b], bcc: [b])258        #expect(unique.to == [a] && unique.cc == [b] && unique.bcc.isEmpty)259    }260261    @Test func sensitiveRecipientsMatchAddressesAndDomains() {262        let prefs = ComposePrefs(undoSeconds: 20, sensitive: ["Boss@Example.org", "@legal.example"])263        #expect(prefs.sensitiveRecipients(among: ["boss@example.org", "x@legal.example", "y@example.org"]) == ["boss@example.org", "x@legal.example"])264        #expect(ComposePrefs(json: prefs.json) == ComposePrefs(undoSeconds: 20, sensitive: ["boss@example.org", "@legal.example"]))265    }266}267268@Suite struct SendPlanningTests {269    private func cal(_ tz: String) -> Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(identifier: tz)!; return c }270    private func at(_ y: Int, _ mo: Int, _ d: Int, _ h: Int, _ mi: Int = 0, tz: String) -> Date { cal(tz).date(from: DateComponents(year: y, month: mo, day: d, hour: h, minute: mi))! }271272    @Test func sendLaterPresetsAreInTheLocalTimeZone() {273        let tz = "America/Toronto", c = cal(tz)274        let friday = at(2026, 11, 20, 10, 30, tz: tz) // a Friday morning275        let options = Dictionary(uniqueKeysWithValues: SendLaterPreset.options(now: friday, calendar: c).map { ($0.preset, $0.date) })276        #expect(options[.inOneHour] == at(2026, 11, 20, 11, 30, tz: tz) && options[.thisEvening] == at(2026, 11, 20, 18, tz: tz) && options[.tomorrowMorning] == at(2026, 11, 21, 8, tz: tz))277        #expect(options[.tomorrowAfternoon] == at(2026, 11, 21, 13, tz: tz) && options[.mondayMorning] == at(2026, 11, 23, 8, tz: tz))278        // the same instant seen from Paris is another wall clock: presets follow the calendar they are given279        #expect(SendLaterPreset.tomorrowMorning.date(now: friday, calendar: cal("Europe/Paris")) == at(2026, 11, 21, 8, tz: "Europe/Paris"))280        // evening: no « this evening »; Sunday: « Monday morning » is tomorrow morning, offered once281        #expect(SendLaterPreset.thisEvening.date(now: at(2026, 11, 20, 17, 5, tz: tz), calendar: c) == nil)282        #expect(SendLaterPreset.mondayMorning.date(now: at(2026, 11, 22, 12, tz: tz), calendar: c) == nil)283        #expect(SendLaterPreset.mondayMorning.date(now: at(2026, 11, 23, 9, tz: tz), calendar: c) == at(2026, 11, 30, 8, tz: tz))284        // across the end of daylight saving time (1 Nov 2026 in Toronto) the wall clock is still 8:00285        #expect(SendLaterPreset.tomorrowMorning.date(now: at(2026, 10, 31, 22, tz: tz), calendar: c) == at(2026, 11, 1, 8, tz: tz))286        #expect(SendLaterPreset.isValid(friday.addingTimeInterval(120), now: friday) && !SendLaterPreset.isValid(friday.addingTimeInterval(30), now: friday) && !SendLaterPreset.isValid(friday.addingTimeInterval(31 * 86400), now: friday))287        #expect(RemindPreset.inTwoDays.date(now: friday, calendar: c) == at(2026, 11, 22, 9, tz: tz) && RemindPreset.inOneWeek.date(now: friday, calendar: c) == at(2026, 11, 27, 9, tz: tz))288    }289290    @Test func idempotencyKeyIsStableForTheSameSendOnly() {291        let base = ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 10), sendAt: nil, files: ["file_a"])292        #expect(base == ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 10), sendAt: nil, files: ["file_a"]))293        #expect(base.range(of: "^spm-[0-9a-f]{40}$", options: .regularExpression) != nil)294        let others = [ComposeSend.idempotencyKey(itemId: "J", digest: "D", options: SendOptions(undoSeconds: 10), sendAt: nil, files: ["file_a"]),295                      ComposeSend.idempotencyKey(itemId: "I", digest: "E", options: SendOptions(undoSeconds: 10), sendAt: nil, files: ["file_a"]),296                      ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 0), sendAt: nil, files: ["file_a"]),297                      ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 10, confirmSensitive: true), sendAt: nil, files: ["file_a"]),298                      ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 10), sendAt: Date(timeIntervalSince1970: 1_800_000_000), files: ["file_a"]),299                      ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 10, remindAt: Date(timeIntervalSince1970: 1_800_000_000), remindIfNoReply: true), sendAt: nil, files: ["file_a"]),300                      ComposeSend.idempotencyKey(itemId: "I", digest: "D", options: SendOptions(undoSeconds: 10), sendAt: nil, files: ["file_b"])]301        #expect(Set(others + [base]).count == others.count + 1)302        #expect(ComposeSend.acceptableCID("<img-1@spmail>") == "img-1@spmail" && ComposeSend.acceptableCID("a b") == nil && ComposeSend.acceptableCID("ii_abc$1") == nil)303    }304305    @Test func sendRequestCarriesInlinePartsAndThreading() {306        var m = OutgoingMessage(from: me, to: [EmailAddress(name: "B", email: "b@stg.spboucher.ai")], subject: "s", text: "t", html: "<div>t</div>", inReplyTo: ["m1@x"], references: ["m0@x", "m1@x"])307        m.quotedHTML = OutgoingMessage.quoteBlockOpen + "q</div>"308        m.quotedText = "> q"309        let r = SendRequest(m, attachments: [SendAttachment(fileId: "file_abcdefghij", filename: "c.png", inline: true, cid: "c@spmail"), SendAttachment(fileId: "file_klmnopqrst")])310        let j = SendOptions(undoSeconds: 10, confirmSensitive: true).apply(to: r.json)311        #expect(j["html"].stringValue == "<div>t</div>" + OutgoingMessage.quoteBlockOpen + "q</div>" && j["text"].stringValue == "t\n\n> q")312        #expect(j["attachments"].arrayValue?.first?["inline"].boolValue == true && j["attachments"].arrayValue?.first?["cid"].stringValue == "c@spmail" && j["attachments"].arrayValue?.count == 2)313        #expect(j["in_reply_to"].stringValue == "m1@x" && j["references"].stringArray == ["m0@x", "m1@x"] && j["undo_seconds"].intValue == 10 && j["confirm_sensitive"].boolValue == true)314    }315}316
Files main
Menu

Theme