python - 如何使用 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')))
我尝试了几种不同的方法,有没有标准的方法可以做到这一点?希望我错过了一些明显的东西。
解决方案
从我所看到的和另一篇文章中解释的那样,不可能模拟与特殊 QFileDialogs 的交互,如getSaveFileName
or 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)
尽管似乎无法测试“另存为”功能。
推荐阅读
- arrays - 如何在 PowerShell 中使用数组模式新名称重命名文件?
- mysql - 数据库 - 将时间表存储在每个工作日的一行或所有工作日的一行?
- python - 模拟类实例而不调用 __init__ 并模拟它们各自的属性
- reactjs - 如何限制表头在地图功能中显示一次?
- laravel - 撇号不能通过服务器端数据表单个列搜索进行搜索
- flutter - 按添加按钮后如何使我的文本输入消失?
- java - 有没有办法减少 JVM 的堆外开销?
- flutter - 更改 Flutter 桌面应用程序窗口大小
- python - PyTorch 的 DataLoader() 中的 next() 和 iter() 做了什么
- java - Java流如何将具有数量的对象解包到单个对象的列表中