如何解决在Pytest中,如何检查是否从另一个方法调用了一个方法?
我正在使用Python 3.8和pytest 6.0.1。我有这堂课
class MyHelperService:
def __init__(self, args):
...
def my_method1(self):
... logic here ...
然后在另一个类中,我从上面调用方法..
def main(req: func.HttpRequest) -> func.HttpResponse:
...
sb = MyHelperService(args)
sb.my_method1()
如何在pytest中模拟“ my_method1”,以便我可以测试它是否被调用而不必执行其中的所有逻辑?
def test_run_it():
...
resp = _import.main(req)
解决方法
假设MyHelperService
生活在my_project/my_helper_service.py
中,而main
生活在my_project/main.py
中,和假设您在main
中导入了该类喜欢:
from my_project.my_helper_service import MyHelperService
您可以像这样修补您的方法(我假设您根据注释使用了另一个夹具my_fixture
)
from unittest import mock
@mock.patch("my_project.main.MyHelperService.my_method1")
def test_run_it(method1_mock,my_fixture):
...
resp = _import.main(req)
method1_mock.assert_called_once()
这将method1
替换为仅记录所有调用而无需执行原始代码的模拟。请注意,模拟参数是位置参数,因此大多数是第一个参数,而夹具参数是关键字参数(必须位于位置参数之后)。
或者,您可以使用上下文管理器版本:
def test_run_it(my_fixture):
...
with mock.patch("my_project.main.MyHelperService.my_method1") as method1_mock:
resp = _import.main(req)
method1_mock.assert_called_once()
或mocker
版本(如果已安装pytest-mock
:
def test_run_it(mocker,my_fixture):
...
method1_mock = mocker.patch("my_project.main.MyHelperService.my_method1")
resp = _import.main(req)
method1_mock.assert_called_once()
一些有用的链接:
- documentation
- 这个blog post,作者Ned Batchelder
- 此cheat sheet用于在Python中进行模拟
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。