微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在另一个函数中调用的模拟类方法

如何解决在另一个函数中调用的模拟类方法

我想模拟一个方法输出,它由不同模块中定义的函数调用。例如:

class_module.py

class my_class:
    def __init__(self,user):
        self.user = user

    def my_method(self):
        return [1,2,3]
    
    def other_methods(self):
        other_func(self.user)
        return "something I do not really want to mock"

function_module.py

from class_module import my_class

def my_fun():
    user = "me"
    foo = my_class(user)
    foo.other_methods()
    return foo.my_method()

test.py

@patch("function_module.my_class")
def test_my_fun(class_mock):
    class_mock.return_value.my_method.return_value = []
    bar = my_fun()

    assert bar == []

但是,我收到一个 AssertionError[1,3] != []。所以我想模拟永远不会发生在我想要的方法上。有人可以解释一下怎么做吗?为什么会发生这种情况?

编辑

实际上,所示的实现不起作用,因为测试正在启动一个完全独立的过程。因此,不能模拟任何函数。对不起,我的误解

解决方法

patch.object 允许修补类的特定方法。

class_module.py

class MyClass:
    def __init__(self,user):
        self.user = user

    def my_method(self):
        return [1,2,3]

    def other_methods(self):
        return "anything"

function_module.py

from class_module import MyClass


def my_fun():
    user = "me"
    foo = MyClass(user)
    assert foo.other_methods() == "anything"
    return foo.my_method()

test_my_func.py

from unittest.mock import patch

from class_module import MyClass
from function_module import my_fun


@patch.object(MyClass,"my_method")
def test_my_fun(my_method):
    # given
    any_value = [99,98,97]
    my_method.return_value = any_value

    # when
    result = my_fun()

    # then
    assert result == any_value

有了这些文件,pytest test_my_func.py 成功通过。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。