axterminator 0.1.0

World's most superior macOS GUI testing framework with background testing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
"""
Pytest fixtures and configuration for AXTerminator tests.

Provides fixtures for:
- Launching/connecting to test applications
- Mock accessibility trees
- Performance measurement
- Background operation verification
"""

from __future__ import annotations

import os
import subprocess
import time
from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable
from unittest.mock import MagicMock, patch

import pytest

if TYPE_CHECKING:
    pass


# Custom pytest markers
def pytest_configure(config: pytest.Config) -> None:
    """Register custom markers."""
    config.addinivalue_line(
        "markers", "background: tests that verify background operation (no focus steal)"
    )
    config.addinivalue_line(
        "markers", "requires_app: tests that need a real running application"
    )
    config.addinivalue_line("markers", "slow: performance tests that may take longer")
    config.addinivalue_line(
        "markers", "integration: tests requiring real macOS accessibility API"
    )


# ============================================================================
# Application Fixtures
# ============================================================================


@dataclass
class TestApp:
    """Wrapper for test application state."""

    name: str
    bundle_id: str
    pid: int | None = None
    process: subprocess.Popen[bytes] | None = None

    def is_running(self) -> bool:
        """Check if the app process is still running."""
        if self.pid is None:
            return False
        try:
            os.kill(self.pid, 0)
            return True
        except OSError:
            return False

    def terminate(self) -> None:
        """Terminate the test app."""
        if self.process:
            self.process.terminate()
            try:
                self.process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.process.kill()


@pytest.fixture
def calculator_app() -> Generator[TestApp, None, None]:
    """
    Launch Calculator.app for testing.

    Calculator is ideal for tests because:
    - Always installed on macOS
    - Simple, predictable UI
    - Has buttons for click testing
    - Has display for value testing
    """
    # Launch Calculator
    process = subprocess.Popen(
        ["open", "-a", "Calculator", "--new"],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )

    # Wait for app to launch and get PID
    time.sleep(1.0)  # Give app time to launch

    # Get PID via pgrep
    result = subprocess.run(
        ["pgrep", "-n", "Calculator"],
        capture_output=True,
        text=True,
        check=False,
    )

    pid = int(result.stdout.strip()) if result.returncode == 0 else None

    app = TestApp(
        name="Calculator",
        bundle_id="com.apple.calculator",
        pid=pid,
        process=process,
    )

    yield app

    # Cleanup: quit the app
    subprocess.run(
        ["osascript", "-e", 'tell application "Calculator" to quit'],
        capture_output=True,
        check=False,
    )
    time.sleep(0.5)


@pytest.fixture
def textedit_app() -> Generator[TestApp, None, None]:
    """
    Launch TextEdit.app for text input testing.

    TextEdit is useful for:
    - Text input testing
    - Has text fields
    - Has value attributes
    """
    # Launch TextEdit with a new document
    process = subprocess.Popen(
        ["open", "-a", "TextEdit", "--new"],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )

    time.sleep(1.0)

    result = subprocess.run(
        ["pgrep", "-n", "TextEdit"],
        capture_output=True,
        text=True,
        check=False,
    )

    pid = int(result.stdout.strip()) if result.returncode == 0 else None

    app = TestApp(
        name="TextEdit",
        bundle_id="com.apple.TextEdit",
        pid=pid,
        process=process,
    )

    yield app

    subprocess.run(
        ["osascript", "-e", 'tell application "TextEdit" to quit saving no'],
        capture_output=True,
        check=False,
    )
    time.sleep(0.5)


@pytest.fixture
def finder_app() -> TestApp:
    """
    Use Finder for testing (always running).

    Finder is useful because:
    - Always running on macOS
    - No need to launch/terminate
    - Stable accessibility tree
    """
    result = subprocess.run(
        ["pgrep", "-x", "Finder"],
        capture_output=True,
        text=True,
        check=False,
    )

    pid = int(result.stdout.strip().split("\n")[0]) if result.returncode == 0 else None

    return TestApp(
        name="Finder",
        bundle_id="com.apple.finder",
        pid=pid,
    )


# ============================================================================
# Mock Accessibility Tree Fixtures
# ============================================================================


@dataclass
class MockAXElement:
    """Mock accessibility element for unit testing."""

    role: str
    title: str | None = None
    value: str | None = None
    identifier: str | None = None
    description: str | None = None
    label: str | None = None
    enabled: bool = True
    focused: bool = False
    bounds: tuple[float, float, float, float] | None = None
    children: list[MockAXElement] | None = None
    parent: MockAXElement | None = None
    data_testid: str | None = None
    aria_label: str | None = None

    def get_children(self) -> list[MockAXElement]:
        """Return children or empty list."""
        return self.children or []


def create_calculator_tree() -> MockAXElement:
    """
    Create a mock accessibility tree resembling Calculator.app.

    Structure:
    - AXApplication
      - AXWindow "Calculator"
        - AXGroup (display)
          - AXStaticText (result display)
        - AXGroup (buttons)
          - AXButton "1" ... "9", "0"
          - AXButton "+", "-", "*", "/"
          - AXButton "="
          - AXButton "AC"
    """
    # Create buttons
    number_buttons = [
        MockAXElement(role="AXButton", title=str(i), identifier=f"calc_btn_{i}")
        for i in range(10)
    ]

    operator_buttons = [
        MockAXElement(role="AXButton", title="+", identifier="calc_btn_plus"),
        MockAXElement(role="AXButton", title="-", identifier="calc_btn_minus"),
        MockAXElement(role="AXButton", title="*", identifier="calc_btn_multiply"),
        MockAXElement(role="AXButton", title="/", identifier="calc_btn_divide"),
        MockAXElement(role="AXButton", title="=", identifier="calc_btn_equals"),
        MockAXElement(role="AXButton", title="AC", identifier="calc_btn_clear"),
    ]

    button_group = MockAXElement(
        role="AXGroup",
        identifier="calculator_buttons",
        children=number_buttons + operator_buttons,
    )

    display = MockAXElement(
        role="AXStaticText",
        value="0",
        identifier="calculator_display",
    )

    display_group = MockAXElement(
        role="AXGroup",
        identifier="calculator_display_group",
        children=[display],
    )

    window = MockAXElement(
        role="AXWindow",
        title="Calculator",
        identifier="calculator_window",
        children=[display_group, button_group],
    )

    app = MockAXElement(
        role="AXApplication",
        title="Calculator",
        identifier="com.apple.calculator",
        children=[window],
    )

    return app


@pytest.fixture
def mock_calculator_tree() -> MockAXElement:
    """Provide mock Calculator accessibility tree."""
    return create_calculator_tree()


@pytest.fixture
def mock_ax_element() -> Callable[..., MockAXElement]:
    """Factory fixture for creating mock elements."""

    def _create(
        role: str = "AXButton",
        title: str | None = "Test",
        value: str | None = None,
        identifier: str | None = None,
        **kwargs: Any,
    ) -> MockAXElement:
        return MockAXElement(
            role=role,
            title=title,
            value=value,
            identifier=identifier,
            **kwargs,
        )

    return _create


# ============================================================================
# Performance Measurement Fixtures
# ============================================================================


@dataclass
class PerformanceResult:
    """Performance measurement result."""

    operation: str
    duration_ms: float
    iterations: int
    min_ms: float
    max_ms: float
    avg_ms: float
    p95_ms: float

    def meets_target(self, target_ms: float) -> bool:
        """Check if p95 meets target."""
        return self.p95_ms <= target_ms


@pytest.fixture
def perf_timer() -> Callable[..., PerformanceResult]:
    """
    Fixture for measuring operation performance.

    Usage:
        result = perf_timer(lambda: app.find("button"), iterations=100)
        assert result.p95_ms < 1.0  # 1ms target
    """

    def _measure(
        operation: Callable[[], Any],
        iterations: int = 100,
        warmup: int = 5,
        name: str = "operation",
    ) -> PerformanceResult:
        # Warmup
        for _ in range(warmup):
            try:
                operation()
            except Exception:
                pass

        # Measure
        durations: list[float] = []
        for _ in range(iterations):
            start = time.perf_counter()
            try:
                operation()
            except Exception:
                pass
            end = time.perf_counter()
            durations.append((end - start) * 1000)  # Convert to ms

        durations.sort()
        p95_idx = int(iterations * 0.95)

        return PerformanceResult(
            operation=name,
            duration_ms=sum(durations),
            iterations=iterations,
            min_ms=min(durations),
            max_ms=max(durations),
            avg_ms=sum(durations) / iterations,
            p95_ms=durations[p95_idx] if p95_idx < len(durations) else durations[-1],
        )

    return _measure


# ============================================================================
# Background Operation Verification
# ============================================================================


@dataclass
class FocusState:
    """Captured focus state for verification."""

    frontmost_app: str
    frontmost_window: str | None
    timestamp: float


@pytest.fixture
def focus_tracker() -> Callable[[], FocusState]:
    """
    Track which app has focus.

    Used to verify background operations don't steal focus.
    """

    def _get_focus() -> FocusState:
        # Get frontmost app via AppleScript
        result = subprocess.run(
            [
                "osascript",
                "-e",
                'tell application "System Events" to get name of first application process whose frontmost is true',
            ],
            capture_output=True,
            text=True,
            check=False,
        )

        frontmost_app = result.stdout.strip() if result.returncode == 0 else "Unknown"

        return FocusState(
            frontmost_app=frontmost_app,
            frontmost_window=None,  # Could be extended
            timestamp=time.time(),
        )

    return _get_focus


@contextmanager
def verify_no_focus_change(
    focus_tracker: Callable[[], FocusState],
) -> Generator[None, None, None]:
    """
    Context manager to verify no focus change occurs.

    Usage:
        with verify_no_focus_change(focus_tracker):
            element.click()  # Should not change focus
    """
    before = focus_tracker()
    yield
    after = focus_tracker()

    if before.frontmost_app != after.frontmost_app:
        pytest.fail(
            f"Focus changed from '{before.frontmost_app}' to '{after.frontmost_app}'"
        )


@pytest.fixture
def no_focus_change(
    focus_tracker: Callable[[], FocusState],
) -> Callable[[], contextmanager[None]]:
    """Fixture providing the no_focus_change context manager."""

    @contextmanager
    def _verify() -> Generator[None, None, None]:
        with verify_no_focus_change(focus_tracker):
            yield

    return _verify


# ============================================================================
# Mocking Fixtures
# ============================================================================


@pytest.fixture
def mock_accessibility_disabled() -> Generator[MagicMock, None, None]:
    """Mock accessibility as disabled."""
    with patch("axterminator.is_accessibility_enabled", return_value=False) as mock:
        yield mock


@pytest.fixture
def mock_accessibility_enabled() -> Generator[MagicMock, None, None]:
    """Mock accessibility as enabled."""
    with patch("axterminator.is_accessibility_enabled", return_value=True) as mock:
        yield mock


@pytest.fixture
def mock_app_connect() -> Generator[MagicMock, None, None]:
    """Mock app connection for unit tests."""

    def _mock_connect(
        name: str | None = None,
        bundle_id: str | None = None,
        pid: int | None = None,
    ) -> MagicMock:
        mock_app = MagicMock()
        mock_app.pid = pid or 12345
        mock_app.bundle_id = bundle_id
        mock_app.name = name
        mock_app.is_running.return_value = True
        return mock_app

    with patch("axterminator.app", side_effect=_mock_connect) as mock:
        yield mock


# ============================================================================
# Test Data Fixtures
# ============================================================================


@pytest.fixture
def sample_queries() -> list[str]:
    """Sample element queries for testing."""
    return [
        "Button",
        "role:AXButton",
        "title:Save",
        "identifier:btn_save",
        "role:AXButton title:Save",
        "//AXWindow/AXButton[@title='Save']",
    ]


@pytest.fixture
def healing_strategies() -> list[str]:
    """All healing strategies in priority order."""
    return [
        "data_testid",
        "aria_label",
        "identifier",
        "title",
        "xpath",
        "position",
        "visual_vlm",
    ]


# ============================================================================
# Skip Conditions
# ============================================================================


def has_accessibility_permission() -> bool:
    """Check if running with accessibility permissions."""
    try:
        import axterminator

        return axterminator.is_accessibility_enabled()
    except (ImportError, AttributeError):
        return False


skip_without_accessibility = pytest.mark.skipif(
    not has_accessibility_permission(),
    reason="Requires accessibility permissions",
)

skip_in_ci = pytest.mark.skipif(
    os.environ.get("CI") == "true",
    reason="Cannot run in CI environment",
)


# ============================================================================
# Async Support
# ============================================================================


@pytest.fixture
def event_loop_policy():
    """Configure event loop for async tests."""
    import asyncio

    return asyncio.DefaultEventLoopPolicy()