如果我们运行下面的最小示例,而不是长篇大论:
$ python3
Python 3.7.6 (default, Jan 30 2020, 09:44:41)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import unittest import sys
>>> from PyQt5.QtWidgets import QMessageBox, QApplication
>>> import unittest
>>>
>>> class Fortest():
... def messagebox(self):
... app = QApplication(sys.argv)
... msg = QMessageBox()
... msg.setIcon(QMessageBox.Warning)
... msg.setText("message text")
... msg.setStandardButtons(QMessageBox.Close)
... msg.buttonClicked.connect(msg.close)
... msg.exec()
...
>>> class Test(unittest.TestCase):
... def testMessagebox(self):
... a=Fortest()
... a.messagebox()
...
>>> unittest(Test().testMessagebox())
我们仍然停留在要求单击“关闭”按钮的小部件上。这与持续集成单元测试不兼容......
如何在测试代码(Test类)中模拟点击关闭按钮,而不改变待测试代码(Fortest类)?
逻辑:
获取QMessageBox,在这里你可以使用QApplication::activeWindow()
.
使用以下命令获取 QPushButtonbutton()
QMessageBox 的方法。
使用 QTest 子模块的 mouseClick() 方法单击。
但上述操作必须在 QMessageBox 显示后立即完成,为此必须进行延迟(在这种情况下您可以使用 threading.Timer())。
import sys
import unittest
import threading
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox, QApplication
from PyQt5.QtTest import QTest
class Fortest:
def messagebox(self):
app = QApplication(sys.argv)
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText("message text")
msg.setStandardButtons(QMessageBox.Close)
msg.buttonClicked.connect(msg.close)
msg.exec_()
class Test(unittest.TestCase):
def testMessagebox(self):
a = Fortest()
threading.Timer(1, self.execute_click).start()
a.messagebox()
def execute_click(self):
w = QApplication.activeWindow()
if isinstance(w, QMessageBox):
close_button = w.button(QMessageBox.Close)
QTest.mouseClick(close_button, Qt.LeftButton)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)