DomainDigUITests/AccessibilityAuditHarness.swift

345 lines · 17381 bytes

  1import XCTest
  2
  3/// Shared plumbing for the accessibility audit suite.
  4///
  5/// `performAccessibilityAudit` checks contrast, hit-region size, clipped text at
  6/// large Dynamic Type, element descriptions, and trait correctness — the same
  7/// categories the accessibility pass in issue #21 works through.
  8///
  9/// **The suite reports by default and fails only for enforced categories.** The
 10/// audit surfaces violations that exist today, so failing on everything would
 11/// block unrelated PRs until the whole pass lands. `enforcedAuditTypes` below is
 12/// the ratchet: widen it as each phase of #21 clears a category.
 13///
 14/// Two alternatives were tried and rejected:
 15///
 16/// - *A per-screen baseline count.* Audit coverage is not nested across OS
 17///   versions — the same screen legitimately yields different counts on the
 18///   floor simulator and the current one, so no single committed number is
 19///   correct for both.
 20/// - *An environment variable.* Neither a plain `xcodebuild` env var nor a
 21///   `TEST_RUNNER_`-prefixed build setting reaches this process, so the toggle
 22///   silently did nothing. A committed constant also makes "when did contrast
 23///   become enforced?" answerable with `git blame` instead of CI tribal
 24///   knowledge.
 25@MainActor
 26enum AccessibilityAuditHarness {
 27    /// Launch argument that lifts feature gating so Pro-only screens are
 28    /// reachable. `PurchaseService` honours this in `DEBUG` builds only.
 29    private static let forceProPlusArgument = "DOMAIN_DIG_FORCE_PRO_PLUS"
 30    /// Matches `AuditFixtures.resetStoreArgument`.
 31    private static let resetStoreArgument = "DOMAIN_DIG_RESET_STORE"
 32
 33    /// Audit categories that fail the build on the empty-state suite. A named
 34    /// finding in any of these is a regression in the phase 1–5 work.
 35    ///
 36    /// `.contrast` is deliberately absent: the two long-standing Settings
 37    /// findings come from rows scrolled under the translucent tab bar, and their
 38    /// attribution flips between a row name and nil run-to-run, so there is no
 39    /// suppression narrow enough to keep CI stable. Contrast stays report-only,
 40    /// with the palette centralised in `Shared/Colors.xcassets` as the actual
 41    /// guard.
 42    static let enforcedAuditTypes: XCUIAccessibilityAuditType = [
 43        .textClipped,
 44        .dynamicType,
 45        .hitRegion,
 46        .elementDetection,
 47        .sufficientElementDescription,
 48        .trait
 49    ]
 50
 51    /// How many times to retry an audit that misses its internal deadline.
 52    private static let auditAttempts = 3
 53
 54    /// Launch argument that seeds deterministic in-memory tracked domains and
 55    /// batch results (DEBUG builds only; never persisted). Without it the dense
 56    /// rows and portfolio sections render nothing, which is how five phases of
 57    /// row treatment went unmeasured.
 58    private static let seedFixturesArgument = "DOMAIN_DIG_SEED_FIXTURES"
 59
 60    /// Matches `AuditFixtures.recentSearchesArgument`. Separate from the
 61    /// fixtures above because Inspect shows either a result or the recent
 62    /// list, never both.
 63    private static let seedRecentSearchesArgument = "DOMAIN_DIG_SEED_RECENT"
 64
 65    /// Launches the app with feature gating lifted, optionally at a specific
 66    /// content size category and with the audit fixtures seeded.
 67    static func launch(
 68        contentSizeCategory: String? = nil,
 69        seeded: Bool = false,
 70        recentSearches: Bool = false
 71    ) -> XCUIApplication {
 72        let app = XCUIApplication()
 73        // Every launch starts from a cleared store, so a screen the enforced
 74        // suite audits as empty is empty whatever ran before it.
 75        app.launchArguments = [forceProPlusArgument, resetStoreArgument]
 76        if seeded {
 77            app.launchArguments.append(seedFixturesArgument)
 78        }
 79        if recentSearches {
 80            app.launchArguments.append(seedRecentSearchesArgument)
 81        }
 82        if let contentSizeCategory {
 83            app.launchArguments += ["-UIPreferredContentSizeCategoryName", contentSizeCategory]
 84        }
 85        app.launch()
 86        return app
 87    }
 88
 89    /// Runs a full audit and records every finding against the test.
 90    ///
 91    /// Findings are logged and attached to the result bundle so a CI run
 92    /// produces the burndown list as an artifact rather than only a pass/fail.
 93    ///
 94    /// Returns `false` if the audit could not complete, leaving the screen
 95    /// unaudited. Callers turn that into an `XCTSkip` — reporting a pass would
 96    /// claim coverage that did not happen.
 97    /// `reportOnly` disables enforcement for this call. Used by the seeded
 98    /// tests: bisection showed the audit degrades on `children: .ignore`
 99    /// content — the correct VoiceOver treatment for dense rows — reporting
100    /// unattributed contrast/dynamicType failures on rows that measure 6–7:1
101    /// and render correctly. Until that behaves, the seeded screens report
102    /// their burndown without gating CI.
103    ///
104    /// `enforcing` narrows the enforced set for one screen, so a screen whose
105    /// burndown is partly clear can gate on the categories it has cleared
106    /// while still reporting the rest. That is the ratchet at screen
107    /// granularity: `enforcedAuditTypes` is what a cleared screen gets.
108    @discardableResult
109    static func audit(
110        _ app: XCUIApplication,
111        screen: String,
112        test: XCTestCase,
113        reportOnly: Bool = false,
114        enforcing: XCUIAccessibilityAuditType = enforcedAuditTypes
115    ) throws -> Bool {
116        var findings: [String] = []
117        var timeout: Error?
118
119        // The audit traverses the whole element tree and has its own internal
120        // deadline, which slower CI runners miss on the denser screens. That is a
121        // tooling timeout, not an app defect, so retry before giving up.
122        //
123        // Only the timeout is retried. If a category is enforced and the audit
124        // reports findings before timing out, those failures are already recorded
125        // and a retry would duplicate them — accepted, because the alternative is
126        // losing the run to an infrastructure hiccup.
127        for attempt in 1...auditAttempts {
128            findings.removeAll()
129            timeout = nil
130            do {
131                try app.performAccessibilityAudit { issue in
132                    // Include the element so the burndown says *what* to fix, not
133                    // just that something is wrong.
134                    let element = issue.element.map { el -> String in
135                        let label = el.label.isEmpty ? el.identifier : el.label
136                        return label.isEmpty ? "\(el.elementType)" : "\"\(label)\""
137                    } ?? "unknown element"
138
139                    // Characterised noise never fails, but is still logged with
140                    // its reason — nothing disappears silently.
141                    if let noise = noiseReason(for: issue) {
142                        findings.append("[noise: \(noise)][\(name(for: issue.auditType))] \(issue.compactDescription) — \(element)")
143                        return true
144                    }
145
146                    let isEnforced = !reportOnly && !enforcing.intersection(issue.auditType).isEmpty
147                    let marker = isEnforced ? "FAIL" : "report"
148                    findings.append("[\(marker)][\(name(for: issue.auditType))] \(issue.compactDescription) — \(element)")
149                    // true suppresses the finding, false reports it as a test failure.
150                    return !isEnforced
151                }
152                break
153            } catch let error as NSError where error.isAccessibilityAuditTimeout {
154                timeout = error
155                print("\(screen): audit timed out (attempt \(attempt) of \(auditAttempts))")
156            }
157        }
158
159        if timeout != nil {
160            let message = "\(screen): audit did not complete in time after \(auditAttempts) attempts — screen NOT audited"
161            print(message)
162            let attachment = XCTAttachment(string: message)
163            attachment.name = "a11y-audit-\(screen)-timeout"
164            attachment.lifetime = .keepAlways
165            test.add(attachment)
166            return false
167        }
168
169        let summary = findings.isEmpty
170            ? "\(screen): no accessibility findings"
171            : "\(screen): \(findings.count) finding(s)\n" + findings.sorted().map { "  • \($0)" }.joined(separator: "\n")
172
173        print(summary)
174
175        let attachment = XCTAttachment(string: summary)
176        attachment.name = "a11y-audit-\(screen)"
177        attachment.lifetime = .keepAlways
178        test.add(attachment)
179
180        return true
181    }
182
183    /// Classifies findings that are measurement artifacts, not app defects.
184    /// Each rule exists because it was proven, not assumed; the evidence is
185    /// recorded inline. A classified finding is logged with its reason and
186    /// never fails the build.
187    private static func noiseReason(for issue: XCUIAccessibilityAuditIssue) -> String? {
188        // WCAG 1.4.3 exempts inactive components from contrast requirements,
189        // but the audit flags them anyway. Proven on Inspect's Run button,
190        // disabled until a domain is typed. (Driving the UI to enable it was
191        // worse: the raised keyboard followed the audit onto later screens and
192        // flagged the emoji picker.)
193        if issue.auditType.contains(.contrast), issue.element?.isEnabled == false {
194            return "disabled control, WCAG 1.4.3 exempt"
195        }
196
197        // "Nearly passed" is the audit's near-miss band, not a failure. The
198        // only occurrences are iOS-rendered Settings section headers, whose
199        // styling is the system's.
200        if issue.compactDescription.localizedCaseInsensitiveContains("nearly passed") {
201            return "near-miss, not a failure"
202        }
203
204        // Placeholder text in text/search fields is reported clipped at ANY
205        // length — shortening "Search portfolio" to "Search" changed nothing —
206        // and the search field's hit region at accessibility sizes is the
207        // system's own control. Reading `elementType` here is safe; reading
208        // `frame` is not (it kills element attribution for the whole audit).
209        if let type = issue.element?.elementType,
210           type == .searchField || type == .textField,
211           issue.auditType.contains(.textClipped) || issue.auditType.contains(.hitRegion) {
212            return "system field placeholder/hit region, length-independent"
213        }
214
215        // Unattributed clipped-text/dynamic-type findings. Bisection showed the
216        // audit loses attribution inside NavigationLink rows and
217        // children-ignored elements and then reports failures on content that
218        // is visually verified correct (and, for the one long-standing
219        // empty-watchlist phantom, renders nothing clipped at all). Named
220        // findings in these categories still enforce.
221        if issue.element == nil,
222           issue.auditType.contains(.textClipped) || issue.auditType.contains(.dynamicType) {
223            return "unattributed, audit artifact on ignored/link content"
224        }
225
226        // iOS-27-only Settings `Section` header dynamicType finding. On iOS 27.0
227        // (and only there) the audit reports "font sizes partially unsupported"
228        // against a Settings section header — the same system-rendered headers
229        // already carved out for the contrast near-miss above. Proof it is a
230        // system-chrome artifact, not an app defect:
231        //   • Each is a plain `Section("Services")` etc. (ContentView.swift ~2768);
232        //     the app sets no font, so the scaling is UIKit's `.footnote` header.
233        //   • Version-specific: absent on the iOS 18.6 floor and on the 26.x
234        //     runtime CI runs (both audit clean); it surfaces only under 27.0.
235        //     ACCESSIBILITY.md's coverage table records the same asymmetry
236        //     ("dynamicType finding 18.6 missed").
237        //   • Attribution is unstable run-to-run across the header set
238        //     (Tier/Preferences/Services), exactly like the documented contrast
239        //     flip — so it lands on whichever header the traversal reaches first.
240        // Overriding every Section header with a custom scaling `Text` to chase
241        // this was rejected for the contrast case (ACCESSIBILITY.md) for trading
242        // platform convention for nothing; the same holds here. Scoped to
243        // dynamicType on the exact Settings header titles so a real regression
244        // on app-controlled text still enforces.
245        if issue.auditType.contains(.dynamicType),
246           let label = issue.element?.label,
247           settingsSectionHeaders.contains(label) {
248            return "iOS-rendered Settings section header, app sets no font (27.0-only)"
249        }
250
251        // The Settings root's own rows, where the finding is a measurement
252        // artifact of the audit's size sweep rather than anything about the
253        // row. Proven by reordering the Services section: the findings stayed
254        // on the same three slots and followed their new occupants.
255        //
256        //   slot | before              | after
257        //   -----+---------------------+--------------------
258        //   1    | Monitoring Log      | Local API
259        //   2    | Integrations        | iCloud Sync
260        //   3    | Local API         * | Monitoring Settings *
261        //   4    | iCloud Sync       * | Monitoring Log      *
262        //   5    | Monitoring Settings*| Integrations        *
263        //   6    | Scheduled Reports   | Scheduled Reports     (contrast)
264        //
265        // Those slots are y 694–850 in a 912pt window: the band directly above
266        // the translucent tab bar, which begins around y 829. The row that
267        // sits fully under the bar reports `contrast` instead — the same
268        // long-standing artifact already carved out for that category, in a
269        // second one. Every row is an identical `NavigationLink("Title")` and
270        // the app sets no font on any of them.
271        //
272        // Scoped to dynamicType on the exact row titles, so a real regression
273        // on anything else on that screen still fails. The equivalent findings
274        // on the report-only Settings destinations are the same artifact and
275        // are left reported; see Docs/ACCESSIBILITY.txt.
276        if issue.auditType.contains(.dynamicType),
277           let label = issue.element?.label,
278           settingsDestinationRows.contains(label) {
279            return "Settings root row in the band above the tab bar, position-dependent"
280        }
281
282        return nil
283    }
284
285    /// The Settings root's `NavigationLink` titles. Used to scope the
286    /// position-dependent dynamicType carve-out above to that one screen.
287    private static let settingsDestinationRows: Set<String> = [
288        "Display", "History & Network",
289        "Monitoring Log", "Integrations", "Local API", "iCloud Sync",
290        "Monitoring Settings", "Scheduled Reports",
291        "Import & Export", "Data Management",
292        "App Info"
293    ]
294
295    /// The Settings screen's `Section(_:)` header titles. UIKit renders these;
296    /// the app passes only a string literal. Used to scope the section-header
297    /// dynamicType carve-out narrowly (see `noiseReason`).
298    private static let settingsSectionHeaders: Set<String> = [
299        "Tier", "Preferences", "Services", "Data", "About"
300    ]
301
302    /// `XCUIAccessibilityAuditType` is an option set whose description is just a
303    /// raw bitmask, which makes the burndown list unreadable. Resolve it against
304    /// the named members rather than hard-coding bit positions, so this keeps
305    /// working if Apple adds audit types.
306    private static func name(for type: XCUIAccessibilityAuditType) -> String {
307        let known: [(XCUIAccessibilityAuditType, String)] = [
308            (.contrast, "contrast"),
309            (.elementDetection, "elementDetection"),
310            (.hitRegion, "hitRegion"),
311            (.sufficientElementDescription, "sufficientElementDescription"),
312            (.dynamicType, "dynamicType"),
313            (.textClipped, "textClipped"),
314            (.trait, "trait")
315        ]
316        let matched = known.filter { type.contains($0.0) }.map(\.1)
317        return matched.isEmpty ? "unknown(\(type.rawValue))" : matched.joined(separator: "+")
318    }
319}
320
321private extension NSError {
322    /// `Audit failed to complete in time` — the audit's own deadline, raised by
323    /// XCTest rather than by anything wrong with the app.
324    var isAccessibilityAuditTimeout: Bool {
325        domain == "com.apple.xcode.xctest.accessibilityAudit" && code == -56
326    }
327}
328
329extension XCUIApplication {
330    /// Taps a root tab by its visible label.
331    ///
332    /// Falls back to a plain button query because the tab bar is only present in
333    /// the compact size class — in regular width `RootTabView` renders a
334    /// `NavigationSplitView` sidebar instead.
335    @MainActor
336    func selectRootTab(_ name: String) {
337        let tabButton = tabBars.buttons[name]
338        let element = tabButton.waitForExistence(timeout: 5) ? tabButton : buttons[name]
339        XCTAssertTrue(
340            element.waitForExistence(timeout: 5),
341            "Could not find a way to reach the \(name) screen"
342        )
343        element.tap()
344    }
345}