In computer programming unit testing is a method by which individual units of source code are tested to determine if they are fit for use. As a dynamic language python it is easier to test than other languages .This article will help you to learn about unit testing in python .
Unit testing in python mainly using the python standard library testing framework called unittest. Unit tests are for testing components of our code ,usually classes or functions.We can start from the standard libarary module unittest
The unittest module
Python unit test sometimes referred to as “PyUnit” is a python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in turn, a Java version of Kent’s Smalltalk testing framework. unittest support test for automation , sharing of setup and shutdown code for tests, aggregation of tests into collections and independance of tests from reporting frame work . The unittest module provide classes that make esay to support the above qualities for a set of tests.
Important concepts in unittest
- test fixure – represent preparation needed to perform one or more tests.
- test case – smallest unit of testing ,it check for a specific response for a particular set of input. unittest provide a base class ,TestCase which used to create test cases.
- test suite – collection of test cases
- test runner – component provide an environment in which tests can execute and provide outcome to user . runner use a graphical interface or textual interface or return a special value to indicate result of executing tests.
Creating test cases
Test cases are most fundamental part of unit testing. A test case answer a simple questions about the code it is testing also a test case run completely itself no need of any human input. It determine by itself whether the function it is testing has passed or failed, without any human interpreting the results. In PyUnit, test cases are represented by the TestCase class in the unittest module. To make your own test cases you must write subclasses of TestCase.
Here a simple example which i do from the official python tutorial creating test cases , we can test three functions from python random module.
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
self.assertRaises(ValueError,random.sample,self.seq,20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
In python a test case is created by subclassing unittest base class TestCase as follows,
class TestSequenceFunctions(unittest.TestCase)
Testcase defining test methods whose names are starting with ‘test’.Test methods performing actions and assert methods are to verify the expected behaviour and results. In the above program three functions in random module are tested, and we use three test methods.Each test is call to assert methods to check results. When a setUp() method is defined, the test runner will run that method prior to each test and when a tearDown() method is defined then test runner will run that method after all methods.
Testing for equality
The most common type of assertion is the assertion of equality between two values. If the assertion fails we got the incorrect result and our test will fail. In above example we check whether the sorted list from 0-9 numbers will equal to range(10). The result is true and test must pass.
assertEqual – This method test equality of two values, if the values are not equal test must fail and raise exception.
self.assertEqual(self.seq, range(10))
asserNotEqual – This method check two values are not equal .
self.assertNotEqual(1 + 2, 4)
Testing for exceptions
There is also testing for exceptions also known as testing for failure. It is not enough that function succed when given a good input , we must also test they fail when we given a bad input or they must fail as our expectations. TestCase class of unittest provide assertRaises method to check the expected exceptions ,which take following arguments,
- Exception you are expecting
- Function you are testing
- Arguments you are passing to function
In the above program test method test_sample test the exception
self.assertRaises(ValueError,random.sample,self.seq,20)
Here we select 20 random sample numbers from the range(10).We know that result will raise an exceptions and we use the assertRaises to get our expected exception as ValueError.
Testing for the truth
Some tests are assert the truth of some condition.In the above program test_choice method test the truthness. We select a random element from the sequence and test the presence of truth of statement.
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
Test Fixtures
Fixtures are the resources needed by a test , For example you are writing several tests for the same class ,those tests all need an instance of those class to use for testing. TestCase include functions to configure and clean up fixtures needed to our test. To configure fixtures override setUp() and clean up override tearDown().
Following a simple example to a test fixture ,
import unittest
class FixturesTest(unittest.TestCase):
def setUp(self):
print 'In setUp()'
self.fixture = range(1, 10)
def tearDown(self):
print 'In tearDown()'
del self.fixture
def test(self):
print 'in test()'
self.failUnlessEqual(self.fixture, range(1, 10))
if __name__ == '__main__':
unittest.main()</pre>
When we run this sample code we can see the order of execution of fixture and test method :
Running testes from the command line
unittest module contain a function called main ,which used to turn a test module into script that it will run the test conatins. unittest.main() automatically load test cases in the current module. When we excute our program in the command line as pyhton test_pgm.py then all tests will run and we get result as follows.

