使用QProcess测试PySide应用程序

2024-03-28 23:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个PySide应用程序,它在QProcess中生成一个工作应用程序。worker执行模拟并创建结果文件供主应用程序读取。我想生成worker,给它一些时间让它工作,然后检查输出。在我的测试函数中(我正在使用py.测试,如果这有帮助的话),我无法找到一种方法在不阻塞主线程的情况下等待工作线程,从而不允许工作进程启动和运行。在

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)

对于名为“等待代码”的部分,我尝试过:

  • 使用一个名为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,我可以用它代替{},而不会阻塞事件循环。但是,qWait不包含在PySide中。

  • 我还尝试过创建一个新的事件循环,比如在this thread中。但是,这似乎阻止了application的事件循环,因此我们无法在工作进程运行时完成worker.start函数并加载数据。在

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

有什么提示吗?在


Tags: 方法selfloop应用程序application进程def事件
1条回答
网友
1楼 · 发布于 2024-03-28 23:26:11

事实证明,选项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更详细的解释。在

相关问题 更多 >