Friday, May 28, 2010

Python unit testing with py.test module

You can install py.test issuing the following command:
easy_install py
py.test offers automatic test discovery:
from py.test import raises
from py.test import skip

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_method(self, state):
        """Automatically called by py.test before and
           for each test method invoked
        self._counter = Counter()

    def teardown_method(self, state):
        """Automatically called by py.test 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):
        raises(ValueError, self._counter.add, 0)

    def test_skip_me(self):
        skip('Not ready yet')
        assert False

if __name__ == '__main__':
In order to execute all tests just run the following:
test1@deby:~$ py.test
============================= test session starts ==================
test object 1: ...s

===================== 3 passed, 1 skipped in 0.08 seconds ==========
Read more about py.test features here.

No comments :

Post a Comment