jeudi 24 décembre 2020

Mock class method that is called within another function

I want to mock a class method's output, which is called by a function defined in a different module. For example:

class_module.py

class my_class:
    def __init__:
        self.a = 1

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

function_module.py

from class_module import my_class

def my_fun():
    foo = my_class()
    return foo.my_method()

test.py

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

    assert bar == []

However, I am getting an AssertionError saying that [1,2,3] != []. So I guess the mock is never happening on the method I want. Can somebody explain how to do it? And why is this happening?

PS: I have also tried patching as follows:

@patch("function_module.my_class.my_method")

Aucun commentaire:

Enregistrer un commentaire