SPB Git

Repository Public License

NavigatoriOSUITests.swift 12.8 KB 239 lines swift

1import XCTest23/// End-to-end flows on the simulator. Pages come from a local static server started by `scripts/uitest.sh`4/// (`ORIX_FIXTURE_URL`); each test uses its own throwaway data directory.5@MainActor6final class NavigatoriOSUITests: XCTestCase {7    private var dataDirectory = ""8    private var fixtureBase: String { ProcessInfo.processInfo.environment["ORIX_FIXTURE_URL"] ?? "http://127.0.0.1:8765" }910    override func setUp() async throws {11        continueAfterFailure = false12        dataDirectory = "/tmp/orix-uitest-\(UUID().uuidString)"13        XCUIDevice.shared.orientation = .portrait14    }1516    override func tearDown() async throws {17        try? FileManager.default.removeItem(atPath: dataDirectory)18    }1920    private func launch(skipOnboarding: Bool, extra: [String] = [], freshData: Bool = false) -> XCUIApplication {21        if freshData {22            try? FileManager.default.removeItem(atPath: dataDirectory)23            dataDirectory = "/tmp/orix-uitest-\(UUID().uuidString)"24        }25        let app = XCUIApplication()26        app.launchArguments = ["-ORIXDataDir", dataDirectory, "-AppleLanguages", "(en)", "-AppleLocale", "en_CA"] + (skipOnboarding ? ["-ORIXSkipOnboarding", "YES"] : []) + extra27        app.launch()28        return app29    }3031    private func open(_ address: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) {32        let field = app.textFields["omnibox.field"]33        if !field.waitForExistence(timeout: 2) {34            XCTAssertTrue(app.buttons["phone.address"].waitForExistence(timeout: 20), file: file, line: line)35            app.buttons["phone.address"].tap()36        }37        XCTAssertTrue(field.waitForExistence(timeout: 5), "the search cover shows the address field", file: file, line: line)38        field.typeText(address + "\n")39    }4041    private func assertPage(_ heading: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) {42        XCTAssertTrue(app.webViews.staticTexts[heading].waitForExistence(timeout: 20), "page “\(heading)” is displayed", file: file, line: line)43    }4445    func testOnboardingBrowsingTabsAndRestoration() throws {46        var app = launch(skipOnboarding: false)4748        // Onboarding is shown once and can be skipped from the first screen.49        XCTAssertTrue(app.staticTexts["onboarding.title"].waitForExistence(timeout: 20))50        app.buttons["onboarding.skip"].tap()51        XCTAssertTrue(app.buttons["phone.address"].waitForExistence(timeout: 5))52        XCTAssertFalse(app.staticTexts["onboarding.title"].exists)5354        // Type an address: the page loads.55        open("\(fixtureBase)/one.html", in: app)56        assertPage("Fixture page one", in: app)57        XCTAssertEqual(app.buttons["phone.address"].value as? String, "127.0.0.1")5859        // New tab, second page.60        app.buttons["phone.newTab"].tap()61        open("\(fixtureBase)/two.html", in: app)62        assertPage("Fixture page two", in: app)63        XCTAssertEqual(app.buttons["phone.tabs"].value as? String, "2 tabs")6465        // Switch back to the first tab through the tab switcher.66        app.buttons["phone.tabs"].tap()67        XCTAssertTrue(app.staticTexts["switcher.title"].waitForExistence(timeout: 5))68        XCTAssertEqual(app.staticTexts["switcher.title"].label, "2 Tabs")69        app.buttons.matching(identifier: "switcher.card").element(boundBy: 0).tap()70        assertPage("Fixture page one", in: app)7172        // Third tab, then close it from the switcher.73        app.buttons["phone.newTab"].tap()74        open("\(fixtureBase)/two.html", in: app)75        assertPage("Fixture page two", in: app)76        app.buttons["phone.tabs"].tap()77        XCTAssertEqual(app.staticTexts["switcher.title"].label, "3 Tabs")78        app.buttons.matching(identifier: "switcher.close").element(boundBy: 2).tap()79        XCTAssertTrue(app.staticTexts["2 Tabs"].waitForExistence(timeout: 5))80        app.buttons.matching(identifier: "switcher.card").element(boundBy: 0).tap()81        assertPage("Fixture page one", in: app)8283        // Leave the app (the session is saved and marked clean), end the process, launch again.84        XCUIDevice.shared.press(.home)85        Thread.sleep(forTimeInterval: 3)86        app.terminate()87        app = launch(skipOnboarding: false)88        XCTAssertTrue(app.buttons["phone.tabs"].waitForExistence(timeout: 20))89        XCTAssertFalse(app.staticTexts["onboarding.title"].exists, "onboarding is shown only once")90        XCTAssertFalse(app.otherElements["banner.restore"].exists, "a clean exit does not ask to restore")91        XCTAssertEqual(app.buttons["phone.tabs"].value as? String, "2 tabs")92        assertPage("Fixture page one", in: app)93        app.buttons["phone.tabs"].tap()94        XCTAssertEqual(app.staticTexts["switcher.title"].label, "2 Tabs")95    }9697    func testCrashRecoveryOffersToRestore() throws {98        var app = launch(skipOnboarding: true)99        open("\(fixtureBase)/one.html", in: app)100        assertPage("Fixture page one", in: app)101        Thread.sleep(forTimeInterval: 3)   // let the debounced session batch reach the disk102        app.terminate()                    // killed while in the foreground: not a clean shutdown103104        app = launch(skipOnboarding: true)105        XCTAssertTrue(app.buttons["Restore"].waitForExistence(timeout: 20), "the restore banner is shown")106        XCTAssertFalse(app.webViews.staticTexts["Fixture page one"].exists, "nothing was reloaded automatically")107        app.buttons["Restore"].tap()108        assertPage("Fixture page one", in: app)109    }110111    func testBlockedSchemeIsExplainedNotOpened() throws {112        let app = launch(skipOnboarding: true)113        open("javascript:alert(1)", in: app)114        XCTAssertTrue(app.descendants(matching: .any)["omnibox.notice"].waitForExistence(timeout: 5))115        XCTAssertTrue(app.textFields["omnibox.field"].exists, "the field stays open")116        XCTAssertEqual(app.alerts.count, 0)117    }118119    func testPanelsOpenFromTheMenu() throws {120        let app = launch(skipOnboarding: true, extra: ["-ORIXShow", "settings"])121        XCTAssertTrue(app.descendants(matching: .any)["settings.appearance"].waitForExistence(timeout: 20))122        XCTAssertTrue(app.buttons["theme.aurora"].exists)123        app.buttons["theme.aurora"].tap()124        XCTAssertTrue(app.buttons["theme.aurora"].isSelected)125    }126127    /// Runs the audit and reports every issue with the element it concerns. `ignore` returns true for issues128    /// that are not the app's (content of a web page).129    private func audit(_ app: XCUIApplication, _ screen: String, ignoring ignore: ((XCUIAccessibilityAuditIssue) -> Bool)? = nil,130                       file: StaticString = #filePath, line: UInt = #line) throws {131        var report: [String] = []132        // Contrast is excluded here: the audit samples pixels through translucent glass over a starfield and133        // reports text whose theme colours pass the computed WCAG checks of LunarDesign's ThemeTests.134        let types: XCUIAccessibilityAuditType = [.dynamicType, .elementDetection, .hitRegion, .sufficientElementDescription,135                                                 .textClipped, .trait]136        try app.performAccessibilityAudit(for: types) { issue in137            if ignore?(issue) == true { return true }138            // Small-caps section headers and count badges use the smallest text style, which the audit reports as139            // "partially" scalable; they do scale (system text styles) and are tracked in LunarDesign.140            // The segments of the appearance control are reported as clipped while their text is fully drawn141            // (checked on docs/screenshots/0.2/iphone-settings-lunar-light.png).142            if issue.auditType == .textClipped, issue.element?.elementType == .button,143               ["System", "Light", "Dark"].contains(issue.element?.label ?? "") { return true }144            // The title of a tab card is reported as clipped although it is drawn in full (see145            // docs/screenshots/0.2/iphone-tab-switcher.png); long titles are truncated on purpose.146            if issue.auditType == .textClipped, screen == "tab switcher", issue.element?.elementType == .staticText { return true }147            if issue.auditType == .dynamicType, let label = issue.element?.label, label == label.uppercased() { return true }148            let element = issue.element149            report.append("[\(screen)] \(issue.compactDescription) — \(element?.identifier ?? "?") “\(element?.label ?? "")” \(element?.elementType.rawValue ?? 0)")150            return true151        }152        if !report.isEmpty {153            let path = "/tmp/orix-audit.txt"154            let previous = (try? String(contentsOfFile: path, encoding: .utf8)) ?? ""155            try? (previous + report.joined(separator: "\n") + "\n").write(toFile: path, atomically: true, encoding: .utf8)156        }157        XCTAssertTrue(report.isEmpty, "Accessibility audit of \(screen): \(report.joined(separator: " | "))", file: file, line: line)158    }159160    func testAccessibilityAudit() throws {161        let app = launch(skipOnboarding: true)162        XCTAssertTrue(app.buttons["phone.address"].waitForExistence(timeout: 20))163        continueAfterFailure = true164        try audit(app, "new tab")165166        app.buttons["phone.tabs"].tap()167        XCTAssertTrue(app.staticTexts["switcher.title"].waitForExistence(timeout: 5))168        try audit(app, "tab switcher")169        app.buttons["switcher.done"].tap()170171        // A loaded page: the audit covers the chrome; the content of the page is the site's responsibility.172        open("\(fixtureBase)/one.html", in: app)173        assertPage("Fixture page one", in: app)174        let webFrame = app.webViews.firstMatch.frame175        try audit(app, "page") { issue in176            guard let element = issue.element else { return false }177            return element.elementType == .webView || (webFrame.contains(element.frame) && element.identifier.isEmpty)178        }179        app.terminate()180181        let onboarding = launch(skipOnboarding: false, freshData: true)182        XCTAssertTrue(onboarding.staticTexts["onboarding.title"].waitForExistence(timeout: 20))183        try audit(onboarding, "onboarding")184        onboarding.terminate()185186        let settings = launch(skipOnboarding: true, extra: ["-ORIXShow", "settings"], freshData: true)187        XCTAssertTrue(settings.descendants(matching: .any)["settings.appearance"].waitForExistence(timeout: 20))188        try audit(settings, "settings")189    }190191    // MARK: Screens that need a gesture (scrolling, rotation) — written to ORIX_CAPTURE_DIR by scripts/uitest.sh192193    private func capture(_ name: String, to directory: String) throws {194        try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)195        try XCUIScreen.main.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: directory).appending(path: name + ".png"))196    }197198    func testCaptureScreens() throws {199        let directory = ProcessInfo.processInfo.environment["ORIX_CAPTURE_DIR"] ?? ""200        try XCTSkipIf(directory.isEmpty, "set ORIX_CAPTURE_DIR to capture screens")201        let isPad = UIDevice.current.userInterfaceIdiom == .pad202        let prefix = isPad ? "ipad" : "iphone"203        let app = XCUIApplication()204        app.launchArguments = ["-ORIXDataDir", dataDirectory, "-ORIXSkipOnboarding", "YES", "-AppleLanguages", "(en)",205                               "-ORIXOpenURL", "https://en.wikipedia.org/wiki/Moon,https://example.com,\(fixtureBase)/one.html"]206        app.launch()207        assertPage("Fixture page one", in: app)208        Thread.sleep(forTimeInterval: 2)209        if isPad {210            try capture("ipad-sidebar-portrait", to: directory)211            XCUIDevice.shared.orientation = .landscapeLeft212            Thread.sleep(forTimeInterval: 2)213            try capture("ipad-sidebar-landscape", to: directory)214            XCUIDevice.shared.orientation = .portrait215            return216        }217        // Scrolling down compacts the dock; the page does not move under it.218        app.webViews.firstMatch.swipeUp()219        XCTAssertTrue(app.buttons["phone.dock.compact"].waitForExistence(timeout: 5), "the dock compacts when the page scrolls down")220        Thread.sleep(forTimeInterval: 1)221        try capture("\(prefix)-dock-compact", to: directory)222        app.webViews.firstMatch.swipeDown()223        XCTAssertTrue(app.buttons["phone.address"].waitForExistence(timeout: 5), "the dock returns when the page scrolls up")224        Thread.sleep(forTimeInterval: 1)225        try capture("\(prefix)-dock-expanded", to: directory)226227        app.buttons["phone.tabs"].tap()228        XCTAssertTrue(app.staticTexts["switcher.title"].waitForExistence(timeout: 5))229        Thread.sleep(forTimeInterval: 1)230        try capture("\(prefix)-tab-switcher", to: directory)231        app.buttons["switcher.done"].tap()232233        XCUIDevice.shared.orientation = .landscapeLeft234        Thread.sleep(forTimeInterval: 2)235        try capture("\(prefix)-landscape", to: directory)236        XCUIDevice.shared.orientation = .portrait237    }238}239
Files main
Menu

Theme