在异步或多线程代码中测试回调的执行

Test execution of callbacks in async or multi-threaded code

我需要检查 threaded/asynchronous 代码中某些操作是否以特定顺序发生。大致如下:

def test_threaded_stuff():
    # I can define the callbacks to the operation
    op = start_operation(callback1, callback2, cbargs...)
    op.checkpoint1.wait()
    # check that callback1 and callback2 have been invoked,
    # in that order
    op.checkpoint2.wait()
    # check that they have been invoked again, in reverse order

我可以提供将由操作调用的测试回调,但我不能在其中放置 py.test 断言,因为我需要测试它们执行的总体顺序,而不是任何单个回调的状态。此外,一些回调是在不受 py.test.

控制的独立线程中执行的

为了测试这样的代码,我想到了以下模式:

def callback1(log):
    log(1)

def callback2(log):
    log(2)

def test_threaded_stuff():
    events = []
    op = start_operation(cb1, cb2, events.append)
    op.checkpoint1.wait()
    assert events == [1, 2]
    op.checkpoint2.wait()
    assert events == [1, 2, 2, 1]

py.test 中是否有惯用的表达方式?例如,自动记录其调用的可调用夹具,以便我可以在我的测试中查询调用。

如果需要具体的例子,this file就是一个例子,同目录下的其他文件也是如此。

pytest 可能没有必要像我认为的那样具有特定功能,标准 Python unittest 模块就足够了。

您可以使用 Mock 对象来跟踪对自身以及方法和属性的调用,reference

您可以将它与您期望和想要测试的 assert_has_calls() by building the list of calls 结合起来。它还允许通过 any_order=False 参数默认测试调用的特定顺序。

因此,通过充分修补您的模块并在您的测试中传递 Mock 对象而不是回调,您将基本上能够创建您的测试。