在 Pytest 中,如何检查一个方法是否是从另一个方法调用的? [英] In Pytest, how can I check if a method was called from another method?

查看:59
本文介绍了在 Pytest 中,如何检查一个方法是否是从另一个方法调用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 3.8 和 pytest 6.0.1.我有这门课

I'm using Python 3.8 and pytest 6.0.1. I have this class

class MyHelperService:
    def __init__(self, args):
        ...

    def my_method1(self):
        ... logic here ...  

然后在另一个类中,我调用上面的方法..

Then in another class, I invoke the method from the above ..

def main(req: func.HttpRequest) -> func.HttpResponse:
        ...
                sb = MyHelperService(args)
                sb.my_method1()

在 pytest 中,我如何模拟my_method1"?这样我就可以测试它是否被调用,而不必执行其中的所有逻辑?

How, in pytest, do I mock "my_method1" so that I can test that it was called without necessarily executing all the logic within it?

def test_run_it():
    ...
    resp = _import.main(req)

推荐答案

假设 MyHelperService 位于 my_project/my_helper_service.pymainmy_project/main.py 中,and 假设在 main 中导入类,如:

Assuming MyHelperService lives in my_project/my_helper_service.py, and main in my_project/main.py, and assuming that in main you import the class like:

from my_project.my_helper_service import MyHelperService

您可以像这样修补您的方法(我假设您根据评论使用另一个夹具 my_fixture):

you can patch your method like this (I assume that you use another fixture my_fixture as per the comments):

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 替换为只记录所有调用而不执行原始代码的模拟.请注意,模拟参数是位置参数,因此大多数是第一个参数,而夹具参数是​​关键字参数(必须位于位置参数之后).

This replaces method1 by a mock that just records all calls without executing the original code. Note that the mock arguments are positional arguments and therefore most be the first arguments, while fixture arguments are keyword arguments (that must be located after the positional arguments).

或者,您可以使用上下文管理器版本:

Alternatively, you can use the context manager version:

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:

or the mocker version, if you have installed 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()

一些有用的链接:

  • the documentation
  • this blog post by Ned Batchelder
  • this cheat sheet for mocking in Python

这篇关于在 Pytest 中,如何检查一个方法是否是从另一个方法调用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆