SPB Git

Repository Public License

UnitTests.swift 29.9 KB 448 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX OS Automation9// File             : Packages/ORIXAppleAutomation/Tests/ORIXAppleAutomationTests/UnitTests.swift10// Description      : Unit tests (no system interaction): manifests, script11//                    target scanner, AppleScript value parser, error parsing,12//                    typing steps, recorder semantics, notification mapping.13// Module           : ORIXAppleAutomationTests14// Repository       : https://git.spboucher.ai/orix-automation15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import ORIXCore93import ORIXTestingSupport94import Testing95@testable import ORIXAppleAutomation9697@Suite("Unit · manifests")98struct ManifestTests {99    @Test func everyCanonicalIdentifierIsPresentOnce() {100        let ids = ORIXAppleAutomationTools.all().map(\.identifier)101        #expect(ids.count == 22)102        #expect(Set(ids).count == ids.count)103        #expect(Set(ids) == Set(ORIXAppleAutomationTools.identifiers))104    }105106    @Test func everyManifestIsStructurallyValid() {107        for tool in ORIXAppleAutomationTools.all() {108            #expect(tool.manifest.problems().isEmpty, "\(tool.identifier): \(tool.manifest.problems())")109            #expect(tool.manifest.identifier == tool.identifier)110            for example in tool.manifest.examples {111                #expect(tool.manifest.inputSchema.validate(example).isEmpty, "example of \(tool.identifier) does not match its schema")112            }113        }114    }115116    @Test func tiersConcurrencyAndTrustFlagsFollowTheContract() throws {117        let tools = Dictionary(uniqueKeysWithValues: ORIXAppleAutomationTools.all().map { ($0.identifier, $0.manifest) })118        for id in ["accessibility.status", "accessibility.tree", "accessibility.find", "accessibility.waitFor", "system.apps", "system.frontmost", "system.windows", "screen.ocr", "applescript.dictionary"] {119            #expect(tools[id]?.defaultTier == .readOnly, "\(id)")120            #expect(tools[id]?.sideEffect == .read, "\(id)")121        }122        for id in ["accessibility.press", "accessibility.setValue", "accessibility.focus", "accessibility.typeText"] {123            #expect(tools[id]?.defaultTier == .consequential, "\(id)")124            #expect(tools[id]?.concurrency == .exclusive, "\(id)")125            #expect(tools[id]?.macPermissions == [.accessibility], "\(id)")126        }127        for id in ["applescript.run", "jxa.run", "system.launchApp", "system.quitApp"] { #expect(tools[id]?.defaultTier == .consequential, "\(id)") }128        for id in ["screen.capture", "clipboard.write", "notifications.post"] { #expect(tools[id]?.defaultTier == .reversibleWrite, "\(id)") }129        for id in ["applescript.run", "jxa.run", "applescript.dictionary", "accessibility.tree", "accessibility.find", "screen.ocr", "clipboard.read", "system.windows"] {130            #expect(tools[id]?.outputIsUntrusted == true, "\(id)")131        }132    }133134    @Test func requirementsDeclareTheExactCapabilities() throws {135        let dir = try TempDirectory(); defer { dir.remove() }136        let ctx = dir.toolContext()137        func req(_ tool: any ORIXTool, _ args: JSONValue) throws -> ToolRequirements { try tool.requirements(for: ToolInput(arguments: args), context: ctx) }138139        let read = try req(ClipboardReadTool(), [:])140        #expect(read.capabilities == [.clipboardRead] && read.tier == .reversibleWrite)141        let write = try req(ClipboardWriteTool(), ["content": "x"])142        #expect(write.capabilities == [.clipboardWrite] && write.tier == .reversibleWrite)143        #expect(throws: ToolError.self) { try req(ClipboardWriteTool(), [:]) }144145        #expect(try req(AccessibilityStatusTool(), [:]).capabilities.isEmpty)146        let tree = try req(AccessibilityTreeTool(), ["bundleID": "com.apple.finder"])147        #expect(tree.capabilities == [.accessibility(bundleID: "com.apple.finder")] && tree.tier == .readOnly)148        let press = try req(AccessibilityPressTool(), ["bundleID": "com.apple.finder", "element": "AXApplication/AXWindow[0]"])149        #expect(press.capabilities == [.accessibility(bundleID: "com.apple.finder")] && press.tier == .consequential)150        let type = try req(AccessibilityTypeTextTool(), ["bundleID": "com.apple.finder", "element": "AXApplication/AXWindow[0]", "text": "hi"])151        #expect(type.tier == .consequential)152        #expect(throws: ToolError.self) { try req(AccessibilityFindTool(), ["bundleID": "com.apple.finder"]) }153        #expect(throws: ToolError.self) { try req(AccessibilityTreeTool(), ["bundleID": "not a bundle id!"]) }154        #expect(throws: ToolError.self) { try req(AccessibilityWaitForTool(), ["bundleID": "com.apple.finder", "condition": "valueEquals", "role": "AXButton"]) }155156        let capture = try req(ScreenCaptureTool(), ["scope": "window", "bundleID": "com.apple.finder"])157        #expect(capture.capabilities.first == .screenCapture(scope: "window:com.apple.finder"))158        #expect(capture.tier == .reversibleWrite)159        if case .fileWrite(let path)? = capture.capabilities.last {160            #expect(path.hasPrefix(dir.url.path + "/artifacts/") && path.hasSuffix(".png"))161        } else { Issue.record("screen.capture must declare the file it writes") }162        let display = try req(ScreenCaptureTool(), ["scope": "display", "path": "shots/a.png"])163        #expect(display.capabilities == [.screenCapture(scope: "display"), .fileWrite(path: dir.url.path + "/shots/a.png")])164        let region = try req(ScreenCaptureTool(), ["scope": "region", "region": ["x": 0, "y": 0, "width": 10, "height": 10]])165        #expect(region.capabilities.first == .screenCapture(scope: "region"))166        #expect(throws: ToolError.self) { try req(ScreenCaptureTool(), ["scope": "region"]) }167        // Password managers are never a capture target.168        do {169            _ = try req(ScreenCaptureTool(), ["scope": "window", "bundleID": "com.apple.keychainaccess"])170            Issue.record("capturing Keychain Access must be refused")171        } catch let e as ToolError {172            if case .permissionDenied = e {} else { Issue.record("expected permissionDenied, got \(e)") }173        }174        #expect(throws: ToolError.self) { try req(ScreenCaptureTool(additionalSensitiveBundleIDs: ["com.example.Vault"]), ["scope": "window", "bundleID": "com.example.vault"]) }175176        let ocr = try req(ScreenOCRTool(), ["path": "a/../b.png"])177        #expect(ocr.capabilities == [.fileRead(path: dir.url.path + "/b.png")] && ocr.tier == .readOnly)178        let compare = try req(ScreenCompareTool(), ["before": "a.png", "after": "b.png", "diffPath": "d.png"])179        #expect(compare.capabilities == [.fileRead(path: dir.url.path + "/a.png"), .fileRead(path: dir.url.path + "/b.png"), .fileWrite(path: dir.url.path + "/d.png")])180181        let launch = try req(SystemLaunchAppTool(), ["bundleID": "com.apple.finder"])182        #expect(launch.capabilities == [.appControl(bundleID: "com.apple.finder")] && launch.tier == .consequential)183        let byPath = try req(SystemLaunchAppTool(), ["path": "/System/Library/CoreServices/Finder.app"])184        #expect(byPath.capabilities == [.appControl(bundleID: "com.apple.finder")])185        let quit = try req(SystemQuitAppTool(), ["bundleID": "com.apple.finder"])186        #expect(quit.capabilities == [.appControl(bundleID: "com.apple.finder")] && quit.tier == .consequential)187        let notify = try req(NotificationsPostTool(), ["title": "Done", "body": "ok"])188        #expect(notify.capabilities == [.notify] && notify.tier == .reversibleWrite)189        #expect(try req(SystemAppsTool(), [:]).tier == .readOnly)190    }191}192193@Suite("Unit · script target scanner")194struct ScannerTests {195    let resolve: (String) -> String? = { name in196        ["finder": "com.apple.finder", "mail": "com.apple.mail", "system events": "com.apple.systemevents", "safari": "com.apple.Safari",197         "/applications/safari.app": "com.apple.Safari", "com.apple.mail": "com.apple.mail"][name.lowercased()]198    }199    func targets(_ script: String, _ language: ScriptLanguage, declared: [String]) throws -> [String] {200        try ScriptTargetScanner.verifiedTargets(ScriptTargetScanner.scan(script, language: language), declared: declared, resolve: resolve, canonical: { $0 })201    }202203    @Test func appleScriptTargetShapes() {204        func refs(_ s: String) -> ([String], [String]) { let r = ScriptTargetScanner.scan(s, language: .applescript); return (r.applicationReferences, r.bundleIDReferences) }205        #expect(refs("tell application \"Finder\" to get name of startup disk").0 == ["Finder"])206        #expect(refs("tell app \"Mail\"\n  activate\nend tell").0 == ["Mail"])207        #expect(refs("tell application id \"com.apple.mail\" to activate").1 == ["com.apple.mail"])208        #expect(refs("tell application id \"com.apple.mail\" to activate").0.isEmpty)209        #expect(refs("set n to name of application \"Safari\"\nactivate application \"Finder\"").0 == ["Safari", "Finder"])210        #expect(refs("tell application \"System Events\" to tell application process \"Finder\" to get windows").0 == ["System Events"])211        #expect(refs("using terms from application \"Mail\"\nend using terms from").0 == ["Mail"])212        #expect(refs("tell  APPLICATION   \"Finder\" to beep").0 == ["Finder"])213        #expect(refs("tell application ¬\n \"Finder\" to beep").0 == ["Finder"])214        #expect(refs("tell application \"Finder\"\n tell application \"Finder\" to beep\nend tell").0 == ["Finder"])215    }216217    @Test func appleScriptIgnoresStringsAndComments() {218        let scan = ScriptTargetScanner.scan("""219        -- tell application "Mail" to delete every message220        # tell application "Safari" to quit221        (* tell application "Notes" (* nested *) to quit *)222        set s to "tell application \\"Terminal\\" to do shell script \\"rm\\""223        return s & " and the application is fine"224        """, language: .applescript)225        #expect(scan.applicationReferences.isEmpty)226        #expect(!scan.usesShell)227        #expect(scan.dynamicConstructs.isEmpty)228        #expect(!scan.hasTargets)229    }230231    @Test func appleScriptPureComputationHasNoTargets() {232        for s in ["2 + 2", "set x to 3\nreturn x * x", "(current date) as string", "count of {1, 2, 3}", "tell current application to return 1",233                  "path to frontmost application", "tell me to return 5", "name of current application"] {234            let scan = ScriptTargetScanner.scan(s, language: .applescript)235            #expect(!scan.hasTargets, "\(s)")236            #expect(scan.dynamicConstructs.isEmpty, "\(s): \(scan.dynamicConstructs)")237            #expect(!scan.needsShellRuntime, "\(s)")238        }239    }240241    @Test func appleScriptDynamicTargetsAreRefused() {242        for s in ["set a to \"Mail\"\ntell application a to quit", "tell application (\"Ma\" & \"il\") to quit", "tell application id theID to quit",243                  "tell app someVariable to activate", "run script \"tell application \\\"Mail\\\" to quit\"", "load script file \"x.scpt\""] {244            let scan = ScriptTargetScanner.scan(s, language: .applescript)245            #expect(!scan.dynamicConstructs.isEmpty, "\(s)")246            #expect(throws: ToolError.self, "\(s)") { try ScriptTargetScanner.verifiedTargets(scan, declared: ["com.apple.mail"], resolve: resolve, canonical: { $0 }) }247        }248    }249250    @Test func appleScriptEscapesAreDetected() {251        #expect(ScriptTargetScanner.scan("do shell script \"ls\"", language: .applescript).usesShell)252        #expect(ScriptTargetScanner.scan("do  shell\tscript \"ls\"", language: .applescript).needsShellRuntime)253        #expect(ScriptTargetScanner.scan("use framework \"Foundation\"\nreturn 1", language: .applescript).usesObjCBridge)254        #expect(ScriptTargetScanner.scan("set f to open for access POSIX file \"/tmp/x\" with write permission", language: .applescript).usesFileIO)255        #expect(ScriptTargetScanner.scan("set the clipboard to \"x\"", language: .applescript).writesClipboard)256        #expect(!ScriptTargetScanner.scan("set the clipboard to \"x\"", language: .applescript).readsClipboard)257        #expect(ScriptTargetScanner.scan("return the clipboard", language: .applescript).readsClipboard)258        #expect(ScriptTargetScanner.scan("open location \"https://example.com\"", language: .applescript).opensLocation)259        #expect(!ScriptTargetScanner.scan("return \"do shell script\"", language: .applescript).usesShell)260    }261262    @Test func jxaTargetShapes() {263        func scan(_ s: String) -> ScriptScan { ScriptTargetScanner.scan(s, language: .jxa) }264        #expect(scan("Application(\"Finder\").startupDisk.name()").applicationReferences == ["Finder"])265        #expect(scan("const m = Application('com.apple.mail'); m.activate()").applicationReferences == ["com.apple.mail"])266        #expect(scan("Application ( `Safari` ).windows()").applicationReferences == ["Safari"])267        #expect(scan("var a = Application('/Applications/Safari.app')\nvar f = Application(\"Finder\")").applicationReferences == ["/Applications/Safari.app", "Finder"])268        let current = scan("var app = Application.currentApplication(); app.includeStandardAdditions = true; app.displayName")269        #expect(current.usesCurrentApplication && !current.hasTargets && current.dynamicConstructs.isEmpty)270        let commented = scan("// Application('Mail').quit()\n/* Application(\"Notes\") */\nvar s = \"Application('Terminal')\"; 1 + 1")271        #expect(!commented.hasTargets && commented.dynamicConstructs.isEmpty)272        for s in ["1 + 2", "JSON.stringify({a: [1, 2]})", "new Date(0).toISOString()", "'abc'.toUpperCase()", "function run() { return 42 }"] {273            let r = scan(s)274            #expect(!r.hasTargets && r.dynamicConstructs.isEmpty && !r.needsShellRuntime, "\(s)")275        }276    }277278    @Test func jxaDynamicTargetsAreRefused() {279        for s in ["var n = 'Mail'; Application(n).quit()", "Application(`${name}`)", "const A = Application; A('Mail')", "Application('Ma' + 'il')",280                  "eval(\"Application('Mail').quit()\")", "new Function('return 1')()", "globalThis['Appl' + 'ication']('Mail')", "this['Application']('Mail')"] {281            let scan = ScriptTargetScanner.scan(s, language: .jxa)282            #expect(!scan.dynamicConstructs.isEmpty, "\(s)")283            #expect(throws: ToolError.self, "\(s)") { try ScriptTargetScanner.verifiedTargets(scan, declared: ["com.apple.mail"], resolve: resolve, canonical: { $0 }) }284        }285    }286287    @Test func jxaEscapesAreDetected() {288        func scan(_ s: String) -> ScriptScan { ScriptTargetScanner.scan(s, language: .jxa) }289        #expect(scan("var a = Application.currentApplication(); a.includeStandardAdditions = true; a.doShellScript('ls')").usesShell)290        #expect(scan("ObjC.import('stdlib'); $.system('ls')").usesShell)291        #expect(scan("ObjC.import('Foundation'); $.NSTask.alloc.init").usesObjCBridge)292        #expect(scan("$('x')").needsShellRuntime)293        #expect(scan("Path('/etc/hosts')").usesFileIO)294        #expect(scan("app.setTheClipboardTo('x')").writesClipboard)295        #expect(scan("app.theClipboard()").readsClipboard)296        #expect(!scan("var s = 'doShellScript'; `costs $5`").needsShellRuntime)297    }298299    @Test func undeclaredTargetsAreRefusedAndDeclaredOnesPass() throws {300        #expect(try targets("tell application \"Finder\" to beep", .applescript, declared: ["com.apple.finder"]) == ["com.apple.finder"])301        #expect(try targets("tell application \"Finder\" to beep", .applescript, declared: ["COM.APPLE.FINDER", "com.apple.finder"]).count == 1)302        #expect(try targets("tell application id \"com.apple.mail\" to beep", .applescript, declared: ["com.apple.mail"]) == ["com.apple.mail"])303        #expect(try targets("Application('Safari').windows()", .jxa, declared: ["com.apple.Safari"]) == ["com.apple.Safari"])304        #expect(try targets("Application('/Applications/Safari.app').windows()", .jxa, declared: ["com.apple.safari"]) == ["com.apple.safari"])305        #expect(try targets("1 + 1", .applescript, declared: []).isEmpty)306        // Declared but unused targets remain declared (they still need the capability).307        #expect(try targets("1 + 1", .jxa, declared: ["com.apple.mail"]) == ["com.apple.mail"])308309        #expect(throws: ToolError.self) { try targets("tell application \"Mail\" to beep", .applescript, declared: []) }310        #expect(throws: ToolError.self) { try targets("tell application \"Mail\" to beep", .applescript, declared: ["com.apple.finder"]) }311        #expect(throws: ToolError.self) { try targets("tell application \"Finder\" to tell application \"Mail\" to beep", .applescript, declared: ["com.apple.finder"]) }312        #expect(throws: ToolError.self) { try targets("tell application id \"com.apple.mail\" to beep", .applescript, declared: ["com.apple.finder"]) }313        #expect(throws: ToolError.self) { try targets("Application('Mail').quit()", .jxa, declared: ["com.apple.finder"]) }314        #expect(throws: ToolError.self) { try targets("tell application \"NoSuchApp12345\" to beep", .applescript, declared: ["com.apple.finder"]) }315        #expect(throws: ToolError.self) { try targets("1", .applescript, declared: ["not a bundle id"]) }316    }317318    @Test func requirementsCarryRuntimeTargetsAndShellEscalation() throws {319        let dir = try TempDirectory(); defer { dir.remove() }320        let ctx = dir.toolContext()321        let apple = ScriptRunTool(language: .applescript), jxa = ScriptRunTool(language: .jxa)322323        let pure = try apple.requirements(for: ToolInput(arguments: ["script": "2 + 2"]), context: ctx)324        #expect(pure.capabilities == [.scriptRuntime(name: "applescript")] && pure.tier == .reversibleWrite)325        let targeted = try apple.requirements(for: ToolInput(arguments: ["script": "tell application \"Finder\" to get name of startup disk", "targets": ["com.apple.finder"]]), context: ctx)326        #expect(targeted.capabilities == [.scriptRuntime(name: "applescript"), .appAutomation(bundleID: "com.apple.finder")] && targeted.tier == .consequential)327        let shell = try apple.requirements(for: ToolInput(arguments: ["script": "do shell script \"date\""]), context: ctx)328        #expect(shell.capabilities == [.scriptRuntime(name: "applescript"), .scriptRuntime(name: "bash")] && shell.tier == .consequential)329        let jxaShell = try jxa.requirements(for: ToolInput(arguments: ["script": "ObjC.import('stdlib'); $.system('date')"]), context: ctx)330        #expect(jxaShell.capabilities == [.scriptRuntime(name: "jxa"), .scriptRuntime(name: "bash")] && jxaShell.tier == .consequential)331        let jxaPure = try jxa.requirements(for: ToolInput(arguments: ["script": "1 + 1"]), context: ctx)332        #expect(jxaPure.capabilities == [.scriptRuntime(name: "jxa")] && jxaPure.tier == .reversibleWrite)333        let clip = try apple.requirements(for: ToolInput(arguments: ["script": "return the clipboard"]), context: ctx)334        #expect(clip.capabilities.contains(.clipboardRead))335336        #expect(throws: ToolError.self) { try apple.requirements(for: ToolInput(arguments: ["script": "tell application \"Finder\" to beep"]), context: ctx) }337        #expect(throws: ToolError.self) { try jxa.requirements(for: ToolInput(arguments: ["script": "Application('Finder').name()", "targets": ["com.apple.mail"]]), context: ctx) }338        #expect(throws: ToolError.self) { try apple.requirements(for: ToolInput(arguments: ["script": "   "]), context: ctx) }339    }340}341342@Suite("Unit · parsers and pure helpers")343struct ParserTests {344    @Test func appleScriptSourceFormBecomesJSON() {345        #expect(AppleScriptValueParser.parse("4") == .int(4))346        #expect(AppleScriptValueParser.parse("-3.5") == .number(-3.5))347        #expect(AppleScriptValueParser.parse("3,5") == .number(3.5))348        #expect(AppleScriptValueParser.parse("1.0E+10") == .number(1.0e10))349        #expect(AppleScriptValueParser.parse("\"a\\\"b\\nc\"") == .string("a\"b\nc"))350        #expect(AppleScriptValueParser.parse("true") == .bool(true))351        #expect(AppleScriptValueParser.parse("missing value") == .null)352        #expect(AppleScriptValueParser.parse("{}") == .array([]))353        #expect(AppleScriptValueParser.parse("{1, 2.5, \"x\", false, {3, 4}}") == [1, 2.5, "x", false, [3, 4]])354        #expect(AppleScriptValueParser.parse("{1,5, 2}") == [1.5, 2])355        #expect(AppleScriptValueParser.parse("{a:1, b:missing value, |my key|:\"v\"}") == ["a": 1, "b": .null, "my key": "v"])356        #expect(AppleScriptValueParser.parse("date \"samedi 21 novembre 2026\"") == nil)357        #expect(AppleScriptValueParser.parse("application \"Finder\"") == nil)358        #expect(AppleScriptValueParser.parse("{1, date \"x\"}") == nil)359        #expect(AppleScriptValueParser.parse("") == nil)360    }361362    @Test func osascriptErrorsAreParsedByNumberNotByLanguage() {363        let script = "set x to 1\ntell application \"Finder\" to get nme of\n"364        let syntax = ScriptError.parseOsascript("50:51: syntax error: expression prévu(s) mais fin de ligne trouvé(s). (-2741)", script: script)365        #expect(syntax.isSyntax && syntax.number == -2741 && syntax.line == 2 && syntax.column == 40)366        let exec = ScriptError.parseOsascript("6:12: execution error: boom (42)", script: "error \"boom\" number 42")367        #expect(!exec.isSyntax && exec.number == 42 && exec.message == "boom" && exec.line == 1)368        let tcc = ScriptError.parseOsascript("0:10: execution error: Not authorized to send Apple events to Finder. (-1743)", script: "x")369        #expect(tcc.number == -1743)370        let jxa = ScriptError.fromJXA(["ok": false, "name": "SyntaxError", "message": "Unexpected token ';'", "line": 3, "column": 9, "errorNumber": .null])371        #expect(jxa.isSyntax && jxa.line == 3 && jxa.column == 9)372        let jxaTCC = ScriptError.fromJXA(["ok": false, "name": "Error", "message": "Not authorized to send Apple events to Finder. (-1743)", "line": 1, "column": .null, "errorNumber": .null])373        #expect(jxaTCC.number == -1743)374    }375376    @Test func typingStepsSplitUnicodeAndControlKeys() {377        typealias Step = AccessibilityTypeTextTool.Step378        #expect(AccessibilityTypeTextTool.steps(for: "ab\tc\nd") == [.text("ab"), .key(48), .text("c"), .key(36), .text("d")])379        #expect(AccessibilityTypeTextTool.steps(for: "a\r\nb") == [.text("a"), .key(36), .text("b")])380        let long = String(repeating: "é👍", count: 20)381        let steps = AccessibilityTypeTextTool.steps(for: long)382        var rebuilt = ""383        for case .text(let t) in steps { #expect(t.utf16.count <= 16); rebuilt += t }384        #expect(rebuilt == long)385    }386387    @Test func secureFieldsAreRecognisedAndNeverDescribed() {388        #expect(AX.isSecure(role: "AXSecureTextField", subrole: nil))389        #expect(AX.isSecure(role: "AXTextField", subrole: "AXSecureTextField"))390        #expect(!AX.isSecure(role: "AXTextField", subrole: nil))391        var info = AX.Info(); info.role = "AXTextField"; info.subrole = "AXSecureTextField"; info.value = .string(AX.securePlaceholder)392        #expect(info.json(path: "p", depth: 0)["value"] == .string("«secure»"))393        #expect(info.json(path: "p", depth: 0)["secure"] == true)394        // A value filter never matches a secure field.395        let filter = AX.Filter(ToolInput(arguments: ["value": "secure"]))396        #expect(!filter.matches(info))397398        let secure = InputRecorder.describeValueChange(role: "AXSecureTextField", subrole: nil, title: "Password", value: .string("hunter2"), captureText: true)399        #expect(secure.value == nil && !secure.summary.contains("hunter2") && !secure.summary.contains("7"))400        let text = InputRecorder.describeValueChange(role: "AXTextField", subrole: nil, title: "Subject", value: .string("Hello world"), captureText: false)401        #expect(text.summary == "typed text of length 11 in field \"Subject\"" && text.value == nil)402        let opted = InputRecorder.describeValueChange(role: "AXTextField", subrole: nil, title: "Subject", value: .string("Hello"), captureText: true)403        #expect(opted.value == .string("Hello"))404        let box = InputRecorder.describeValueChange(role: "AXCheckBox", subrole: nil, title: "Remember", value: .int(1), captureText: false)405        #expect(box.value == .int(1) && box.summary.contains("Remember"))406    }407408    @Test func accessibilityFilterMatchesRoleTitleIdentifierValue() {409        var info = AX.Info(); info.role = "AXButton"; info.title = "Save As…"; info.identifier = "save-button"; info.value = .string("on")410        #expect(AX.Filter(ToolInput(arguments: ["role": "AXButton", "title": "save"])).matches(info))411        #expect(AX.Filter(ToolInput(arguments: ["identifier": "save-button", "value": "ON"])).matches(info))412        #expect(!AX.Filter(ToolInput(arguments: ["role": "AXCheckBox"])).matches(info))413        #expect(!AX.Filter(ToolInput(arguments: ["identifier": "save"])).matches(info))414        #expect(AX.Filter(ToolInput(arguments: [:])).isEmpty)415    }416417    @Test func notificationResponsesMapToActions() {418        typealias B = NotificationCenterBridge419        let approve = B.interpret(actionIdentifier: B.approveActionID, notificationID: "n1", userInfo: [B.runIDKey: "run-1", B.approvalIDKey: "ap-1"])420        #expect(approve.action == .approve && approve.runID == "run-1" && approve.approvalID == "ap-1" && approve.notificationID == "n1")421        #expect(B.interpret(actionIdentifier: B.denyActionID, notificationID: "n", userInfo: [:]).action == .deny)422        #expect(B.interpret(actionIdentifier: B.openActionID, notificationID: "n", userInfo: [:]).action == .open)423        #expect(B.interpret(actionIdentifier: "com.apple.UNNotificationDefaultActionIdentifier", notificationID: "n", userInfo: [:]).action == .open)424        #expect(B.interpret(actionIdentifier: "com.apple.UNNotificationDismissActionIdentifier", notificationID: "n", userInfo: [:]).action == .dismissed)425        #expect(B.interpret(actionIdentifier: "x", notificationID: "n", userInfo: [:]).action == .other)426        let ids = B.categories().map(\.identifier).sorted()427        #expect(ids == [B.approvalCategoryID, B.infoCategoryID].sorted())428        let actions = B.categories().first { $0.identifier == B.approvalCategoryID }?.actions.map(\.identifier)429        #expect(actions == [B.approveActionID, B.denyActionID, B.openActionID])430    }431432    @Test func settingsLinksAndBundleIdentifierValidation() {433        for p in MacPermission.allCases {434            let url = MacPermissions.settingsURL(for: p)435            #expect(url.scheme == "x-apple.systempreferences")436            #expect(!MacPermissions.howToEnable(p).isEmpty)437        }438        #expect(MacPermissions.settingsURL(for: .accessibility).absoluteString.hasSuffix("Privacy_Accessibility"))439        #expect(MacPermissions.settingsURL(for: .screenRecording).absoluteString.hasSuffix("Privacy_ScreenCapture"))440        #expect(MacPermissions.settingsURL(for: .appleEvents).absoluteString.hasSuffix("Privacy_Automation"))441        #expect(MacPermissions.settingsURL(for: .fullDiskAccess).absoluteString.hasSuffix("Privacy_AllFiles"))442        #expect(AppResolver.isValidBundleID("com.apple.finder"))443        #expect(!AppResolver.isValidBundleID("com.apple finder"))444        #expect(!AppResolver.isValidBundleID("../etc"))445        #expect(!AppResolver.isValidBundleID(""))446    }447}448
Files main
Menu

Theme