hdji7a
Last Updated: February 25, 2016
·
936
· mrako
4fe949ea9ee7c0bc5eb4bf3e17b09d75

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__':
  unittest.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
OK

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.

Say Thanks
Respond

2 Responses
Add your response

2336
Thumb alyssa pohahau

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 ·
2337
4fe949ea9ee7c0bc5eb4bf3e17b09d75

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

over 1 year ago ·