簡體   English   中英

模擬在單元測試 CI 期間單擊 PyQt5 QMessageBox 小部件中的按鈕

[英]Simulate the click on a button in the PyQt5 QMessageBox widget, during unittest CI

如果我們運行下面的最小示例,而不是冗長的演講:

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

  • 使用 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM