SPB Git

Repository Public BSD-3-Clause

AccessibilityTests.swift 12.6 KB 267 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Tests/ORIXMapsUITests/AccessibilityTests.swift10// Module           : ORIXMapsUITests11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import XCTest8990/// Runs the system accessibility audit on the main screens, in light, dark and at the largest text size.91/// Every finding is written to the log (lines starting with "A11Y") and to an attachment; a finding fails the test92/// unless `accepted(_:_:element:)` gives the reason it is a false positive or a known limitation.93@MainActor94final class AccessibilityTests: ORIXUITestCase {95    private var findings: [String] = []96    private var failures: [String] = []97    private var configuration = "light"9899    /// Why a finding is accepted, or nil when it must fail the test. `element` is "type|identifier|label|frame"100    /// (type 9 = button, 48 = text). The reasons are repeated in docs/TESTING.md.101    private func accepted(_ type: XCUIAccessibilityAuditType, _ description: String, element: String) -> String? {102        let isButton = element.hasPrefix("9|")103        switch type {104        case .textClipped where configuration != "xxxl":105            // At the default size nothing is cut on the captures of the audited screens (kept with the results).106            return "false positive: SwiftUI reports text frames tighter than the font's line height; the text is fully drawn on the capture"107        case .textClipped:108            // At the largest size some one- and two-line texts end with an ellipsis: a limitation, listed as such.109            return "known limitation at the largest text size: long titles and addresses are limited to two or three lines"110        case .contrast where !isButton:111            return "not actionable: text on the system's translucent sheet material above the map, or system list header; the audit samples the blurred map behind. Checked by eye in light and dark"112        case .dynamicType where description.contains("partially"):113            return "false positive: system text styles, seen scaling on the captures at the largest size; the search bar is deliberately capped at the first accessibility size (fixed-height bar)"114        case .hitRegion where element.contains("|Page "):115            return "false positive: the page indicator is not a control"116        default:117            return nil118        }119    }120121    private func describe(_ type: XCUIAccessibilityAuditType) -> String {122        switch type {123        case .contrast: "contrast"124        case .elementDetection: "elementDetection"125        case .hitRegion: "hitRegion"126        case .sufficientElementDescription: "sufficientElementDescription"127        case .dynamicType: "dynamicType"128        case .textClipped: "textClipped"129        case .trait: "trait"130        default: "other(\(type.rawValue))"131        }132    }133134    private func audit(_ screen: String) {135        screenshot("a11y-\(configuration)-\(screen)")136        do {137            try app.performAccessibilityAudit { issue in138                let element = issue.element.map { e in "\(e.elementType.rawValue)|\(e.identifier)|\(e.label)|\(NSCoder.string(for: e.frame))" } ?? "no element"139                let line = "A11Y [\(self.configuration)] \(screen): \(self.describe(issue.auditType)) — \(issue.compactDescription) — \(element)"140                let reason = self.accepted(issue.auditType, issue.compactDescription, element: element)141                self.findings.append(line + (reason.map { "  ACCEPTED: \($0)" } ?? ""))142                if reason == nil { self.failures.append(line) }143                return true   // keep auditing: every finding of the screen is collected144            }145        } catch {146            failures.append("A11Y [\(configuration)] \(screen): the audit could not run: \(error)")147        }148    }149150    private func report() {151        for line in findings { print(line) }152        let attachment = XCTAttachment(string: findings.isEmpty ? "no finding" : findings.joined(separator: "\n"))153        attachment.name = "a11y-findings-\(configuration)"154        attachment.lifetime = .keepAlways155        add(attachment)156        XCTAssertTrue(failures.isEmpty, "\(failures.count) accessibility finding(s) in \(configuration):\n" + failures.joined(separator: "\n"))157    }158159    private func auditMainScreens() {160        launch(onboarding: true)161        require(app.buttons["onboarding.next"])162        audit("onboarding")163        app.terminate()164165        launch(region: true)166        audit("map")167        app.buttons["category.cafe"].tap()168        require(app.buttons.matching(identifier: "search.result").firstMatch)169        audit("search-results")170        app.buttons.matching(identifier: "search.result").firstMatch.tap()171        require(app.buttons["place.directions"])172        audit("place-card")173        app.buttons["panel.close"].tap()174        openMenu(.downloads)175        require(element("downloads.installed.\(Place.region)"))176        audit("downloads")177        closeModal()178        openMenu(.collections)179        require(app.buttons["collections.new"])180        audit("collections")181        closeModal()182        openMenu(.settings)183        require(app.navigationBars.firstMatch)184        audit("settings")185        closeModal()186        app.terminate()187188        launch(region: true, reset: false, extra: ["-ORIXRouteFrom", Place.downtown, "-ORIXRouteTo", Place.olympicStadium])189        require(app.buttons["directions.route.0"], timeout: 60)190        audit("directions")191        app.terminate()192193        launch(region: true, reset: false, extra: ["-ORIXRouteFrom", Place.downtown, "-ORIXRouteTo", Place.olympicStadium, "-ORIXSimulate", "YES"])194        require(element("navigation.banner"), timeout: 60)195        audit("guidance")196    }197198    func testAuditLight() throws {199        try requireLightPhase()200        configuration = "light"201        auditMainScreens()202        report()203    }204205    func testAuditDark() throws {206        try requireDarkPhase()207        configuration = "dark"208        auditMainScreens()209        report()210    }211212    func testAuditLargestTextSize() throws {213        try requireLightPhase()214        configuration = "xxxl"215        commonArguments = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]216        auditMainScreens()217        report()218    }219220    /// Every button of the map and of the panels has a spoken name; icon-only buttons included.221    func testMapControlsAndIconButtonsHaveLabels() {222        launch(region: true, camera: "45.5017,-73.5673,14,30,40")223        XCTAssertEqual(require(map).label, "Map")224        XCTAssertTrue((map.value as? String ?? "").hasPrefix("Centered on "), "the map says where it is centred: \(map.value ?? "")")225        XCTAssertEqual(app.buttons["map.layers"].label, "Map layers and themes")226        XCTAssertEqual(app.buttons["map.3d"].label, "Switch to flat view", "the camera is tilted")227        XCTAssertEqual(app.buttons["map.location"].label, "Show my position")228        let compass = require(app.buttons["map.compass"], "the compass button appears when the map is rotated")229        XCTAssertEqual(compass.label, "Reset to north")230        XCTAssertEqual(compass.value as? String, "Heading 30 degrees")231        compass.tap()232        waitGone(app.buttons["map.compass"])233        wait("the 3D button offers the tilted view again") { self.app.buttons["map.3d"].label == "Switch to 3D view" }234        XCTAssertEqual(app.buttons["home.menu"].label, "Menu")235236        func assertAllButtonsLabelled(_ screen: String) {237            let buttons = app.buttons.allElementsBoundByIndex.filter(\.exists)238            let labelled = buttons.filter { !$0.label.trimmingCharacters(in: .whitespaces).isEmpty }.map(\.frame)239            // SwiftUI's Menu exposes its trigger twice: the named element and, inside it with the same frame, an240            // unnamed one that assistive technologies do not stop on. Only buttons with no named twin are reported.241            for button in buttons where button.label.trimmingCharacters(in: .whitespaces).isEmpty && !labelled.contains(where: { $0.insetBy(dx: -2, dy: -2).contains(button.frame) }) {242                XCTFail("\(screen): a button has no accessibility label (identifier '\(button.identifier)', frame \(button.frame))\n\(app.debugDescription)")243            }244        }245        assertAllButtonsLabelled("map")246        app.buttons["category.cafe"].tap()247        require(app.buttons.matching(identifier: "search.result").firstMatch)248        XCTAssertEqual(app.buttons["search.clear"].label, "Clear search")249        assertAllButtonsLabelled("search results")250        app.buttons.matching(identifier: "search.result").firstMatch.tap()251        require(app.buttons["place.directions"])252        XCTAssertEqual(app.buttons["panel.close"].label, "Close")253        assertAllButtonsLabelled("place card")254        app.buttons["place.save"].tap()255        require(app.buttons["save.confirm"])256        app.switches.firstMatch.switches.firstMatch.tap()   // own symbol and colour: the grids appear257        require(app.buttons["Star"], "pin symbols have spoken names")258        require(app.buttons["Colour 1"])259        assertAllButtonsLabelled("save place")260        app.buttons["Cancel"].tap()261        app.buttons["panel.close"].tap()262        openMenu(.downloads)263        XCTAssertEqual(require(app.buttons["downloads.delete.\(Place.region)"]).label, "Delete Greater Montréal")264        assertAllButtonsLabelled("downloads")265    }266}267
Files main
Menu

Theme