Cotton code
127 lines · 7.3 KB · SwiftRaw
// The machine and quota faces (the approved Codex designs): a machine's// facts, its three dials and which Mac is drawn; a quota's trend; and both// faces drawn on the deck's paper to files for a person to set beside the designs.import CottonPaperimport CottonValuesimport SwiftUIimport UniformTypeIdentifiersimport XCTest@testable import CottonFaces@testable import CottonUI@MainActorfinal class GaugeFacesTests: XCTestCase {    private static let card = CGSize(width: 360, height: 450)    private static func machine(_ name: String, chip: String, memory: (Double, Double), disk: (Double, Double), free: String,                                load: (Double, Double), sessions: String, reported: String, model: String? = nil) -> DeckCard {        var fields: [String: RecordValue] = [            "title": .text(name), "subtitle": .text(chip), "body": .text("macOS 26.1"), "date": .text(reported),            "facts": .list([                .object(["label": .text("Chip"), "said": .text(chip)]),                .object(["label": .text("Memory"), "said": .text("\(Int(memory.1)) GB")]),                .object(["label": .text("Disk"), "said": .text(free)]),                .object(["label": .text("Load"), "said": .text("\(load.0)")]),                .object(["label": .text("Coding sessions"), "said": .text(sessions)]),            ]),            "memory_dial": .object(["used": .number(memory.0), "total": .number(memory.1)]),            "disk_dial": .object(["used": .number(disk.0), "total": .number(disk.1)]),            "load_dial": .object(["used": .number(load.0), "total": .number(load.1)]),        ]        if let model { fields["model"] = .text(model) }        return DeckCard(face: .machine, fields: fields)    }    /// The pilot's two machines, on the numbers the designs were drawn on.    static let mini = machine("mini", chip: "M4", memory: (19, 32), disk: (900, 2000), free: "1.1 TB free",                              load: (0.6, 10), sessions: "1", reported: "5 min ago", model: "Mac mini")    static let macC = machine("mac-c", chip: "M4 Pro", memory: (30, 48), disk: (614, 926), free: "312 GB free",                              load: (1.4, 14), sessions: "3", reported: "2 min ago")    func testAMachinesDialsAreItsUsedOfItsWholeInTheFacesOrder() {        let dials = MachineReading.dials(Self.macC)        XCTAssertEqual(dials.map(\.slot), ["memory_dial", "disk_dial", "load_dial"])        XCTAssertEqual(dials[0].share, 30.0 / 48, accuracy: 0.0001)        XCTAssertEqual(dials[2].share, 0.1, accuracy: 0.0001)        let over = DeckCard(face: .machine, fields: ["load_dial": .object(["used": .number(30), "total": .number(14)])])        XCTAssertEqual(MachineReading.dials(over).first?.share, 1, "a load past the cores is a full dial, never past it")        let none = DeckCard(face: .machine, fields: ["disk_dial": .object(["used": .number(3), "total": .number(0)])])        XCTAssertTrue(MachineReading.dials(none).isEmpty, "a dial with no whole is not drawn")    }    func testAMachinesFactsAreTheCardsAndAnOlderCardSaysItsLines() {        XCTAssertEqual(MachineReading.facts(Self.mini).first, MachineReading.Fact(label: "Chip", said: "M4"))        XCTAssertEqual(MachineReading.facts(Self.mini).count, 5)        let older = DeckCard(face: .machine, fields: ["subtitle": .text("M2"), "body": .text("macOS 26.1\n16 GB"), "count": .text("2")])        XCTAssertEqual(MachineReading.facts(older).map(\.said), ["M2", "macOS 26.1", "16 GB", "2"])    }    func testALabelTooLongForItsColumnIsWrittenAcrossTheTable() {        XCTAssertFalse(MachineReading.spans("Memory"))        XCTAssertTrue(MachineReading.spans("Coding sessions"), "it would wrap in the label column")    }    func testTheMacDrawnIsTheModelTheCardNames() {        XCTAssertEqual(MachineReading.art(Self.mini), "face-art-mac-mini")        XCTAssertEqual(MachineReading.art(DeckCard(face: .machine, fields: ["title": .text("mini")])), "face-art-mac-mini",                       "with no model the name may say it")        XCTAssertEqual(MachineReading.art(Self.macC), GaugeFacesKnobs.deskMac)        let laptop = Self.machine("air", chip: "M3", memory: (8, 16), disk: (100, 512), free: "412 GB free",                                  load: (0.2, 8), sessions: "0", reported: "now", model: "MacBook Air")        XCTAssertEqual(MachineReading.art(laptop), "face-art-laptop")        for (_, art) in GaugeFacesKnobs.macArt {            XCTAssertNotNil(CottonMedia.image(art), "\(art) is in the catalogue")        }    }    /// The pilot's quota, on the design's numbers.    static let claude = DeckCard(face: .quota, fields: [        "title": .text("Claude usage this week"), "subtitle": .text("Max 5x \u{00B7} claude"),        "used": .number(62), "share": .text("62 percent used"), "hours_left": .text("38 hours left"),        "resets_on": .text("resets Sunday"), "period": .text("resets in 1d 14h"),        "trend": .list([.number(24), .number(43), .number(62)]), "date": .text("4 min ago"),    ])    func testAQuotasTrendIsItsReadingsOldestFirstAndFewAreAllTyped() {        XCTAssertEqual(QuotaReading.points(Self.claude).map(\.share), [0.24, 0.43, 0.62])        XCTAssertEqual(QuotaReading.typed(3), [0, 1, 2])        XCTAssertEqual(QuotaReading.typed(7), [0, 3, 6], "a week's readings type the first, the middle and the last")        XCTAssertTrue(QuotaReading.points(DeckCard(face: .quota, fields: ["used": .number(5)])).isEmpty)        let over = DeckCard(face: .quota, fields: ["trend": .list([.number(120), .text("x")])])        XCTAssertEqual(QuotaReading.points(over).map(\.share), [1], "a reading past the limit is full; words are not a reading")    }    /// A capture utility, not a guard: with `GAUGE_CAPTURE=<dir>` (passed as    /// `TEST_RUNNER_GAUGE_CAPTURE`) it draws the pilot's faces on the deck's    /// paper as PNGs. Without the variable it skips.    func testCaptureThePilot() throws {        guard let dir = ProcessInfo.processInfo.environment["GAUGE_CAPTURE"], !dir.isEmpty else {            throw XCTSkip("set TEST_RUNNER_GAUGE_CAPTURE=<dir> to capture")        }        let out = URL(fileURLWithPath: dir, isDirectory: true)        try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)        let theme = Theme.paper        let faces: [(String, DeckCard, AnyView)] = [            ("machine-mini", Self.mini, AnyView(MachineFace(card: Self.mini))),            ("machine-mac-c", Self.macC, AnyView(MachineFace(card: Self.macC))),            ("quota-claude", Self.claude, AnyView(QuotaFace(card: Self.claude))),        ]        for (name, _, view) in faces {            let face = view                .frame(width: Self.card.width, height: Self.card.height)                .padding(12)                .background(theme.colors.ground.color)                .environment(\.theme, theme)                .environment(\.colorScheme, .light)            let renderer = ImageRenderer(content: face)            renderer.scale = 3            let url = out.appendingPathComponent("\(name).png")            guard let image = renderer.cgImage,                  let dest = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil)            else { return XCTFail("\(name) drew nothing") }            CGImageDestinationAddImage(dest, image, nil)            CGImageDestinationFinalize(dest)        }    }}