Unittest

unittest supports you in test automation with shared setup and tear-down code as well as aggregation and independence of tests.

It provides the following test concepts:

Test Case

tests a single scenario.

Test Fixture

is a consistent test environment.

Test Suite

is a collection of several test cases.

Test Runner

runs through a Test Suite and displays the results.

Example

Suppose you have implemented the following add method in the test_arithmetic.py module:

1def add(x, y):
2    """
3    >>> add(7,6)
4    13
5    """
6    return x + y

… then you can test this method with a Unittest.

  1. To do this, you must first import your module and the unittest module:

    1import unittest
    2class TestArithmetic(unittest.TestCase):
    
  2. Then you can write a test method that illustrates your addition method:

    6class TestArithmetic(unittest.TestCase):
    7    def test_addition(self):
    8        self.assertEqual(arithmetic.add(7, 6), 13)
    9
    
  3. In order to import the unittests into other modules, you should add the following lines:

    23if __name__ == "__main__":
    24    unittest.main()
    
  4. Finally, all tests in test_arithmetic.py can be executed:

    $ bin/python test_arithmetic.py
    ....
    ----------------------------------------------------------------------
    Ran 4 tests in 0.000s
    
    OK
    
    C:> python test_arithmetic.py
    ....
    ----------------------------------------------------------------------
    Ran 4 tests in 0.000s
    
    OK
    

    … or a little more detailed:

    $ python test_arithmetic.py -v
    test_addition (__main__.TestArithmetic) ... ok
    test_division (__main__.TestArithmetic) ... ok
    test_multiplication (__main__.TestArithmetic) ... ok
    test_subtraction (__main__.TestArithmetic) ... ok
    
    ----------------------------------------------------------------------
    Ran 4 tests in 0.000s
    
    OK
    
    C:> Scripts\python test_arithmetic.py -v
    test_addition (__main__.TestArithmetic) ... ok
    test_division (__main__.TestArithmetic) ... ok
    test_multiplication (__main__.TestArithmetic) ... ok
    test_subtraction (__main__.TestArithmetic) ... ok
    
    ----------------------------------------------------------------------
    Ran 4 tests in 0.000s
    
    OK