Python Unit Testing with unittest: Reference and Examples

Python Unit Testing with unittest: Reference and Examples

Last updated:
Table of Contents

Basic testing

.
├── mylib.py
│ 
└── mytest.py
# mylib.py
def sum_integers(a,b):
    return a+b
# mytest.py
import unittest

import mylib

class MyTests(unittest.TestCase):
    def test1(self):
        # test code here
        expected = 100
        actual = mylib.sum_integers(50,50)

        self.assertEqual(expected, actual, "summing 50 and 50 must equal 100")

if __name__ == '__main__':
    unittest.main()

Save this file as mytest.py and call it as you would a regular script:

$ python mytest.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Assert exception is raised

The code within the with block must raise an exception, or else the test case fails.

import unittest

import mylibs

class MyTests(unittest.TestCase):
    def testException(self):

        with self.assertRaises(IOError):
            # this raises an exception
            mylibs.methodThatRaisesException('some input')

if __name__ == '__main__':
    unittest.main()

Run a single test from a class

Pass the class name and the method names as command-line arguments.

For example:

If mytests.py has the following contents:

# mytests.py
import unittest

class MyTests(unittest.TestCase):

    def test1(self):
        # test code here
        pass

    def test2(self):
        # test code here
        pass

class MyOtherTests(unittest.TestCase):

    def test1(self):
        # test code here
        pass

    def test2(self):
        # test code here
        pass

if __name__ == '__main__':
    unittest.main()

To run all tests in the file:

$ python mytests.py.

To run all tests in class MyTests:

$ python mytests.py MyTests

To run just test2 in class MyOtherTests:

$ python mytests.py MyOtherTests.test1

Group tests in suit

Create a file called run_all_tests.py and add all tests from other files into it:

# run_all_tests.py
import unittest

# let MyTests and MyOtherTests be class that inherit from 
# unittest.TestCase as in the examples above
from mytests import MyTests
from mytests import MyOtherTests

suite1 = unittest.TestLoader().loadTestsFromTestCase(MyTests)
suite2 = unittest.TestLoader().loadTestsFromTestCase(MyOtherTests)

all_tests = unittest.TestSuite([suite1, suite2])

unittest.TextTestRunner().run(all_tests)

Running:

$ python run_all_tests.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

Assert print output

References