Cotton code
174 lines · 10.0 KB · SwiftRaw
// A change or a delete of one day of a repeating event always asks "Only this// one" or "Every one" before it writes (SEV 1, 5 Oct: one day's new time moved// a whole series). The core marks the records that ask (`scope_columns`) and// refuses such a write without a `scope`; these hold the app's half — the// wire carries the reach, the page and the list ask first, the bar never// writes past the question. Every record is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class RepeatScopeTests: XCTestCase {    private static var resources: Bundle? {        Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))    }    private static let asking: RecordValue = .list([.text("title"), .text("starts_at"), .text("rrule")])    private static let session = TableDefinition(        id: "session", name: "Session", plural: "Sessions",        columns: [            ColumnDefinition(key: "title", type: .text, required: true),            ColumnDefinition(key: "starts_at", type: .date),            ColumnDefinition(key: "project", type: .text),            ColumnDefinition(key: "rrule", type: .text, format: .repeatRule),        ],        title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList),        page: [PageSection(heading: nil, columns: ["title", "starts_at", "project", "rrule"])])    /// One later day of a weekly swim, as the core lists it.    private static let day = TableRecord(id: "ses-1@2026-10-12T09:00:00Z", values: [        "title": .text("Swim"), "starts_at": .text("2026-10-12T09:00:00Z"), "rrule": .text("FREQ=WEEKLY"),        TableRecord.scopeColumnsKey: asking,    ])    private static let oneOff = TableRecord(id: "ses-2", values: [        "title": .text("Dentist"), "starts_at": .text("2026-10-13T15:00:00Z"),    ])    private func scoping() -> ScopingRecords {        ScopingRecords(FixtureRecords(definitions: [Self.session], records: ["session": [Self.day, Self.oneOff]]), ownRow: "ses-own")    }    // ── (a) The wire ──────────────────────────────────────────────────────    /// RULE: A write to a record that repeats sends its reach to the core as "scope": "this" or "all" on records.update and records.delete, and a write with no reach sends no scope key at all.    func testTheCoreIsSentTheReachOfAWrite() async throws {        let core = ScriptedCore([            "records.update": .ok(#"{"change":{"id":"ch-1","record_id":"ev-own","byline":"user","before":{"starts_at":"2026-10-12T09:00:00Z"},"after":{"starts_at":"2026-10-12T10:00:00Z"},"undoable":true,"reason":null},"record":{"table":"event","id":"ev-own","data":{"title":"Swim","starts_at":"2026-10-12T10:00:00Z"}}}"#),            "records.delete": .ok(#"{"change":{"id":"ch-2","record_id":"ev-1","byline":"user","before":{"title":"Swim"},"after":null,"undoable":true,"reason":null},"record":null}"#),        ])        let store = CoreRecords(core: core, bundle: try TestResources.bundle())        let patch: [String: RecordValue] = ["starts_at": .text("2026-10-12T10:00:00Z")]        let moved = try await store.update(table: "event", id: "ev-1@2026-10-12T09:00:00Z", patch: patch, scope: .this)        XCTAssertEqual(moved.after?.id, "ev-own", "the answer is the record the write made")        _ = try await store.delete(table: "event", id: "ev-1", scope: .all)        _ = try await store.update(table: "event", id: "ev-3", patch: patch, scope: nil)        _ = try await store.delete(table: "event", id: "ev-3", scope: nil)        let sent = try await requests(core)        XCTAssertEqual(sent.map(\.method), ["records.update", "records.delete", "records.update", "records.delete"])        XCTAssertEqual(sent[0].body["scope"], .text("this"))        XCTAssertEqual(sent[0].body["patch"], .object(patch))        XCTAssertEqual(sent[1].body["scope"], .text("all"))        XCTAssertNil(sent[2].body["scope"], "no reach, no key")        XCTAssertNil(sent[3].body["scope"], "no reach, no key")    }    /// RULE: A record the core lists with scope_columns repeats; a record without the key does not repeat.    func testTheCoresScopeColumnsMarkARecordThatRepeats() throws {        let decode = { (json: String) in            try JSONDecoder().decode(CoreRecords.WireRecord.self, from: Data(json.utf8)).record        }        let day = try decode(#"{"id":"ev-1@2026-10-12T09:00:00Z","data":{"title":"Swim","rrule":"FREQ=WEEKLY"},"scope_columns":["title","starts_at","ends_at","all_day","location","notes","rrule"]}"#)        XCTAssertTrue(day.repeats)        let plain = try decode(#"{"id":"ev-2","data":{"title":"Dentist"}}"#)        XCTAssertFalse(plain.repeats)    }    // ── (b) The page ──────────────────────────────────────────────────────    // ── (c) The offers ────────────────────────────────────────────────────    // ── (d) A store that cannot carry the reach ───────────────────────────    /// RULE: A store that cannot carry a write's reach refuses a scoped update or delete (ScopeNotCarried) and writes nothing, rather than write a whole series silently; with no scope it writes as before.    func testAStoreWithoutReachRefusesAScopedWrite() async throws {        let store = FixtureRecords(definitions: [Self.session], records: ["session": [Self.oneOff]])        do {            _ = try await store.update(table: "session", id: Self.oneOff.id, patch: ["title": .text("Moved")], scope: .this)            XCTFail("a scoped update is refused")        } catch is ScopeNotCarried {}        do {            _ = try await store.delete(table: "session", id: Self.oneOff.id, scope: .all)            XCTFail("a scoped delete is refused")        } catch is ScopeNotCarried {}        let kept = try await store.get(table: "session", id: Self.oneOff.id)        XCTAssertEqual(kept?["title"], .text("Dentist"), "nothing was written")        let changed = try await store.update(table: "session", id: Self.oneOff.id, patch: ["title": .text("Moved")], scope: nil)        XCTAssertEqual(changed.after?["title"], .text("Moved"))        _ = try await store.delete(table: "session", id: Self.oneOff.id, scope: nil)        let gone = try await store.get(table: "session", id: Self.oneOff.id)        XCTAssertNil(gone)    }    // ── (e) The bar ───────────────────────────────────────────────────────    // ── Helpers ───────────────────────────────────────────────────────────    private func requests(_ core: ScriptedCore) async throws -> [(method: String, body: [String: RecordValue])] {        let calls = await core.calls        return try calls.map { call in            (call.method, try JSONDecoder().decode([String: RecordValue].self, from: Data(call.requestJSON.utf8)))        }    }}/// The fixture verbs, carrying a write's reach as the core does: every write/// is recorded with its scope, and "Only this one" answers a record of its/// own (`ownRow`) that no longer repeats.private actor ScopingRecords: Records {    struct Write: Equatable {        let verb: String        let id: String        let patch: [String: RecordValue]        let scope: WriteScope?    }    private let inner: FixtureRecords    private let ownRow: String    private(set) var writes: [Write] = []    init(_ inner: FixtureRecords, ownRow: String) {        self.inner = inner        self.ownRow = ownRow    }    func update(table: String, id: String, patch: [String: RecordValue], scope: WriteScope?) async throws -> ChangeRecord {        writes.append(Write(verb: "update", id: id, patch: patch, scope: scope))        var change = try await inner.update(table: table, id: id, patch: patch)        if scope == .this, var after = change.after {            after.id = ownRow            after.values[TableRecord.scopeColumnsKey] = nil            change.after = after        }        return change    }    func delete(table: String, id: String, scope: WriteScope?) async throws -> ChangeRecord {        writes.append(Write(verb: "delete", id: id, patch: [:], scope: scope))        return try await inner.delete(table: table, id: id)    }    func tableDefinitions() async throws -> [TableDefinition] { try await inner.tableDefinitions() }    func count(table: String) async throws -> Int { try await inner.count(table: table) }    func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        try await inner.list(table: table, project: project, query: query, page: page, where: filter)    }    func get(table: String, id: String) async throws -> TableRecord? { try await inner.get(table: table, id: id) }    func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { try await inner.create(table: table, data: data) }    func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord {        try await update(table: table, id: id, patch: patch, scope: nil)    }    func delete(table: String, id: String) async throws -> ChangeRecord { try await delete(table: table, id: id, scope: nil) }    func reorder(table: String, ids: [String]) async throws -> ChangeRecord { try await inner.reorder(table: table, ids: ids) }    func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord {        try await inner.link(table: table, id: id, column: column, target: target)    }    func undo(change: String) async throws -> ChangeRecord { try await inner.undo(change: change) }}