Cotton code
81 lines · 4.4 KB · SwiftRaw
#if os(macOS)import AppKitimport CottonKitimport SwiftUIimport XCTest@testable import CottonUI/// An opt-in evidence utility, with no pixel or layout expectations. Run via/// scripts/ui-tests-stub.sh --summary -- --filter RecordSurfaceCaptures,/// setting COTTON_RECORD_CAPTURE_DIR and COTTON_RECORD_CAPTURE_TABLE./// COTTON_RECORD_CAPTURE_ID selects a record, drawn on its deck; omit it for/// the list; COTTON_RECORD_CAPTURE_BLANK=1 draws the deck on its blank card,/// as Add opens it. All rows come from the/// bundled synthetic fixtures, never a live database.@MainActorfinal class RecordSurfaceCaptures: XCTestCase {    func testCapture() async throws {        let env = ProcessInfo.processInfo.environment        guard let folder = env["COTTON_RECORD_CAPTURE_DIR"],              let table = env["COTTON_RECORD_CAPTURE_TABLE"] else {            throw XCTSkip("Record surface capture was not requested")        }        let bundle = try TestResources.bundle()        let definitions = FixtureDefinitions.load(from: bundle).definitions        let definition = try XCTUnwrap(definitions.first { $0.id == table })        let blank = env["COTTON_RECORD_CAPTURE_BLANK"] == "1"        let rows = blank ? [] : try FixtureDefinitions.fixtureRecords(for: table, bundle: bundle)        // A declared link is drawn against its existing synthetic target        // fixtures, exactly as a normal surface reads linked records.        var fixtureTables = [table: rows]        for target in Set(definition.columns.compactMap(\.linkTo)) where target != table {            fixtureTables[target] = try FixtureDefinitions.fixtureRecords(for: target, bundle: bundle)        }        let records = FixtureRecords(definitions: definitions, records: fixtureTables)        let id = env["COTTON_RECORD_CAPTURE_ID"]        let name = env["COTTON_RECORD_CAPTURE_NAME"] ?? (blank ? "\(table)-blank" : id == nil ? "\(table)-list" : "\(table)-card")        let view: AnyView        if blank {            view = AnyView(RecordOpening(definition: definition, opens: .blank([:])))        } else if let id {            let row = try XCTUnwrap(rows.first { $0.id == id }, "The fixture has no record \(id)")            view = AnyView(RecordOpening(definition: definition, opens: .record(id, row)))        } else {            view = AnyView(RecordListSurface(definition: definition, onOpen: { _ in }))        }        _ = NSApplication.shared        let height = Int(env["COTTON_RECORD_CAPTURE_HEIGHT"] ?? "") ?? 1100        guard (512...12000).contains(height) else { throw CaptureError.invalidHeight }        let width = Int(env["COTTON_RECORD_CAPTURE_WIDTH"] ?? "") ?? 1024        guard (320...2048).contains(width) else { throw CaptureError.invalidWidth }        let size = NSSize(width: width, height: height)        let host = NSHostingView(rootView: view            .environment(Navigator())            .environment(ToastCenter())            .environment(\.records, records)            .environment(\.tableDefinitions, TableDefinitions(definitions))            .environment(\.colorScheme, .light)            .frame(width: size.width, height: size.height))        let window = NSWindow(contentRect: NSRect(origin: .zero, size: size),                              styleMask: [.borderless], backing: .buffered, defer: false)        window.isReleasedWhenClosed = false        window.contentView = host        window.orderFront(nil)        defer { window.close() }        // Let the surfaces' task-driven fixture reads finish in a real host.        try await Task.sleep(for: .seconds(1))        host.layoutSubtreeIfNeeded()        let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil,            pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8,            samplesPerPixel: 4, hasAlpha: true, isPlanar: false,            colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))        bitmap.size = size // one pixel per point, irrespective of the display        host.cacheDisplay(in: host.bounds, to: bitmap)        let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))        let destination = URL(fileURLWithPath: folder, isDirectory: true)        try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)        try png.write(to: destination.appendingPathComponent("\(name).png"))    }}private enum CaptureError: Error { case invalidHeight, invalidWidth }#endif