Cotton code
273 lines · 13.2 KB · SwiftRaw
// Which shares knock, where they knock, and what the app does about it.//// The rule used to be a `guard` inside `ShareOpener.arrived` naming one// classifier, which is why adding the second kind meant editing a decision// rather than a list. Every fixture here is synthetic.@testable import CottonKitimport XCTestfinal class ShareKnockTests: XCTestCase {    /// Cotton's shelf: a PDF is a document. Cotton Books' takes it as a book.    private let cotton = ShareShelf(pdfIsBook: false)    private let books = ShareShelf(pdfIsBook: true)    private func file(_ name: String, mime: String? = nil) -> SharedFile {        SharedFile(path: "/tmp/share-inbox/abc", fileName: name, mimeType: mime)    }    // ── Which kinds ───────────────────────────────────────────────────────    func testAChatExportKnocks() {        XCTAssertEqual(ShareKnock.kind(file("WhatsApp Chat - Priya.zip"), shelf: cotton, head: { nil }), .chatExport)    }    /// **The walk's finding 5.** A shared voice note staged quietly, did    /// nothing visible, and was still in the app group when the person went    /// looking for their meeting. A recording ends on a screen — the meeting it    /// became — so it knocks.    func testARecordingKnocks() {        XCTAssertEqual(ShareKnock.kind(file("voice-note.m4a"), shelf: cotton, head: { nil }), .recording)        XCTAssertEqual(            ShareKnock.kind(file("PTT-20260915-WA0007.opus"), shelf: cotton, head: { nil }), .recording,            "a WhatsApp voice note is the recording this owner shares most often")        XCTAssertEqual(            ShareKnock.kind(file("memo", mime: "audio/x-m4a"), shelf: cotton, head: { nil }), .recording,            "a share that declares its type and names no container is still a recording")    }    // RULE (Cotton Music, 4 Nov 2026): in Cotton Music every audio share and a shared folder is a song; in Cotton a lossless rip is a song and a voice note stays a recording.    func testASongKnocksInMusicAndALosslessRipEverywhere() {        let music = ShareShelf.of(flavour: ShareShelf.musicFlavour)        XCTAssertTrue(music.audioIsMusic)        XCTAssertEqual(ShareKnock.kind(file("01 Low Tide.mp3"), shelf: music, head: { nil }), .song)        XCTAssertEqual(ShareKnock.kind(file("02 Night Bus.opus"), shelf: music, head: { nil }), .song)        XCTAssertEqual(ShareKnock.kind(file("03 Harbour.flac"), shelf: cotton, head: { nil }), .song)        XCTAssertEqual(ShareKnock.kind(file("PTT-20260915-WA0007.opus"), shelf: cotton, head: { nil }), .recording)        XCTAssertEqual(ShareKnock.kind(file("voice-note.m4a"), shelf: cotton, head: { nil }), .recording)        XCTAssertEqual(ShareKnock.route(.song), ShareKnock.songList)    }    /// **Every kind knocks** (the owner, 23 Oct 2026: when the sheet closes    /// the app opens, for every kind of shared item, as it does for a chat    /// export) — in the drain's own precedence.    func testEveryKindOfShareKnocks() {        XCTAssertEqual(ShareKnock.kind(file("IMG_0001.jpg"), shelf: cotton, head: { nil }), .picture)        XCTAssertEqual(ShareKnock.kind(file("clip.mov"), shelf: cotton, head: { nil }), .picture)        XCTAssertEqual(ShareKnock.kind(file("statement.pdf"), shelf: cotton, head: { nil }), .document)        XCTAssertEqual(ShareKnock.kind(file("backup.7z"), shelf: cotton, head: { nil }), .document)        XCTAssertEqual(ShareKnock.kind(file("home.cottonpkg"), shelf: cotton, head: { nil }), .package)        let link = ShareEntry(at: "2026-10-23T10:00:00Z", kind: ShareKind.url.rawValue, url: "https://example.com/a")        XCTAssertEqual(ShareKnock.kind(link, shelf: cotton, head: { _ in nil }), .link)        let prose = ShareEntry(at: "2026-10-23T10:00:00Z", kind: ShareKind.text.rawValue, text: "buy milk")        XCTAssertEqual(ShareKnock.kind(prose, shelf: cotton, head: { _ in nil }), .link)        let nothing = ShareEntry(at: "2026-10-23T10:00:00Z", kind: ShareKind.text.rawValue)        XCTAssertNil(ShareKnock.kind(nothing, shelf: cotton, head: { _ in nil }), "an entry with nothing in it files nothing")    }    /// The classification is the DRAIN's, so a share that knocks is always a    /// share the branch it knocked for will take. Two lists that must agree is    /// how a fix lands on only one of them.    func testAChatExportOutranksItsOwnTextFile() {        // A WhatsApp `_chat.txt` is decided by its first line, which is the one        // rule that looks inside a file — and the drain reads it the same way.        let head = "[15/09/2026, 10:00:00] Priya Example: hello\n"        XCTAssertEqual(ShareKnock.kind(file("_chat.txt"), shelf: cotton, head: { head }), .chatExport)    }    /// An EPUB is a book in every app; a PDF is one in Cotton Books and a    /// document in Cotton; a Goodreads export knocks as one, told by its first    /// line, and any other CSV is a document.    func testABookAndAGoodreadsLibraryKnock() {        XCTAssertEqual(ShareKnock.kind(file("The Lantern Orchard.epub"), shelf: cotton, head: { nil }), .book)        XCTAssertEqual(ShareKnock.kind(file("book", mime: "org.idpf.epub-container"), shelf: cotton, head: { nil }), .book)        XCTAssertEqual(ShareKnock.kind(file("statement.pdf"), shelf: cotton, head: { nil }), .document)        XCTAssertEqual(ShareKnock.kind(file("statement.pdf"), shelf: books, head: { nil }), .book)        let library = "Book Id,Title,Author,Author l-f,Additional Authors,ISBN\n1,Invented,Someone,,,\n"        XCTAssertEqual(ShareKnock.kind(file("goodreads_library_export.csv"), shelf: books, head: { library }), .goodreads)        XCTAssertEqual(ShareKnock.kind(file("export", mime: "text/csv"), shelf: cotton, head: { "\u{FEFF}" + library }), .goodreads)        XCTAssertEqual(ShareKnock.kind(file("budget.csv"), shelf: books, head: { "Date,Amount\n" }), .document)        XCTAssertEqual(ShareKnock.route(.book), ShareKnock.bookList)        XCTAssertEqual(ShareKnock.route(.goodreads), ShareKnock.bookList)    }    // ── Where ─────────────────────────────────────────────────────────────    /// The knock is not navigation — the drain decides where the app goes. The    /// route matters for the one case where the drain finds nothing, and there    /// it has to be honest about the kind that was shared.    func testEachKindKnocksWhereItsOwnShareWouldLand() {        XCTAssertEqual(ShareKnock.route(.chatExport), .messagesImport)        XCTAssertEqual(ShareKnock.route(.recording), .meetings(importing: false))        XCTAssertEqual(ShareKnock.route(.picture), .photos(show: nil))        XCTAssertEqual(ShareKnock.route(.document), .documents(status: nil))        XCTAssertEqual(ShareKnock.route(.package), .bringIn)        XCTAssertEqual(ShareKnock.route(.link), .reader)    }    func testTheKnockCarriesTheEntrysIdAndTheMarker() throws {        let url = try XCTUnwrap(ShareKnock.url(.recording, shareId: "share-7"))        XCTAssertEqual(url.scheme, CottonURLScheme.name)        XCTAssertEqual(Route.deepLink(url), .meetings(importing: false))        let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []        XCTAssertEqual(items.first(where: { $0.name == ShareOpen.marker })?.value, "share-7")    }    // ── Coming back ───────────────────────────────────────────────────────    func testEveryKindOfKnockIsRecognisedAsAnArrival() throws {        for kind in ShareKnockKind.allCases {            let url = try XCTUnwrap(ShareKnock.url(kind, shareId: "share-1"))            XCTAssertTrue(ShareKnock.isArrival(url), "\(kind) is a knock")            XCTAssertTrue(ShareOpen.isShareArrival(url), "and the old name still answers")        }    }    /// Only a knock triggers a drain: an ordinary deep link into the same    /// screen — a notification's, one typed by hand — is navigation.    func testADeepLinkWithoutTheMarkerIsNotAnArrival() throws {        for kind in ShareKnockKind.allCases {            let plain = try XCTUnwrap(                URL(string: "\(CottonURLScheme.name)://\(ShareKnock.route(kind).path)"))            XCTAssertFalse(ShareKnock.isArrival(plain))        }        let elsewhere = try XCTUnwrap(            URL(string: "\(CottonURLScheme.name):///todos?\(ShareOpen.marker)=share-1"))        XCTAssertFalse(            ShareKnock.isArrival(elsewhere),            "a `?share=` on some other screen is somebody else's query parameter")        let foreign = try XCTUnwrap(URL(string: "https://example.com/meetings?share=1"))        XCTAssertFalse(ShareKnock.isArrival(foreign))    }    // ── The opener ────────────────────────────────────────────────────────    /// The whole of `ShareOpener`, with two closures and no share sheet.    @MainActor    private func opener(opens: Bool = true) -> (ShareOpener, Box) {        let box = Box()        let opener = ShareOpener(            open: { url in                box.opened.append(url)                return opens            },            head: { _ in nil },            shelf: cotton        )        return (opener, box)    }    private final class Box: @unchecked Sendable {        var opened: [URL] = []    }    @MainActor    func testARecordingOpensCottonAtTheMeetingsList() async throws {        let (opener, box) = opener()        let entry = ShareEntry(            id: "share-9",            at: "2026-09-15T14:56:00Z",            kind: ShareKind.file.rawValue,            path: "/tmp/share-inbox/share-9",            fileName: "voice-note.m4a"        )        let outcome = await opener.arrived(entry)        let url = try XCTUnwrap(box.opened.first)        XCTAssertEqual(outcome, .opened(url))        XCTAssertEqual(Route.deepLink(url), .meetings(importing: false))        XCTAssertTrue(ShareOpen.isShareArrival(url))    }    @MainActor    func testAPictureOpensCottonAtPhotos() async throws {        let (opener, box) = opener()        let entry = ShareEntry(            id: "share-3",            at: "2026-09-15T14:56:00Z",            kind: ShareKind.file.rawValue,            path: "/tmp/share-inbox/share-3",            fileName: "IMG_0001.jpg"        )        let outcome = await opener.arrived(entry)        let url = try XCTUnwrap(box.opened.first)        XCTAssertEqual(outcome, .opened(url))        XCTAssertEqual(Route.deepLink(url), .photos(show: nil))    }    /// **The share is not lost** when nobody on the responder chain will open    /// it: the mailbox entry stands and the next foreground drains it.    @MainActor    func testAKnockNobodyAnswersIsStillAShareThatWaits() async throws {        let (opener, box) = opener(opens: false)        let entry = ShareEntry(            id: "share-4",            at: "2026-09-15T14:56:00Z",            kind: ShareKind.file.rawValue,            path: "/tmp/share-inbox/share-4",            fileName: "voice-note.m4a"        )        let outcome = await opener.arrived(entry)        let url = try XCTUnwrap(box.opened.first)        XCTAssertEqual(outcome, .couldNotOpen(url))    }}// MARK: - The mailbox's one exceptionfinal class ShareReofferTests: XCTestCase {    private final class Storage: ShareMailboxStorage, @unchecked Sendable {        private let lock = NSLock()        private var values: [String: String] = [:]        func text(_ key: String) -> String? {            lock.lock()            defer { lock.unlock() }            return values[key]        }        func set(_ key: String, _ value: String?) {            lock.lock()            defer { lock.unlock() }            if let value { values[key] = value } else { values.removeValue(forKey: key) }        }    }    private func entry(attempt: Int = 0) -> ShareEntry {        ShareEntry(            id: "share-1",            at: "2026-09-15T14:56:00Z",            kind: ShareKind.file.rawValue,            path: "/tmp/share-inbox/share-1",            fileName: "voice-note.m4a",            attempt: attempt        )    }    /// One more try, and exactly one: the count IS the bound, so a caller that    /// asks twice gets one.    func testAShareIsPutBackOnceAndNeverTwice() {        let mailbox = ShareMailbox(storage: Storage())        XCTAssertTrue(mailbox.reoffer(entry()))        let waiting = mailbox.drain()        XCTAssertEqual(waiting.map(\.attempt), [1])        XCTAssertFalse(mailbox.reoffer(waiting[0]), "twice is a leak with extra steps")        XCTAssertEqual(mailbox.drain(), [])    }    /// An entry put back names the file that is actually on disk: a branch may    /// rename a staged copy before it hands it over.    func testAPutBackEntryNamesWhereTheBytesAreNow() {        let mailbox = ShareMailbox(storage: Storage())        let moved = ShareEntry(entry(), movedTo: "/tmp/share-inbox/share-1.m4a")        XCTAssertTrue(mailbox.reoffer(moved))        XCTAssertEqual(mailbox.drain().first?.path, "/tmp/share-inbox/share-1.m4a")    }}