The meaning of a class method that is used through an instance

I am trying to fix a class method using mock as described in the documentation . The Mock object itself works fine, but its methods are not executed: for example, their attributes, such as call_count , are not updated, even if the method_calls attribute of the class Mock object. More importantly, their return_value attribute return_value ignored:

 class Lib: """In my actual program, a module that I import""" def method(self): return "real" class User: """The class I want to test""" def run(self): l = Lib() return l.method() with patch("__main__.Lib") as mock: #mock.return_value = "bla" # This works mock.method.return_value = "mock" u = User() print(u.run()) >>> mock <MagicMock name='Lib().method()' id='39868624'> 

What am I doing wrong here?

EDIT: passing the Mock class through the constructor does not work either, so this is not related to the patch function.

+8
python unit-testing mocking
source share
3 answers

I found my mistake: in order to configure my layout methods, I have to use mock().method instead of mock.method .

 class Lib: """In my actual program, a module that I import""" def method(self): return "real" class User: """The class I want to test""" def run(self): l = Lib() return l.method() with patch("__main__.Lib") as mock: #mock.return_value = "bla" # This works mock().method.return_value = "mock" u = User() print(u.run()) 
+14
source share
 from mock import * class Lib: """In my actual program, a module that I import""" def method(self): return "real" class User: """The class I want to test""" def run(self, m): return m.method() with patch("__main__.Lib") as mock: #mock.return_value = "bla" # This works mock.method.return_value = "mock" print User().run(mock) 
+1
source share

I mock such methods:

 def raiser(*args, **kwargs): raise forms.ValidationError('foo') with mock.patch.object(mylib.Commands, 'my_class_method', classmethod(raiser)): response=self.admin_client.get(url, data=dict(term='+1000')) 
+1
source share

All Articles