Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

4.6 KB
Raw Blame
import Foundation
import Testing

@Suite(.tags(.integration))
struct ProtectionStoreTests {
    @Test func expiredRecordsArePrunedAtExactDeadline() async throws {
        let directory = try TestDirectory()
        defer { try? directory.remove() }
        let store = ProtectionStore(directoryURL: directory.url)
        let record = makeRecord("task", markedAfter: 0, expiresAfter: 10)
        try await store.apply(upserts: [record], now: TestFixtures.now)
        #expect(try await store.load(now: TestFixtures.now.addingTimeInterval(9))["task"] == record)
        #expect(try await store.load(now: TestFixtures.now.addingTimeInterval(10)).isEmpty)
        let reopened = ProtectionStore(directoryURL: directory.url)
        #expect(try await reopened.load(now: TestFixtures.now).isEmpty)
    }

    @Test func olderUpsertAndStaleRemovalCannotOverwriteNewerRecord() async throws {
        let directory = try TestDirectory()
        defer { try? directory.remove() }
        let first = ProtectionStore(directoryURL: directory.url)
        let second = ProtectionStore(directoryURL: directory.url)
        let older = makeRecord("task", markedAfter: 0)
        let newer = makeRecord("task", markedAfter: 5)
        try await first.apply(upserts: [newer], now: TestFixtures.now)
        try await second.apply(upserts: [older], removals: [ProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: older.markedAt)], now: TestFixtures.now)
        #expect(try await first.load(now: TestFixtures.now)["task"] == newer)
        try await second.apply(removals: [ProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: newer.markedAt)], now: TestFixtures.now)
        #expect(try await first.load(now: TestFixtures.now).isEmpty)
    }

    @Test func concurrentStoreInstancesPreserveIndependentRecords() async throws {
        let directory = try TestDirectory()
        defer { try? directory.remove() }
        let first = ProtectionStore(directoryURL: directory.url)
        let second = ProtectionStore(directoryURL: directory.url)
        async let firstWrite: Void = first.apply(upserts: [makeRecord("first", markedAfter: 0)], now: TestFixtures.now)
        async let secondWrite: Void = second.apply(upserts: [makeRecord("second", markedAfter: 0)], now: TestFixtures.now)
        _ = try await (firstWrite, secondWrite)
        #expect(try await Set(first.load(now: TestFixtures.now).keys) == ["first", "second"])
    }

    @Test(arguments: ["not-json", #"{"schemaVersion":999,"records":[]}"#])
    func invalidStateIsPreservedAndRejectsWrites(_ content: String) async throws {
        let directory = try TestDirectory()
        defer { try? directory.remove() }
        _ = try directory.write(content, to: "Protection/state.json")
        let store = ProtectionStore(directoryURL: directory.url)
        await #expect(throws: (any Error).self) { try await store.load(now: TestFixtures.now) }
        let record = makeRecord("task", markedAfter: 0)
        await #expect(throws: (any Error).self) { try await store.apply(upserts: [record], now: TestFixtures.now) }
        #expect(try String(contentsOf: directory.url.appendingPathComponent("Protection/state.json"), encoding: .utf8) == content)
    }

    @Test func duplicateStoredIdentifiersChooseLatestMarkAndFileIsPrivate() async throws {
        let directory = try TestDirectory()
        defer { try? directory.remove() }
        let older = makeRecord("task", markedAfter: 0)
        let newer = makeRecord("task", markedAfter: 5)
        let records = try #require(String(data: JSONEncoder().encode([newer, older]), encoding: .utf8))
        let url = try directory.write("{\"schemaVersion\":1,\"records\":\(records)}", to: "Protection/state.json")
        let store = ProtectionStore(directoryURL: directory.url)
        #expect(try await store.load(now: TestFixtures.now)["task"] == newer)
        try await store.apply(now: TestFixtures.now)
        let stored = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
        #expect(Set(stored.keys) == ["schemaVersion", "records"])
        #expect(stored["schemaVersion"] as? Int == 1)
        let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
        #expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600)
    }

    private nonisolated func makeRecord(_ identifier: String, markedAfter: TimeInterval, expiresAfter: TimeInterval = 60) -> ProtectionRecord {
        ProtectionRecord(
            taskIdentifier: identifier, lastProgressAt: TestFixtures.now.addingTimeInterval(-3600),
            markedAt: TestFixtures.now.addingTimeInterval(markedAfter), expiresAt: TestFixtures.now.addingTimeInterval(expiresAfter)
        )
    }
}