Cotton code
320 lines · 17.3 KB · SwiftRaw
// What every Days UI test does: launch Days Dev on the invented days and the// crowd (days-dev-seed.json, then days-crowd.json: sixty-four invented to-dos// on today and sixty-four in Sometime), find a row by its words, a panel by// what it says, and drag from a given part of an element as a finger would.// Nothing here is anyone's real day.import XCTestenum DaysUI {    /// Days Dev on the invented days and the crowd, with any extra launch arguments (a look to open, a text size).    @MainActor static func launch(_ extra: [String] = []) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-days-crowd", "YES"] + extra        app.launch()        return app    }    /// The largest accessibility text size, set at launch.    static let largestText = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]    /// A row by its words (its label starts with them, then its suffix or "To-do").    @MainActor static func row(_ app: XCUIApplication, _ words: String) -> XCUIElement {        app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@ OR label CONTAINS %@", words + ",", ", " + words + ",")).firstMatch    }    /// Every row of the crowd standing whole in the middle of the window. The    /// synced crowd may stand more than once in a list, its copies far    /// apart: a row is followed by where it stands (`whereIs`), never found    /// again by its label alone.    @MainActor static func middleRows(_ app: XCUIApplication, _ words: String) -> [Seen] {        let window = app.windows.firstMatch.frame        return seen(app).filter { row in            let frame = row.frame            return row.type == .button && row.label.contains(words) && frame.minY > window.height * 0.3 && frame.maxY < window.height * 0.7 && frame.height < 90        }    }    /// Where the row labelled `label` stands now: of its copies, the one nearest `y`.    @MainActor static func whereIs(_ app: XCUIApplication, _ label: String, near y: CGFloat) -> CGFloat? {        seen(app).filter { $0.type == .button && $0.label == label }.map(\.frame.minY).min { abs($0 - y) < abs($1 - y) }    }    /// A point of a row a snapshot saw (0…1 across and down it), to touch.    @MainActor static func point(_ app: XCUIApplication, _ row: Seen, _ at: CGVector) -> XCUICoordinate {        app.windows.firstMatch.coordinate(withNormalizedOffset: .zero)            .withOffset(CGVector(dx: row.frame.minX + row.frame.width * at.dx, dy: row.frame.minY + row.frame.height * at.dy))    }    /// A finger put down on a part of a row a snapshot saw and moved `by` quickly.    @MainActor static func drag(_ app: XCUIApplication, _ row: Seen, at: CGVector, by: CGVector, hold: TimeInterval = 0.05) {        let start = point(app, row, at)        start.press(forDuration: hold, thenDragTo: start.withOffset(by), withVelocity: .fast, thenHoldForDuration: 0.05)    }    /// Days has come in with the crowd: one of today's chores stands.    /// (The dev account the standing simulator is signed into syncs, so the    /// crowd may stand more than once; no test counts on one of a name.)    @MainActor @discardableResult static func days(_ app: XCUIApplication) -> XCUIElement {        let first = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Invented chore")).firstMatch        XCTAssertTrue(first.waitForExistence(timeout: 90), "the crowd came in")        return first    }    /// Sometime has come in with the crowd.    @MainActor static func sometime(_ app: XCUIApplication) {        let any = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Invented")).firstMatch        XCTAssertTrue(any.waitForExistence(timeout: 90), "Sometime came in with the crowd")    }    /// What stands on screen, read in one snapshot (hundreds of rows asked    /// one by one for their frames took minutes): each element's type,    /// label and frame.    struct Seen {        let type: XCUIElement.ElementType        let label: String        let frame: CGRect    }    @MainActor static func seen(_ app: XCUIApplication) -> [Seen] {        guard let root = try? app.snapshot() else { return [] }        var out: [Seen] = []        func walk(_ s: XCUIElementSnapshot) {            if s.elementType == .button || s.elementType == .textField || s.elementType == .textView || s.elementType == .staticText {                out.append(Seen(type: s.elementType, label: s.label, frame: s.frame))            }            s.children.forEach(walk)        }        walk(root)        return out    }    /// Where the foot begins: the switch, the button back to today or the adding bar, whichever stands highest.    @MainActor static func footTop(_ app: XCUIApplication, _ all: [Seen]? = nil) -> CGFloat {        let all = all ?? seen(app)        let foot = all.filter { ($0.type == .button && ["Days", "Sometime", "Back to today"].contains($0.label)) || $0.label == "What, and when?" }        return foot.filter { $0.frame.height > 0 }.map { $0.frame.minY - ($0.type == .button ? 6 : 12) }.min()            ?? app.windows.firstMatch.frame.maxY    }    /// Every to-do row standing on screen above the foot (a row may scroll on under the foot), top to bottom.    @MainActor static func todosOnScreen(_ app: XCUIApplication, _ all: [Seen]? = nil) -> [Seen] {        let all = all ?? seen(app)        let window = app.windows.firstMatch.frame        let foot = footTop(app, all)        return all.filter { $0.type == .button && $0.label.contains(", To-do") && $0.frame.minY > window.minY && $0.frame.minY < foot && $0.frame.height > 0 }            .sorted { $0.frame.minY < $1.frame.minY }    }    /// The row a snapshot saw, to touch: the button of that label (the first, if the synced crowd has two).    @MainActor static func element(_ app: XCUIApplication, _ row: Seen) -> XCUIElement {        app.buttons.matching(NSPredicate(format: "label == %@", row.label)).firstMatch    }    /// A to-do of today's crowd standing whole in the middle of the window.    @MainActor static func middleChore(_ app: XCUIApplication) -> Seen? {        middleRows(app, "Invented chore").first { $0.label.contains(", To-do") }    }    /// A row's words: its label up to its time-free tail (", To-do", ", Done").    static func words(_ label: String) -> String {        label.components(separatedBy: ", To-do").first?.components(separatedBy: ", Done").first ?? label    }    /// A button by its exact label.    @MainActor static func button(_ app: XCUIApplication, _ label: String) -> XCUIElement {        app.buttons.matching(NSPredicate(format: "label == %@", label)).firstMatch    }    /// Any element by its exact label.    @MainActor static func any(_ app: XCUIApplication, _ label: String) -> XCUIElement {        app.descendants(matching: .any).matching(NSPredicate(format: "label == %@", label)).firstMatch    }    /// A finger put down at `at` (0…1 across and down `element`) and moved    /// `by` points quickly, as a swipe that starts on that part of it.    @MainActor static func drag(_ element: XCUIElement, at: CGVector, by: CGVector, hold: TimeInterval = 0.05) {        let start = element.coordinate(withNormalizedOffset: at)        start.press(forDuration: hold, thenDragTo: start.withOffset(by), withVelocity: .fast, thenHoldForDuration: 0.05)    }    /// A drag from a point of the window (0…1 of its width and height).    @MainActor static func drag(_ app: XCUIApplication, from: CGVector, by: CGVector, hold: TimeInterval = 0.05) {        drag(app.windows.firstMatch, at: from, by: by, hold: hold)    }    /// Scrolls up the list (the finger going up) until `element` can be touched, at most `tries` flicks.    @MainActor static func scrollTo(_ element: XCUIElement, in app: XCUIApplication, tries: Int = 40) -> Bool {        for _ in 0..<tries {            if element.exists, element.isHittable, inside(element, app, top: 60, bottom: 120) { return true }            let start = app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.7))            start.press(forDuration: 0.01, thenDragTo: start.withOffset(CGVector(dx: 0, dy: -app.windows.firstMatch.frame.height * 0.35)), withVelocity: .fast, thenHoldForDuration: 0)        }        return element.exists && element.isHittable    }    /// Whether a frame stands wholly inside the window's safe part.    @MainActor static func inside(_ frame: CGRect, _ app: XCUIApplication, top: CGFloat = 44, bottom: CGFloat = 20) -> Bool {        let window = app.windows.firstMatch.frame        return frame.minY >= window.minY + top && frame.maxY <= window.maxY - bottom && frame.minX >= window.minX && frame.maxX <= window.maxX    }    /// Whether `element` stands wholly inside the window's safe part: under    /// the clock and above the home indicator, clear of the sides.    @MainActor static func inside(_ element: XCUIElement, _ app: XCUIApplication, top: CGFloat = 44, bottom: CGFloat = 20) -> Bool {        let window = app.windows.firstMatch.frame        let frame = element.frame        return frame.minY >= window.minY + top && frame.maxY <= window.maxY - bottom            && frame.minX >= window.minX && frame.maxX <= window.maxX    }    /// The software keyboard, once it has risen.    @MainActor static func keyboard(_ app: XCUIApplication) -> XCUIElement {        let keys = app.keyboards.firstMatch        XCTAssertTrue(keys.waitForExistence(timeout: 5), "the keyboard rose")        // Let it finish rising.        _ = app.buttons["__none__"].waitForExistence(timeout: 0.6)        return keys    }    /// A text field or view by the name it is read by.    @MainActor static func field(_ app: XCUIApplication, _ name: String) -> XCUIElement {        app.descendants(matching: .any).matching(NSPredicate(format: "label == %@ AND (elementType == %d OR elementType == %d)",                                                             name, XCUIElement.ElementType.textField.rawValue, XCUIElement.ElementType.textView.rawValue)).firstMatch    }    /// Show at the top left ("Showing All. Choose what to show").    @MainActor static func filter(_ app: XCUIApplication) -> XCUIElement {        app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Showing ")).firstMatch    }    /// Show's All (its count beside it).    @MainActor static func all(_ app: XCUIApplication) -> XCUIElement {        app.buttons.matching(NSPredicate(format: "label == %@ OR label BEGINSWITH %@", "All", "All,")).firstMatch    }    /// The quiet line said at the foot after a tick or a move, with its Undo.    @MainActor static func undo(_ app: XCUIApplication) -> XCUIElement { button(app, "Undo") }}/// Every Days UI test: upright to start, upright again after, and the/// screen kept with a failure so it can be looked at.class DaysUITestCase: XCTestCase {    override func setUp() {        continueAfterFailure = false        XCUIDevice.shared.orientation = .portrait    }    override func tearDown() {        if let run = testRun, run.failureCount > 0 {            let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())            shot.name = name            shot.lifetime = .keepAlways            add(shot)        }        XCUIDevice.shared.orientation = .portrait    }    /// Another device asking to be let in stands the shell's card at the top    /// of the screen (the dev server's own traffic, not this test's). The    /// card pushes Days down, so this skips only when it truly stands over    /// one of Days' own top controls (`controls`, else Show and More): on    /// top, where a finger would land on it. The card is never tapped.    @MainActor func skipUnderTheShellsCard(_ app: XCUIApplication, wait: TimeInterval = 2, _ controls: [XCUIElement] = []) throws {        let tops = controls.isEmpty ? [DaysUI.button(app, "More: settings"), DaysUI.filter(app)] : controls        if ShellCard.covers(app, tops, wait: wait) {            throw XCTSkip("another device's unlock request stands over Days' own top")        }    }    /// Where Days' own top stands (under the shell's card, if one stands): a tap    /// a little under it, while a panel is up, lands on the scrim above the panel.    @MainActor func daysTop(_ app: XCUIApplication) -> CGFloat {        for top in [DaysUI.filter(app), DaysUI.button(app, "More: settings")] where top.exists { return top.frame.minY }        return 62    }    /// Waits until `element` can be touched (a panel's closing slide has finished).    @MainActor func waitHittable(_ element: XCUIElement, _ timeout: TimeInterval = 3) {        let deadline = Date().addingTimeInterval(timeout)        while Date() < deadline, !(element.exists && element.isHittable) {            RunLoop.current.run(until: Date().addingTimeInterval(0.1))        }    }    /// A moment for a slide or a scroll to settle.    @MainActor func settle(_ seconds: TimeInterval = 0.5) {        RunLoop.current.run(until: Date().addingTimeInterval(seconds))    }}/// The shell's card of another device asking to be let in. `seed` stands an/// invented one (Walk Mac, `-shell-card-seed YES`, a development build only):/// it reaches no server, and its Refuse only takes it down and says so (`ShellToastUI`).enum ShellCard {    static let seed = ["-shell-card-seed", "YES"]    /// The card's Refuse: standing on top while it can be touched. Its id is    /// `approval-refuse`, or the card's own `approval-banner` where the card    /// (an app's look) hands its id to everything in it.    @MainActor static func refuse(_ app: XCUIApplication) -> XCUIElement {        app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "approval-")).firstMatch    }    /// The band the shell's cards stand in, scrolling inside when they are taller than it.    @MainActor static func band(_ app: XCUIApplication) -> XCUIElement {        app.scrollViews.containing(NSPredicate(format: "identifier BEGINSWITH %@", "approval-")).firstMatch    }    /// Everything of the card drawn on screen (inside its band), or nil while none of it is drawn.    @MainActor static func frame(_ app: XCUIApplication) -> CGRect? {        let parts = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "approval-"))        guard parts.firstMatch.exists else { return nil }        var frame = parts.allElementsBoundByIndex.reduce(CGRect.null) { $0.union($1.frame) }        let band = band(app)        if band.exists { frame = frame.intersection(band.frame) }        return frame.isNull ? nil : frame    }    /// Whether the card stands on top (its Refuse can be touched) over any of `controls`.    @MainActor static func covers(_ app: XCUIApplication, _ controls: [XCUIElement], wait: TimeInterval) -> Bool {        let refuse = refuse(app)        guard refuse.waitForExistence(timeout: wait), refuse.isHittable, let card = frame(app) else { return false }        return controls.contains { $0.exists && $0.frame.intersects(card) }    }    /// `control` stands, can be touched, and lies wholly outside the card.    @MainActor static func clear(_ app: XCUIApplication, _ control: XCUIElement, _ name: String,                                 file: StaticString = #filePath, line: UInt = #line) {        XCTAssertTrue(control.waitForExistence(timeout: 10), "\(name) stands", file: file, line: line)        let card = frame(app) ?? .null        XCTAssertFalse(card.isNull, "the card stands while \(name) is looked at", file: file, line: line)        XCTAssertTrue(control.isHittable, "\(name) can be touched", file: file, line: line)        // A page drawn over the whole window (a note) covers the card: it stands under that page, over nothing.        if refuse(app).isHittable {            XCTAssertFalse(control.frame.intersects(card), "\(name) \(control.frame) stands clear of the card \(card)", file: file, line: line)        }        let window = app.windows.firstMatch.frame        XCTAssertTrue(window.contains(control.frame), "\(name) \(control.frame) is on screen", file: file, line: line)    }    /// The card fits: no taller than half the screen, and its Refuse whole on screen above the home bar.    @MainActor static func fits(_ app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) {        let window = app.windows.firstMatch.frame        let refuse = refuse(app)        XCTAssertTrue(refuse.waitForExistence(timeout: 10), "the card stands", file: file, line: line)        let card = frame(app) ?? .null        XCTAssertLessThanOrEqual(card.height, window.height * 0.5, "the card \(card) takes at most half the screen", file: file, line: line)        // Taller than its band, the card scrolls: Refuse is reached by a swipe up inside it, never tapped.        let band = band(app)        for _ in 0..<4 where band.exists && !(refuse.isHittable && refuse.frame.maxY <= band.frame.maxY + 1) {            let start = band.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.8))            start.press(forDuration: 0.01, thenDragTo: start.withOffset(CGVector(dx: 0, dy: -band.frame.height * 0.5)))        }        if band.exists {            XCTAssertLessThanOrEqual(refuse.frame.maxY, band.frame.maxY + 1, "Refuse \(refuse.frame) stands whole in the card's band \(band.frame)", file: file, line: line)        }        XCTAssertTrue(refuse.isHittable, "Refuse can be touched", file: file, line: line)        XCTAssertLessThanOrEqual(refuse.frame.maxY, window.maxY - 34, "Refuse \(refuse.frame) stands above the home bar", file: file, line: line)    }}