Tests GUI components and interface flows using pytest and pytest-qt.

Install

mkdir -p .claude/skills/gui-testing && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/13630" && unzip -o skill.zip -d .claude/skills/gui-testing && rm skill.zip

Installs to .claude/skills/gui-testing

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Шаг ④ workflow: pytest + pytest-qt тестирование GUI. Triggers: "протестируй UI", "test GUI", "run gui tests", "verify UI". Запускает pytest тесты после написания тестов через test-writer.
187 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Automate testing of PyQt6 GUI applications
  • Utilize `pytest` and `pytest-qt` for test execution
  • Generate coverage reports with `pytest-cov`
  • Structure tests into unit, GUI, and integration categories
  • Test widget creation, signal emission, and user input
  • Verify data flow within the application

How it works

This skill automates GUI testing for PyQt6 applications by running `pytest` tests, including those specifically designed for GUI components using `pytest-qt`.

Inputs & outputs

You give it
PyQt6 application code and `pytest` test files
You get back
Test results (PASS/FAIL), coverage report (htmlcov/), and a summary report

When to use gui-testing

  • Testing GUI
  • Running UI tests
  • Verifying interface behavior
  • Automated PyQt6 testing

About this skill

GUI Testing

Шаг ④ workflow — автоматизированное тестирование PyQt6 GUI через pytest + pytest-qt.

Workflow Contract

entry:
  branch: NOT main | master
  artifacts:
    - .ai/specs/{branch-name}.md  # все этапы ✅
  condition: все этапы в spec имеют статус ✅

exit:
  condition: все pytest тесты пройдены
  artifacts:
    - htmlcov/ (отчёт покрытия, при --cov)
  cleanup: удалить временные файлы тестов

recommended_next_skill: merge-helper  # Рекомендуемый следующий skill для Codex

Architecture Overview

Тестируемое приложение:

  • GUI Framework: PyQt6
  • Позиционирование: src/gui/ (widgets, windows, panels)
  • Business Logic: src/core/ (calculations, data)
  • Тестирование: pytest + pytest-qt + pytest-cov

Prerequisites

Required

# Установка зависимостей тестирования
pip install pytest pytest-qt pytest-cov

# Для Linux CI/CD (headless)
pip install pytest-xvfb

Конфигурация pyproject.toml

[tool.pytest.ini_options]
testpaths = ["tests"]
qt_api = "pyqt6"
markers = [
    "gui: GUI тесты, требующие display",
    "slow: Медленные тесты",
]

Testing Guidelines

1. Структура тестов

tests/
├── conftest.py              # Общие fixtures
├── unit/                    # Unit тесты (без GUI)
│   ├── test_calculation.py
│   └── test_curve_fitting.py
├── gui/                     # GUI тесты (pytest-qt)
│   ├── test_main_window.py
│   ├── test_sidebar.py
│   └── test_plot_canvas.py
└── integration/             # Интеграционные тесты
    └── test_workflow.py

2. Использование qtbot

def test_button_click(qtbot):
    """Тест клика по кнопке."""
    from PyQt6.QtWidgets import QPushButton
    from PyQt6.QtCore import Qt

    button = QPushButton("Click me")
    qtbot.addWidget(button)

    clicked = []
    button.clicked.connect(lambda: clicked.append(True))

    qtbot.mouseClick(button, Qt.MouseButton.LeftButton)

    assert len(clicked) == 1

3. Ожидание сигналов

def test_signal_emission(qtbot):
    """Тест эмиссии сигнала."""
    from src.core.base_signals import BaseSignals

    signals = BaseSignals()

    with qtbot.wait_signal(signals.response_signal, timeout=1000):
        signals.dispatch_request({"action": "test"})

4. Тестирование виджетов

@pytest.fixture
def main_window(qtbot):
    """Fixture главного окна."""
    from src.gui.main_window import MainWindow
    window = MainWindow()
    qtbot.addWidget(window)
    return window

def test_main_window_loads(main_window):
    """Проверка загрузки главного окна."""
    assert main_window.isVisible()
    assert main_window.tab_widget.count() >= 1

Core Testing Patterns

Pattern 1: Widget Creation

1. Создать виджет
2. Добавить в qtbot (qtbot.addWidget)
3. Проверить начальное состояние
4. Выполнить действие
5. Проверить результат

Pattern 2: Signal Testing

1. Создать объект с сигналами
2. Подключить обработчик или использовать wait_signal
3. Выполнить действие, эмитирующее сигнал
4. Дождаться сигнала (с timeout)
5. Проверить данные сигнала

Pattern 3: User Input

1. Создать виджет с вводом
2. Использовать qtbot.keyClicks для текста
3. Использовать qtbot.mouseClick для кнопок
4. Проверить состояние виджета

Pattern 4: Data Flow

1. Загрузить тестовые данные
2. Передать в тестируемый компонент
3. Выполнить расчёт/обработку
4. Проверить результат с ожидаемым

Running Tests

Локально

# Все тесты
pytest

# Только GUI тесты
pytest -m gui

# С покрытием
pytest --cov=src --cov-report=html

# Конкретный файл
pytest tests/gui/test_main_window.py -v

# С выводом print
pytest -s tests/gui/test_main_window.py

CI/CD

# Linux (headless)
export QT_QPA_PLATFORM=offscreen
pytest --cov=src

# Windows (native display)
pytest --cov=src

Error Handling

При падении тестов:

  1. Проверить stack trace
  2. Проверить fixture dependencies
  3. Проверить timeout (увеличить если нужно)
  4. Проверить изоляцию теста (нет ли побочных эффектов)
  5. Запустить с -s для отладки

Reporting Format

## Test Results

**Status:** PASS / FAIL

**Summary:**
- Total: X tests
- Passed: Y
- Failed: Z
- Skipped: W

**Coverage:** XX%

**Failures:**
- test_name: reason

**Run command:**
pytest tests/ -v --cov=src

Best Practices

  1. Изоляция — каждый тест независим
  2. Fixtures — переиспользование через conftest.py
  3. Явные ожидания — wait_signal вместо sleep
  4. Параметризация — @pytest.mark.parametrize
  5. Маркировка — @pytest.mark.gui, @pytest.mark.slow

References


Remember: Этот навык использует pytest + pytest-qt. Доступны все возможности pytest: fixtures, parametrize, markers, hooks.

When not to use it

  • When the application does not use PyQt6 for its GUI
  • When tests are not written using `pytest`

Prerequisites

pytestpytest-qtpytest-covpytest-xvfb (for Linux CI/CD headless environments)

Limitations

  • Requires PyQt6 as the GUI framework
  • Tests must be structured in a specific directory layout
  • Relies on `pytest` for test execution

How it compares

This workflow provides a structured approach to PyQt6 GUI testing with specific patterns and tools, offering more complete and automated validation than manual UI checks.

Compared to similar skills

gui-testing side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
gui-testing (this skill)04moReviewIntermediate
qt-testing17moReviewIntermediate
textual1439moReviewIntermediate
streamlit869moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

qt-testing

talmolab

Capture and visually inspect Qt GUI widgets using screenshots. Use when asked to verify GUI rendering, test widget appearance, check layouts, or visually inspect any PySide6/Qt component. Enables Claude to "see" Qt interfaces by capturing offscreen screenshots and analyzing them with vision.

19

textual

KyleKing

Expert guidance for building TUI (Text User Interface) applications with the Textual framework. Invoke when user asks about Textual development, TUI apps, widgets, screens, CSS styling, reactive programming, or testing Textual applications.

143346

streamlit

sverzijl

When working with Streamlit web apps, data dashboards, ML/AI app UIs, interactive Python visualizations, or building data science applications with Python

86239

python-testing-patterns

wshobson

Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.

77204

backtesting-frameworks

wshobson

Build robust backtesting systems for trading strategies with proper handling of look-ahead bias, survivorship bias, and transaction costs. Use when developing trading algorithms, validating strategies, or building backtesting infrastructure.

17126

temporal-python-testing

wshobson

Test Temporal workflows with pytest, time-skipping, and mocking strategies. Covers unit testing, integration testing, replay testing, and local development setup. Use when implementing Temporal workflow tests or debugging test failures.

880

Search skills

Search the agent skills registry