3

How can I "okay" a QMessageBox using pytestqt?

For instance, given:

# MessageBoxFactory.py
from PyQt5.QtWidgets import QMessageBox, QWidget

def messageBoxFactory(parent : QWidget, title:str, msg:str, level="info"):
    """Display a popup of type `level` containing msg[0] (title) and msg[1] the message.

    Makes use of the full QMessageBox (rather than QMessageBox.warning, for example) because
    it is necessary to have a handle to the box later for testing.
    """
    box = None
    if level == "info":
        box = QMessageBox(QMessageBox.Information, title, msg, QMessageBox.Ok, parent)
    elif level == "warning":
        box = QMessageBox(QMessageBox.Warning, title, msg, QMessageBox.Ok, parent)
    elif level == "critical":
        box = QMessageBox(QMessageBox.Critical, title, msg, QMessageBox.Ok, parent)

    if not box:
        raise ValueError("no QMessageBox created")
    box.exec()
    return box

And the test code:

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import Qt
import pytest
from pytestqt.qtbot import QtBot
from accos.view.MessageBoxFactory import messageBoxFactory


def test_mbf(qtbot: QtBot):
    main_window = QMainWindow()
    box = messageBoxFactory(main_window, "Informational Message", "Some information", level="info")
    dialogButtonBox : QDialogButtonBox = box.children()[2]
    okayBtn = dialogButtonBox.buttons()[0]
    qtbot.mouseClick(okayBtn, Qt.LeftButton, Qt.NoModifier)

How can I get the qtbot to okay the message box?

CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • I always use a mock object with monkeypatch in these situations. – Alexander Jul 07 '22 at 14:55
  • @alexpdev I have limited experience using the Python mock packages (although I've used googlemock extensively). Would you be able to provide an example of how to do so? Thanks. – CiaranWelsh Jul 08 '22 at 08:02
  • well I upvoted your question in the hopes that someone else might have a better answer. – Alexander Jul 08 '22 at 20:45

0 Answers0