[英]Testing a QFileDialog while using PySide
我正在為用 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)
然而,這並沒有奏效。 文件對話框仍然啟動,我必須與它交互才能完成測試。
我的解決方案是在啟動文件對話框的 GUI 類中構建一個測試模式參數。 像這樣的東西...
class MyWindow(QtGui.QMainWindow):
def __init__(self, testMode=False):
QtGui.QMainWindow.__init__(self)
self.testMode = testMode
如果 testMode 為真(例如在運行單元測試時),我只是隱藏對話框,然后在單元測試中手動設置行編輯。
這確實有效,但我擔心是否會破壞測試的目的。 另一方面,我想您可以說我只是“截斷”了用戶的交互。
另一種選擇是直接用鍵盤模塊控制鍵盤,用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.