How to get the call count using Mock @patch?

I’d not use mocked_post as the new argument here. I’d set up the side_effect attribute of a fresh Mock instead:

@patch('mylib.requests.post')
class MyTest(TestCase):

    def test_foo(self, post_mock):
        post_mock.side_effect = mocked_post

        # Some test logic

        self.assertEqual(post_mock.call_count, 3)

Now you have the Mock object that patch generates for you as an argument to all your test methods, and you can thus test how many times that mock was called.

You should be able to set the side_effect attribute in the decorator as well, to apply to all tests:

@patch('mylib.requests.post', side_effect=mocked_post)
class MyTest(TestCase):

    def test_foo(self, post_mock):
        # Some test logic

        self.assertEqual(post_mock.call_count, 3)

You’ll still have trouble accessing the returned response object, however; you may want to return mock.DEFAULT from mocked_post instead of creating one in the function, so that you can then use post_mock.return_value to make further assertions on the returned object.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)