A Simple Testing Framework for Python


python A Simple Testing Framework for Python python

python

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:

1
2
3
4
5
6
7
8
9
10
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.")
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
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:

1
2
3
def sample_test():
    if 1 != 2:
        raise Exception("Failing this on purpose.")
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:

1
2
3
4
def assert_test(condition, msg):
    if condition:
        return True
    raise Exception(msg)
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) —

GD Star Rating
loading...
491 words
Last 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

The Permanent URL is: A Simple Testing Framework for Python

Leave a Reply