Find Out If a Function has been Called

前端 未结 5 1374
遇见更好的自我
遇见更好的自我 2020-12-05 08:18

I am programming in Python, and I am wondering if i can test if a function has been called in my code

def example():
    pass
example()
#Pseudocode:
if exam         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-05 08:30

    A minimal example using unittest.mock.Mock from the standard library:

    from unittest.mock import Mock
    
    def example():
        pass
    
    example_mock = Mock(side_effect=example)
    example_mock()
    #Pseudocode:
    if example_mock.called:
       print("foo bar")
    

    Console output after running the script:

    foo bar
    

    This approach is nice because it doesn't require you to modify the example function itself, which is useful if you want to perform this check in some unit-testing code, without modifying the source code itself (EG to store a has_been_called attribute, or wrap the function in a decorator).

    Explanation

    As described in the documentation for the unittest.mock.Mock class, the side_effect argument to the Mock() constructor specifies "a function to be called whenever the Mock is called".

    The Mock.called attribute specifies "a boolean representing whether or not the mock object has been called".

    The Mock class has other attributes you may find useful, EG:

    call_count: An integer telling you how many times the mock object has been called

    call_args: This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with

    call_args_list: This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list

    The Mock class also has convenient methods for making assert statements based on how many times a Mock object was called, and what arguments it was called with, EG:

    assert_called_once_with(*args, **kwargs): Assert that the mock was called exactly once and that that call was with the specified arguments

提交回复
热议问题