To test that two functions return the same value, you can use the assert
statement in Python. Here’s an example of how to do it:
def function1(): return 5 def function2(): return 5 assert function1() == function2()
In this example, we have two functions function1
and function2
that both return the integer value 5
. We use the assert
statement to check that the return value of function1
is equal to the return value of function2
. If the assertion fails (i.e., the values are not equal), then Python will raise an AssertionError
with a message indicating what went wrong.
You can modify this example to use your own functions and the expected return value. For example:
def function1(): return "hello world" def function2(): return "hello world" assert function1() == function2()
This code will pass the assertion since both functions return the same string value “hello world”. If the functions returned different values, the assertion would fail and raise an AssertionError
.
This is how you can run up to 1 million tests using the for loop + range()
:
if __name__ == "__main__": # for testing for i in range(1,1000000): assert function1() == function2(), "Results are not equal" print("All tests passed")
This article is part of Broplanner’s Python tips
Leave a Reply