Simple Test in Python

Testing is the process of knowing whether the code is successfully executed or not. In Python there is a inbuilt module unittest, which give us whether the Test condition is True or false.

Unit test

The test condition should be written as a separate program. The name of the program should be either test_filename.py or filename_test.py. Let’s write a program to find square of a number.

Save the file name as Square.py

def sq(n):

return n*n

Test code

To write the test code, first we want to import unittest module which is a inbuilt module.

import unittest

from square import sq

Class Testing (unittest.TestCase):

def test_sq(self):

r = sq(5)

self.assertEqual(r, 25)

Thus when we execute the text file, the output will be.

————————————————–

Ran test 1 in 0.00s

OK

Assert functions

Python has many inbuilt functions to test the functions. One of it is assert function. There are many functions like assertTrue, assertFalse, assertEqual, assertNotEqual and so on.

Testing Exception

Exception can be handled in Python using assertRaises function. In case of division by zero, we can raise the exception by.

self.assertRaises(ZeroDivisionError, Divnum, 0)

Test Coverage

Test Coverage method is used to detect untested part of the code. We can install it by simply typing

pip install coverage

Leave a comment