Cotton code
61 lines · 2.9 KB · SwiftRaw
// The Keychain seam's own contract, held on the double.//// `KeychainSecretStore` itself is not exercised here and must not be: a// simulator's Keychain is shared between test runs, so a test that writes into// the real one is a test that passes once — which is the reason `SecretStore`// is a protocol at all (`SecretStore.swift`'s header says so about// `DeviceKeyStore`).//// What IS testable is the CONTRACT both sides implement, and one clause of it// is load-bearing enough to be worth pinning: **a write that does not land// leaves the previous value where it was.** The real store is delete-then-add,// so without care a refused add destroys the key the person already had — they// see "Something went wrong" and the working key is gone with the one they// typed. `KeychainSecretStore.write` reads the old value first and puts it back// on a failed add; `InMemorySecretStore` refuses before touching the slot. The// two agree, and this is the assertion that says so out loud.import XCTest@testable import CottonKitfinal class SecretStoreTests: XCTestCase {    func testARefusedWriteLeavesThePreviousValueWhereItWas() {        let store = InMemorySecretStore(["cotton.byok.anthropic": "sk-ant-synthetic-old"])        store.refusing = ["cotton.byok.anthropic"]        XCTAssertFalse(            store.write("sk-ant-synthetic-new", to: "cotton.byok.anthropic"),            "a write the store refused must answer false — a screen that said 'Key saved' over it would be lying"        )        XCTAssertEqual(            store.read("cotton.byok.anthropic"), "sk-ant-synthetic-old",            "a refused write must not destroy the key that was already there"        )    }    func testAWriteThatLandsReplacesWhatWasThere() {        let store = InMemorySecretStore(["cotton.byok.openai": "sk-synthetic-first"])        XCTAssertTrue(store.write("sk-synthetic-second", to: "cotton.byok.openai"))        XCTAssertEqual(store.read("cotton.byok.openai"), "sk-synthetic-second")    }    func testForgettingAnEmptySlotIsASuccessRatherThanAFailure() {        let store = InMemorySecretStore()        store.forget("cotton.byok.anthropic")        XCTAssertNil(store.read("cotton.byok.anthropic"))        XCTAssertTrue(store.occupied.isEmpty)    }    func testOneSlotDoesNotSeeAnother() {        // The Keychain separates these by ACCOUNT under one service, which is        // what lets the BYOK keys and the code-hosting tokens share a store.        let store = InMemorySecretStore()        store.write("sk-ant-synthetic-x4Kq", to: "cotton.byok.anthropic")        store.write("ghp_synthetic_value", to: "cotton.code.github.com")        XCTAssertEqual(store.read("cotton.byok.anthropic"), "sk-ant-synthetic-x4Kq")        XCTAssertEqual(store.read("cotton.code.github.com"), "ghp_synthetic_value")        XCTAssertEqual(store.occupied, ["cotton.byok.anthropic", "cotton.code.github.com"])    }}