2014-07-01 54 views
0

我有一個PySide應用程序,在QProcess中生成一個工作應用程序。工作人員執行模擬並創建結果文件供主應用程序讀取。我想產生工人,給它時間讓它工作,然後檢查輸出。在我的測試函數中(我使用py.test,如果有幫助),我找不到阻止主線程等待worker的方法,因此不允許worker進程啓動和運行。使用QProcess測試PySide應用程序

def test_worker_thread(): 
    application = Application() # Waits for and loads result files 
    application.worker.start() # Runs in a new process 

    # How to wait right here without blocking thread? 

    <wait_code> 

    assert_correct_data(application.worker.results) 

名爲 「wait_code」 一節中,我曾嘗試:

  • 創建一個名爲done一個屬性的本地對象。我將worker.finished信號連接到done設置爲True。然後我用一個time.sleep循環來阻止等待工作完成。

    class WaitObject: 
    
        def __init__(self): 
         self.condition = False 
    
        def set_true(self): 
         self.condition = True 
    
    wait = WaitObject() 
    application.worker.finished(wait.set_true) 
    
    while not wait.condition: 
        time.sleep(1) 
    
  • 我用Google搜索方法來測試異步Qt代碼,和我遇到QTest.qWait,我可以代替time.sleep()使用不堵塞事件循環。但是,PySide中不包含qWait

  • 我也嘗試創建一個新的事件循環,如this thread。但是,這似乎阻止了application的事件循環,所以我們無法完成worker.start函數並在worker工作時加載數據。

    loop = QtCore.QEventLoop() 
    application.worker.finished(loop.quit) 
    loop.exec_() 
    

任何提示嗎?

回答

1

事實證明,選項3實際工作。由於無關錯誤,我的工作人員未啓動。這裏是一些完整的骨架代碼:

def test_worker_thread(): 
    application = Application() # Waits for and loads result files 
    application.worker.start() # Runs in a new process 

    loop = QtGui.QEventLoop() 
    application.worker.finished(loop.quit) # Resume when worker done 
    loop.exec_() # Blocks at this line until loop quits 

    assert_correct_data(application.worker.results) 

我要去研究這種模式的抽象。我將使用連接到loop.quit的單拍QTimer添加超時,以防從不調用worker.finished

編輯:這是一個blog post解釋更詳細。

+1

基本上你使用了一個信號。這樣你就不再等待線程了,但線程在完成時就告訴你了。這確實是一個很好的解決方案。 – Trilarion