使用pytest测试回调的推荐方法是什么?
我在文档、谷歌或者这里的StackOverflow上找不到关于用pytest测试回调函数的具体例子。我找到这个链接:用Python unittest测试回调函数的正确方法是什么?;但那是关于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 个回答
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')
谢谢你。
6
这个想法还是一样的。
你需要把 hello()
这个函数换成一个叫做 Mock 的东西,简单来说,就是“模拟”这个函数。
然后你可以用 assert_called_with() 来检查这个函数是否用你需要的特定参数被调用过。