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)
先感谢您.
这个想法仍然是一样的.
你需要hello()用模拟替换函数,换句话说,"模拟"函数.
然后,您可以使用assert_called_with()来检查是否使用您需要的特定参数调用它.
这是应用@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)
谢谢。