Saturday, March 27, 2010

Python - unit tests with the unittest module

# python has a built in unit test module "unittest"
#

# Using python's unittest module is similar to NUnit
# or JUnit (if you are familiar with those).
#


import unittest


# my example function
# Normally you would have the class in its own
# file and then just import ExampleFunction into

# the unit test file.
class ExampleFunction(object):
    def __init__(self):
        self.example = 0
        self.example2 = 1
        self.example3 = 2
    def processVariable(self, item):
        item *= self.example2 * self.example3
        return item
    def setExampleVariables(self, example):
        self.example = example
        self.example2 = self.example + 1
        self.example3 = self.example2 + 1


# The test class inherits from unittest's TestCase.
# Inheriting ensures that the tests will run when you
# call unittest.Main()
class TestExampleFunction(unittest.TestCase):
    def setUp(self):
        self.ef = ExampleFunction()
    def test_defaults(self):
        # There are a lot types of asserts available

        # I only demo the assertEqual here.
        self.assertEqual(self.ef.example, 0, "example is not set to 0")
        self.assertEqual(self.ef.example2, 1, "example2 is not set to 1")
        self.assertEqual(self.ef.example3, 2, "example3 is not set to 2")
    def test_processVariable(self):
        self.assertEqual(self.ef.processVariable(1), 2, "example error message")
    def test_setExampleVariables(self):
        self.ef.setExampleVariables(5)
        self.assertEqual(self.ef.example, 5, "example is not set to 0")
        self.assertEqual(self.ef.example2, 6, "example2 is not set to 1")
        self.assertEqual(self.ef.example3, 7, "example3 is not set to 2")


if __name__ == '__main__':
    unittest.main()


# My Output:
#    ...
#    -------------------------------------
#    Ran 3 tests in 0.000s
#
#    OK


No comments:

Post a Comment