我无法在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
提前谢谢。
答案 0 :(得分:5)
答案 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')
谢谢。