Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock attributes in Python mock?

I'm having a fairly difficult time using mock in Python:

def method_under_test():     r = requests.post("http://localhost/post")      print r.ok # prints "<MagicMock name='post().ok' id='11111111'>"      if r.ok:        return StartResult()     else:        raise Exception()  class MethodUnderTestTest(TestCase):      def test_method_under_test(self):         with patch('requests.post') as patched_post:             patched_post.return_value.ok = True              result = method_under_test()              self.assertEqual(type(result), StartResult,                 "Failed to return a StartResult.") 

The test actually returns the right value, but r.ok is a Mock object, not True. How do you mock attributes in Python's mock library?

like image 938
Naftuli Kay Avatar asked May 31 '13 23:05

Naftuli Kay


People also ask

What is Side_effect in mock Python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.

Can you mock a variable Python?

With a module variable you can can either set the value directly or use mock.


2 Answers

You need to use return_value and PropertyMock:

with patch('requests.post') as patched_post:     type(patched_post.return_value).ok = PropertyMock(return_value=True) 

This means: when calling requests.post, on the return value of that call, set a PropertyMock for the property ok to return the value True.

like image 68
Simeon Visser Avatar answered Sep 23 '22 18:09

Simeon Visser


A compact and simple way to do it is to use new_callable patch's attribute to force patch to use PropertyMock instead of MagicMock to create the mock object. The other arguments passed to patch will be used to create PropertyMock object.

with patch('requests.post.ok', new_callable=PropertyMock, return_value=True) as mock_post:     """Your test""" 
like image 23
Michele d'Amico Avatar answered Sep 22 '22 18:09

Michele d'Amico