[Python] How to get the call count using Mock @patch?

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I am writing a unit test for some library we are working on. This library makes use of requests.post() to perform POST HTTP requests to an external server.

    Inside my UT, I obviously don't want to contact the real server but to mock the response.

    To do that, I wrote a function that goes like:

    def mocked_post(url, headers, data, **kwargs):
    response = Mock()

    # Some logic, irrelevant here.

    return response


    And I patched this function around my unit test class:

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

    def test_foo(self):
    # Some test logic


    This is working perfectly.

    Now I'd like to get the number of calls to my mocked function. I tried mocked_post.call_count but that doesn't exist. I tried to find this property on a lot of different objects (including mylib.requests.post) but no luck so far.

    How can I access the call_count for this mocked function ?

    Continue reading...

Compartilhe esta Página