Tuesday, 4 March 2014

Unit Test In Python

Unit testing is testing individual "unit" or function of a program. Here we use TDD test driven development that is first write the test case then write the code . In python unit test is possible by "unittest" module .

  "isodd.py" is a program to convert any number to odd:
 class IsoddError(Exception): pass   
 class TypeError(IsoddError):pass  
 def isOdd(n):  
   if type(n)==int :  
      if n%2 != 0 :   
        return n  
      else:   
        return n+1        
   else:       
     raise TypeError,"Invalid"  

How to write test cases :

  1. First  write known result with known output
  2. Check the above cases
  3. next check failure of isOdd
here is the TDD code for isOdd:
 class TestData(unittest.TestCase):  
      TestData=( (0,1),  
           (1,1),  
                 (-1,-1),  
           (-2,-1),  
           (8,9),  
           (10,11),  
           (55,55),  
           (100,101) )  
      def testIsOddTestData(self):  
           """isOdd give known result with known output"""  
           for integer,fn_value in self.TestData:  
                result=isodd.isOdd(integer)  
                self.assertEqual(fn_value, result)  
 class IsOddBadInput(unittest.TestCase):  
      def testIsOddInput(self):  
           """isOdd fails for bad input"""  
           self.assertRaises(isodd.TypeError, isodd.isOdd, 'hello')  
   

To see the source code click here

1 comment:

  1. unittest is wonderfull... man tell me your contact info....

    ReplyDelete