App/UITests/AccessibilityAuditTests.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/App/UITests/AccessibilityAuditTests.swift history · blame · raw

179 lines · 8907 bytes

14 symbols in this file
  1import XCTest
  2
  3/// Opens every model's step list and every step of every model by the labels VoiceOver sees and
  4/// runs Xcode's accessibility audit on each screen, at the default text size and at the largest
  5/// accessibility size. Also checks that two-finger gestures on the paper change the view without
  6/// advancing the fold or touching the diagram. XCUITest has no two-finger drag, so a pinch and a
  7/// rotation stand in for it.
  8final class AccessibilityAuditTests: XCTestCase {
  9    static let largestText = "UICTContentSizeCategoryAccessibilityXXXL"
 10    /// Elements that exist only under `-UITesting`.
 11    static let testHooks: Set<String> = ["fold.path", "paper.camera", "step.kind"]
 12    /// Every model in the list, by title, with its number of steps.
 13    static let models = [("Cup", 6), ("Box", 12), ("Sampan", 6), ("Crane", 16)]
 14
 15    private var sizeName = ""
 16
 17    override func setUp() {
 18        continueAfterFailure = true
 19    }
 20
 21    func testEveryScreenPassesTheAccessibilityAuditAtDefaultTextSize() throws {
 22        try everyScreen(textSize: nil)
 23    }
 24
 25    func testEveryScreenPassesTheAuditAtTheLargestTextSize() throws {
 26        try everyScreen(textSize: Self.largestText)
 27    }
 28
 29    func testPaperViewDescribesTheCurrentStepInWords() {
 30        let app = XCUIApplication(); app.launch()
 31        app.buttons["Cup"].tap()
 32        XCTAssertTrue(app.otherElements["fold.paper"].label.hasPrefix("Valley fold"))
 33    }
 34
 35    func testTwoFingerGesturesChangeTheViewWithoutAdvancingTheFold() {
 36        let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
 37        app.buttons["Cup"].tap()
 38        let paper = app.otherElements["fold.paper"]
 39        let camera = app.descendants(matching: .any)["paper.camera"]
 40        XCTAssertTrue(camera.waitForExistence(timeout: 5))
 41        let before = paper.value as? String
 42        let cameraBefore = camera.value as? String
 43        twoFingerGestures(paper)
 44        XCTAssertEqual(app.staticTexts["step.index"].label, "1")
 45        XCTAssertEqual(paper.value as? String, before)
 46        XCTAssertNotEqual(camera.value as? String, cameraBefore)
 47    }
 48
 49    func testDiagramDoesNotChangeWhenTheModelViewChanges() {
 50        let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
 51        app.buttons["Cup"].tap()
 52        let diagram = app.descendants(matching: .any)["diagram"]
 53        let camera = app.descendants(matching: .any)["paper.camera"]
 54        XCTAssertTrue(diagram.waitForExistence(timeout: 5))
 55        XCTAssertTrue(camera.waitForExistence(timeout: 5))
 56        let before = diagram.screenshot().pngRepresentation
 57        let cameraBefore = camera.value as? String
 58        twoFingerGestures(app.otherElements["fold.paper"])
 59        XCTAssertNotEqual(camera.value as? String, cameraBefore)
 60        XCTAssertEqual(diagram.screenshot().pngRepresentation, before)
 61    }
 62
 63    // MARK: - Helpers
 64
 65    /// The model list, then for every model its step list and every step, each advanced by the
 66    /// user's own drag: a reorient drag on a turn-over or rotate step, the fold drag otherwise.
 67    private func everyScreen(textSize: String?) throws {
 68        sizeName = textSize == nil ? "default" : "largest"
 69        let app = XCUIApplication()
 70        app.launchArguments = ["-UITesting"]
 71        if let textSize { app.launchArguments += ["-UIPreferredContentSizeCategoryName", textSize] }
 72        app.launch()
 73        try audit(app, "models")
 74        for (title, steps) in Self.models {
 75            app.buttons[title].tap()
 76            let index = app.staticTexts["step.index"]
 77            XCTAssertTrue(index.waitForExistence(timeout: 5))
 78            app.buttons["steps.button"].tap()
 79            XCTAssertTrue(app.buttons["step.1"].waitForExistence(timeout: 5))
 80            try audit(app, "\(title) step list")
 81            app.buttons["step.1"].tap()
 82            XCTAssertTrue(app.buttons["step.1"].waitForNonExistence(timeout: 5))
 83            while true {
 84                let step = index.label
 85                try audit(app, "\(title) step \(step)")
 86                if ["turnOver", "rotate"].contains(stepKind(app)) {
 87                    dragAcross(app.otherElements["fold.paper"])
 88                } else {
 89                    completeCurrentFold(app)
 90                }
 91                if index.label == step { break }
 92            }
 93            // Stopping before the last step means an advance failed.
 94            XCTAssertEqual(index.label, "\(steps)", title)
 95            try audit(app, "\(title) finished")
 96            app.navigationBars.buttons.firstMatch.tap()
 97            XCTAssertTrue(app.buttons[title].waitForExistence(timeout: 5))
 98        }
 99    }
100
101    private func audit(_ app: XCUIApplication, _ name: String) throws {
102        sleep(1)
103        let shot = XCTAttachment(screenshot: app.screenshot())
104        shot.name = "\(sizeName) \(name)"
105        shot.lifetime = .keepAlways
106        add(shot)
107        let screen = app.windows.firstMatch.frame
108        let navigationBar = app.navigationBars.firstMatch
109        let barFrame = navigationBar.exists ? navigationBar.frame : .null
110        let scrollFrames = app.scrollViews.allElementsBoundByIndex.map(\.frame)
111        let cutRows = rowsCutByTheStepList(app)
112        var clipped: [String] = []
113        try app.performAccessibilityAudit { issue in
114            if self.isExpected(issue, screen: screen, barFrame: barFrame, scrollFrames: scrollFrames) { return true }
115            if self.isCutStepRow(issue, cutRows) { return true }
116            // Clipping is re-checked below: it is reported now and then for text that is not clipped.
117            if issue.auditType == .textClipped {
118                clipped.append(issue.element?.label ?? "")
119                return true
120            }
121            self.report(issue, name)
122            return false
123        }
124        guard !clipped.isEmpty else { return }
125        sleep(1)
126        try app.performAccessibilityAudit(for: .textClipped) { issue in
127            guard clipped.contains(issue.element?.label ?? ""), !self.isCutStepRow(issue, cutRows) else { return true }
128            self.report(issue, name)
129            return false
130        }
131    }
132
133    private func isExpected(_ issue: XCUIAccessibilityAuditIssue, screen: CGRect, barFrame: CGRect,
134                            scrollFrames: [CGRect]) -> Bool {
135        if let element = issue.element, Self.testHooks.contains(element.identifier) { return true }
136        // Navigation bar buttons are drawn by the system.
137        if let element = issue.element, barFrame.intersects(element.frame) { return true }
138        // Text growth is checked by the largest-text run, where clipping shows.
139        if sizeName == "default", issue.auditType == .dynamicType { return true }
140        // Contrast is measured from pixels, so text partly off screen measures wrong.
141        if issue.auditType == .contrast, let element = issue.element, !screen.contains(element.frame) { return true }
142        // The same for the caption, which at the largest size runs past the bottom of its scroll view.
143        if issue.auditType == .contrast, let element = issue.element, element.identifier == "diagram.caption",
144           scrollFrames.contains(where: { $0.intersects(element.frame) && !$0.contains(element.frame) }) {
145            return true
146        }
147        return false
148    }
149
150    /// The frames of the step list's rows (`step.N`) partly scrolled out of the list, whose text the
151    /// list's edge clips.
152    private func rowsCutByTheStepList(_ app: XCUIApplication) -> [CGRect] {
153        let list = app.collectionViews.firstMatch
154        guard list.exists else { return [] }
155        let edge = list.frame
156        let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'step.'")).allElementsBoundByIndex
157        return rows.map(\.frame).filter { $0.intersects(edge) && !edge.contains($0) }
158    }
159
160    /// Whether `issue` is text clipped in a step-list row that the list's edge cuts. The audit
161    /// reports such text without an element at times, which matches only while a row is cut.
162    private func isCutStepRow(_ issue: XCUIAccessibilityAuditIssue, _ cutRows: [CGRect]) -> Bool {
163        guard issue.auditType == .textClipped, !cutRows.isEmpty else { return false }
164        guard let element = issue.element else { return true }
165        return cutRows.contains { $0.intersects(element.frame) }
166    }
167
168    private func report(_ issue: XCUIAccessibilityAuditIssue, _ name: String) {
169        print("AUDIT [\(sizeName)] [\(name)] \(issue.auditType.rawValue) \(issue.compactDescription) :: \(issue.element?.debugDescription.prefix(200) ?? "-")")
170    }
171}
172
173/// The two-finger gestures XCUITest can make on the element: a pinch out, a pinch in and a
174/// rotation.
175func twoFingerGestures(_ element: XCUIElement) {
176    element.pinch(withScale: 1.6, velocity: 1)
177    element.pinch(withScale: 0.8, velocity: -1)
178    element.rotate(0.6, withVelocity: 1)
179}