python - 如何测试使用 exec_() 调用的自定义对话框窗口?

标签 python pyqt pyqt5 pytest pytest-qt

我正在尝试为我的项目编写系统测试。我有一个启动各种窗口的 Controller 类。但是,我似乎无法使用 exec 和 qtbot 来控制 Windows 启动。

这是一个 MVCE:

from PyQt5.QtWidgets import *
from PyQt5 import QtGui
class Controller:
    def __init__(self):
        self.name = None
        self.a = WindowA(self)

    def launchB(self):
        self.b = WindowB(self)

        if self.b.exec_():
            self.name = self.b.getData()

class WindowA(QDialog):
    def __init__(self, controller):
        super(WindowA, self).__init__()
        self.controller = controller
        layout = QVBoxLayout()
        self.button = QPushButton('Launch B')
        self.button.clicked.connect(self.controller.launchB)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.show()

class WindowB(QDialog):
    def __init__(self, controller):
        super(WindowB, self).__init__()
        self.controller = controller
        layout = QVBoxLayout()
        self.le = QLineEdit()
        self.button = QPushButton('Save')
        self.button.clicked.connect(self.save)
        layout.addWidget(self.le)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.show()

    def getData(self):
        return self.le.text()

    def save(self):
        if self.le.text():
            self.accept()
            self.close()   
        else:
            self.reject()

from PyQt5.QtWidgets import QApplication

if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)
    window = Controller()
    sys.exit(app.exec_())

我想测试用户是否成功在行编辑中输入数据。在我的测试中,我能够成功单击 WindowA 中的按钮来启动 WindowB,但无法使用 keyClicks 在 lineedit 中输入数据。

这是测试:

def test_1(qtbot):
    control = Controller()
    qtbot.mouseClick(control.a.button, QtCore.Qt.LeftButton)

    qtbot.keyClicks(control.b.le, 'Test_Project')
    qtbot.mouseClick(control.b.button, QtCore.Qt.LeftButton)

    assert control.name == 'Test_Project'

最佳答案

问题是使用 exec_() 会阻塞所有同步任务,直到窗口关闭,解决方案是使用 QTimer 异步启动剩余任务:

def test_1(qtbot):
    control = Controller()

    def on_timeout():
        qtbot.keyClicks(control.b.le, "Test_Project")
        qtbot.mouseClick(control.b.button, QtCore.Qt.LeftButton)

    QtCore.QTimer.singleShot(0, on_timeout)
    qtbot.mouseClick(control.a.button, QtCore.Qt.LeftButton)

    assert control.name == "Test_Project"

关于python - 如何测试使用 exec_() 调用的自定义对话框窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073275/

相关文章:

python - DFS中c++和Python的区别

Python如何从unicode字符串中获取空填充字节字符串

python - 使用 PyQt4 的空白窗口

python - 如何使用表单上的按钮向 QTabWidget 添加选项卡?

python - gui 在处理过程中没有响应?

python - AirFlow DAG 在 DST 后运行两次

python - LSTM 0 准确率

python - pyqt向导将字段注册为字符串而不是整数

python - PyQt4 初学者 - 无窗口图标

python - 如何使用 QToolButton 或 QPushButton 将本地保存的 GeoJSON 加载到带有 QTableWidget 或 QTableTree 的 Qt 对话框中?