def divide(a,b): #simple example, e.g. 'hello world'
return a/b
This is based on the original example found in this Youtube video about the "Getting started with automated testing" talk given by Carl Meyer at PyCon 2013 in Santa Clara. The video can also be watched at the bottom of this notebook.
def test_unity():
assert divide(1,1)==1
def test_bad(): #this is just to show a bad test example
assert divide(1,2)==2
def test_zero_divide(): #this should through an error
assert divide(1,0)==inf
for func in test_unity, test_bad, test_zero_divide:
try:
func()
except Exception as e:
print("{} FAILED: {}".format(func.__name__, e))
else:
print("{} Passed.".format(func.__name__))
test_unity Passed. test_bad FAILED: test_zero_divide FAILED: division by zero
The advantage of this version is that is takes up less screen space in the notebook since each additional test takes up only one line.
# Each test in the list of tests is a dictionary that contains
# the test name as a key with the value being a tuple, of a
# tuple of the function arguments, and the expected result of
# the function.
tests = [{'bad test':((1,2),2)},
{'unity test':((1,1),1)},
{'Zero divide':((1,0),inf)}]
for Test in tests:
Name = list(Test.keys())[0]
arg ,result = Test[Name]
try:
assert divide(*arg)==result #the test is implemented here
except Exception as e:
print("{} - FAILED: {}".format(Name, e))
else:
print("{} - Passed.".format(Name))
bad test - FAILED: unity test - Passed. Zero divide - FAILED: division by zero
from IPython.display import YouTubeVideo
YouTubeVideo('ukm64IUANwE')