在unittest CI期间,模拟在PyQt5 QMessageBox小部件中单击按钮

2024-05-13 22:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

而不是长篇大论,如果我们运行下面的最小示例:

$ 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())

我们仍然停留在要求点击关闭按钮的小部件上。这与连续集成单元测试不兼容

如何模拟在测试代码(类测试)中单击关闭按钮,而不更改要测试的代码(类Fortest)


Tags: testimportself示例defsysmsgunittest
1条回答
网友
1楼 · 发布于 2024-05-13 22:25:51

逻辑是:

  • 获取QMessageBox,在这里您可以使用QApplication::activeWindow()

  • 使用QMessageBox的button()方法获取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)

相关问题 更多 >