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 nose.tools 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

    @raises(ValueError)
    def test_add_zero_raises_error(self):
        self._counter.add(0)

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

if __name__ == '__main__':
    import nose
    nose.runmodule()
In order to execute all tests just run the following:
test1@deby:~$ python noseexample.py
...S
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK (SKIP=1)
You can run doctests with nose. The easiest way to do so is to add the following to your setup.cfg file:
[nosetests]
verbosity=1
with-doctest=1
And use command-line:
nosetest noseexample.py
Read more about nose testing tools here.

No comments :

Post a Comment