krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDayUITests/AccessibilityAuditTests.swift

main
daybyday/DayByDayUITests/AccessibilityAuditTests.swift history · blame · raw

191 lines · 8949 bytes

21 symbols in this file
  1import XCTest
  2
  3/// Opens every screen a child or grown-up uses, by the labels VoiceOver and
  4/// Voice Control see, and runs Xcode's accessibility audit on each one: at the
  5/// default text size and at the largest accessibility size.
  6final class AccessibilityAuditTests: XCTestCase {
  7    static let largestText = "UICTContentSizeCategoryAccessibilityXXXL"
  8    static let topics = ["Days", "Months", "Seasons", "Numbers", "Colors", "Shapes", "Animals",
  9                         "Alphabet", "Weather", "Body", "Food"]
 10
 11    private var sizeName = ""
 12
 13    override func setUp() {
 14        continueAfterFailure = true
 15    }
 16
 17    func testTopicsAndGames() throws { try topicsAndGames(textSize: nil) }
 18    func testTopicsAndGamesLargestText() throws { try topicsAndGames(textSize: Self.largestText) }
 19    func testTodayRoutine() throws { try todayRoutine(textSize: nil) }
 20    func testTodayRoutineLargestText() throws { try todayRoutine(textSize: Self.largestText) }
 21    func testGrownUps() throws { try grownUps(textSize: nil) }
 22    func testGrownUpsLargestText() throws { try grownUps(textSize: Self.largestText) }
 23    func testProfiles() throws { try profiles(textSize: nil) }
 24    func testProfilesLargestText() throws { try profiles(textSize: Self.largestText) }
 25
 26    // MARK: - Walks
 27
 28    private func topicsAndGames(textSize: String?) throws {
 29        let app = launch("home", textSize: textSize)
 30        try audit(app, "home")
 31        for topic in Self.topics {
 32            let hub = app.buttons["activity:Look and listen"]
 33            tap(app.buttons[topic], in: app)
 34            // A tap that lands while the grid is still scrolling does not navigate.
 35            if !hub.waitForExistence(timeout: 3) { tap(app.buttons[topic], in: app) }
 36            XCTAssert(hub.waitForExistence(timeout: 3), "\(topic) did not open")
 37            try audit(app, topic)
 38            let activities = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'activity:'"))
 39            let titles = activities.allElementsBoundByIndex.map(\.identifier)
 40            for id in titles {
 41                tap(app.buttons[id], in: app)
 42                try audit(app, "\(topic) \(id.dropFirst("activity:".count))")
 43                back(app)
 44            }
 45            back(app)
 46        }
 47    }
 48
 49    private func todayRoutine(textSize: String?) throws {
 50        let app = launch("home", textSize: textSize)
 51        tap(app.buttons.matching(NSPredicate(format: "label BEGINSWITH 'Today is'")).firstMatch, in: app)
 52        var lines = 0
 53        while app.buttons["Next"].waitForExistence(timeout: 2) {
 54            try audit(app, "routine line \(lines)")
 55            app.buttons["Next"].tap()
 56            lines += 1
 57        }
 58        try audit(app, "routine weather")
 59        tap(app.buttons["Sunny"], in: app)
 60        XCTAssert(app.buttons["Done"].waitForExistence(timeout: 3))
 61        try audit(app, "routine calendar")
 62    }
 63
 64    private func grownUps(textSize: String?) throws {
 65        let app = launch("home", textSize: textSize)
 66        tap(app.buttons["Grown-Ups"], in: app)
 67        try passGate(app)
 68        XCTAssert(app.navigationBars["Grown-Ups"].waitForExistence(timeout: 3))
 69        try audit(app, "grown-ups")
 70        app.buttons.matching(NSPredicate(format: "label CONTAINS 'Olive'")).firstMatch.tap()
 71        try audit(app, "edit profile")
 72        back(app)
 73        app.buttons.matching(NSPredicate(format: "label CONTAINS 'Olive'")).element(boundBy: 1).tap()
 74        try audit(app, "progress")
 75    }
 76
 77    private func profiles(textSize: String?) throws {
 78        var app = launch("setup", textSize: textSize)
 79        try audit(app, "welcome")
 80        app.buttons["Get Started"].tap()
 81        try passGate(app)
 82        XCTAssert(app.navigationBars["New Child"].waitForExistence(timeout: 3))
 83        try audit(app, "new child")
 84        app.textFields["Child's name"].tap()
 85        app.textFields["Child's name"].typeText("Robin")
 86        app.buttons["Bunny"].tap()
 87        app.buttons["Save"].tap()
 88        XCTAssert(app.buttons["Grown-Ups"].waitForExistence(timeout: 3))
 89
 90        app.terminate()
 91        app = launch("picker", textSize: textSize)
 92        try audit(app, "picker")
 93        app.buttons["Max"].tap()
 94        XCTAssert(app.buttons["Switch child"].waitForExistence(timeout: 3))
 95    }
 96
 97    // MARK: - Helpers
 98
 99    private func launch(_ scene: String, textSize: String?) -> XCUIApplication {
100        sizeName = textSize == nil ? "default" : "largest"
101        let app = XCUIApplication()
102        app.launchArguments = ["-screenshot", scene]
103        if let textSize { app.launchArguments += ["-UIPreferredContentSizeCategoryName", textSize] }
104        app.launch()
105        return app
106    }
107
108    /// Press and hold, then answer the sum.
109    private func passGate(_ app: XCUIApplication) throws {
110        let hold = app.buttons["Hold for grown-ups"]
111        XCTAssert(hold.waitForExistence(timeout: 3))
112        try audit(app, "gate")
113        hold.press(forDuration: 2.5)
114        let question = app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH 'What is'")).firstMatch
115        XCTAssert(question.waitForExistence(timeout: 3))
116        let numbers = question.label.split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) }
117        app.textFields["Answer"].typeText("\(numbers.reduce(0, +))")
118        app.buttons["Continue"].tap()
119    }
120
121    /// Scrolls until `element` can be tapped, then taps it.
122    private func tap(_ element: XCUIElement, in app: XCUIApplication) {
123        for _ in 0..<12 where !(element.exists && element.isHittable) {
124            app.swipeUp()
125        }
126        XCTAssert(element.exists, "\(element) not found")
127        element.tap()
128    }
129
130    private func back(_ app: XCUIApplication) {
131        let button = app.navigationBars.buttons.firstMatch
132        XCTAssert(button.waitForExistence(timeout: 5), "No back button")
133        button.tap()
134    }
135
136    private func audit(_ app: XCUIApplication, _ name: String) throws {
137        // Lets celebrations and scrolling finish.
138        sleep(2)
139        let shot = XCTAttachment(screenshot: app.screenshot())
140        shot.name = name
141        shot.lifetime = .keepAlways
142        add(shot)
143        let screen = app.windows.firstMatch.frame
144        let navigationBar = app.navigationBars.firstMatch
145        let barFrame = navigationBar.exists ? navigationBar.frame : .null
146        var clipped: [String] = []
147        try app.performAccessibilityAudit { issue in
148            if self.isExpected(issue, screen: screen, barFrame: barFrame, name: name) { return true }
149            // Clipping is re-checked below: it is reported now and then for text that is not clipped.
150            if issue.auditType == .textClipped {
151                clipped.append(issue.element?.label ?? "")
152                return true
153            }
154            self.report(issue, name)
155            return false
156        }
157        guard !clipped.isEmpty else { return }
158        sleep(1)
159        try app.performAccessibilityAudit(for: .textClipped) { issue in
160            guard clipped.contains(issue.element?.label ?? "") else { return true }
161            self.report(issue, name)
162            return false
163        }
164    }
165
166    private func isExpected(_ issue: XCUIAccessibilityAuditIssue, screen: CGRect, barFrame: CGRect, name: String) -> Bool {
167        // Toolbar buttons are drawn by the system.
168        if let element = issue.element, barFrame.intersects(element.frame) { return true }
169        // Text growth is checked by the largest-text run, where clipping shows; at the
170        // default size the audit reports any label in a sized tile as partly unsupported.
171        if sizeName == "default", issue.auditType == .dynamicType { return true }
172        // The sticker calendar's seven columns stop growing at the first accessibility size.
173        if name.hasSuffix("calendar"), issue.auditType == .dynamicType { return true }
174        // The year wheel's month names are part of the picture, sized to its wedges.
175        if name.hasSuffix("Year wheel"), issue.auditType == .dynamicType { return true }
176        // Contrast is measured from pixels, so text partly off screen measures wrong.
177        if issue.auditType == .contrast, let element = issue.element, !screen.contains(element.frame) { return true }
178        // Contrast warnings without an element come from system list section headers.
179        if issue.auditType == .contrast, issue.element == nil { return true }
180        // Food emoji are pictures, not text.
181        if let label = issue.element?.label, !label.isEmpty,
182           label.unicodeScalars.allSatisfy({ $0.properties.isEmojiPresentation || $0.properties.isEmojiModifier }) {
183            return true
184        }
185        return false
186    }
187
188    private func report(_ issue: XCUIAccessibilityAuditIssue, _ name: String) {
189        print("AUDIT [\(sizeName)] [\(name)] \(issue.auditType.rawValue) \(issue.compactDescription) :: \(issue.element?.debugDescription.prefix(200) ?? "-")")
190    }
191}