【问题标题】:Simulate the click on a button in the PyQt5 QMessageBox widget, during unittest CI模拟在单元测试 CI 期间单击 PyQt5 QMessageBox 小部件中的按钮
【发布时间】:2020-04-14 17:31:19
【问题描述】:

如果我们运行下面的最小示例,而不是冗长的演讲:

$ 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类)?

【问题讨论】:

    标签: python python-3.x pyqt5 python-unittest


    【解决方案1】:

    逻辑:

    • 获取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)
    

    【讨论】:

    • 感谢您的有效回答!最后一个问题:当我启动这个小例子时,一切都很好,但我观察到这条消息:QBackingStore::endPaint() called with active painter; did you forget to destroy it or call QPainter::end() on it? 我用谷歌搜索但我没有找到有趣的东西。您知道它的来源以及如何隐藏此消息吗?
    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 2019-03-26
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多