pythonunit-testingtestingmockingpython-mock

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?


Solution

  • 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.