How to mock a function inside another function?

I am trying to make fun of this function call with another function without success. How can I do it?

from mock import patch
from path.to.a import function_a

@patch("class_b.function_c")
def test_method(self, method_to_mock):
    method_to_mock.return_value = 7890
    result = function_a() #error - type object 'class_b' has no attribute 'function_c'

#another module -- "path.to.a module"
def function_a():
    return class_b.function_c()

#another module
class class_b(class_c):
    pass

#another module
class class_c():
    @classmethod
    def function_c():
        return 123
+4
source share
1 answer

There are two problems in the code:

1) The class method is not declared correctly

class class_c():
    @classmethod
    def function_c(cls):
        return 123

2) @patch is used incorrectly. You need to change it to

def mock_method(cls):
    return 7890

# asssume the module name of class_b is modb
@patch("modb.class_b.function_c", new=classmethod(mock_method))
def test_method():
    result = function_a() 
    print result # check the result
+1
source

All Articles