View with Opera!

Taming the Snake:
Python unit tests

Esteban Manchado Velázquez

Assumptions

Contents

The unittest module

Example unit test

import unittest

class WidgetSizeTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def tearDown(self):
        self.widget.dispose()
        self.widget = None

    def testDefaultSize(self):
        self.failUnless(self.widget.size() == (50,50),
                        'incorrect default size')

    def testResize(self):
        self.widget.resize(100,150)
        self.failUnless(self.widget.size() == (100,150),
                        'wrong size after resize')

Assertions

How do I run this?

import foo, unittest

suite = unittest.TestLoader(). \
            loadTestsFromModule(foo)
unittest.TextTestRunner().run(suite)

Conventions

By example

dev@machine$ ls -l tests/
total 4
-rw-r--r-- 1 dev dev 486 2009-08-31 12:48 test_serializer.py
dev@machine$ cat tests/test_serializer.py
import unittest, serializer

class BinarySerializationTestCase(unittest.TestCase):
    def setUp(self):
        self.serializer = Serializer()

    def tearDown(self):
        self.serializer = None

    def testNullSerialization(self):
        string = "\x00foobar\x00"
        result = self.serializer.serialize(string)
        self.failUnlessEqual(string,
                             self.serialize.unserialize(result),
                             'Serializing nulls should work')

Free advice

They

don't

make

sense.

Don't

write

them.

srsly.

Nosetests

By example

# All tests
nosetests

# All tests, show test names
nosetests -v

# Only this file
nosetests test_serializer.py

# Only this testcase
nosetests test_serializer.py:BinarySerializationTestCase

# Only this method inside this testcase!!!11
nosetests test_serializer.py:BinarySerializationTestCase. \
            testNullSerialization

Wrapping up

TESTS, MÖTHAFÖCKA, DO YOU WRITE THEM‽

Picture credits