Cotton code
80 lines · 3.6 KB · SwiftRaw
// The write gate: one wrapper over the core, and `write` is the one method// it turns away while a refusal stands.import XCTest@testable import CottonKitfinal class WriteGateTests: XCTestCase {    private func subject() -> (GatedCore, WriteGate, ScriptedCore) {        let inner = ScriptedCore([            CottonMethod.write: .ok(#"{"id":"n1"}"#),            CottonMethod.readSyncStatus: .ok(#"{"connected":true,"pending":0,"canReachServer":true}"#),            "join.start": .ok(#"{}"#),        ])        let gate = WriteGate()        return (GatedCore(over: inner, gate: gate), gate, inner)    }    func testAnOpenGatePassesEveryCallThrough() async throws {        let (core, _, inner) = subject()        let answered = try await core.callRaw(CottonMethod.write, requestJSON: #"{"tool":"create_note"}"#)        XCTAssertTrue(answered.contains(#""ok":true"#))        let asked = await inner.methodsCalled()        XCTAssertEqual(asked, [CottonMethod.write])    }    func testAHeldGateRefusesAWriteWithTheSentenceAndAsksNothingBelow() async throws {        let (core, gate, inner) = subject()        gate.hold("this phone's access was revoked on that server — pair it again to reconnect Nothing new is saved until this phone joins again.")        let answered = try await core.callRaw(CottonMethod.write, requestJSON: #"{"tool":"create_note"}"#)        let envelope = try JSONDecoder().decode(JSONValue.self, from: Data(answered.utf8))        XCTAssertEqual(envelope["ok"]?.bool, false)        XCTAssertEqual(envelope["error"]?["code"]?.string, WriteGate.code)        XCTAssertEqual(            envelope["error"]?["message"]?.string,            "this phone's access was revoked on that server — pair it again to reconnect Nothing new is saved until this phone joins again."        )        let asked = await inner.methodsCalled()        XCTAssertTrue(asked.isEmpty, "a refused write never reaches the crate")    }    func testTheRefusalIsTheSameErrorTheCrateWouldThrow() async {        // `CottonCalling.call` reads the envelope the wrapper wrote, so a        // screen's `ScreenWriter` sees an ordinary `CottonCallError` and        // shows the sentence where it shows every refusal.        let (core, gate, _) = subject()        gate.hold("This phone is read-only.")        do {            _ = try await core.call(CottonMethod.write, as: JSONValue.self)            XCTFail("a held write must throw")        } catch let refusal as CottonCallError {            XCTAssertEqual(refusal.code, "read_only")            XCTAssertEqual(refusal.message, "This phone is read-only.")        } catch {            XCTFail("not the crate's error: \(error)")        }    }    func testTheWayBackInAndEveryReadStillPass() async throws {        let (core, gate, inner) = subject()        gate.hold("This phone is read-only.")        _ = try await core.callRaw(CottonMethod.readSyncStatus, requestJSON: "{}")        _ = try await core.callRaw("join.start", requestJSON: "{}")        let asked = await inner.methodsCalled()        XCTAssertEqual(asked, [CottonMethod.readSyncStatus, "join.start"])    }    func testReleasingTheGateLetsWritesThroughAgain() async throws {        let (core, gate, inner) = subject()        gate.hold("This phone is read-only.")        _ = try await core.callRaw(CottonMethod.write, requestJSON: "{}")        gate.hold(nil)        XCTAssertNil(gate.refusal)        _ = try await core.callRaw(CottonMethod.write, requestJSON: "{}")        let asked = await inner.methodsCalled()        XCTAssertEqual(asked, [CottonMethod.write], "one refused, one through")    }}