Find Out If a Function has been Called

前端 未结 5 1389
遇见更好的自我
遇见更好的自我 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:25

    We can use mock.Mock

    from unittest import mock
    
    
    def check_called(func):
        return mock.Mock(side_effect=func)
    
    
    @check_called
    def summator(a, b):
        print(a + b)
    
    
    summator(1, 3)
    summator.assert_called()
    assert summator.called == True
    assert summator.call_count > 0
    
    summator.assert_called_with(1, 3)
    
    summator.assert_called_with(1, 5)  # error
    # AssertionError: Expected call: mock(1, 5)
    # Actual call: mock(1, 3)
    

提交回复
热议问题