Building simple test cases in Python using unittest library

Posted by

python testing

Introduction to Python test cases:

In Python code development, building test cases in another aspect of creating quality and robust softwares. In this article I will show step by step of the bare minimum requirement to build the same. Python has quite a few number of libaries for building test cases like unittest, pytest  and mock library.

The Unittest Library of Python:

The Unittest library of python is a standard library that comes in bundled with every installation. It relies heavily on object oriented paradigm. Therefore, expect many objects, classes and its related terms. However, we can build test case of python codes that do not follow the same(OOPS).

In the following section I will show the process of building test cases of the python code that follows either OOPS or modular pattern.

Scenario 1: Building test case for  modular pattern python code :

Base Python code : sortDictbyKey function define below just sort dictionary by key.

The code below is inside a file called somefile.py

def sortDictbyKey(argDict):

    sortedDict = {k:v for k,v in sorted(argDict.items(),key=lambda keys:keys[0])}

    return sortedDict

dataDict = {'f':6,'n':3,'e':7}
Insert a print(dataDict) to get the output.
Output –> {‘f’: 6, ‘n’: 3, ‘e’: 7}

Uttitest Code:

The code below is inside a file called testSomefile.py

import unittest
from somefile import sortDictbyKey

class TestsortDictbyKey(unittest.TestCase):
    def test_sortDictbyKey(self):
    self.assertEqual(sortDictbyKey({'h':7,'d':4,'f':1}),{'d':4,'f':1,'h':7})

if __name__ == "__main__":
    unittest.main()

Explanation:

The above two files must be inside a same folder.
  1.  First two lines are used to import libraries. The second line is importing the sortDictbyKey function.
  2. Class TestsortDictbyKey(unittest.TestCase) –> defining a class name, the class is inheritated from unittest.TestCase
  3. def test_sortDictbyKey(self): –> defining the member function name, we have to prepend test_ for each function we want to test.
  4. self.assertEqual(sortDictbyKey({‘h’:7,’d’:4,’f’:1}),{‘d’:4,’f’:1,’h’:7}) –> assertEqual function compares the input and the output of the function we want to test. Dict in green is the input, dict in red is the output.
  5. if __name__ == “__main__”:
    unittest.main()—> is the boiler plate to run the unittest code.

The following image the output of the test case. Here the . means the test case is successfull.

test case result

Scenario 2: Building test case for  python code  with class:

Base Python code:

Explaination of the code below: Here is a student class that takes first name, last name score mark and full mark. The two member functions getEmail and percentageMark, creates emailid and calculates the percentage mark from the scored mark and full mark.

class Student:
    def __init__(self,firstName,LastName,scoredMark,fullMark):
    self.firstName = firstName
    self.lastName = LastName
    self.scoredMark = scoredMark
    self.fullMark = fullMark


    def getEmail(self):
        returnf'{self.firstName}{self.lastName}@gmail.com'

    def percentageMark(self):
       return int((self.scoredMark/self.fullMark) * 100)

def main():
  tom = Student("tom","boy",45,70)
  print(tom.getEmail())
  print(tom.percentageMark())

if __name__ == "__main__":
    main()

Unittest code for above Python class:

import unittest
from student import Student

class TestStudent(unittest.TestCase):
    def setUp(self):
       self.student1 = Student("gom","jom",50,100)
       self.student2 = Student("dick","son",23,30)

   def tearDown(self):
       delself.student1
       delself.student2
   
   def test_getEmail(self):
       self.assertEqual(self.student1.getEmail(),"gomjom@gmail.com")
       self.assertEqual(self.student2.getEmail(),"dickson@gmail.com")

   def test_percentageMark(self):
      self.assertEqual(self.student1.percentageMark(),50)
      self.assertEqual(self.student2.percentageMark(),76)

if __name__ == '__main__':
    unittest.main()

Explaination of the above Class:

  1. def setUp(self): –> create sample obect for testing
  2. def tearDown(self) –> destroyes sample object created by setUp method.
  3. test_getEmail(self) –> compares generated emailid with given email id.
  4. test_percentageMark(self) –> compares generated percentange with given percentage mark scored.

The Image below show the test results:

test result of python class

Conclusion:

There are multiple libraries in Python that helps us to create test cases. Another important library is mock. However, we need to use the most appropriate according to our need.

In this article we have learned to build test cases, hope you will find this article helpfull.

Leave a Reply

Your email address will not be published. Required fields are marked *