gpt4 book ai didi

python - QMessageBox 的功能测试...为什么不起作用?

转载 作者:行者123 更新时间:2023-12-01 05:09:52 25 4
gpt4 key购买 nike

我会为使用 PyQt(或 PySide)作为 GUI 库的 pyqt 应用程序开发一些功能测试。测试使用 Unittest 和 Qttest 库,正如许多资源中所报告的那样,例如这个 stackoverflow 问题:Unit and functional testing a PySide-based application?对于主窗口,一切工作正常,并且代码完美地模拟键盘类型和鼠标点击和移动,但是“魔鬼在于细节”......并且此方法不适用于 QMessageBox。

在主窗口的类中,为了管理打开文件时的IOError,我初始化了一个QMessageBox:

self.IOErrMsgBox = QtGui.QMessageBox()
self.IOErrMsgBox.setText("<b>Error</b>")
self.IOErrMsgBox.setInformativeText("""
<p>There was an error opening
the project file:
%s.</p>"""%(path,))
self.IOErrMsgBox.setStandardButtons(QtGui.QMessageBox.Ok)
self.IOErrMsgBox.setDefaultButton(QtGui.QMessageBox.Ok)
self.IOErrMsgBox.exec_()

为了测试它是如何工作的,在功能测试中我有:

def test__open_project(self):
self.MainWin._project_open(wrong_path, flag='c')
# the function that handles the exception
# and initializes the QMessageBox.
IOErrMsgBox = self.MainWin.IOErrMsgBox
# Reference to the initialized QMessageBox.
self.assertIsInstance(IOErrMsgBox, QMessageBox)
okWidget = self.MainWin.IOErrMsgBox.button(IOErrMsgBox.Ok)
QTest.mouseClick(okWidget, Qt.LeftButton)

或者,另一种选择:

def test__open_project(self):
#... some code, exactly like previous example except for last row...
QTest.keyClick(okWidget, 'o', Qt.AltModifier)

但是没有人工作...并且“确定”按钮没有被单击,我可以用鼠标指针来完成它:(

有什么建议吗?

最佳答案

问题一般是关于如何测试模式对话框

包括 QMessageBox 在内的任何模式对话框在关闭之前都不会从 exec_() 返回,因此第二个代码框中的测试代码可能永远不会被执行。

您可以show()它(使其成为非模态),然后按照您的代码进行操作,但不要忘记随后关闭并删除对话框。

或者您使用计时器并安排单击“确定”按钮(类似于 Test modal dialog with Qt Test )。这是一个例子:

from PySide import QtGui, QtCore

app = QtGui.QApplication([])

box = QtGui.QMessageBox()
box.setStandardButtons(QtGui.QMessageBox.Ok)
button = box.button(QtGui.QMessageBox.Ok)
QtCore.QTimer.singleShot(0, button.clicked)
box.exec_()

关于python - QMessageBox 的功能测试...为什么不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24382773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com