Thursday, May 27, 2010

Python unit testing with unittest module

The unittest module (also known as pyunit) is a unit test framework included in Python standard library. Let see how you can test the following:
class Counter:
    def __init__(self, value = 0):
        self.value = value
    
    def add(self, x):
        if not x:
            raise ValueError
        self.value += x
        return self.value
All test methods should start with word test by convention. Here is a unit test (file unittestexample.py):
import unittest

class CounterTestCase(unittest.TestCase):
    def setUp(self):
        """Automatically called by TestCase before and
           for each test method invoked
        """
        self._counter = Counter()

    def tearDown(self):
        """Automatically called by TestCase after and
           for each test method invoked
        """
        self._counter = None

    def test_initial_value(self):
        self.assertFalse(self._counter.value)
        
    def test_add(self):        
        self.assertEqual(5, self._counter.add(5))
        self.assertEqual(5, self._counter.value)

    def test_add_zero_raises_error(self):
        self.assertRaises(ValueError, lambda: self._counter.add(0))

    def skip_test_skip_me(self):
        assert False

if __name__ == '__main__':
    unittest.main()
In order to execute all tests just run the following (each dot corresponds to a test run):
test1@deby:~$ python unittestexample.py
...
---------------------------------------
Ran 3 tests in 0.000s
Verbose output:
python unittestexample.py -v
A selected test run:
python unittestexample.py CounterTestCase.test_add
Alternatively you can combine several test cases into test suites.
 ...

def suite():
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    suite.addTest(loader.loadTestsFromTestCase(CounterTestCase))
    return suite

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())
Here is file __init__.py
import unittest

import unittestexample

def suite():
    suite = unittest.TestSuite()
    suite.addTests(unittestexample.suite())
    return suite

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())
You can read more about unittest module here and here.

No comments :

Post a Comment