Skip to content

Pytest Example

A complete, runnable pytest suite lives in the repository at examples/pytest/. It automates the bundled WPF test application (test_applications/WPFApplication/WpfApplication.exe), which ships in the repo, so the suite runs with no external setup.

Run it

uv run pytest examples/pytest -v

pytest is already a project dependency.

Fixtures (conftest.py)

The bridge is initialised before any C#-backed import, then the application is launched once per session and disposed in teardown:

"""Pytest fixtures for the FlaUI for Python example suite.

Launches the bundled WPF test application once per session and hands each test a ready-to-use main
window and condition factory. This mirrors the structure of the project's own ``tests/`` suite, but
is trimmed down to a single self-contained example.
"""

from pathlib import Path
from typing import Generator

# isort: off  -- the bridge must be initialised before any C#-backed import is used.
from flaui.lib.pythonnet_bridge import setup_pythonnet_bridge

setup_pythonnet_bridge()

from flaui.core.automation_elements import Window
from flaui.core.condition_factory import ConditionFactory
from flaui.lib.enums import UIAutomationTypes
from flaui.modules.automation import Automation
import pytest

# isort: on


def find_test_app() -> Path:
    """Locate the bundled WPF test application by walking up from this file.

    :raises FileNotFoundError: If the bundled executable cannot be found.
    :return: The path to ``WpfApplication.exe``.
    """
    for parent in Path(__file__).resolve().parents:
        candidate = parent / "test_applications" / "WPFApplication" / "WpfApplication.exe"
        if candidate.exists():
            return candidate
    raise FileNotFoundError("Could not locate the bundled WPF test application under test_applications/.")


@pytest.fixture(scope="session")
def automation() -> Generator[Automation, None, None]:
    """Launch the WPF test application for the whole session and dispose it afterwards.

    :yield: A ready ``Automation`` instance with the application launched.
    """
    auto = Automation(UIAutomationTypes.UIA3)
    auto.application.launch(str(find_test_app()))
    auto.application.wait_while_main_handle_is_missing(3000)
    try:
        yield auto
    finally:
        auto.application.kill()
        auto.automation_base.dispose()




@pytest.fixture
def main_window(automation: Automation) -> Window:
    """Return the application's main window.

    :param automation: The session automation instance.
    :return: The main ``Window`` of the test application.
    """
    return automation.application.get_main_window(automation)


@pytest.fixture
def condition_factory(automation: Automation) -> ConditionFactory:
    """Return the automation's condition factory for building search conditions.

    :param automation: The session automation instance.
    :return: The shared ``ConditionFactory``.
    """
    return automation.cf


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo[None]) -> Generator[None, object, object]:
    """Save a screenshot of the whole screen when a test body fails.

    The file lands in ``artifacts/<test name>.png`` (git-ignored), ready to upload from CI. Only the
    ``call`` phase is captured, so failing fixtures and teardowns don't produce extra images.

    :param item: The test item being reported.
    :param call: Information about the phase that just ran.
    :yield: Control to pytest, which builds the report.
    :return: The test report.
    """
    report = yield
    if call.when == "call" and getattr(report, "failed", False):
        from flaui.core.capturing import Capture

        artifacts = Path("artifacts")
        artifacts.mkdir(exist_ok=True)
        safe_name = "".join(c if c.isalnum() or c in "-_." else "_" for c in item.name)
        try:
            with Capture.main_screen() as image:
                image.to_file(str(artifacts / f"{safe_name}.png"))
        except Exception as error:  # a broken screenshot must never hide the real failure
            item.add_report_section("call", "screenshot", f"could not capture screen: {error}")
    return report

The tests (test_simple_controls.py)

Find → wrap → act, and leave shared state clean:

"""Example pytest suite driving the bundled WPF test application with FlaUI for Python.

Run it from the project root::

    uv run pytest examples/pytest

Each test finds a control on the **Simple Controls** tab by automation id (or name), wraps it with
the matching typed element, and asserts a real interaction. The session-scoped ``automation``
fixture (see ``conftest.py``) launches the application once and disposes it at the end.
"""

from flaui.core.automation_elements import Window
from flaui.core.condition_factory import ConditionFactory
from flaui.core.tools import Retry


def test_window_title(main_window: Window) -> None:
    """The launched application exposes its title."""
    assert main_window.title == "FlaUI WPF Test App"


def test_enter_text(main_window: Window, condition_factory: ConditionFactory) -> None:
    """Typing into the text box round-trips through the ``text`` property."""
    text_box = main_window.find_first_descendant(condition=condition_factory.by_automation_id("TextBox")).as_text_box()
    text_box.text = "hello from pytest"
    assert text_box.text == "hello from pytest"


def test_invoke_button(main_window: Window, condition_factory: ConditionFactory) -> None:
    """The invokable button can be located and invoked through the Invoke pattern."""
    button = main_window.find_first_descendant(
        condition=condition_factory.by_automation_id("InvokableButton")
    ).as_button()
    button.invoke()  # raises if the Invoke pattern is unavailable
    # The test app renames the button once the invoke is processed.
    assert Retry.WhileFalse(lambda: button.name == "Invoked!", timeout=2000)


def test_toggle_checkbox(main_window: Window, condition_factory: ConditionFactory) -> None:
    """Toggling the checkbox flips its state; the test restores the original state."""
    checkbox = main_window.find_first_descendant(condition=condition_factory.by_name("Test Checkbox")).as_check_box()
    original = checkbox.is_checked
    try:
        checkbox.toggle()
        assert checkbox.is_checked != original
    finally:
        # The application is shared across the session, so leave the checkbox as we found it.
        if checkbox.is_checked != original:
            checkbox.toggle()


def test_read_slider(main_window: Window, condition_factory: ConditionFactory) -> None:
    """The slider exposes its current value within its reported range."""
    slider = main_window.find_first_descendant(condition=condition_factory.by_automation_id("Slider")).as_slider()
    assert slider.minimum <= slider.value <= slider.maximum

More in this folder

The same fixtures also drive the recipes the docs include:

File Docs page
test_element_cookbook.py Element Cookbook: one test per control
test_advanced.py Advanced: XPath, conditions, caching, retry, expect, post_wait
test_configuration.py Configuration & logging: C# logging, timeouts, mouse speed
test_multi_instance.py Multiple instances: several copies of one app
test_utilities.py Utilities: Wait, keyboard, mouse, drawing, capture, highlight, tools
test_name_mapping.py, app_map.py, app_settings.py Test design tips: element name maps and pydantic settings

Keep skips/xfails in fixtures, not tests

The project's own suite (tests/conftest.py) launches all four combinations (UIA2/UIA3 × WinForms/WPF) and guards platform limitations in fixtures. See Testing for the matrix conventions.