Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Desktop Automation Example · Chapter 02 / 04

Test automation learning path

Python + pytest + pywinauto

Study the Python implementation as one lifecycle: pytest fixtures, UIA discovery, deterministic interaction, synchronization, assertions, evidence and cleanup.

Python implementation: pytest + pywinauto

The Python implementation should be read as one lifecycle rather than as a list of helper functions. pytest owns test discovery and fixture execution. The fixture owns the temporary document and application lifecycle. pywinauto connects to the Windows UI Automation tree. Helper functions then solve four recurring desktop-automation problems: identifying the correct application state, locating the correct control, synchronizing with asynchronous UI/file-system changes, and collecting diagnostic evidence.

pytest test function
      ↑ receives window + temp path
fixture setup
      ↓
Desktop(backend="uia")
      ↓
window / tab / editor helpers
      ↓
keyboard + clipboard interaction
      ↓
poll until UI/file state is observable
      ↓
assertions
      ↓
fixture teardown

A central lesson here is that desktop automation is stateful. A process starting successfully does not mean the expected window is ready; a window existing does not mean the correct tab is active; a key press being sent does not mean the file has already been written. Reliable tests therefore identify state explicitly and wait for observable conditions instead of relying on fixed sleeps as the primary synchronization strategy.

Python dependencies: what each package contributes

Read `requirements.txt` as the boundary of the Python automation stack.

Concept

Pinned versions make a small lab reproducible. Desktop automation is sensitive to library and platform differences, so a known dependency set reduces one source of unexplained behavior.

Code from the project

Reviewed source: `python/requirements.txt`


pywinauto==0.6.9
pytest==8.4.1
Pillow==11.3.0
allure-pytest==2.16.0
pyperclip==1.9.0

Detailed explanation

pytest discovers and executes tests and fixtures. pywinauto connects Python to Windows GUI automation through the UIA backend. pyperclip provides deterministic clipboard text input. Pillow is used by screenshot/image handling, and allure-pytest writes structured Allure result files and attachments.

Initially, Python cannot import the automation/test/reporting libraries. Once this step completes, the interpreter has the exact packages required by the project.

Design reasoning

Removing pytest removes the runner; removing pywinauto removes GUI access; removing pyperclip breaks the layout-independent input strategy; removing Allure integration removes Python report results.

Key points

  • Dependencies describe responsibilities, not just installation commands.
  • Pinned versions improve reproducibility.

Common pitfalls

  • Assuming Pillow is a test runner dependency just because it is in the same file.

pytest fixture: setup, yield and guaranteed cleanup

Follow the `notepad` fixture as the lifecycle owner of one test document.

Concept

The fixture makes resource ownership explicit: one test gets one unique document and the same fixture that creates it is responsible for closing and deleting it.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


@pytest.fixture
def notepad(request):
    window = None
    temp_path = None

    try:
        with tempfile.NamedTemporaryFile(
            prefix="desktop-automation-",
            suffix=".txt",
            delete=False,
        ) as temp_file:
            temp_path = Path(temp_file.name)

        subprocess.Popen(["notepad.exe", str(temp_path)])
        desktop = Desktop(backend="uia")
        window = find_window_for_file(desktop, temp_path.name, timeout=15)
        yield window, temp_path
    finally:
        if window is not None and temp_path is not None:
            close_test_tab(window, temp_path.name)
        if temp_path is not None:
            temp_path.unlink(missing_ok=True)

Detailed explanation

pytest sees the test parameter named notepad, calls this fixture first, creates a unique temporary text file, launches Notepad with that file, obtains a UI Automation desktop connection, finds the matching window and pauses the fixture at yield. The tuple becomes the test argument. When the test ends—pass or fail—execution returns after yield and enters finally for cleanup.

Initially, no test document/window. When execution reaches yield, a known file is open and a window wrapper is available. Once this step completes, the test tab is closed and the temporary file is removed.

Design reasoning

Replacing yield with return would skip the post-yield teardown path. Removing finally would leak files/tabs when an assertion or helper fails.

Key points

  • Fixture injection is dependency injection performed by pytest.
  • yield divides setup from teardown.

Common pitfalls

  • Thinking code after yield only runs after successful tests.

Find the correct Notepad window by test identity

Understand why the project searches UI windows for the unique filename instead of trusting the launcher PID.

Concept

Modern Notepad can reuse an existing process/window and open documents as tabs. The process returned by subprocess.Popen is therefore not a reliable identity for the final visible test document; the unique filename is.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


def find_window_for_file(desktop, file_name: str, timeout: float):
    deadline = time.monotonic() + timeout
    last_titles = []

    while time.monotonic() < deadline:
        last_titles = []
        for candidate in desktop.windows(control_type="Window"):
            try:
                title = candidate.window_text()
                last_titles.append(title)
                if file_name.lower() in title.lower():
                    return desktop.window(handle=candidate.handle)
            except Exception:
                continue
        time.sleep(0.25)

    raise RuntimeError(
        f"Could not find Notepad window for '{file_name}'. "
        f"Top-level windows seen: {last_titles}"
    )

Detailed explanation

The helper creates a monotonic deadline, repeatedly enumerates top-level UIA Window controls, reads their titles and returns a wrapper for the first title containing the unique test filename. Windows that disappear or become inaccessible while being enumerated are ignored and the search continues until timeout.

Initially, Notepad was launched, but the test does not yet own a UI wrapper. Once this step completes, the test has the top-level window that contains its uniquely named document.

Design reasoning

Attaching to the first Notepad process/window can drive a user's unrelated tab or another parallel test. Removing the timeout can hang indefinitely when the UI never appears.

Key points

  • UI identity and process identity are not always the same.
  • time.monotonic() is appropriate for timeout measurement.

Common pitfalls

  • Assuming Popen(...).pid must be the process owning the final modern Notepad tab.

Locate the editor across different Notepad UI trees

See how the project handles `Document` and `Edit` controls without a brittle single-version locator.

Concept

Windows application versions can expose different UI Automation trees. The fallback is deliberate compatibility logic, while the visibility/size checks reduce accidental matches.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


def find_editor(window):
    root = window.wrapper_object()

    for control_type in ("Document", "Edit"):
        candidates = []
        for candidate in root.descendants(control_type=control_type):
            try:
                rect = candidate.rectangle()
                if (
                    candidate.is_visible()
                    and candidate.is_enabled()
                    and rect.width() > 0
                    and rect.height() > 0
                ):
                    candidates.append(candidate)
            except Exception:
                continue

        if candidates:
            return max(
                candidates,
                key=lambda item: item.rectangle().width() * item.rectangle().height(),
            )

Detailed explanation

The window wrapper becomes the search root. The helper first looks for visible, enabled Document descendants; if none are usable it tries Edit. It filters zero-size/inactive candidates and chooses the candidate with the largest rectangle area, which is expected to be the actual text editing surface rather than a small incidental edit control.

Initially, the test owns only a top-level Notepad window. Once this step completes, it owns a wrapper for the interactive text editor control.

Design reasoning

Hard-coding only Document or only Edit can fail on another Notepad build. Returning the first descendant without filtering can select the wrong control.

Key points

  • ControlType is one UIA locator dimension, not a complete identity.
  • Compatibility fallbacks should be intentional and observable.

Common pitfalls

  • Using broad descendant search without checking whether the result is actually interactive and visible.

Deterministic text input through the Windows clipboard

Understand why arbitrary text is pasted while control shortcuts remain real keyboard input.

Concept

Simulated character typing depends on the active keyboard layout. Pasting exact text avoids a Ukrainian/English layout turning intended Latin characters into different glyphs, while shortcuts such as Ctrl+A/S/V still represent real user interactions.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


def set_text(editor, text: str) -> None:
    previous_clipboard_text = ""
    try:
        previous_clipboard_text = pyperclip.paste()
    except pyperclip.PyperclipException:
        pass

    editor.set_focus()
    editor.type_keys("^a")
    pyperclip.copy(text)
    editor.type_keys("^v")

    wait_until(
        lambda: read_text(editor) == text,
        timeout=3,
        failure=f"Editor did not become exactly {text!r}",
    )

Detailed explanation

The helper saves the current clipboard when possible, focuses the editor, selects existing content with Ctrl+A, places the exact target string into the Windows clipboard and pastes it with Ctrl+V. It then polls the editor until UI Automation reports the expected value before continuing.

Initially, editor text may be anything and clipboard has user state. Once this step completes, editor equals the requested string and the helper later restores the previous clipboard when possible.

Design reasoning

Typing the string with type_keys(text) can make the test depend on keyboard layout. Omitting the post-paste check creates a race where the assertion/save can run before the UI reflects the paste.

Key points

  • Determinism sometimes requires separating text data from keyboard gestures.
  • A UI action is not complete until an observable condition confirms it.

Common pitfalls

  • Treating fixed sleeps as proof that paste completed.

Read text through UI Automation patterns

Learn why the code has a ValuePattern/TextPattern fallback instead of reading screen pixels.

Concept

UI Automation patterns expose semantic control capabilities. Reading through those patterns is more robust and meaningful than OCR or pixel inspection for a text editor.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


def read_text(editor) -> str:
    try:
        value = editor.iface_value.CurrentValue
    except (NoPatternInterfaceError, AttributeError):
        value = editor.iface_text.DocumentRange.GetText(-1)
    return value.rstrip("\r\n")

Detailed explanation

The helper first asks the editor for UIA ValuePattern's current value. If that pattern is not exposed by this control/version, it falls back to TextPattern and reads the entire document range. Trailing CR/LF characters are normalized away before equality assertions.

Initially, the test has an editor wrapper. Once this step completes, it has a normalized Python string representing the editor's current semantic text value.

Design reasoning

Assuming every editor supports the same UIA pattern can break across application versions. Comparing raw text without newline normalization can create false failures.

Key points

  • UIA patterns describe supported behavior, not visual appearance.
  • Fallbacks should correspond to genuine platform variation.

Common pitfalls

  • Catching every exception and silently returning an empty string.

Synchronization: poll observable state instead of sleeping blindly

Dissect the generic polling helper used for UI and file-system state changes.

Concept

Desktop UI and file writes are asynchronous from the test's point of view. Polling a meaningful post-condition reduces both flakiness and wasted time compared with arbitrary multi-second sleeps.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


def wait_until(condition, timeout: float, failure: str, interval: float = 0.1) -> None:
    deadline = time.monotonic() + timeout
    last_error = None

    while time.monotonic() < deadline:
        try:
            if condition():
                return
        except Exception as exc:
            last_error = exc
        time.sleep(interval)

    suffix = f" Last error: {last_error}" if last_error else ""
    raise AssertionError(f"{failure}.{suffix}")

Detailed explanation

The caller supplies a condition function. wait_until evaluates it repeatedly until true or timeout, tolerating transient exceptions and remembering the latest one for diagnostics. A successful condition returns immediately; the test does not wait for the full timeout.

Initially, the desired condition may still be false. Once this step completes, either the condition has actually become true, or the helper fails with a bounded timeout and useful diagnostic context.

Design reasoning

Replacing polling with sleep(5) makes fast operations unnecessarily slow and slow operations still flaky. Removing the timeout can hang the suite forever.

Key points

  • Wait for state, not time.
  • Timeouts convert indefinite hangs into diagnosable failures.

Common pitfalls

  • Polling a condition that itself changes the application state.

The complete Python scenario: UI assertion plus file assertion

Trace the user-visible action and the persisted-state verification in one test.

Concept

A desktop test should not stop at 'the UI looks right'. This scenario verifies both the application-facing state (text control) and the externally persisted result (file contents), so it detects failures in either editing or saving.

Code from the project

Reviewed source: `python/tests/test_notepad.py`


@allure.feature("Notepad desktop automation")
@allure.title("Can type, read and save text in Notepad")
def test_can_type_read_and_save_text(notepad, request):
    window, temp_path = notepad
    test_name = request.node.name

    with allure.step("Open the exact Notepad test tab"):
        activate_file_tab(window, temp_path.name, timeout=3)
        capture_window(window, test_name, "00-opened")
        editor = find_editor(window)

    with allure.step("Paste layout-independent text into Notepad"):
        set_text(editor, TEXT)
        capture_window(window, test_name, "01-text-entered")
        assert read_text(editor) == TEXT

    with allure.step("Save with Ctrl+S and verify exact file contents"):
        editor.set_focus()
        editor.type_keys("^s")
        wait_for_saved_text(temp_path, TEXT)
        capture_window(window, test_name, "02-saved")
        assert temp_path.read_text(encoding="utf-8") == TEXT

Detailed explanation

pytest injects the fixture result, then the test activates the exact tab and locates its editor. The second step changes UI state and verifies the semantic editor value. The third sends Ctrl+S, waits for persisted disk state and independently reads the temporary file for an exact assertion. Screenshots are attached around meaningful state transitions.

Initially, unique empty document. Once this step completes, editor contains exact text, the file on disk contains the same text, screenshots and Allure step data exist, and fixture teardown can safely clean the document.

Design reasoning

Removing the file assertion would allow a broken Save operation to pass. Removing the UI assertion would make it harder to distinguish input failure from persistence failure.

Key points

  • Assert at meaningful boundaries.
  • Allure steps organize evidence but do not replace assertions.

Common pitfalls

  • Treating screenshots as the assertion instead of machine-readable state.

Source registry

10 chapter references
Desktop Automation Lab — reviewed commit

Exact source code used by every project-walkthrough lesson

sergiiiavt · Reference implementation
Source ↗
UI Automation Overview

Windows UI Automation tree, elements, control types, properties and patterns

Microsoft Learn · Official documentation
Source ↗
pywinauto documentation

Python Windows GUI automation, UIA backend and wrappers

pywinauto · Official documentation
Source ↗
pytest fixtures reference

Fixture injection, yield values and teardown semantics

pytest · Official documentation
Source ↗
FlaUI

FlaUI architecture, UIA2/UIA3 backends and Windows automation elements

FlaUI · Official repository
Source ↗
NUnit SetUp and TearDown

Per-test setup/teardown lifecycle and inheritance behavior

NUnit · Official documentation
Source ↗
Workflow syntax for GitHub Actions

Triggers, jobs, runners, steps, actions and conditions

GitHub Docs · Official documentation
Source ↗
Contexts reference

github, runner, secrets and variables contexts used by the CI workflow

GitHub Docs · Official documentation
Source ↗
Allure Report — Pytest

pytest result generation, attachments and Allure report workflow

Allure Report · Official documentation
Source ↗
Allure Report — NUnit

NUnit integration, result directory, metadata and attachments

Allure Report · Official documentation
Source ↗