python-3.x - 在 Pytest 中,如何检查一个方法是否是从另一个方法调用的?

标签 python-3.x mocking 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()

一些有用的链接:

关于python-3.x - 在 Pytest 中,如何检查一个方法是否是从另一个方法调用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63636108/

相关文章:

python - 频率和百分比不均匀组 sns barplot

python - Jupyter笔记本,从单元格输出多个表达式

python - 在 doctest (python) 中模拟 Y of (from X import Y)

javascript - 是否有等同于 pytest 的参数化固定装置的 Javascript?

testing - 如何使用 Pytest 仅使用特定参数将测试标记为 xfail

python - 如果测试通过,pytest fixture 可以清理吗?

python - 如何根据小时标准获得每天每组的最小值

python - 如何优化 100000 次迭代的 python 循环?

Typescript Jest 说我希望模拟的类型不存在 mock 或 mockReturnedValue

c# - 我如何使用最小起订量模拟一个集合