有没有一种用pytest测试回调的首选方法?

时间:2014-04-04 13:51:06

标签: python python-2.7 testing mocking pytest

我无法在docs,google或SO上找到使用pytest测试回调的具体示例。我发现了这个:What is the right way to test callback invocation using Python unittest?;但这是为了单位测试。我猜测pytest的monkeypatch功能是我应该看的地方,但我是自动化测试的新手,我正在寻找一个例子。

def foo(callback):
    callback('Buzz', 'Lightyear')

#--- pytest code ----
def test_foo():
    foo(hello)
    # how do I test that hello was called?
    # how do I test that it was passed the expected arguments?

def hello(first, last):
    return "hello %s %s" % first, last

提前谢谢。

2 个答案:

答案 0 :(得分:5)

这个想法仍然是一样的。

您需要将hello()函数替换为Mock,或者换句话说,“模拟”该函数。

然后,您可以使用assert_called_with()检查是否使用您需要的特定参数调用它。

答案 1 :(得分:1)

在应用@alecxe提供的答案后,这是我的工作代码。

def foo(callback):
    callback('Buzz', 'Lightyear')

#--- pytest code ---

import mock

def test_foo():
    func = mock.Mock()

    # pass the mocked function as the callback to foo
    foo(func)

    # test that func was called with the correct arguments
    func.assert_called_with('Buzz', 'Lightyear')

谢谢。

相关问题