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