UnitTest Framework – API

UnitTest Framework - API

UnitTest Framework – API chapter discusses the classes and methods defined in the unit test module. There are five major classes in this module.

Type of classes UnitTest Framework – API :-

TestCase Class

The object of this class represents the smallest testable unit. It holds the test routines and provides hooks for preparing each routine and for cleaning up thereafter.

The following in TestCase class −

Sr.No.Method & Description
1setUp()Method called to prepare the test fixture. This is called immediately before calling the test method
2tearDown()Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception,
3setUpClass()A class method called before tests in an individual class run.
4tear down class()A class method called after tests in an individual class has run.
5run(result = None)Run the test, collecting the result into the test result object passed as a result.
6skipTest(reason)Calling this during a test method or setUp() skips the current test.
7debug()Run the test without collecting the result.
8shortDescription()Returns a one-line description of the test.

Fixtures

TestCase includes a special hook to configure and clean up any fixtures needed by your tests. To configure the fixtures, override setUp(). To clean up, override tearDown().

In the following example, two tests are written inside the TestCase class. They test the result of addition and subtraction of two values.

import unittest

class simpleTest2(unittest.TestCase):
   def setUp(self):
      self.a = 10
      self.b = 20
      name = self.shortDescription()
      if name == "Add":
         self.a = 10
         self.b = 20
         print name, self.a, self.b
      if name == "sub":
         self.a = 50
         self.b = 60
         print name, self.a, self.b
   def tearDown(self):
      print '\nend of test',self.shortDescription()

   def testadd(self):
      """Add"""
      result = self.a+self.b
      self.assertTrue(result == 100)
   def testsub(self):
      """sub"""
      result = self.a-self.b
      self.assertTrue(result == -10)
      
if __name__ == '__main__':
   unittest.main()

Run the above code from the command line. It gives the following output −

C:\Python27>python test2.py
Add 10 20
F
end of test Add
sub 50 60
end of test sub
.
================================================================
FAIL: testadd (__main__.simpleTest2)
Add
----------------------------------------------------------------------
Traceback (most recent call last):
   File "test2.py", line 21, in testadd
      self.assertTrue(result == 100)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.015s

FAILED (failures = 1)

Class Fixture

Both the methods are class methods @classmethod directive.

The following example demonstrates the use of these class methods −

import unittest

class TestFixtures(unittest.TestCase):

   @classmethod
   def setUpClass(cls):
      print 'called once before any tests in class'

   @classmethod
   def tearDownClass(cls):
      print '\ncalled once after all tests in class'

   def setUp(self):
      self.a = 10
      self.b = 20
      name = self.shortDescription()
      print '\n',name
   def tearDown(self):
      print '\nend of test',self.shortDescription()

   def test1(self):
      """One"""
      result = self.a+self.b
      self.assertTrue(True)
   def test2(self):
      """Two"""
      result = self.a-self.b
      self.assertTrue(False)
      
if __name__ == '__main__':
unittest.main()

TestSuite Class

Python’s testing framework provides a useful mechanism by which test case instances can be grouped together according to the features they test. This mechanism is made available by the TestSuite class in the unit test module.

The following steps are involved in creating and running a test suite.

Step1 − Create an instance of TestSuite class.

suite = unittest.TestSuite()

Step2 − Add tests inside a TestCase class in the suite.

suite.addTest(testcase class)

Step3 − You can also use the make Suite() method to add tests from a class

suite = unittest.makeSuite(test case class)

Step4 − Individual tests can also be added to the suite.

suite.addTest(testcaseclass(""testmethod")

Step5 − Create an object of the TestTestRunner class.

runner = unittest.TextTestRunner()

Step6 − Call the run() method to run all the tests in the suite

runner.run (suite)

The following methods are defined in TestSuite class −

Sr.No.Method & Description
1add Test()Adds a test method in the test suite.
2add Tests()Adds tests from multiple TestCase classes.
3run()Runs the tests associated with this suite, collecting the result into the test result object
4debug()Runs the tests associated with this suite without collecting the result.
5count test cases()Returns the number of tests represented by this test object

The following example shows how to use TestSuite class −

import unittest
class suiteTest(unittest.TestCase):
   def setUp(self):
      self.a = 10
      self.b = 20
      
   def testadd(self):
      """Add"""
      result = self.a+self.b
      self.assertTrue(result == 100)
   def testsub(self):
      """sub"""
      result = self.a-self.b
      self.assertTrue(result == -10)
      
def suite():
   suite = unittest.TestSuite()
##   suite.addTest (simpleTest3("testadd"))
##   suite.addTest (simpleTest3("testsub"))
   suite.addTest(unittest.makeSuite(simpleTest3))
   return suite
   
if __name__ == '__main__':
   runner = unittest.TextTestRunner()
   test_suite = suite()
   runner.run (test_suite)

You can experiment with the addTest() method by uncommenting the lines and comment statement having the make site() method.

TestLoader Class

The unit test package has the TestLoader class which is used to create test suites from classes and modules. By default, the unit test.defaultTestLoader instance is automatically created when the unit test.main(0 methods are called. An explicit instance, however, enables the customization of certain properties.

In the following code, tests from two classes are collected in a List by using the TestLoader object.

import unittest
testList = [Test1, Test2]
testLoad = unittest.TestLoader()

TestList = []
for testCase in testList:
   testSuite = testLoad.loadTestsFromTestCase(testCase)
   TestList.append(testSuite)
   
newSuite = unittest.TestSuite(TestList)
runner = unittest.TextTestRunner()
runner.run(newSuite)

The following table shows a list of methods in the TestLoader class −

Sr.NoMethod & Description
1loadTestsFromTestCase()Return a suite of all tests cases contained in a TestCase class
2loadTestsFromModule()Return a suite of all tests cases contained in the given module.
3loadTestsFromName()Return a suite of all tests cases given a string specifier.
4discover()Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object

T estResult Class

This Result object stores the results of a set of a TestResult TestRunner.run() method.

This Result instances have the following attributes −

Sr.No.Attribute & Description
1Errors A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test that raised an unexpected exception.
2Failures A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signaled using the TestCase.assert*() methods.
3Skipped A list containing 2-tuples of the TestCase instances and strings holding the reason for skipping the test.
4Was Successful()Return True if all tests run so far have passed, otherwise returns False.
5Stop()This method can be called to signal that the set of tests being run should be aborted.
6Start Test Run()Called once before any tests are executed.
7StopTest Run()Called once after all tests are executed.
8Tests Run The total number of tests run so far.
9BufferIf set to true, sys.stdout and sys.stderr will be buffered in between startTest() and stopTest() being called.

The following code executes a test suite −

if __name__ == '__main__':
   runner = unittest.TextTestRunner()
   test_suite = suite()
   result = runner.run (test_suite)
   
   print "---- START OF TEST RESULTS"
   print result

   print "result::errors"
   print result.errors

   print "result::failures"
   print result.failures

   print "result::skipped"
   print result.skipped

   print "result::successful"
   print result.wasSuccessful()
   
   print "result::test-run"
   print result.testsRun
   print "---- END OF TEST RESULTS"

The code when executed displays the following output −

---- START OF TEST RESULTS
<unittest.runner.TextTestResult run = 2 errors = 0 failures = 1>
result::errors
[]
result::failures
[(<__main__.suiteTest testMethod = testadd>, 'Traceback (most recent call last):\n
   File "test3.py", line 10, in testadd\n 
   self.assertTrue(result == 100)\nAssert
   ionError: False is not true\n')]
result::skipped
[]
result::successful
False
result::test-run
2
---- END OF TEST RESULTS

Next Topic – Click Here

This Post Has One Comment

Leave a Reply