Last Updated: February 25, 2016
· mrako

Unit testing in Python

Many think unit testing is difficult, complicated or requires lots of boilerplate code. This is however not true. Consider the following example in Python (let's name it unittest_example.py):

import unittest

class RomanNumerals:
  def convert(self, number):
      return "I"

class TestRomanNumeralsConverter(unittest.TestCase):
    def test_returns_I_for_1(self):
      self.assertEquals(RomanNumerals().convert(1), 'I')

if __name__ == '__main__':

I can hear some of you thinking "Cannot be true!" and "What about the dependencies, and installations?", but believe or not this code works in almost every OSX and Linux distribution out of the box by running:

$ python unittest_example.py

Ran 1 test in 0.000s

And by installing nose you can run all unit tests in your project with

$ nosetests

For more information and the rest of the assertion types, check out the official python unittest documentation

More about python projects, python installations and nosetests in Python: Creating Your Project Structure.

2 Responses
Add your response


thanks for sharing! simple yet useful. here are more assert statements for reference: http://docs.python.org/3.3/library/unittest.html?highlight=unittest#assert-methods

over 1 year ago ·

@arpohahau Thanks! I'll add it to the tip.

over 1 year ago ·