使用PySide时测试QFileDialog

时间:2015-09-18 20:34:43

标签: python unit-testing pyside python-unittest

我正在为PySide 1.2.2编写的简单GUI编写单元测试。我正在使用Windows 7和Python 2.7.6。

我想测试这个功能,当单击一个按钮时会激活该功能。

def setDestination(self):
    directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")
    self.destLineEdit.setText(directory)

到目前为止,我已经提出了以下测试用例:

def test_browse_dest(self):
    # Reset the GUI to its defaults
    self.clear()

    # Click the destination browse button
    QTest.mouseClick(self.window.browseButton_2, QtCore.Qt.LeftButton)

    # Test paths
    destPath = os.path.join(os.getcwd(), TEST_DIR_B, "test")
    self.assertEqual(self.window.destLineEdit.text(), destPath)

此测试确实有效,但它是交互式的。我必须选择目录并单击“选择文件夹”按钮。虽然这当然很酷且很有趣,但我想知道是否有办法让这些行动自动化。

我确实尝试隐藏文件对话框并在行编辑中自行设置文本。首先,我写了这个:

def setDestination(self):
    self.fileDialog = QtGui.QFileDialog()
    directory = self.fileDialog.getExistingDirectory(self, "Select Directory")
    self.destLineEdit.setText(directory)

然后我尝试访问单元测试中的文件对话框。

def test_browse_dest(self):
    # Reset the GUI to its defaults
    self.clear()

    # Click the destination browse button
    QTest.mouseClick(self.window.browseButton_2, QtCore.Qt.LeftButton)
    self.window.fileDialog.hide()

    # Test paths
    destPath = os.path.join(os.getcwd(), TEST_DIR_B, "test")
    self.window.destLineEdit.setText(destPath)
    self.assertEqual(self.window.destLineEdit.text(), destPath)

然而,这不起作用。文件对话框仍然启动,我不得不与它进行交互以完成测试。

2 个答案:

答案 0 :(得分:0)

我的解决方案是在GUI类中构建一个测试模式参数,以启动文件对话框。像这样......

class MyWindow(QtGui.QMainWindow):
    def __init__(self, testMode=False):
        QtGui.QMainWindow.__init__(self)
        self.testMode = testMode

如果testMode为true(例如运行单元测试时),我只是隐藏对话框,然后在单元测试中手动设置行编辑。

这确实有效,但我担心如果我打败了测试的目的。另一方面,我猜你可以说我只是“抄袭”了用户的互动。

答案 1 :(得分:0)

另一种选择是直接通过键盘模块控制键盘,并通过Qt计时器单脉冲延迟输入。有点混乱,因为这意味着您无法在GUI正在执行操作的同时使用计算机,但意味着您不必更改基本代码:

import keyboard
QtCore.QTimer.singleShot(1, lambda: keyboard.write(base_dir + '/test_save_excel.xlsx'))
QtCore.QTimer.singleShot(10, lambda: keyboard.press('enter'))
# test method that calls dialog