如何在使用 pytest-qt 测试 PyQt5 应用程序时显示 GUI?

How can I display GUI while testing PyQt5 app with pytest-qt?

我是 PyQt 的新手,但我打算使用 pytestpytest-qt 插件来测试我的 PyQt5 应用程序。我在 Java 和 SWTBotRCPTT 中有一些 GUI 测试经验,我可以在其中实时查看控件和整个 GUI 在测试期间发生的情况。我希望我的新 python 工具有这样的行为,但似乎 pytest-qt 以某种后台方式测试 GUI。所有代码都按预期工作,但在测试期间我看不到 GUI。代码和教程一样简单:

from tests.test import MyApp
from time import sleep
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


def test_myapp(qtbot):
    app = QApplication([])
    window = MyApp()
    # window.show()
    # app.exec_()
    qtbot.addWidget(window)
    qtbot.mouseClick(window.buttonBox.buttons()[0], Qt.LeftButton)
    sleep(5)
    assert window.label.text() == 'accept'

如果我取消注释 window.show() 行(他们在 tutorial 中这样做),我会看到一个奇怪的 window,它包含冻结的背景:

我想理论上可以显示界面,因为我知道 PyQt5 可以从 python shell (more):

you can, for example, create widgets from the Python shell prompt, interact with them, and still being able to enter other Python commands

但是不知道怎么用pytest-qt实现

这段代码按照我的要求工作,它正确地显示了界面。关键是qtbot.waitForWindowShown(window)行。

from tests.test import MyApp
from time import sleep
from PyQt5.QtCore import *


def test_myapp(qtbot):
    window = MyApp()
    qtbot.addWidget(window)
    window.show()
    qtbot.waitForWindowShown(window)
    sleep(3)
    qtbot.mouseClick(window.buttonBox.buttons()[0], Qt.LeftButton)
    assert window.label.text() == 'accept'
    qtbot.stopForInteraction()