Cotton code
409 lines · 22.1 KB · SwiftRaw
// Real touches on the synthetic Home, recorded by scripts/home-preview/walk.sh// (`ui-tests-stub.sh --home-walk`). One test per walk; the script records the// simulator's screen while it runs. Every walk launches the preview with the// app arguments the script hands it (HOME_WALK_ARGS, tab-separated).////   edge — fan3 part 9: for each tile named in HOME_WALK_TILES (default//   "mood|notes"), turn to it, scroll its page slowly past the fan and back,//   leave it scrolled, turn the fan while scrolled and release.////   collapse — fancollapse: for each tile named in HOME_WALK_TILES (default//   "mood|notes"), scroll its page down to read (the fan folds into the//   circle), open a record and close it (it stays folded), scroll up (it//   blooms); then fold it again and tap the circle (it listens).////   caps — the bottom band for a review: the caps' arc turned a cap out and//   back, then on Mood the page read down (folds), a swipe up on the circle//   (blooms), read down again and back up (folds, blooms).////   search — the 286 blocker (qa on 285): with the keyboard up, Home's//   search, Notes' and People's, and the hold-to-type composer each stand//   whole on screen below the status bar and can be tapped, and the page's//   head row has not moved. Asserts; a failure fails the walk.////   switches — lane stalepic: with -databases naming three, a tap on the//   cap beside the chosen one, one switch every 6 s or HOME_WALK_PAUSE (first, second, third,//   second, first, …) — a warm-up round that shows each database once (its//   page pictures drawn), then ten switches the switch's timeline is read//   from (`SwitchClock`, switch-times.py).////   recordhead — fan3 part 10: on Notes a record opened and closed by each//   route (its X, the edge swipe, a pull down from its head), a long press on//   the X listing the stack; then Mood, Alarms and AI usage's head rows.////   script — any walk, without a rebuild: the steps of HOME_WALK_SCRIPT (see//   testScript), frames and accessibility trees written to HOME_WALK_OUT.import XCTest@MainActorfinal class HomeWalk: XCTestCase {    private var app: XCUIApplication!    private func launch() {        app = XCUIApplication(bundleIdentifier: "com.cottondb.homepreview")        let args = ProcessInfo.processInfo.environment["HOME_WALK_ARGS"] ?? ""        app.launchArguments = args.split(separator: "\t").map(String.init)        app.launch()        XCTAssertTrue(app.descendants(matching: .any)["home-fan"].waitForExistence(timeout: 60), "the fan is on screen")        // Every page picture drawn, as on a warm app.        Thread.sleep(forTimeInterval: 8)    }    private func point(_ x: Double, _ y: Double) -> XCUICoordinate {        app.coordinate(withNormalizedOffset: CGVector(dx: x, dy: y))    }    /// The tile whose key holds `name`, turned to by tapping it once it is    /// drawn, swiping the fan a tile at a time toward it until it is.    private func turn(to name: String) throws {        let tile = app.descendants(matching: .any)            .matching(NSPredicate(format: "identifier BEGINSWITH 'fan-tile-' AND identifier CONTAINS %@", name)).firstMatch        let screen = app.windows.firstMatch.frame        for _ in 0 ..< 12 where !(tile.exists && screen.intersects(tile.frame) && tile.frame.width > 0) {            point(0.8, deckRow()).press(forDuration: 0.01, thenDragTo: point(0.55, deckRow()))            Thread.sleep(forTimeInterval: 1)        }        XCTAssertTrue(tile.exists, "the \(name) tile is on the fan")        tile.tap()        Thread.sleep(forTimeInterval: 3)    }    /// The deck's row, as a fraction of the screen's height: the settled tile's middle.    private func deckRow() -> Double {        let screen = app.windows.firstMatch.frame        let tiles = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-tile-'"))        let drawn = tiles.allElementsBoundByIndex.map(\.frame).filter { $0.width > 0 && screen.intersects($0) }        guard let settled = drawn.min(by: { abs($0.midX - screen.midX) < abs($1.midX - screen.midX) }) else { return 0.8 }        return settled.midY / screen.height    }    /// A slow drag on the page, from `from` to `to` (fractions of the height).    private func scroll(_ from: Double, _ to: Double) {        point(0.5, from).press(forDuration: 0.2, thenDragTo: point(0.5, to), withVelocity: .slow, thenHoldForDuration: 0.4)        Thread.sleep(forTimeInterval: 1.2)    }    func testEdge() throws {        launch()        let asked = ProcessInfo.processInfo.environment["HOME_WALK_TILES"] ?? ""        let names = (asked.isEmpty ? "mood|notes" : asked).split(separator: "|")        for name in names.map(String.init) {            try turn(to: name)            // Up the page: the fan steps aside; back down: it returns, and            // the page runs on under it.            scroll(0.55, 0.3)            scroll(0.3, 0.45)            scroll(0.3, 0.42)            Thread.sleep(forTimeInterval: 2)            // Turn while scrolled: a slow drag a tile over, held, then let go.            let row = deckRow()            point(0.65, row).press(forDuration: 0.3, thenDragTo: point(0.4, row), withVelocity: .slow,                                   thenHoldForDuration: 1.0)            Thread.sleep(forTimeInterval: 3)            // And back to it.            try turn(to: name)            Thread.sleep(forTimeInterval: 2)        }    }    func testCollapse() throws {        launch()        let asked = ProcessInfo.processInfo.environment["HOME_WALK_TILES"] ?? ""        let names = (asked.isEmpty ? "mood|notes" : asked).split(separator: "|")        // The record button's width: the circle's when folded.        let record = app.descendants(matching: .any)["fan-record"]        for name in names.map(String.init) {            try turn(to: name)            let bloomed = record.frame.width            // Down the page to read: the fan folds into the circle (a page            // too short to scroll does not fold it).            scroll(0.6, 0.35)            Thread.sleep(forTimeInterval: 1.5)            let read = record.frame.width            // A record opened from the page, and closed by the edge swipe: still folded.            point(0.5, 0.4).tap()            Thread.sleep(forTimeInterval: 2.5)            point(0.01, 0.5).press(forDuration: 0.05, thenDragTo: point(0.85, 0.5), withVelocity: .default,                                   thenHoldForDuration: 0.1)            Thread.sleep(forTimeInterval: 2.5)            XCTAssertEqual(record.frame.width, read, accuracy: 1, "\(name): opening and closing a record leaves the fan as it was")            // Back up the page: the fan blooms.            scroll(0.35, 0.55)            Thread.sleep(forTimeInterval: 2)            XCTAssertEqual(record.frame.width, bloomed, accuracy: 1, "\(name): a scroll back up blooms the fan")        }        // Folded once more, a tap on the circle listens.        scroll(0.6, 0.35)        Thread.sleep(forTimeInterval: 1.5)        app.descendants(matching: .any)["fan-record"].tap()        Thread.sleep(forTimeInterval: 4)    }    func testSwitches() throws {        launch()        let caps = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-database-'"))        let ids = caps.allElementsBoundByIndex.map(\.identifier)        XCTAssertGreaterThanOrEqual(ids.count, 3, "three databases' caps")        // Always the cap beside the chosen one: a cap further round is off        // the arc. Each database once from the first, then to and fro.        // HOME_WALK_EVERY=<n>: n databases, out along the arc and back, each        // cap beside the last (294 row 2: the frame guard across all of them,        // the way back on each one's kept Home).        let every = !(ProcessInfo.processInfo.environment["HOME_WALK_EVERY"] ?? "").isEmpty        let order = [ids[1], ids[2], ids[1], ids[0]]        // HOME_WALK_PAUSE: seconds between switches (default 6).        let pause = Double(ProcessInfo.processInfo.environment["HOME_WALK_PAUSE"] ?? "") ?? 6        // Out along the arc and back, each time the cap on screen just beside        // the chosen one (which stands at the arc's middle).        let count = ProcessInfo.processInfo.environment["HOME_WALK_EVERY"].flatMap(Int.init) ?? ids.count        var right = true        for turn in 0 ..< (every ? 2 * (count - 1) : 3 + 10) {            // At the arc's end, back the other way.            if every, capBeside(right: right) == nil { right.toggle() }            let cap = every ? try XCTUnwrap(capBeside(right: right), "a cap beside the chosen one")                : app.descendants(matching: .any)[order[turn % order.count]]            XCTAssertTrue(cap.waitForExistence(timeout: 10), "the cap \(cap.identifier) is drawn")            cap.tap()            Thread.sleep(forTimeInterval: pause)        }    }    /// The cap on screen next to the arc's middle, to its right or left.    private func capBeside(right: Bool) -> XCUIElement? {        let screen = app.frame        let caps = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-database-'"))            .allElementsBoundByIndex.filter { $0.exists && screen.contains(CGPoint(x: $0.frame.midX, y: $0.frame.midY)) }            .sorted { $0.frame.midX < $1.frame.midX }        return right ? caps.first { $0.frame.midX > screen.midX + 10 } : caps.last { $0.frame.midX < screen.midX - 10 }    }    func testCaps() throws {        launch()        let caps = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-database-'"))        let screen = app.windows.firstMatch.frame        let drawn = caps.allElementsBoundByIndex.map(\.frame).filter { $0.width > 0 && screen.intersects($0) }        if let row = drawn.min(by: { abs($0.midX - screen.midX) < abs($1.midX - screen.midX) })?.midY {            let y = row / screen.height            point(0.7, y).press(forDuration: 0.05, thenDragTo: point(0.45, y), withVelocity: .slow, thenHoldForDuration: 0.5)            Thread.sleep(forTimeInterval: 2)            point(0.45, y).press(forDuration: 0.05, thenDragTo: point(0.7, y), withVelocity: .slow, thenHoldForDuration: 0.5)            Thread.sleep(forTimeInterval: 2)        }        try turn(to: "mood")        scroll(0.6, 0.35)        Thread.sleep(forTimeInterval: 1.5)        // A swipe up on the circle blooms the fan.        let circle = app.descendants(matching: .any)["fan-record"].frame        let from = app.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: circle.midX, dy: circle.midY))        from.press(forDuration: 0.05, thenDragTo: from.withOffset(CGVector(dx: 0, dy: -90)), withVelocity: .fast,                   thenHoldForDuration: 0)        Thread.sleep(forTimeInterval: 2)        scroll(0.6, 0.35)        Thread.sleep(forTimeInterval: 1.5)        scroll(0.35, 0.55)        Thread.sleep(forTimeInterval: 2)    }    /// Below the status bar of every phone with an island.    private let safeTop = 54.0    private func standsOnScreen(_ element: XCUIElement, _ what: String) {        XCTAssertTrue(element.waitForExistence(timeout: 5), "\(what) is drawn")        let window = app.windows.firstMatch.frame        XCTAssertTrue(window.contains(element.frame), "\(what) whole on screen: \(element.frame)")        XCTAssertGreaterThanOrEqual(Double(element.frame.minY), safeTop, "\(what) below the status bar: \(element.frame)")        XCTAssertTrue(element.isHittable, "\(what) can be tapped")    }    /// Opens a search with `open`, then checks its field and Cancel with the    /// keyboard up, and that `head` stands where it stood; Cancel closes it.    private func search(_ what: String, head: XCUIElement, open: () -> Void) {        guard head.waitForExistence(timeout: 10) else {            let ids = app.descendants(matching: .any).allElementsBoundByIndex.map(\.identifier).filter { !$0.isEmpty }            return XCTFail("\(what): the head row is not drawn; on screen: \(ids.prefix(60))")        }        let before = head.frame        open()        XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5), "\(what): the keyboard is up")        Thread.sleep(forTimeInterval: 1)        standsOnScreen(app.textFields.firstMatch, "\(what)'s field")        let cancel = app.buttons["Cancel"].firstMatch        standsOnScreen(cancel, "\(what)'s Cancel")        if head.exists {            XCTAssertEqual(Double(head.frame.minY), Double(before.minY), accuracy: 1, "\(what): the head row moved")        }        cancel.tap()        Thread.sleep(forTimeInterval: 1.5)    }    func testSearch() throws {        launch()        let any = app.descendants(matching: .any)        // The record button held: the composer rises with the keyboard, above        // it, and the page behind stays where it stood.        let head = any["board-more"]        XCTAssertTrue(head.waitForExistence(timeout: 10), "Home's head row is drawn")        let before = head.frame        any["fan-record"].press(forDuration: 1.0)        XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5), "composer: the keyboard is up")        Thread.sleep(forTimeInterval: 1.5)        let keyboardTop = app.keyboards.firstMatch.frame.minY        print("walk: keyboard top \(keyboardTop), home-fan \(any["home-fan"].frame), head \(head.frame) (was \(before))")        for (id, what) in [("cap-input", "field"), ("cap-cancel", "cancel"), ("cap-send", "send")] {            let element = any[id].firstMatch            print("walk: \(id) \(element.exists ? "\(element.frame)" : "missing")")            standsOnScreen(element, "the composer's \(what)")            XCTAssertLessThanOrEqual(element.frame.maxY, keyboardTop + 1,                                     "the composer's \(what) above the keyboard: \(element.frame), keyboard at \(keyboardTop)")        }        XCTAssertGreaterThanOrEqual(Double(any["home-fan"].frame.minY), 0, "composer: the page behind stays where it was")        if any["cap-cancel"].exists { any["cap-cancel"].firstMatch.tap() }        Thread.sleep(forTimeInterval: 1.5)        search("Home", head: any["board-more"]) { any["bar-search"].tap() }        for (name, table) in [("notes", "note"), ("people", "person")] {            // From Home's own grid: a tile tapped there turns the fan to it            // and shows its page (a leaning fan tile's frame overlaps its            // neighbour's, and a tap on it can land on the neighbour).            launch()            any["board-tool-\(name)"].tap()            Thread.sleep(forTimeInterval: 3)            let menu = any["list-\(table)-menu"]            search(name, head: menu.waitForExistence(timeout: 3) ? menu : any["list-\(table)-new"]) {                any["list-\(table)-search"].firstMatch.tap()            }        }    }    func testRecordhead() throws {        launch()        try turn(to: "notes")        let close = app.descendants(matching: .any)["page-back"]        // By its X.        point(0.5, 0.35).tap()        XCTAssertTrue(close.waitForExistence(timeout: 10), "the record wears its X")        Thread.sleep(forTimeInterval: 2.5)        close.tap()        Thread.sleep(forTimeInterval: 2.5)        // By the edge swipe.        point(0.5, 0.35).tap()        Thread.sleep(forTimeInterval: 2.5)        point(0.01, 0.5).press(forDuration: 0.05, thenDragTo: point(0.85, 0.5), withVelocity: .default,                               thenHoldForDuration: 0.1)        Thread.sleep(forTimeInterval: 2.5)        // By a pull down from its head.        point(0.5, 0.35).tap()        Thread.sleep(forTimeInterval: 2.5)        point(0.4, 0.12).press(forDuration: 0.05, thenDragTo: point(0.4, 0.55), withVelocity: .default,                               thenHoldForDuration: 0.2)        Thread.sleep(forTimeInterval: 2.5)        // A long press on the X lists the stack; dismissed, then closed.        point(0.5, 0.35).tap()        Thread.sleep(forTimeInterval: 2.5)        if close.waitForExistence(timeout: 5) {            close.press(forDuration: 1.0)            Thread.sleep(forTimeInterval: 2)            point(0.5, 0.6).tap()            Thread.sleep(forTimeInterval: 1)            close.tap()            Thread.sleep(forTimeInterval: 2.5)        }        for name in ["mood", "alarms", "ai_usage"] {            try turn(to: name)            Thread.sleep(forTimeInterval: 3)        }    }    // MARK: script — a walk read from HOME_WALK_SCRIPT (steps split by ";;",    // words by "\t"), frames and trees written to HOME_WALK_OUT on the host.    //   launch <args...> | wait <s> | shot <name> | tree <name>    //   tap <id> | tapprefix <prefix> [contains] | tapat <x> <y> | taplabel <label>    //   hold <id> <s> | drag <x1> <y1> <x2> <y2> [hold s] | edge | turn <name>    //   type <text> | has <id> <name>  (logs whether it exists and is hittable)    private var out = ""    /// The app the script drives: the preview unless a `target <bundle id>` step names another.    private var target = "com.cottondb.homepreview"    private func log(_ line: String) {        let url = URL(fileURLWithPath: out).appendingPathComponent("walk.log")        let data = Data((line + "\n").utf8)        if let handle = try? FileHandle(forWritingTo: url) { handle.seekToEndOfFile(); handle.write(data); handle.closeFile() }        else { try? data.write(to: url) }    }    private func element(_ id: String) -> XCUIElement { app.descendants(matching: .any)[id].firstMatch }    func testScript() throws {        let env = ProcessInfo.processInfo.environment        out = env["HOME_WALK_OUT"] ?? NSTemporaryDirectory()        try? FileManager.default.createDirectory(atPath: out, withIntermediateDirectories: true)        let steps = (env["HOME_WALK_SCRIPT"] ?? "").components(separatedBy: ";;").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }        for step in steps where !step.isEmpty {            let w = step.components(separatedBy: "\t")            let started = Date()            switch w[0] {            case "target": target = w[1]            case "launch":                app = XCUIApplication(bundleIdentifier: target)                app.launchArguments = Array(w.dropFirst())                app.launch()            case "attach":                app = XCUIApplication(bundleIdentifier: target)            case "wait": Thread.sleep(forTimeInterval: Double(w[1]) ?? 1)            case "waitfor": log("waitfor \(w[1]) -> \(element(w[1]).waitForExistence(timeout: Double(w[safe: 2] ?? "") ?? 30))")            case "shot":                let png = XCUIScreen.main.screenshot().pngRepresentation                try? png.write(to: URL(fileURLWithPath: out).appendingPathComponent(w[1] + ".png"))            case "tree":                try? Data(app.debugDescription.utf8).write(to: URL(fileURLWithPath: out).appendingPathComponent(w[1] + ".txt"))            case "tap":                let e = element(w[1])                if e.waitForExistence(timeout: 5) { e.tap(); log("tap \(w[1]) ok") } else { log("tap \(w[1]) MISSING") }            case "tapprefix":                let predicate = w.count > 2                    ? NSPredicate(format: "identifier BEGINSWITH %@ AND identifier CONTAINS %@", w[1], w[2])                    : NSPredicate(format: "identifier BEGINSWITH %@", w[1])                let e = app.descendants(matching: .any).matching(predicate).firstMatch                if e.waitForExistence(timeout: 5) { log("tapprefix \(e.identifier) ok"); e.tap() } else { log("tapprefix \(w[1]) MISSING") }            case "taplabel":                let e = app.descendants(matching: .any).matching(NSPredicate(format: "label == %@", w[1])).firstMatch                if e.waitForExistence(timeout: 5) { e.tap(); log("taplabel \(w[1]) ok") } else { log("taplabel \(w[1]) MISSING") }            case "tapat": point(Double(w[1])!, Double(w[2])!).tap()            case "hold":                let e = element(w[1])                if e.waitForExistence(timeout: 5) { e.press(forDuration: Double(w[2]) ?? 1); log("hold \(w[1]) ok") } else { log("hold \(w[1]) MISSING") }            case "drag":                point(Double(w[1])!, Double(w[2])!).press(forDuration: 0.05, thenDragTo: point(Double(w[3])!, Double(w[4])!),                    withVelocity: .default, thenHoldForDuration: Double(w[safe: 5] ?? "") ?? 0)            case "slowdrag":                point(Double(w[1])!, Double(w[2])!).press(forDuration: 0.2, thenDragTo: point(Double(w[3])!, Double(w[4])!),                    withVelocity: .slow, thenHoldForDuration: 0.4)            case "edge":                point(0.005, 0.5).press(forDuration: 0.05, thenDragTo: point(0.8, 0.5), withVelocity: .default, thenHoldForDuration: 0)            case "turn": try turn(to: w[1])            case "fanflick":                let row = deckRow()                point(Double(w[1])!, row).press(forDuration: 0.01, thenDragTo: point(Double(w[2])!, row))            case "tapsettled":                let screen = app.windows.firstMatch.frame                let tiles = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fan-tile-'"))                let drawn = tiles.allElementsBoundByIndex.filter { $0.frame.width > 0 && screen.intersects($0.frame) }                if let settled = drawn.min(by: { abs($0.frame.midX - screen.midX) < abs($1.frame.midX - screen.midX) }) {                    log("tapsettled \(settled.identifier)"); settled.tap()                } else { log("tapsettled NONE") }            case "type": app.typeText(w[1])            case "has":                let e = element(w[1])                log("has \(w[1]) exists=\(e.exists) hittable=\(e.exists && e.isHittable) frame=\(e.exists ? e.frame : .zero) [\(w[safe: 2] ?? "")]")            case "count":                let n = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", w[1])).count                log("count \(w[1]) = \(n) [\(w[safe: 2] ?? "")]")            default: log("unknown step \(step)")            }            log(String(format: "%.2fs  %@", Date().timeIntervalSince(started), step.replacingOccurrences(of: "\t", with: " ")))        }    }}private extension Array {    subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }}