Writing a Simple Testing Framework in Python
We often need to run some tests (unit tests or integration tests). We can organize the tests in such way:
testing = TestSuite()
# register test 1
testing.register_test(setup1, teardown1, test1)
# register test 2
testing.register_test(setup2, teardown2, test2)
if testing.run(continue_on_failure=True):
print("Passed.")
else:
print("Failed.")
We can specify optional setup and teardown function for each test. And also we can specify whether we want to continue testing the remaining tests if we have some failing tests. This is actually quite simple to implement. See following Python class TestSuite that stores the tests in an array of tuples (triplets).
The Teardown function is placed at finally statement so it is always called no matter what happens.
class TestSuite(object):
def __init__(self):
self.tests = []
## Register a Test
## with optional setup, teardown and the test function itself
def register_test(self, setup, teardown, test):
self.tests.append((setup, teardown, test))
## Run registered tests
def run(self, continue_on_failure = False):
succ = True
for setup, teardown, test in self.tests:
try:
if setup:
setup()
if test:
test()
except Exception as ex:
print(f"**Error** {ex}")
if continue_on_failure:
succ = False
continue
return False
finally:
try:
if teardown:
teardown()
except Exception as ex:
print(f"**Error at TearDown** {ex}")
if continue_on_failure:
succ = False
continue
return False
return succ
We can fail the tests by throwing an exception, see following:
def sample_test():
if 1 != 2:
raise Exception("Failing this on purpose.")
Of course, we can use existing testing framework which provides some assert functions such as “pytest“. Here is a simple replacement:
def assert_test(condition, msg):
if condition:
return True
raise Exception(msg)
Conclusion
We have shown that the simple class written in Python that allows us to write unit or integration tests in an organized way.
–EOF (The Ultimate Computing & Technology Blog) —
474 wordsLast Post: Teaching Kids Programming - Nearest Exit from Entrance in Maze via Iterative Deepening Search Algorithm (IDS)
Next Post: Teaching Kids Programming - Algorithms to Find the Pivot Integer of the First N Natural Numbers
