首页 > 解决方案 > 如何使用 PyQt 和 QTest 模拟完成 QFileDialog?

问题描述

我想自动化 GUI 的测试。特别是我想测试文件菜单中的“保存”选项。即,当单击保存按钮时,会收集 UI 中字段的数据,然后将其写入 json 文件。

问题是,当弹出 QFileDialog 要求用户输入要保存到的文件的名称时,我无法在对话框上获得句柄以继续测试。你如何自动化这个位?我不确定如何处理 QFileDialog。

    def hdl_save_report_as(self):
        try:
            self.dialog.setDefaultSuffix('json')
            save_file, _ = self.dialog.getSaveFileName(caption="Save Report", filter="JSON Files (*.json)")
            if save_file:
                score = self.parent.main_tab_view.get_fields()
                self.ui_model.report_path = save_file
                with open(save_file, 'w') as f:
                    json.dump(score, f, indent=4)
        except Exception as e:
            result = dlg.message_dialog("Exception", "We ran into an error!", QMessageBox.Warning, e)
            print(e)
    def test_save_report(self):
        self.main_window.menu.bt_save_file.trigger()
        self.main_window.menu.dialog.selectFile('a_test_report.json')

        ## save_dialog = QApplication.activeModalWidget()
        # save_dialog = QApplication.activeWindow()
        # children = save_dialog.findChildren()
        # active_line_edit = None
        # confirm_button = None
        # for c in children:
        #     if type(c) is QLineEdit:
        #         if c.hasFocus():
        #             active_line_edit = QLineEdit(c)
        #     # if type(c) is QPushButton:
        #     #     if
        # active_line_edit.setText("a_test_report")
        self.assertTrue(os.path.exists(os.path.join(os.getcwd(), 'a_test_report.json')))

我尝试了几种不同的方法,有没有标准的方法可以做到这一点?希望我错过了一些明显的东西。

标签: pythonunit-testingpyqtpyqt5

解决方案


从我所看到的和另一篇文章中解释的那样,不可能模拟与特殊 QFileDialogs 的交互,如getSaveFileNameor getOpenFileName

我的方法现在是在设置功能中管理文件,例如

    def setUp(self):
        self.test_report = "a_test_report.json"
        
        # Remove an existing test report
        if os.path.exists(self.test_report):
            os.remove(self.test_report)
        self.assertFalse(os.path.exists(os.path.join(os.getcwd(), self.test_report)))
        
        # Create a file to test reading / writing
        with open(self.test_report, 'w') as f:
            f.write("")
        self.assertTrue(os.path.exists(os.path.join(os.getcwd(), self.test_report)))
        self.assertTrue(os.stat(self.test_report).st_size == 0)
        
        self.main_window = MainWindow()

和测试一样

    def test_save_action(self):
        # Trigger the save button - check if the file was overwritten with new info
        self.main_window.menu.bt_save_file.trigger()
        self.assertTrue(os.stat(self.test_report).st_size > 0)

尽管似乎无法测试“另存为”功能。


推荐阅读