如果我们运行下面的最小示例,则无需长篇大论:
$ 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()
。
使用button()
QMessageBox的方法获取QPushButton 。
使用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句