Saturday, May 29, 2010

Python unit testing with nose module

You can install nose issuing the following command:
easy_install nose
nose collects tests automatically, as long as you follow some simple guidelines for organizing test code.
from nose import SkipTest
from import raises

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

class TestCounter:
    def setup(self):
        """Automatically called by nose before and
           for each test method invoked
        self._counter = Counter()

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

    def test_initial_value(self):
        assert self._counter.value == 0

    def test_add(self):
        assert 5 == self._counter.add(5)
        assert 5 == self._counter.value

    def test_add_zero_raises_error(self):

    def test_skip_me(self):
        raise SkipTest("Not ready yet")
        assert False

if __name__ == '__main__':
    import nose
In order to execute all tests just run the following:
test1@deby:~$ python
Ran 4 tests in 0.000s

You can run doctests with nose. The easiest way to do so is to add the following to your setup.cfg file:
And use command-line:
Read more about nose testing tools here.

No comments :

Post a Comment