Python unittest

From wikinotes

UntTest is a python implementation of the xUnit testing suite. Tests are created in a separate file, and modules are tested one-by-one. It is not the simplest unittest for python, but it is the most universal so it deserves mentioning.

Usage

## Sample UnitTest File
import unittest												## Import UnitTest
from unnecessary_math import multiply					## Import Module being tested
 
class TestUM(unittest.TestCase):							## Create a test object (all tests are subclasses of unittest.TestCase)
     def setUp(self):
        pass

    def test_numbers_3_4(self):							## This is an example test function
        self.assertEqual( multiply(3,4), 12)			 # it checks that ( multiply(3,4) == 12 )

    def test_numbers_5_2(self):
        assert multiply(5,2) == 10


if __name__ == '__main__':									## if run from interpreter, run tests
    unittest.main()


Components

Setup & TearDown

Two special methods of all unittest.TestCase subclasses are setup and teardown. Setup is run before any test, and teardown is run after any test.

class TestUM(unittest.TestCase):							## Create a test object
     def setUp(self):
        pass

		def tearDown(self):
			pass


Package Setup/Teardown

In addition to the usual setup/teardown, you can create setup/teardown methods directly in a package's __init__.py file. These will be run before and after a collection of modules are being tested. This is convenient if you need to create a database to test against.

# (no example, but presumably would be another subclass of unittest.TestCase)


Discovery

unittests can also automatically import/discover testfiles under a python package. I think I'll be using nose though...

#### unittest can recurse down python packages importing and running
#### all unittests it encounters
.
|-- test_pylib
|   |-- __init__.py
|   |-- test_dirtools
|   |-- test_ostest
|   `-- test_subprocess
|
`-- test.py

#### test.py
import unittest

if __name__ == "__main__":
    suite = unittest.TestLoader().discover('.', pattern = "test_*.py")
    unittest.TextTestRunner(verbosity=2).run(suite)

#### CLI
python2 test.py

maxDiff

When you are asserting two large datastructures are equal, it is useful to turn off the maxDiff attribute:

import unittest


class Test_MyClass( unittest.TestCase ):
	def test_mytest( self ):
		self.maxDiff = None		## turns off maxdiff, so full diff is displayed.


References

References:
http://pythontesting.net/framework/unittest/unittest-introduction/