Pry - Writing Tests

A basic example

import libpry

class MySuite(libpry.AutoTree):
    def setUpAll(self):
        self.all_fixture = True

    def tearDownAll(self):
        self.all_fixture = False

    def setUp(self):
        self.fixture = True

    def tearDown(self):
        self.fixture = False

    def test_one(self):
        assert self.fixture
        assert self.all_fixture

    def test_two(self):
        d = dict()
        libpry.raises(KeyError, d.__getitem__, "foo")

    def test_three(self):
        d = dict(foo="one")
        # This will fail:
        assert d["foo"] == "two"

tests = [
    MySuite()
]
(examples/test_basic.py)

This example should look familiar to anyone who has used the built-in Python unittest module. The main points to note are:

  • setUpAll and tearDownAll run before and after the group of contained tests as a whole.

  • setUp and tearDown run before and after each of the contained tests.

  • pry is a tree-based test framework. AutoTree turns methods with names of the form "test_*" into test nodes automatically.

  • Unlike the built-in unittest module, pry does not automatically instantiate test suites. Instead, they need to be instantiated manually and added to a tests list in the module scope.

  • Test assertions are written using the assert keyword. Assertion errors are caught, and the failing expression is parsed and re-evaluated to give an informative error message.

Running the tests

From the examples in the pry distribution, we can run the tests as follows:

> pry test_basic.py
.E.

ERRORS
======
./test_basic.MySuite.test_three
    Traceback (most recent call last):
      File "./test_basic.py", line 27, in test_three
    assert d["foo"] == "two"
    AssertionError

    :: Re-evaluating expression:
    :: d["foo"] == "two"
    :: 'one' == 'two'


3 tests (pass: 2, fail: 1) - 0.001s

Copyright Nullcube 2008