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?
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.
With a module variable you can can either set the value directly or use mock.
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.
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"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With