Cotton code
143 lines · 6.0 KB · SwiftRaw
// The Swift `Route` enum against the table that owns it.//// The route STRINGS are wire protocol (P6) and Rust declares them:// `crates/cotton-ffi/src/phone/routes.rs::ROUTES`, held by `routes_tests.rs`.// This enum// is a parser and a formatter over that list, so the two have to be compared by// PATH — and a missing table has to fail LOUDLY, never against an empty list.//// **Two comparisons, and they catch different things.** The design asks for a// SHARED `routes.list` method so the comparison runs through the FFI, and that// has landed: `testTheEnumMatchesWhatTheCoreAnswers` opens a core over a// temporary container, calls the method and compares — which also proves the// phone build ANSWERS it, something no amount of reading the source can.//// The by-path read STAYS beside it rather than being replaced. A stale enum and// a build that cannot answer are two different failures, and only the by-path// read survives an XCFramework that was not rebuilt: the archive is a build// PRODUCT, so a test bundle can link an old one and agree with itself all day.//// The path below belongs to the RUST FFI lane. Grep it repo-wide — tests and// every open worktree included — before moving that file.import CottonKitimport XCTestfinal class RouteTableTests: XCTestCase {    private static let routesPath =        "crates/cotton-ffi/src/phone/routes.rs"    private func rustRoutes() throws -> [String] {        let source = try SourceSweep.mustRead(            RouteTableTests.routesPath,            ownedBy: "Rust FFI (the phone's route table, `phone/routes.rs`)"        )        guard            let start = source.range(of: "pub const ROUTES"),            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 ROUTES in \(RouteTableTests.routesPath)")            return []        }        let body = String(source[open.upperBound ..< close.lowerBound])        let quoted = try SourceSweep.matches(#""/[^"]*""#, in: body)        return quoted.map { String($0.dropFirst().dropLast()) }    }    func testTheEnumMatchesWhatTheCoreAnswers() throws {        // Through the FFI, not through the source. This is the half that proves        // the linked build actually ANSWERS `routes.list` — a by-path read        // cannot tell a shipped archive from a stale one.        // The linked module identifies the real core; the stub has no module.        // A real build still runs every assertion below.        guard CottonRuntime.linksFFI else {            throw XCTSkip("The module-less FFI stub cannot answer routes.list; this guard requires the real XCFramework.")        }        let container = FileManager.default.temporaryDirectory            .appendingPathComponent("cotton-routes-\(UUID().uuidString)")        try FileManager.default.createDirectory(at: container, withIntermediateDirectories: true)        defer { try? FileManager.default.removeItem(at: container) }        // No device secret and no server: `routes.list` is a table read and        // opens nothing. That is the point of it being SHARED.        let core = try CottonRuntime.open(CottonConfig(containerPath: container.path))        let answered = try awaitRoutes(from: core)        XCTAssertEqual(            answered.count,            answered.routes.count,            "`count` and `routes` disagree, which means one of them is remembered"        )        XCTAssertEqual(            Set(answered.routes),            Set(Route.allPatterns),            "the build this bundle links names different screens than the Swift enum"        )        XCTAssertEqual(            answered.routes,            answered.routes.sorted(),            "the table is sorted where it is declared, and the answer carries that order"        )    }    private struct RoutesAnswer: Decodable {        let routes: [String]        let count: Int    }    /// `CottonCalling` is async and `XCTestCase` here is not, so the one call is    /// pumped through a semaphore rather than making every case in this file    /// async for it.    private func awaitRoutes(from core: any CottonCalling) throws -> RoutesAnswer {        let box = UncheckedBox<Result<RoutesAnswer, Error>>()        let waiting = DispatchSemaphore(value: 0)        Task {            do {                box.value = .success(                    try await core.call(CottonMethod.routesList, as: RoutesAnswer.self)                )            } catch {                box.value = .failure(error)            }            waiting.signal()        }        XCTAssertEqual(waiting.wait(timeout: .now() + 30), .success, "routes.list never answered")        return try XCTUnwrap(box.value).get()    }    /// A one-slot box, because the closure above is `@Sendable` and a captured    /// `var` would not be.    private final class UncheckedBox<T>: @unchecked Sendable {        private let lock = NSLock()        private var stored: T?        var value: T? {            get {                lock.lock()                defer { lock.unlock() }                return stored            }            set {                lock.lock()                defer { lock.unlock() }                stored = newValue            }        }    }    func testEveryRouteInTheTableParsesThroughTheEnum() throws {        // The set comparison above is over TEMPLATES; this is over the parser.        // A template with `[id]` is not a path, so it is filled with a synthetic        // segment first — which also proves the parameter positions agree.        for template in try rustRoutes() {            let filled =                template                .split(separator: "/", omittingEmptySubsequences: false)                .map { $0.hasPrefix("[") ? "x1" : String($0) }                .joined(separator: "/")            XCTAssertNotNil(                Route.parse(filled),                "\(template) is a screen this app has and \(filled) did not parse"            )        }    }}