White Box Testing
Test your code
   Home      UnitTestingWithPyUnit
 

'PyUnit', is a Python language version of JUnit. JUnit was written by smart cookies Kent Beck and Erich Gamma, and is, in turn, a Java version of Kent's Smalltalk testing framework. Each is the de facto standard unit testing framework for its respective language, and therefore both are a strong basis for an effective and elegant Python framework.
 
1) Create class file to be tested ‘calc.py’
 
class Calc(object):
    '''
    Operands
    attributes: a, b
    '''
    def __init__(self, a, b):
        self.a = a
        self.b = b
       
    def add(self):
        return int(self.a) + int(self.b)
   
    def subtract(self):
        return int(self.a) - int(self.b)
   
    def multiply(self):
        return int(self.a) * int(self.b)
   
    def divide(self):
        try:
            result = int(self.a)/ int(self.b)
        except ZeroDivisionError:
            print("Result:Division by zero ERROR!")
        else:
            return result     
 
2) Create test class ‘calcTest.py’
 
3) Import required classes unittest and the class to be tested
import unittest
import calc
 
 
class CalcTest(unittest.TestCase):
 
 
setUp():will be called before each test method in test class
tearDown():will be called after each test method in test class
setUpClass():will be called before individual test class
tearDownClass():will be called after individual test class
 
   
    def setUp(self):
        print("Creating a new Calc...")
        self.calc1 = calc.Calc(15,3)
       
    def tearDown(self): 
        print("Destroying Calc...")
        self.calc1 = None 
 
 
Following decorators can be used to skip particular test
unittest.skip(reason):Unconditionally skip the decorated test. reason should describe why the test is being skipped.
unittest.skipIf(condition, reason):Skip the decorated test if condition is true.
unittest.skipUnless(condition, reason):Skip the decorated test unless condition is true.
unittest.expectedFailure():Mark the test as an expected failure. If the test fails when run, the test is not counted as a failure.
unittest.SkipTest(reason):This exception is raised to skip a test.
 
Following asserts can be used to check methods and reports
assertEqual(a, b, msg=None) a == b
assertNotEqual(a, b, msg=None) a != b
assertTrue(x, msg=None) bool(x) is True
assertFalse(x, msg=None) bool(x) is False
assertIs(a, b, msg=None)a is b
assertIsNot(a, b, msg=None) a is not b
assertIsNone(x, msg=None) x is None
assertIsNotNone(x, msg=None) x is not None
assertIn(a, b, msg=None) a in b
assertNotIn(a, b, msg=None) a not in b
assertIsInstance(a, b, msg=None) isinstance(a, b, msg=None)
assertNotIsInstance(a, b, msg=None) not isinstance(a, b, msg=None)
assertRaises(exception, callable, *args, **kwds)
assertRaises(exception)
assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
assertRaisesRegexp(exception, regexp)
   
    def test_add(self):
        self.assertEqual(18,self.calc1.add())
       
    def test_subtract(self):
        self.assertEqual(12,self.calc1.subtract())
       
    def test_multiply(self):
        self.assertEqual(45,self.calc1.multiply())
       
    def test_devide(self):
        self.assertEqual(5,self.calc1.divide())
        calc1 = calc.Calc(15,0)
        self.assertRaises(ZeroDivisionError, calc1.divide())
       
    def test_fail(self):
        self.assertRaises(ZeroDivisionError, self.calc1.divide())
 
7) Make the entire script runnable and then use the test runner of unittest
We can also make separate test runner class
 
if __name__ == "__main__":
    unittest.main()
   
suite1 = unittest.TestLoader().loadTestsFromTestCase(CalcTest)
#suite2 = unittest.TestLoader().loadTestsFromTestCase(TestClass2)
#suite = unittest.TestSuite([suite, suite2])
#unittest.TextTestRunner(verbosity=2).run(suite)
unittest.TextTestRunner(verbosity=2).run(suite1)
 
 
 
http://docs.python.org/2/library/unittest.html