Python Unit Testing

FREE Online Courses: Click, Learn, Succeed, Start Now!

There are many cases we would have come across or will be coming across in the future when we want to test if our code is working properly or not with different test cases. Do you know Python provides frameworks for the testing Purpose? In this article, we will be discussing one of these modules named ‘unittest’. So, let us start with the introduction to unit testing.

What is Python Unit Testing?

Before looking into the module, let us know what is unit testing?

Unit testing is the process of testing the small units of the program. This is done to make sure that each unit of the program is designed and working properly. The following modules are provided by Python for this purpose:
1. Unittest
2. PyTest
3. DocTest
4. Testify
5. Nose2
As said above we will be covering the first two modules. Let us first look at the Unittest.

Unittest Module

Unittest is one of the Python frameworks for unit testing. It is inspired by the JUnit framework used in the other programming languages. Its features include:

1. Test automation
2. Ability to share the setup and shutdown code for tests
3. Aggregation of the tests into collections
4. The tests are independent of the framework

When we want to test a code, we create a class that contains functions to test the particular unit of the program. The following are the OOPS concepts supported by this framework:

1. test fixture:

A test fixture can be thought of as preparation to run the tests and to ensure that there is a fixed environment in which tests are run so that results are repeatable.

2. test case:

A test case is a set of codes that are considered as a single unit while testing.

3. test suite:

It is a collection of test cases or test suites themselves or both.

4. test runner:

It is a component that is used for the execution of tests and to give the outputs to the user.

Now let us see an example.

Example of unit testing:

import unittest
def prod(a,b): #defining the function to be tested
    return a*b
class Tests(unittest.TestCase): #creating the class
    def test(self):  #method that tests the function 
        self.assertEqual(prod(4,-2),-8) #testing by calling the function and passing the predicted result
        
if __name__ == '__main__':
    unittest.main()

Output:

.
———————————————————————-
Ran 1 test in 0.003s
OK

We got the Output as OK as the output of prod(4,-2) and -8 match. There are three possible outputs:
1. OK: We get this output when all the tests are passed.
2. FAIL: We get this when the test did not pass and raise an AssertionError exception
3. ERROR: We get this when the test gives rise to an exception other than AssertionError.

Let us see what happens when we give wrong input in the 2nd argument.

Example of unit testing failed:

import unittest
def prod(a,b): #defining the function to be tested
    return a*b
class Tests(unittest.TestCase): #creating the class
    def test(self):  #method that tests the function 
        self.assertEqual(prod(5,4),-9) #testing by calling the function and passing the predicted result
        
if __name__ == '__main__':
    unittest.main()

Output:

F
======================================================================
FAIL: test (__main__.Tests)
———————————————————————-
Traceback (most recent call last):
File “<ipython-input-2-24f46f01c8ce>”, line 6, in test
self.assertEqual(prod(5,4),-9) #testing by calling the function and passing the predicted result
AssertionError: 20 != -9———————————————————————-
Ran 1 test in 0.002sFAILED (failures=1)

We can see that we got the output that the test failed since there is a mismatch.

Understanding with Another Example

Let us see another example of unit testing for further understanding.

Example of unit testing:

import unittest

def div(a,b):
    return a/b


class TestMethods(unittest.TestCase):
  def setUp(self): #Function that runs before each test to set any pre-requisites 
    pass

  def test_abs(self):
    self.assertEqual( abs(-5), 5) #tests if the absolute value of -5 is 5

  def test_pow(self):	  #tests if 2 to the power of 5 is 32 
    self.assertEqual(pow(2,5),32)

  # Tests and returns TRUE if the boolean value is non empty or non 0
  # or else returns False.
  def test_bool(self):		
    self.assertTrue(bool(5))
    self.assertFalse(bool(''))

  # Returns true if the string splits and matches
  # the given output.
  def test_div(self):		
    s = 'hello world'
    self.assertEqual(div(2,5),0.4)
    with self.assertRaises(ZeroDivisionError):
      div(2,0)
        
if __name__ == '__main__':
    unittest.main()

Output:

….
———————————————————————-
Ran 4 tests in 0.003sOK

In the above example, we used the functions assertEqual(), assertTrue(), assertFalse() and assertRaises(). The
1. assertEqual() is used to check if the result in the first argument matches the one in the 2nd argument.
2. assertTrue() and assertFalse() verify if the given input statement is True or False
3. assertRaises() returns the specified exception

Also, observe that each of the functions in the class TestMethods() starts with the keyword ‘test’ followed by an underscore and the function name. The
1. setUp() function is a default function in the Unittest that is executed before the execution of each test.
2. test_abs checks if the absolute value of -5, the first argument, is equal to 5 ( the 2nd argument.
3. Similarly, test_pow checks if 2 to the power of 5 is equal to 32.
4. test_bool checks the boolean value acquired from the argument and checks if it is equal to the particular boolean based on the assert() method used.
5. test_div checks if the division of 2/5 is 0.4. And also it checks if an exception is raised if the denominator is 0.
Finally, unittest.main() function provides a command-line interface to the test script. Its outputs describe if the test ran correctly or if it failed.

Python assert() methods

In the above examples, we have seen a few assert() methods like Equal, True, etc. These can be used to do different types of tests.
Let us see some more and their meaning.

1. assertEqual(): Tests if the values of the two arguments are equal or not.
2. assertNotEqual(): Tests if the values of the two arguments are unequal or not.
3. assertTrue(): Tests if the argument outputs a Boolean True.
4. assertFalse(): Tests if the argument outputs a Boolean False.
5. assertIs(): Tests if the given arguments evaluate belong to the same object.
6. assertIsNot(): Tests if the given arguments evaluate belong to the same object.
7. assertIsNone(): Tests if the given argument evaluates to None.
8. assertIsNotNone(): Tests if the given argument does not evaluates to None.
9. assertIn(): Takes input of two objects and tests if the first argument is in the second one (child of the 2nd one).
10. assertNotIn(): Tests if the first argument is not in the second argument.
11. assertIsInstance(): Tests if the first argument (object) is an instance of the second argument(class).
12. assertRaises(): Tests if the argument raises an exception when we call the callable with positional/ keyword arguments.
13. assertRaisesRegex(): It is similar to assertRaises(). It tests if the regex matches the string representation of the raised exception.
14. assertWarns(): Tests if the argument gives a warning when we call the callable with positional/ keyword arguments.
15. assertWarnsRegex(): It is similar to assertWarns(). It tests if the regex matches the warning message.
16. assertLogs(): Tests if the Python has logged at least one message on the logger or a child of the logger.
17. assertAlmostEqual(): Tests if the value of the first is approximately equal to the second argument.
18. assertNotAlmostEqual(): Tests if the first and the second arguments do not have approximate values.
19. assertGreater(): Tests if the first argument is greater than the second one.
20. assertGreaterEqual(): Tests if the first argument is greater than or equal to the second one.
21. assertLess(): Tests if the first argument is greater than the second one.
22. assertLessEqual(): Tests if the first argument is greater than or equal to the second one.
23. assertRegex(): Tests if the regex search matches the given text.
24. assertNotRegex()- Tests if the regex search does not match with the given text.
25. assertCountEqual()- Takes two sequences and check if they have the same count of the elements.
26. assertMultiLineEqual()- Tests if the multiline string given as the first argument is equal to the second.
27. assertSequenceEqual()- Tests if two input sequences are equal.
28. assertListEqual()- Tests if two input lists are equal.
29. assertTupleEqual()- Tests if two input tuples are equal.
30. assertSetEqual()- Tests if two input sets are equal.
31. assertDictEqual()- Tests if two input dictionaries are equal.

Conclusion

In this article, we have discussed unit testing and also did some examples using Unittest module. Then we have seen a lot of assert() methods in the module. Hope all the concepts discussed are clear. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

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