diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py index c0752f8e..b4941143 100644 --- a/tests/unit_tests/conftest.py +++ b/tests/unit_tests/conftest.py @@ -1,4 +1,6 @@ import pytest +from pytestqt.exceptions import TimeoutError as QtBotTimeoutError +from qtpy.QtWidgets import QApplication from bec_widgets.cli.rpc_register import RPCRegister from bec_widgets.qt_utils import error_popups @@ -6,9 +8,16 @@ from bec_widgets.utils import bec_dispatcher as bec_dispatcher_module @pytest.fixture(autouse=True) -def qapplication(qapp): # pylint: disable=unused-argument +def qapplication(qtbot): # pylint: disable=unused-argument yield - qapp.processEvents() # make sure all events are processed before shutting down + + qapp = QApplication.instance() + qapp.quit() + qapp.processEvents() + try: + qtbot.waitUntil(lambda: qapp.topLevelWidgets() == []) + except QtBotTimeoutError as exc: + raise TimeoutError(f"Failed to close all widgets: {qapp.topLevelWidgets()}") from exc @pytest.fixture(autouse=True) @@ -31,3 +40,25 @@ def bec_dispatcher(threads_check): # pylint: disable=unused-argument @pytest.fixture(autouse=True) def clean_singleton(): error_popups._popup_utility_instance = None + + +def create_widget(qtbot, widget, *args, **kwargs): + """ + Create a widget and add it to the qtbot for testing. This is a helper function that + should be used in all tests that require a widget to be created. + DO NOT CREATE WIDGETS DIRECTLY IN A FIXTURE! + + Args: + qtbot (fixture): pytest-qt fixture + widget (QWidget): widget class to be created + *args: positional arguments for the widget + **kwargs: keyword arguments for the widget + + Returns: + QWidget: the created widget + + """ + widget = widget(*args, **kwargs) + qtbot.addWidget(widget) + qtbot.waitExposed(widget) + return widget