Cotton code
156 lines · 10.0 KB · SwiftRaw
// The boot gate and the Backup card READ the core's answer (`shell.home`,// boundary review move 5): these hold the reading, never a decision — every// stage, word and way out below is written into the scripted answer, and the// test asserts the shell drew exactly that.import CottonKitimport XCTest@testable import CottonUI@MainActorfinal class HomeReaderTests: XCTestCase {    private func answer(stage: String, code: String? = nil, refusal: String = "none", erase: Bool = false,                        ways: String = "[]", stand: String = "local", notices: String = "[]",                        words: String = #"{"title": "Opening", "body": "Still opening", "clock": "0:07"}"#) -> String {        """        {"gate": {"stage": "\(stage)", "code": \(code.map { "\"\($0)\"" } ?? "null"), "refusal": "\(refusal)", "erase": \(erase),                  "beat": 3, "words": \(words), "progress": null, "ways_out": \(ways)},         "stand": "\(stand)", "backup": {"sent": 40, "of": 120, "line": "Backing up… 40 of 120 rows"},         "sync": {"state": "alone", "line": "Everything is on this phone", "line_state": "alone", "counter": 0, "failures": 0},         "device": null, "acts": [{"id": "sign_in", "label": "Sign in", "rank": "main", "red": false}],         "notices": \(notices)}        """    }    private func boot(_ json: String) async -> (BootModel, ScriptedCore) {        let core = ScriptedCore([            CottonMethod.readBoot: .ok(#"{"paired": true, "stage": "joined", "ownerId": "o1", "workspaceId": "w1"}"#),            CottonMethod.shellHome: .ok(json),        ])        let boot = BootModel(core: core)        await boot.start()        return (boot, core)    }    /// RULE: the gate the core answers `open` is the app, `door` is a business's door, `wait` paints nothing, and anything else is the core's slip; every ask files this phone under its name, for the database the core starts on a device holding none.    func testTheStageIsTheCores() async {        let (open, _) = await boot(answer(stage: "open"))        XCTAssertEqual(open.screen, .ready)        let (door, _) = await boot(answer(stage: "door"))        XCTAssertEqual(door.screen, .door)        let (_, asked) = await boot(answer(stage: "wait"))        let ask = (await asked.calls).first { $0.method == CottonMethod.shellHome }        XCTAssertTrue(ask?.requestJSON.contains(#""device_name":""#) == true, "the ask names this phone")        let (wait, _) = await boot(answer(stage: "wait"))        XCTAssertEqual(wait.screen, .waiting)        let (opening, _) = await boot(answer(stage: "opening"))        guard case .gate(let gate) = opening.screen else { return XCTFail("\(opening.screen)") }        let slip = GateSlip.of(gate)        XCTAssertEqual(slip.title, "Opening")        XCTAssertEqual(slip.progress, .activity(beat: 3, label: "0:07", identifier: "wait-elapsed"), "the clock is the core's line")    }    /// RULE: a refusal's wall draws the core's words and exactly its ways out, in its order and weight.    func testARefusalDrawsTheCoresWaysOut() async {        let ways = #"[{"id": "retry", "label": "Try again", "weight": "ink"}, {"id": "erase", "label": "Erase", "weight": "red"}]"#        let words = #"{"reason": "Removed", "title": "This phone was removed", "body": "Ask the owner."}"#        let (boot, _) = await boot(answer(stage: "refused", code: "device_revoked", refusal: "wall", erase: true, ways: ways, words: words))        guard case .gate(let gate) = boot.screen else { return XCTFail("\(boot.screen)") }        let slip = GateSlip.of(gate)        XCTAssertEqual(slip.reason, "Removed")        XCTAssertEqual(slip.actions, [.retry, .erase])        XCTAssertEqual(slip.buttons.map(\.weight), [.ink, .red])        XCTAssertTrue(boot.mustErase)        XCTAssertEqual(boot.standingRefusal?.code, "device_revoked")    }    /// RULE: a refusal the core places as a banner is read-only over the open app, and the mailboxes are held.    func testABannerIsReadOnlyOverTheApp() async {        let words = #"{"title": "Not approved", "body": "Your copy is here."}"#        let (boot, _) = await boot(answer(stage: "open", code: "device_not_approved", refusal: "banner", words: words))        XCTAssertEqual(boot.screen, .ready)        XCTAssertEqual(boot.readOnly?.title, "Not approved")        XCTAssertTrue(boot.holdsDrains)    }    /// RULE: the gate asks again on the core's own frames, and a retry asks for a new wait.    func testTheGateAsksAgainOnTheCoresFrames() async {        let (boot, core) = await boot(answer(stage: "wait"))        await core.answer(CottonMethod.shellHome, .ok(answer(stage: "open")))        boot.receive(.home(stage: "opened"))        for _ in 0 ..< 50 where boot.screen != .ready { await Task.yield() }        XCTAssertEqual(boot.screen, .ready)        await boot.retry()        let asked = await core.calls.filter { $0.method == CottonMethod.shellHome }        XCTAssertTrue(asked.last?.requestJSON.contains(#""retry":true"#) == true, "\(asked)")    }    /// RULE: the Backup card draws the stand and the backup's line the core answered.    func testTheBackupCardReadsTheCoresStand() throws {        let personal = PersonalObject(            client: BusinessClient(core: ScriptedCore(), address: BusinessAddress(server: "https://cottondb.example.com", window: [:]), store: InMemorySecretStore()),            core: ScriptedCore(), name: "Cotton", server: "https://cottondb.example.com")        XCTAssertEqual(personal.stand, .local)        personal.take(try JSONDecoder().decode(HomeAnswer.self, from: Data(answer(stage: "open", stand: "backing_up").utf8)))        XCTAssertEqual(personal.stand, .backingUp)        XCTAssertEqual(personal.backupLine, "Backing up… 40 of 120 rows")        personal.take(try JSONDecoder().decode(HomeAnswer.self, from: Data(answer(stage: "open", stand: "connected", notices: #"[{"id": "backed_up", "words": "Backed up", "kind": "done"}]"#).utf8)))        XCTAssertEqual(personal.stand, .connected)        XCTAssertTrue(personal.backedUp)    }    /// RULE (signin-sticks, 11 Nov 2026): a sign-in the object took and this phone did not finish is said in the core's own line, as an error — the connect's refusal is never only logged — and the stand-local that follows says nothing of a sign-out, so the core keeps saying why; Sign out says it is one.    func testASignInThisPhoneDidNotFinishIsSaid() async throws {        let failed = #"{"gate": {"stage": "open", "code": null, "refusal": "none", "erase": false, "beat": 3, "words": {"title": "", "body": "", "clock": ""}, "progress": null, "ways_out": []}, "stand": "failed", "backup": {"sent": 0, "of": 0, "line": "Could not sign in (the object is another)"}, "sync": {"state": "alone", "line": "", "line_state": "alone", "counter": 0, "failures": 0}, "device": null, "acts": [], "notices": []}"#        let core = ScriptedCore([            CottonMethod.personalSignIn: .ok(#"{"credential": "synthetic-credential", "person": {"id": "p1", "role": "owner", "name": "Invented"}, "expiresIn": 3600, "databaseId": "d1"}"#),            CottonMethod.personalConnect: .refuse(code: "wrong_database", message: "the object is another"),            CottonMethod.personalStandLocal: .ok("{}"),            CottonMethod.shellHome: .ok(failed),        ])        let personal = PersonalObject(            client: BusinessClient(core: core, address: BusinessAddress(server: "https://cottondb.example.com", window: [:]), store: InMemorySecretStore()),            core: core, name: "Todos", server: "https://cottondb.example.com")        var said: [(String, Bool)] = []        personal.say = { line, failed in said.append((line, failed)) }        personal.phone = "+15550100199"        personal.code = "000000"        await personal.confirm(BusinessChallenge(challengeId: "c1", known: true, databaseId: "d1"))        XCTAssertEqual(personal.stand, .backupFailed)        XCTAssertEqual(said.map(\.0), ["Could not sign in (the object is another)"])        XCTAssertEqual(said.map(\.1), [true])        let stood = await core.calls.filter { $0.method == CottonMethod.personalStandLocal }        XCTAssertTrue(stood.last?.requestJSON.contains(#""signedOut":false"#) == true, "\(stood)")        // Tapped again with the credential kept: it connects again and says why again, never silence.        await personal.backUp()        XCTAssertEqual(said.count, 2)        await personal.stopBackingUp()        let after = await core.calls.filter { $0.method == CottonMethod.personalStandLocal }        XCTAssertTrue(after.last?.requestJSON.contains(#""signedOut":true"#) == true, "\(after)")    }    /// RULE (one copy, one object, 14 Nov 2026): a launch holding no credential is signed out, so a copy an object's person left is set aside by the core (`copy_aside`), never drawn for whoever opens the app next.    func testALaunchHoldingNoCredentialStandsSignedOut() async throws {        let local = #"{"gate": {"stage": "open", "code": null, "refusal": "none", "erase": false, "beat": 3, "words": {"title": "", "body": "", "clock": ""}, "progress": null, "ways_out": []}, "stand": "local", "backup": {"sent": 0, "of": 0, "line": ""}, "sync": {"state": "alone", "line": "", "line_state": "alone", "counter": 0, "failures": 0}, "device": null, "acts": [], "notices": []}"#        let core = ScriptedCore([            CottonMethod.personalStandLocal: .ok("{}"),            CottonMethod.shellHome: .ok(local),        ])        let personal = PersonalObject(            client: BusinessClient(core: core, address: BusinessAddress(server: "https://cottondb.example.com", window: [:]), store: InMemorySecretStore()),            core: core, name: "Books", server: "https://cottondb.example.com")        await personal.launch()        let stood = await core.calls.filter { $0.method == CottonMethod.personalStandLocal }        XCTAssertEqual(stood.count, 1, "\(stood)")        XCTAssertTrue(stood.last?.requestJSON.contains(#""signedOut":true"#) == true, "\(stood)")        let connected = await core.calls.filter { $0.method == CottonMethod.personalConnect }        XCTAssertTrue(connected.isEmpty, "\(connected)")    }}