Cotton code
161 lines · 9.2 KB · SwiftRaw
// Videos as its table's page, with nothing the old film screen showed lost// (rebuild item 4, the no-loss audit ~/m5b17-audit-videos.md): the film// playing in its print's window, where its bytes are said honestly (the// original asked first, the ledger before the one fetch, the view stamped,// the crate's refusal kept, an arrival asking the ledger only), the margin's// caption or else its length beside the play mark, the day and place by hand,// its albums as tags, "What Cotton saw", the review with Keep and Delete,// "Seen in", the size and length in words, and Delete's words with no Undo;// and the films in the one library — `/videos` is the library showing the// films, a film's print its poster, never the film.//// Each is a generic definition key or surface drawn once (the player is// Faces/MediaStage, Photos' build), never Videos' own Swift. Every record is// invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class VideosNoLossTests: XCTestCase {    private static var resources: Bundle? {        Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))    }    private func definitions() throws -> [String: TableDefinition] {        let loaded = FixtureDefinitions.load(from: try XCTUnwrap(Self.resources))        XCTAssertEqual(loaded.failures, [])        return Dictionary(uniqueKeysWithValues: loaded.definitions.map { ($0.id, $0) })    }    private func table(_ id: String) throws -> TableDefinition {        try XCTUnwrap(try definitions()[id], "\(id) has no definition")    }    private func records(_ table: String) throws -> [TableRecord] {        try FixtureDefinitions.fixtureRecords(for: table, bundle: try XCTUnwrap(Self.resources)).map { record in            guard let words = Self.said[table]?[record.id] else { return record }            return CoreSaid.read(record, words: words)        }    }    /// The core's words for each fixture film's typed columns, as a read    /// carries them (`CoreSaid`); Swift spells no size or length.    private static let said: [String: [String: [String: String]]] = [        "video": ["example-video-1": ["size_bytes": "13 MB", "duration_ms": "0:42"]],    ]    private func record(_ table: String, _ id: String) throws -> TableRecord {        try XCTUnwrap(try records(table).first { $0.id == id }, "\(table) has no \(id)")    }    private func code(_ path: String) throws -> String {        SourceSweep.withoutComments(            try String(contentsOf: SourceSweep.iosSources.appendingPathComponent("CottonUI/\(path)"), encoding: .utf8))    }    /// A film on this phone, or not, and the crate's refusal of the fetch.    private func stage(        key: String? = "ws-1/videos/aa.mov",        path: ScriptedCore.Reply = .ok(#"{"present":false}"#),        ensure: ScriptedCore.Reply = .refuse(            code: "no_media_fetch", message: "these bytes are not on this device and this build has no way to fetch them.")    ) -> (MediaStageModel, ScriptedCore) {        let core = ScriptedCore([            CottonMethod.readMediaPath: path,            CottonMethod.mediaEnsure: ensure,            CottonMethod.mediaViewed: .ok("{}"),        ])        return (MediaStageModel(media: PhotosMediaSource(core: core), key: key), core)    }    // ── The key ─────────────────────────────────────────────────────────────    /// RULE: A picture's `caption_fallback` is optional and read only when its `caption` says nothing — a column naming neither reads as before, and the key round-trips — because a newer or older build's definition must still draw.    func testTheCaptionFallbackDecodesAndIsReadOnlyWhenTheCaptionIsBlank() throws {        let json = #"{"key": "key", "type": "file", "caption": "caption", "caption_fallback": "duration_ms"}"#        let column = try JSONDecoder().decode(ColumnDefinition.self, from: Data(json.utf8))        XCTAssertEqual(column.captionFallback, "duration_ms")        let again = try JSONDecoder().decode(ColumnDefinition.self, from: try JSONEncoder().encode(column))        XCTAssertEqual(again.captionFallback, "duration_ms")        let plain = try JSONDecoder().decode(ColumnDefinition.self, from: Data(#"{"key": "key", "type": "photo"}"#.utf8))        XCTAssertNil(plain.captionFallback)        let photo = try table("photo")        let untitled = try record("photo", "example-photo-2")        XCTAssertNil(photo.pictureCaption(of: "key", in: untitled), "a photo names no fallback: its blank caption stays blank")    }    // ── A film's page ──────────────────────────────────────────────────────    /// RULE: (film 2) Where the film's bytes are is asked for the ORIGINAL first (a film's key resolves under the tile's order to its thumbnail JPEG and would play nothing), the ledger before the one fetch, and a film already here is played and its view stamped with no fetch.    func testTheFilmIsAskedForAsTheOriginalLedgerFirst() async throws {        let (here, hereCore) = stage(path: .ok(#"{"present":true,"path":"/var/media/aa.mov","tier":"original"}"#))        await here.resolve()        XCTAssertEqual(here.bytes, .ready(path: "/var/media/aa.mov"))        let asked = await hereCore.calls        let ledger = try XCTUnwrap(asked.first { $0.method == CottonMethod.readMediaPath })        XCTAssertTrue(ledger.requestJSON.contains(#""tier":"original""#), ledger.requestJSON)        XCTAssertFalse(asked.map(\.method).contains(CottonMethod.mediaEnsure), "bytes here are never fetched again")        XCTAssertTrue(asked.map(\.method).contains(CottonMethod.mediaViewed), "opening the page stamps the view")        let (away, awayCore) = stage()        await away.resolve()        let order = await awayCore.methodsCalled()        let read = try XCTUnwrap(order.firstIndex(of: CottonMethod.readMediaPath))        let fetch = try XCTUnwrap(order.firstIndex(of: CottonMethod.mediaEnsure))        XCTAssertLessThan(read, fetch, "the ledger first, then the one fetch")    }    /// RULE: (film 2) A refused fetch says in the app's own words that it could not be fetched (never the store's own sentence), the poster stands in the window, and a film with no key asks nothing and says it is not here.    func testARefusedFetchKeepsTheCratesSentence() async throws {        let (away, _) = stage()        await away.resolve()        XCTAssertEqual(away.bytes, .absent)        let refusal = try XCTUnwrap(away.refusal)        XCTAssertFalse(refusal.isEmpty)        XCTAssertFalse(refusal.contains("this build has no way"), "never the store's own words")        let (none, noneCore) = stage(key: nil)        await none.resolve()        XCTAssertEqual(none.bytes, .absent)        let asked = await noneCore.methodsCalled()        XCTAssertTrue(asked.isEmpty, "\(asked)")    }    /// RULE: (film 2) Bytes arriving on this phone while the film is absent are asked of the LEDGER only (tier original), never the radio — a refused fetch re-run on every tick once pulled a whole film sixty times an hour.    func testAnArrivalWhileAbsentAsksTheLedgerOnly() async throws {        let (model, core) = stage()        await model.resolve()        let fetches = await core.methodsCalled().filter { $0 == CottonMethod.mediaEnsure }.count        XCTAssertEqual(fetches, 1, "opening the page is the one fetch")        await model.resolveHere()        XCTAssertEqual(model.bytes, .absent)        await core.answer(CottonMethod.readMediaPath, .ok(#"{"present":true,"path":"/var/media/aa.mov","tier":"original"}"#))        await model.resolveHere()        XCTAssertEqual(model.bytes, .ready(path: "/var/media/aa.mov"))        XCTAssertNil(model.refusal)        let asked = await core.calls        XCTAssertEqual(asked.filter { $0.method == CottonMethod.mediaEnsure }.count, fetches, "an arrival fetched")        XCTAssertTrue(asked.filter { $0.method == CottonMethod.readMediaPath }.allSatisfy { $0.requestJSON.contains(#""tier":"original""#) })        XCTAssertTrue(try code("Faces/MediaStage.swift").contains(".onMediaArrival { await model?.resolveHere() }"))    }    /// RULE: (film 3) The print's margin is the film's length ("0:42") beside the play mark; with no length, the mark alone — never "0:00" for a film nobody measured. The title is said once, by the page's head, never again as a caption.    func testTheMarginIsTheLengthWithThePlayMark() throws {        let video = try table("video")        let kettle = try record("video", "example-video-1")        let unmeasured = try record("video", "example-video-2")        let margin = video.pictureMargin(of: "key", in: kettle)        XCTAssertEqual(margin.words, "0:42")        XCTAssertFalse(margin.own)        XCTAssertNil(video.pictureMargin(of: "key", in: unmeasured).words)    }    // ── Films in the library ───────────────────────────────────────────────    // ── The old screen is gone ─────────────────────────────────────────────}