mercredi 25 décembre 2019

How to count function calls without mocking the function's logic?

I want to count how many times a function was called in a test. I cannot save the original function object in order to mock the function and still have the original logic. The reason is, that the function is being called from different instances of the class, which are created in the function itself.

For example:

class A(object):
    def do_something(self):
        new_instance = A()
        new_instance.do_something()
        ........

So, I cannot mock like this:

from mock import patch

def test():
    instance = A()
    original_do_something = instance.do_something

    with patch('A.do_something', original_do_something) as do_something_mock:
        instance.do_something()
        assert do_something_mock.call_count == 5

This will end up with StackOverflow, because all of the different instances of class A will call the original function of the first instance of A that I created. It will keep creating instances that will call the original do_something and create more instances, etc.

Does anyone know a way to count all of the function calls of do_something from all the different instances, without changing the logic?

(Python 2.7)

Thanks!

Aucun commentaire:

Enregistrer un commentaire