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

guy*_*yja 3 python testing mocking pytest python-2.7

我无法找到在文档,谷歌或此处使用pytest测试回调的具体示例.我发现了这个:使用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
Run Code Online (Sandbox Code Playgroud)

先感谢您.

ale*_*cxe 5

这个想法仍然是一样的.

你需要hello()模拟替换函数,换句话说,"模拟"函数.

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

  • @guyja 好吧,一般来说,如果您想要良好的覆盖率或测试特定的难以重现的情况,`mock` 模块是必备工具。对于模拟本身,使用什么测试框架并不重要。很长一段时间以来,我一直在使用带有“nose”的“mock”。 (2认同)

guy*_*yja 5

这是应用@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')
Run Code Online (Sandbox Code Playgroud)

谢谢。