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 example.has_been_called: print("foo bar")
How would I do this?
You can log a message when the function is called using: Debug. Log("Function called!"); You can store a bool that starts as false and set it to true when you enter the function. You can then check this bool elsewhere in code to tell whether your function has been called.
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
If it's OK for the function to know its own name, you can use a function attribute:
def example(): example.has_been_called = True pass example.has_been_called = False example() #Actual Code!: if example.has_been_called: print("foo bar")
You could also use a decorator to set the attribute:
import functools def trackcalls(func): @functools.wraps(func) def wrapper(*args, **kwargs): wrapper.has_been_called = True return func(*args, **kwargs) wrapper.has_been_called = False return wrapper @trackcalls def example(): pass example() #Actual Code!: if example.has_been_called: print("foo bar")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With