SPB Git

Repository Public License

MathMissionUITests.swift 7.4 KB 154 lines swift

1// ORIX Alarm2// File: UITests/MathMissionUITests.swift3// Description: Plays the Math Blitz mission to completion through its accessibility identifiers (keypad and estimation choices).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import XCTest89@MainActor10final class MathMissionUITests: XCTestCase {11    override func setUp() async throws { continueAfterFailure = false }1213    func testSolvesMathMissionAtLevel1() throws { try play(level: 1, seed: 7) }14    func testSolvesMathMissionAtLevel2() throws { try play(level: 2, seed: 21) }15    func testSolvesMathMissionAtLevel3() throws { try play(level: 3, seed: 5) }16    func testSolvesMathMissionAtLevel4() throws { try play(level: 4, seed: 12) }1718    /// A wrong answer keeps the same question on screen and is counted as one mistake in the summary.19    func testWrongAnswerKeepsTheQuestion() throws {20        let app = launch(level: 1, seed: 7)21        let question = app.staticTexts["math.question"]22        XCTAssertTrue(question.waitForExistence(timeout: 15))23        let prompt = try XCTUnwrap(question.value as? String)24        let answer = try XCTUnwrap(Solver.solve(prompt))25        type(answer + 1, in: app)26        app.buttons["math.submit"].tap()27        sleep(2)28        XCTAssertEqual(question.value as? String, prompt, "a wrong answer must not skip the question")29        try finish(app)30        let mistakes = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Mistakes'")).firstMatch31        XCTAssertTrue(mistakes.waitForExistence(timeout: 5))32        XCTAssertTrue(mistakes.label.contains("1"), mistakes.label)33    }3435    private func launch(level: Int, seed: Int) -> XCUIApplication {36        let app = XCUIApplication()37        app.launchArguments = ["-ORIXUITest", "YES", "-ORIXReset", "YES", "-ORIXSkipOnboarding", "YES",38                               "-ORIXMission", "math", "-ORIXLevel", "\(level)", "-ORIXSeed", "\(seed)"]39        app.launch()40        return app41    }4243    private func type(_ value: Int, in app: XCUIApplication) {44        if value < 0 { app.buttons["math.key.negative"].tap() }45        for digit in String(abs(value)) { app.buttons["math.key.\(digit)"].tap() }46    }4748    private func play(level: Int, seed: Int) throws {49        let app = launch(level: level, seed: seed)50        XCTAssertTrue(app.staticTexts["math.question"].waitForExistence(timeout: 15))51        try finish(app)52        let mistakes = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Mistakes'")).firstMatch53        XCTAssertTrue(mistakes.waitForExistence(timeout: 5))54        XCTAssertTrue(mistakes.label.contains("0"), mistakes.label)55    }5657    /// Answers every remaining question correctly until the runner shows its summary.58    private func finish(_ app: XCUIApplication) throws {59        let question = app.staticTexts["math.question"]60        let summary = app.staticTexts["mission.summaryTitle"]61        var solved = 0, lastPrompt = ""62        let deadline = Date().addingTimeInterval(90)63        while !summary.exists, Date() < deadline {64            guard question.exists, let prompt = question.value as? String, prompt != lastPrompt else { usleep(150_000); continue }65            if prompt.hasSuffix("≈ ?") {66                let exact = try XCTUnwrap(Solver.evaluate(String(prompt.dropLast(4))), prompt)67                let choices = (0..<4).map { app.buttons["math.choice.\($0)"] }68                let values = try choices.map { try XCTUnwrap(Int($0.label.filter(\.isNumber)), prompt) }69                let best = try XCTUnwrap(values.indices.min { abs(values[$0] - exact) < abs(values[$1] - exact) })70                choices[best].tap()71            } else {72                let answer = try XCTUnwrap(Solver.solve(prompt), "cannot solve \(prompt)")73                type(answer, in: app)74                app.buttons["math.submit"].tap()75            }76            lastPrompt = prompt; solved += 177            usleep(1_300_000) // success feedback, then the next question or the summary replaces this one78        }79        XCTAssertTrue(summary.waitForExistence(timeout: 5), "the mission did not finish")80        XCTAssertGreaterThanOrEqual(solved, 1)81    }82}8384/// Solves the questions from their text alone, independently of the engine.85enum Solver {86    static func solve(_ prompt: String) -> Int? {87        if prompt.hasSuffix(", ?") { return nextTerm(prompt.dropLast(3).components(separatedBy: ", ").compactMap { Int($0) }) }88        if prompt.contains("=") {89            let sides = prompt.components(separatedBy: " = ")90            guard sides.count == 2, let right = Int(sides[1]) else { return nil }91            return (0...3_000).first { evaluate(sides[0].replacingOccurrences(of: "?", with: String($0))) == right }92        }93        return evaluate(prompt)94    }9596    static func nextTerm(_ terms: [Int]) -> Int? {97        guard terms.count >= 4, let last = terms.last else { return nil }98        let diffs = zip(terms.dropFirst(), terms).map { $0 - $1 }99        if Set(diffs).count == 1 { return last + diffs[0] }100        for ratio in 2...3 where zip(terms.dropFirst(), terms).allSatisfy({ $0 == $1 * ratio }) { return last * ratio }101        if (2..<terms.count).allSatisfy({ terms[$0] == terms[$0 - 1] + terms[$0 - 2] }) { return last + terms[terms.count - 2] }102        let second = zip(diffs.dropFirst(), diffs).map { $0 - $1 }103        if Set(second).count == 1, let lastDiff = diffs.last { return last + lastDiff + second[0] }104        return nil105    }106107    /// Integer expression with `+ − × ÷` and parentheses; `nil` on a syntax error or an inexact division.108    static func evaluate(_ text: String) -> Int? {109        var tokens: [String] = [], number = ""110        for ch in text where ch != " " {111            if ch.isNumber { number.append(ch) } else {112                if !number.isEmpty { tokens.append(number); number = "" }113                tokens.append(String(ch))114            }115        }116        if !number.isEmpty { tokens.append(number) }117        var position = 0118        func factor() -> Int? {119            guard position < tokens.count else { return nil }120            let token = tokens[position]; position += 1121            if token == "(" {122                let value = expression()123                guard position < tokens.count, tokens[position] == ")" else { return nil }124                position += 1125                return value126            }127            return Int(token)128        }129        func term() -> Int? {130            guard var value = factor() else { return nil }131            while position < tokens.count, tokens[position] == "×" || tokens[position] == "÷" {132                let op = tokens[position]; position += 1133                guard let rhs = factor() else { return nil }134                if op == "×" { value *= rhs } else {135                    guard rhs != 0, value % rhs == 0 else { return nil }136                    value /= rhs137                }138            }139            return value140        }141        func expression() -> Int? {142            guard var value = term() else { return nil }143            while position < tokens.count, tokens[position] == "+" || tokens[position] == "−" {144                let op = tokens[position]; position += 1145                guard let rhs = term() else { return nil }146                value = op == "+" ? value + rhs : value - rhs147            }148            return value149        }150        guard let value = expression(), position == tokens.count else { return nil }151        return value152    }153}154
Files main
Menu

Theme