Cotton code
292 lines · 13.3 KB · SwiftRaw
// The faces walk (scripts/faces-walk/walk.sh): the Cotton flavour, walked// over a database it makes and fills with samples. Every step saves// NN-tool-step.png and its tree; a missing control and a crash fail the// walk, anything else is a line in walk.log.import XCTestfinal class FacesWalk: XCTestCase {    private var app: XCUIApplication!    private var out: URL!    private var frame = 0    private var missing: [String] = []    override func setUp() {        continueAfterFailure = true        let env = ProcessInfo.processInfo.environment        app = XCUIApplication(bundleIdentifier: env["FACES_WALK_APP"] ?? "com.cottondb.cotton.dev")        out = URL(fileURLWithPath: env["FACES_WALK_OUT"] ?? NSTemporaryDirectory())    }    // MARK: - The walk    /// The walk: each tool the faces lane draws, opened from the fan.    func testWalk() {        app.launch()        if let start = find(label: "Start a new database", wait: 8) { start.tap() }        guard need("home-fan", wait: 90) != nil else { return }        settle(6)        shot("home", "fan")        for tool in tools { walk(tool); backToFan() }        // Opened from the Tools deck, a tool is the same deck as from the fan.        if tools.contains("tools") {            for name in ["Birthdays", "Artifacts"] { openFromTools(name); backToFan() }        }        if !missing.isEmpty { log("missing: " + missing.joined(separator: ", ")) }    }    /// The tools, by their fan key, in the walk's order.    private var tools: [String] {        let named = ProcessInfo.processInfo.environment["FACES_WALK_TOOLS"] ?? ""        let keys = named.split(separator: ",").map(String.init)        return keys.isEmpty            ? ["money", "machines", "quotas", "subscriptions", "passwords", "email", "messages", "artifacts", "birthdays", "tools", "home"]            : keys    }    /// One tool: open it, shoot it, turn its views, swipe its card, pinch it    /// whole and back, and hold it.    private func walk(_ tool: String) {        // A tool the fan does not deal (Cotton's fan is spelled by its        // manifest; an imported tool stands in the Tools deck) is opened        // from the Tools deck, by its name.        let onFan = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "fan-tile-"))            .allElementsBoundByIndex.contains { $0.identifier == "fan-tile-\(tool)" }        if onFan {            guard turn(to: tool) else { return }        } else {            openFromTools(tool.prefix(1).uppercased() + tool.dropFirst())        }        settle(3)        shot(tool, "open")        let chips = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "ring-\(tool)-"))        let views = chips.allElementsBoundByIndex.map { $0.identifier }        log("\(tool) views: " + views.joined(separator: ", "))        for view in views.dropFirst().prefix(3) { pick(view, tool) }        if let first = views.first { pick(first, tool, shoot: false) }        // A tool of several tables and no views opens on its tables' board:        // the first table is the deck walked.        let table = app.descendants(matching: .any)            .matching(NSPredicate(format: "identifier BEGINSWITH %@", "tool-table-")).firstMatch        if views.isEmpty, table.exists {            log("\(tool) opens \(table.identifier)")            table.tap()            settle(3)            shot(tool, "table")        }        guard let card = frontCard() else {            log("\(tool): no card")            shot(tool, "no-card")            return        }        card.swipeLeft()        settle(1.5)        shot(tool, "swiped")        card.pinch(withScale: 2.5, velocity: 4)        settle(2)        shot(tool, "pinched")        // A conversation's card opens its chat: one mic, and nothing under        // the head row's X.        if tool == "messages", let thread = frontCard() {            thread.tap()            settle(3)            shot(tool, "chat")            let mics = app.descendants(matching: .any).matching(identifier: "fan-record").allElementsBoundByIndex.filter { $0.isHittable }.count            log("\(tool) chat: \(mics) record button(s) over its own composer")            point(0.01, 0.45).press(forDuration: 0.05, thenDragTo: point(0.8, 0.45), withVelocity: .fast, thenHoldForDuration: 0)            settle(2)        }        // The hold last: a card with one act does it (the Tools deck's Open        // turns the fan away), several lift the card with them.        guard let held = frontCard() else { return log("\(tool): no card to hold") }        held.press(forDuration: 1.2)        settle(1.5)        shot(tool, "held")        putAway()    }    /// The Tools deck turned to `name`'s card and tapped: its tool opens,    /// as a deck of cards.    private func openFromTools(_ name: String) {        guard turn(to: "tools") else { return }        settle(2)        for _ in 0..<20 {            let title = app.descendants(matching: .any).matching(identifier: "deck-title").firstMatch            if title.exists, title.label == name { break }            frontCard()?.swipeLeft()            settle(1)        }        guard let card = frontCard() else { return log("tools: no card for \(name)") }        card.tap()        settle(3)        shot("tools", "opens-" + name.lowercased())        let deck = app.descendants(matching: .any)["deck-card"].firstMatch.exists        log("tools opens \(name): \(deck ? "a deck" : "NOT A DECK")")        // A list's row opens its tool's deck at that card.        if !deck, let row = app.buttons.matching(NSPredicate(format: "identifier MATCHES %@", ".*-[0-9a-f]{8}-[0-9a-f]{4}-.*"))            .allElementsBoundByIndex.first {            row.tap()            settle(3)            log("tools \(name): its first row opens \(app.descendants(matching: .any)["deck-card"].firstMatch.exists ? "a deck" : "NO DECK")")        }    }    /// A view's chip on the ring, tapped where it stands (the ring's chips,    /// like the fan's tiles, read as not hittable); one off the screen is    /// brought in with a swipe along the ring.    private func pick(_ id: String, _ tool: String, shoot: Bool = true) {        let chip = app.descendants(matching: .any)[id].firstMatch        guard chip.waitForExistence(timeout: 2) else { return }        // Off either edge: the outermost chip standing on the screen on        // that side is tapped, which turns the ring a step toward it — a        // swipe at the chip's height lands on the fan's tiles and turns the        // tool, and a tap beyond the screen lands on the fan too.        let prefix = "ring-\(tool)-"        for _ in 0..<6 where chip.frame.maxX > app.frame.maxX - 8 || chip.frame.minX < 8 {            let left = chip.frame.minX < 8            let shown = app.descendants(matching: .any)                .matching(NSPredicate(format: "identifier BEGINSWITH %@", prefix)).allElementsBoundByIndex                .filter { $0.frame.minX >= 8 && $0.frame.maxX <= app.frame.maxX - 8 }            guard let step = left ? shown.min(by: { $0.frame.minX < $1.frame.minX })                                  : shown.max(by: { $0.frame.maxX < $1.frame.maxX }) else { break }            step.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()            settle(1)        }        chip.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()        settle(2)        if shoot { shot(tool, "view-" + id.replacingOccurrences(of: "ring-\(tool)-", with: "")) }    }    /// The deck's front card: `deck-card`; on a screen whose outer name    /// stands on every element in it (DeckSurface did, until c7c907d99), the    /// last card-sized one named `deck`, which is the card in front.    private func frontCard() -> XCUIElement? {        let card = app.descendants(matching: .any)["deck-card"].firstMatch        if card.waitForExistence(timeout: 3) { return card }        let named = app.descendants(matching: .other).matching(identifier: "deck").allElementsBoundByIndex        return named.last { $0.frame.height > 250 && $0.frame.width > 250 }    }    /// The fan again: folded into its circle, a tap there blooms it; from a    /// page a card opened, a swipe in from the edge, as far as it takes.    private func backToFan() {        let tiles = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-tile-'"))        let circle = app.descendants(matching: .any)["fan-record"].firstMatch        if tiles.count == 0, circle.exists {            log("the fan was folded")            circle.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()            settle(1.5)        }        for _ in 0..<4 where tiles.count == 0 {            point(0.01, 0.45).press(forDuration: 0.05, thenDragTo: point(0.8, 0.45), withVelocity: .fast, thenHoldForDuration: 0)            settle(1.5)        }        if tiles.count == 0 { log("MISSING the fan, after leaving a deck"); missing.append("fan"); XCTFail("missing control: the fan") }    }    /// Whatever the hold raised goes away: its close, else a tap high up.    private func putAway() {        for id in ["fan-record-close", "deck-whole-close"] {            let close = app.descendants(matching: .any)[id].firstMatch            if close.exists, close.isHittable { close.tap(); settle(1.2); return }        }        point(0.5, 0.06).tap()        settle(1.2)    }    /// One flick of the fan, right to left, along its row.    private func flick() {        point(0.8, 0.83).press(forDuration: 0.05, thenDragTo: point(0.55, 0.83), withVelocity: .slow, thenHoldForDuration: 0.1)        settle(0.8)    }    /// Turns the fan until `key`'s tile stands in the middle, and taps it.    @discardableResult    private func turn(to key: String) -> Bool {        let tile = app.descendants(matching: .any)["fan-tile-\(key)"]        for _ in 0..<28 {            // The fan's tiles read as not hittable under its gesture layer:            // the one in the middle is tapped where it stands.            if tile.exists, abs(tile.frame.midX - app.frame.midX) < 60 {                tile.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.4)).tap()                return true            }            // A tile the fan has not drawn lies the way its name does: the            // fan is in order of the tools' names, so a key before the middle            // tile's is to the left.            if tile.exists ? tile.frame.midX < app.frame.midX : key < middleKey() {                point(0.45, 0.83).press(forDuration: 0.05, thenDragTo: point(0.7, 0.83), withVelocity: .slow, thenHoldForDuration: 0.1)                settle(0.8)            } else {                flick()            }        }        missing.append("fan-tile-\(key)")        log("MISSING fan-tile-\(key)")        XCTFail("missing control fan-tile-\(key)")        return false    }    /// The key of the tile in the middle of the fan.    private func middleKey() -> String {        let tiles = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-tile-'")).allElementsBoundByIndex        let middle = tiles.min { abs($0.frame.midX - app.frame.midX) < abs($1.frame.midX - app.frame.midX) }        return middle.map { String($0.identifier.dropFirst("fan-tile-".count)) } ?? ""    }    private func point(_ x: Double, _ y: Double) -> XCUICoordinate {        app.coordinate(withNormalizedOffset: CGVector(dx: x, dy: y))    }    // MARK: - Helpers    private func settle(_ seconds: Double) {        RunLoop.current.run(until: Date().addingTimeInterval(seconds))        crashed()    }    /// The app is gone: a crash, which fails the walk.    private func crashed() {        if app.state != .runningForeground {            log("CRASH app state \(app.state.rawValue)")            XCTFail("the app is not running (state \(app.state.rawValue))")        }    }    private func shot(_ tool: String, _ step: String) {        frame += 1        let name = String(format: "%02d-%@-%@", frame, tool, step)        let png = XCUIScreen.main.screenshot().pngRepresentation        try? png.write(to: out.appendingPathComponent(name + ".png"))        try? app.debugDescription.write(to: out.appendingPathComponent(name + ".txt"), atomically: true, encoding: .utf8)        log("shot \(name)")    }    /// An element by its identifier, else nil and a MISSING line.    @discardableResult    private func need(_ id: String, wait: Double = 6) -> XCUIElement? {        let element = app.descendants(matching: .any)[id].firstMatch        if element.waitForExistence(timeout: wait) { return element }        missing.append(id)        log("MISSING \(id)")        XCTFail("missing control \(id)")        return nil    }    private func find(label: String, wait: Double = 6) -> XCUIElement? {        let element = app.descendants(matching: .any).matching(NSPredicate(format: "label == %@", label)).firstMatch        return element.waitForExistence(timeout: wait) ? element : nil    }    private func log(_ line: String) {        let url = out.appendingPathComponent("walk.log")        let stamped = "\(Date()) \(line)\n"        if let handle = try? FileHandle(forWritingTo: url) {            handle.seekToEndOfFile()            handle.write(Data(stamped.utf8))            try? handle.close()        } else {            try? stamped.write(to: url, atomically: true, encoding: .utf8)        }    }}