Cotton code
83 lines · 3.9 KB · SwiftRaw
import CottonKitimport XCTestfinal class ThoughtFilingTests: XCTestCase {    private let yoga = DatabaseRef(id: "yoga", name: "Yoga studio")    private func core(audio: String = "null", attachments: String = "[]", status: String = "pending") -> ScriptedCore {        ScriptedCore([            CottonMethod.readThoughts: .ok("""                {"thoughts":[{"id":"original","rawText":"same words","audioUrl":\(audio),                "attachments":\(attachments),"routeStatus":"\(status)"}]}                """),            CottonMethod.captureCreate: .ok(#"{"id":"copy"}"#),            CottonMethod.write: .ok("{}")        ])    }    private func requests(_ core: ScriptedCore) async throws -> [JSONValue] {        try await core.calls.map { try JSONDecoder().decode(JSONValue.self, from: Data($0.requestJSON.utf8)) }    }    func testMoveCopiesToNamedDatabaseBeforeRetractingSourceAndUndoReversesIt() async throws {        let core = core()        let filing = CoreThoughtFiling(core: core)        try await filing.move(thoughtId: "original", to: yoga)        try await filing.takeBack(thoughtId: "original")        let methods = await core.methodsCalled()        XCTAssertEqual(methods, [CottonMethod.readThoughts, CottonMethod.captureCreate,                                CottonMethod.write, CottonMethod.write, CottonMethod.write])        let calls = try await requests(core)        XCTAssertEqual(calls[1]["database"]?.string, "yoga")        XCTAssertEqual(calls[1]["text"]?.string, "same words")        XCTAssertNil(calls[2]["database"])        XCTAssertEqual(calls[2]["args"]?["dismissed"], .bool(true))        XCTAssertEqual(calls[3]["args"]?["dismissed"], .bool(false))        XCTAssertEqual(calls[3]["args"]?["id"]?.string, "original")        XCTAssertEqual(calls[4]["database"]?.string, "yoga")        XCTAssertEqual(calls[4]["args"]?["id"]?.string, "copy")    }    func testDestinationRefusalNeverRetractsTheSource() async throws {        let core = core()        await core.answer(CottonMethod.captureCreate, .refuse(code: "refused", message: "no"))        do {            try await CoreThoughtFiling(core: core).move(thoughtId: "original", to: yoga)            XCTFail("a refused copy cannot be reported as moved")        } catch {}        let methods = await core.methodsCalled()        XCTAssertFalse(methods.contains(CottonMethod.write))    }    func testRetryAfterSourceRefusalReusesTheSuccessfulCopy() async throws {        let core = core()        let filing = CoreThoughtFiling(core: core)        await core.answer(CottonMethod.write, .refuse(code: "refused", message: "no"))        do {            try await filing.move(thoughtId: "original", to: yoga)            XCTFail("must report that the source remains")        } catch let error as ThoughtFilingGap {            XCTAssertEqual(error, .sourceRetractionFailed(destination: yoga.name))        }        await core.answer(CottonMethod.write, .ok("{}"))        try await filing.move(thoughtId: "original", to: yoga)        let methods = await core.methodsCalled()        XCTAssertEqual(methods.filter { $0 == CottonMethod.captureCreate }.count, 1)        XCTAssertEqual(methods.filter { $0 == CottonMethod.write }.count, 2)    }    func testMoveNeverSilentlyDropsMediaOrDuplicatesFiledRecords() async throws {        for (core, expected) in [            (core(audio: #""voice/key""#), ThoughtFilingGap.mediaNeedsTransfer),            (core(attachments: #"[{"kind":"photo","id":"picture"}]"#), .mediaNeedsTransfer),            (core(status: "routed"), .alreadyFiled)        ] {            do {                try await CoreThoughtFiling(core: core).move(thoughtId: "original", to: yoga)                XCTFail("must refuse before copying")            } catch let error as ThoughtFilingGap { XCTAssertEqual(error, expected) }            let methods = await core.methodsCalled()            XCTAssertEqual(methods, [CottonMethod.readThoughts])        }    }}