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.
Written by Marko Klemetti
Related protips
2 Responses
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
@arpohahau Thanks! I'll add it to the tip.