SPB Git

Repository Public License

PuzzleMissionsUITests.swift 8.3 KB 164 lines swift

1// ORIX Alarm2// File: UITests/PuzzleMissionsUITests.swift3// Description: Plays the Memory Matrix, Pattern Lock, Color Sequence and Word Scramble missions to completion through their accessibility elements.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import XCTest89@MainActor10final class PuzzleMissionsUITests: XCTestCase {11    override func setUp() async throws { continueAfterFailure = false }1213    func testMemoryMatrixLevel1() throws { try playMemory(level: 1) }14    func testMemoryMatrixLevel4() throws { try playMemory(level: 4) }15    func testPatternLockLevel1() throws { try playPattern(level: 1) }16    func testPatternLockLevel4() throws { try playPattern(level: 4) }17    func testColorSequenceLevel1() throws { try playColors(level: 1) }18    func testWordScrambleLevel1() throws { try playWords(level: 1) }19    func testWordScrambleLevel4() throws { try playWords(level: 4) }2021    private func launch(_ mission: String, level: Int) -> XCUIApplication {22        let app = XCUIApplication()23        app.launchArguments = ["-ORIXUITest", "YES", "-ORIXReset", "YES", "-ORIXSkipOnboarding", "YES",24                               "-ORIXMission", mission, "-ORIXLevel", "\(level)", "-ORIXSeed", "7"]25        app.launch()26        return app27    }2829    /// One atomic reading of the screen: identifier → (label, value) for every identified element.30    private func read(_ app: XCUIApplication) -> [String: (label: String, value: String)] {31        var result: [String: (label: String, value: String)] = [:]32        guard let root = try? app.snapshot() else { return result }33        var stack: [XCUIElementSnapshot] = [root]34        while let element = stack.popLast() {35            if !element.identifier.isEmpty { result[element.identifier] = (element.label, element.value as? String ?? "") }36            stack.append(contentsOf: element.children)37        }38        return result39    }4041    // MARK: Memory Matrix4243    private func playMemory(level: Int) throws {44        let app = launch("memoryMatrix", level: level)45        let summary = app.staticTexts["mission.summaryTitle"]46        XCTAssertTrue(app.buttons["memory.cell.0"].waitForExistence(timeout: 20))47        let deadline = Date().addingTimeInterval(150)48        var seen: [String] = []49        while !summary.exists, Date() < deadline {50            let screen = read(app)51            let status = screen["memory.status"]?.label ?? ""52            if status.contains("selected") {53                // A flash was missed (sequential rounds are fast): ask for the pattern again, as a player would.54                if seen.isEmpty { app.buttons["memory.replay"].tap(); continue }55                for identifier in seen { app.buttons[identifier].tap() }56                seen = []57                usleep(1_200_000)58            } else {59                // Cells lit right now, appended in the order they were first seen (the order matters in sequential rounds).60                let lit = screen.filter { $0.key.hasPrefix("memory.cell.") && $0.value.label.hasSuffix("lit") }.keys.sorted()61                for identifier in lit where !seen.contains(identifier) { seen.append(identifier) }62                if status.contains("Not quite") { seen = [] }63            }64        }65        XCTAssertTrue(summary.waitForExistence(timeout: 5), "the mission did not finish")66    }6768    // MARK: Pattern Lock6970    private func playPattern(level: Int) throws {71        let app = launch("patternLock", level: level)72        let summary = app.staticTexts["mission.summaryTitle"]73        XCTAssertTrue(app.descendants(matching: .any)["pattern.node.0"].waitForExistence(timeout: 20))74        let deadline = Date().addingTimeInterval(150)75        var steps: [Int: String] = [:]76        while !summary.exists, Date() < deadline {77            let screen = read(app)78            let status = screen["pattern.status"]?.label ?? ""79            if status.contains("connected") {80                // "0 of N stars connected": replay when the whole path was not observed, as a player would.81                let expected = status.split(separator: " ").compactMap { Int($0) }.last ?? 082                if steps.count != expected || Set(steps.keys) != Set(1...max(expected, 1)) {83                    app.buttons["pattern.clear"].tap(); app.buttons["pattern.replay"].tap(); steps = [:]84                    continue85                }86                for step in steps.keys.sorted() { app.descendants(matching: .any)[steps[step]!].tap() }87                steps = [:]88                usleep(1_200_000)89            } else if status.contains("Not quite") {90                steps = [:]91            } else {92                for (identifier, element) in screen where identifier.hasPrefix("pattern.node.") && element.value.hasPrefix("step ") {93                    if let step = Int(element.value.split(separator: " ").dropFirst().first ?? "") { steps[step] = identifier }94                }95            }96        }97        XCTAssertTrue(summary.waitForExistence(timeout: 5), "the mission did not finish")98    }99100    // MARK: Color Sequence101102    /// Watches which panel is lit. A read may miss a flash, in which case the game replays the sequence and the test reads it again.103    private func playColors(level: Int) throws {104        let app = launch("colorSequence", level: level)105        let summary = app.staticTexts["mission.summaryTitle"]106        XCTAssertTrue(app.buttons["color.panel.0"].waitForExistence(timeout: 20))107        let deadline = Date().addingTimeInterval(240)108        var sequence: [String] = [], previous = ""109        while !summary.exists, Date() < deadline {110            let screen = read(app)111            let status = screen["color.status"]?.label ?? ""112            if status.contains("Your turn") {113                for identifier in sequence { app.buttons[identifier].tap() }114                sequence = []; previous = ""115                usleep(1_300_000)116            } else if status.contains("Not quite") {117                sequence = []; previous = ""118            } else {119                let lit = screen.first { $0.key.hasPrefix("color.panel.") && $0.value.value == "lit" }?.key ?? ""120                if !lit.isEmpty, lit != previous { sequence.append(lit) }121                previous = lit122            }123        }124        XCTAssertTrue(summary.waitForExistence(timeout: 5), "the mission did not finish")125    }126127    // MARK: Word Scramble128129    private func playWords(level: Int) throws {130        // The bundled English lists, read from the repository next to this file.131        let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()132            .appendingPathComponent("Packages/AlarmCore/Sources/AlarmCore/Resources")133        var words: [String] = []134        for tier in 1...3 {135            words += try String(contentsOf: resources.appendingPathComponent("words-en-\(tier).txt"), encoding: .utf8).split(separator: "\n").map(String.init)136        }137        let app = launch("wordScramble", level: level)138        let summary = app.staticTexts["mission.summaryTitle"]139        XCTAssertTrue(app.buttons["word.shuffle"].waitForExistence(timeout: 20))140        let deadline = Date().addingTimeInterval(120)141        var solved = 0142        while !summary.exists, Date() < deadline {143            // One atomic reading: tile identifier → letter, and the number of answer slots.144            let screen = read(app)145            var tiles = screen.filter { $0.key.hasPrefix("word.tile.") }.mapValues { String($0.label.split(separator: " ").last ?? "").lowercased() }146            let slots = screen.keys.filter { $0.hasPrefix("word.slot.") }.count147            guard slots > 0, tiles.count == slots else { usleep(300_000); continue }148            let key = tiles.values.joined().sorted()149            let word = try XCTUnwrap(words.first { $0.count == slots && $0.sorted() == key }, "no word for \(tiles)")150            if solved == 0 { app.buttons["word.shuffle"].tap() }151            for character in word {152                // Each tile is used once, so repeated letters tap two different tiles.153                let tile = try XCTUnwrap(tiles.first { $0.value == String(character) }?.key)154                tiles[tile] = nil155                app.buttons[tile].tap()156            }157            solved += 1158            usleep(1_600_000)159        }160        XCTAssertTrue(summary.waitForExistence(timeout: 5), "the mission did not finish")161        XCTAssertEqual(solved, 2)162    }163}164
Files main
Menu

Theme