Cotton code
255 lines · 13.2 KB · SwiftRaw
// The phone's audio tables are the CRATE's, held by a by-path read.//// `MeetingAudioFormats` is a twin of two tables — the containers in// `crates/cotton-core/src/media/meeting_audio.rs` and the types the server// signs an upload for in `crates/cotton-rules/src/media.rs` (where the Worker// reads them too, as WASM) — generated in neither direction, and it has to be a twin: the phone decides what a picker OFFERS// and what a share sheet CLAIMS before it copies a byte, and a picker that// showed a container the server signs no upload for is a picker that lied. The// alternative to a twin is finding out three hours later on a train.//// So this reads the Rust files and holds the two Swift tables to them. It is rule// (b) of the by-path guards — `SourceSweep.mustRead` fails loudly naming the// path and the lane, so a file that MOVES reddens here rather than quietly// making the guard cover nothing.@testable import CottonKit@testable import CottonUIimport XCTestfinal class MeetingAudioContractTests: XCTestCase {    private static let formatsPath = "crates/cotton-core/src/media/meeting_audio.rs"    /// Where `MEETING_AUDIO_TYPES` is declared: the one upload table the phone's    /// core and the Worker both read (c891223a14).    private static let typesPath = "crates/cotton-rules/src/media.rs"    /// What `meetings.create` ANSWERS, written by the Rust test that runs it.    private static let answerPath = "crates/cotton-ffi/src/phone/meetings-create-answer.json"    /// Every `("ext", "mime")` pair inside one `&[…]` table in the Rust file.    private func rustPairs(_ table: String) throws -> [(String, String)] {        let source = try SourceSweep.mustRead(            Self.formatsPath,            ownedBy: "the Rust core (a meeting's audio containers, `media/meeting_audio.rs`)")        guard            let start = source.range(of: table),            // `= &[` and not `[`: the declaration's own TYPE carries brackets            // (`&[&str]`, `&[(&str, &str)]`), so the first `[` after the name is            // not the table's.            let open = source.range(of: "= &[", range: start.upperBound..<source.endIndex),            let close = source.range(of: "];", range: open.upperBound..<source.endIndex)        else {            XCTFail("could not find \(table) in \(Self.formatsPath)")            return []        }        let body = String(source[open.upperBound..<close.lowerBound])        let quoted = try SourceSweep.matches(#""[^"]+""#, in: body)            .map { String($0.dropFirst().dropLast()) }        XCTAssertEqual(quoted.count % 2, 0, "\(table) did not read as pairs")        return stride(from: 0, to: quoted.count - 1, by: 2).map { (quoted[$0], quoted[$0 + 1]) }    }    /// Every quoted string inside one `&[…]` table of the rules' media file — for the flat list.    private func rustStrings(_ table: String) throws -> [String] {        let source = try SourceSweep.mustRead(            Self.typesPath,            ownedBy: "the Rust rules (what the server signs an upload for, `cotton-rules/src/media.rs`)")        guard            let start = source.range(of: table),            // `= &[` and not `[`: the declaration's own TYPE carries brackets            // (`&[&str]`, `&[(&str, &str)]`), so the first `[` after the name is            // not the table's.            let open = source.range(of: "= &[", range: start.upperBound..<source.endIndex),            let close = source.range(of: "];", range: open.upperBound..<source.endIndex)        else {            XCTFail("could not find \(table) in \(Self.typesPath)")            return []        }        let body = String(source[open.upperBound..<close.lowerBound])        return try SourceSweep.matches(#""[^"]+""#, in: body)            .map { String($0.dropFirst().dropLast()) }    }    /// **The canonical type per container.** What the object key is written    /// with, and what the vendor is told.    func testEveryContainerAndItsCanonicalTypeMatchTheCrate() throws {        let declared = try rustPairs("MEETING_AUDIO_FORMATS")        XCTAssertFalse(declared.isEmpty, "the crate's table read as nothing")        let mine = MeetingAudioFormats.formats.map { ($0.ext, $0.mime) }        XCTAssertEqual(            declared.map(\.0).sorted(), mine.map(\.0).sorted(),            "the containers this phone offers are not the ones the crate accepts"        )        for (ext, mime) in declared {            XCTAssertEqual(                MeetingAudioFormats.mime(forExtension: ext), mime,                ".\(ext) is written as \(mime) by the crate and as something else here"            )        }    }    /// **Every spelling a caller may SAY.** Wider than one per container on    /// purpose — a picker, a share sheet and a download report the same file    /// differently — and this phone reads it in the direction the crate does    /// not: type → the extension to file under.    func testEveryTypeTheServerSignsAnUploadForIsOneThisPhoneCanFile() throws {        let accepted = try rustStrings("MEETING_AUDIO_TYPES")        XCTAssertFalse(accepted.isEmpty, "the crate's type list read as nothing")        for type in accepted {            let filed = MeetingAudioFormats.fileExtension(forDeclaredType: type)            XCTAssertNotNil(                filed,                """                the crate accepts \(type) and this phone has no container to file it \                under, so a share declaring it would be renamed to nothing                """            )            guard let filed else { continue }            XCTAssertTrue(                MeetingAudioFormats.extensions.contains(filed),                "\(type) files as .\(filed), which is not a container the crate takes"            )        }    }    /// The other direction: nothing here invents a type the server would refuse.    func testThisPhoneClaimsNoTypeTheCrateWouldRefuse() throws {        let accepted = Set(try rustStrings("MEETING_AUDIO_TYPES"))        for (type, _) in MeetingAudioFormats.acceptedTypes {            XCTAssertTrue(accepted.contains(type), "\(type) is not on the crate's list")        }        for (_, mime) in MeetingAudioFormats.formats {            XCTAssertTrue(accepted.contains(mime), "\(mime) is written but not accepted")        }    }    // ── The rules around the tables ───────────────────────────────────────    func testAnExtensionIsReadCaseAndDotInsensitively() {        XCTAssertEqual(MeetingAudioFormats.mime(forExtension: "M4A"), "audio/mp4")        XCTAssertEqual(MeetingAudioFormats.mime(forExtension: ".opus"), "audio/ogg")        XCTAssertEqual(MeetingAudioFormats.mime(forFileName: "/a/b/Voice Memo.M4A"), "audio/mp4")    }    /// **`nil` is a refusal, never a default.** Sending    /// `application/octet-stream` for an extension nobody listed would be this    /// phone asking the server to guess at a file it has already decided not to    /// understand.    func testAnExtensionNobodyListedIsNothing() {        XCTAssertNil(MeetingAudioFormats.mime(forFileName: "notes.txt"))        XCTAssertNil(MeetingAudioFormats.mime(forFileName: "blob"))        XCTAssertFalse(MeetingAudioFormats.accepts(fileName: "clip.mov"))        XCTAssertNil(MeetingAudioFormats.fileExtension(forDeclaredType: "application/zip"))    }    func testTheRecordersOwnContainerIsOneTheCrateAccepts() {        XCTAssertTrue(MeetingAudioFormats.extensions.contains(MeetingAudioFormats.recordedExtension))    }    /// **The capture container has to be one the crate accepts too**, because a    /// recording the export could not make an MPEG-4 of is filed as it is — a    /// capture file torn off mid-packet is exactly that case. If `.caf` ever    /// left the crate's table, that path would become a refusal at the    /// boundary over bytes the person can hear.    func testTheContainerTheRecorderCapturesIntoIsOneTheCrateAccepts() {        XCTAssertTrue(MeetingAudioFormats.extensions.contains(MeetingAudioFormats.capturedExtension))    }    /// The two names the holding area uses, and that they are not the same    /// file: the encode writes BESIDE the capture, never over the only copy of    /// the audio.    func testTheCaptureAndTheDeliveredFileAreTwoFiles() {        XCTAssertNotEqual(MeetingFiles.capturedFileName, MeetingFiles.deliveredFileName)    }    // ── The title a file lends a meeting ──────────────────────────────────    func testTheTitleIsTheFilesOwnStem() {        XCTAssertEqual(MeetingAudioFormats.titleFromFileName("Board review.m4a"), "Board review")        XCTAssertEqual(MeetingAudioFormats.titleFromFileName("/a/b/PTT-0007.opus"), "PTT-0007")        XCTAssertEqual(MeetingAudioFormats.titleFromFileName("memo"), "memo")    }    /// Empty means "say nothing", and the crate's own default is what names it.    func testAFileThatIsNothingButAnExtensionLendsNoTitle() {        // A name that is NOTHING but an extension keeps it: a leading dot is        // not a container, it is a hidden file called `.m4a`.        XCTAssertEqual(MeetingAudioFormats.titleFromFileName(".m4a"), ".m4a")        XCTAssertEqual(MeetingAudioFormats.titleFromFileName(""), "")        // A stem of nothing but spaces is nothing: the crate's own default is a        // better name than three blanks.        XCTAssertEqual(MeetingAudioFormats.titleFromFileName("   .opus  "), "")    }    /// A blank title is an ABSENT title on the wire: a person who cleared the    /// field said "you name it", not "call it nothing".    func testABlankTitleIsNotSent() throws {        let sent = MeetingCreateRequest(path: "/a/x.m4a", source: .record, title: "   ")        let json = String(decoding: try JSONEncoder().encode(sent), as: UTF8.self)        XCTAssertFalse(json.contains("title"), json)        let named = MeetingCreateRequest(path: "/a/x.m4a", source: .record, title: "  Standup ")        XCTAssertEqual(named.title, "Standup", "and a typed one is trimmed")    }    // ── The answer ────────────────────────────────────────────────────────    /// **The route is the crate's**, parsed rather than rebuilt: the route    /// strings are wire protocol and a second spelling up here would be a    /// second opinion about where a meeting lives.    func testTheAnswersRouteIsParsedAndNotRebuilt() throws {        let answered = #"{"id":"m-1","route":"/meetings/meeting/m-1","key":"ws/meetings/m-1/full.m4a"}"#        let created = try JSONDecoder().decode(MeetingCreated.self, from: Data(answered.utf8))        XCTAssertEqual(created.landing, .meetingsMeeting(id: "m-1"))    }    /// A newer server is allowed to be ahead of an older app, and losing the    /// meeting that was just created would be the worse failure.    func testARouteThisBuildCannotParseStillOpensTheMeeting() throws {        let answered = #"{"id":"m-2","route":"/meetings/meeting/m-2/highlights"}"#        let created = try JSONDecoder().decode(MeetingCreated.self, from: Data(answered.utf8))        XCTAssertEqual(created.landing, .meetingsMeeting(id: "m-2"))    }    /// **The answer the CRATE actually emits, decoded by the shape this app    /// declares.**    ///    /// The two cases above decode a string written here, which is the app    /// saying what it would like to receive. That is not a contract: the crate    /// answered a write envelope — `{answer: {…}, rail, queued, …}` — for the    /// whole of PR #699 and #700, `MeetingCreated`'s defaulted fields decoded    /// it to `("", "")`, and every landing in the app pushed a route with no id    /// (the walk of 15 Sep 2026). Both sides were tested and neither test could    /// see the other.    ///    /// So this reads the file a `cargo test` WRITES from a real run of    /// `meetings.create` over a synthetic phone    /// (`crates/cotton-ffi/src/phone/meetings_tests.rs`, the emitter says how    /// to regenerate it). Change the answer's shape on either side and one of    /// the two goes red.    func testTheCratesOwnAnswerDecodesIntoTheShapeThisAppDeclares() throws {        let emitted = try SourceSweep.mustRead(            Self.answerPath,            ownedBy: "the Rust core (what `meetings.create` answers, emitted by its own test)")        struct Emitted: Decodable { let answer: MeetingCreated }        let file = try JSONDecoder().decode(Emitted.self, from: Data(emitted.utf8))        XCTAssertFalse(file.answer.id.isEmpty, "the id is at the top of `data`, not under `answer`")        XCTAssertEqual(file.answer.route, "/meetings/meeting/\(file.answer.id)")        XCTAssertEqual(file.answer.landing, .meetingsMeeting(id: file.answer.id))        // And the envelope's own words are NOT what a meeting answers with.        let tree = try JSONSerialization.jsonObject(with: Data(emitted.utf8))        let answer = (tree as? [String: Any])?["answer"] as? [String: Any]        XCTAssertNotNil(answer)        for envelope in ["answer", "rail", "queued", "tables", "method"] {            XCTAssertNil(                answer?[envelope],                "`\(envelope)` is the write envelope's word; `meetings.create` answers its own shape"            )        }    }}