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?
You need to use
return_value
andPropertyMock
:This means: when calling
requests.post
, on the return value of that call, set aPropertyMock
for the propertyok
to return the valueTrue
.With mock version '1.0.1' the simpler syntax mentioned in the question is supported and works as is!
Example code updated (py.test is used instead of unittest):
Run this code with: (make sure you install pytest)
A compact and simple way to do it is to use
new_callable
patch
's attribute to forcepatch
to usePropertyMock
instead ofMagicMock
to create the mock object. The other arguments passed topatch
will be used to createPropertyMock
object.