Site icon DataFlair

Unit Testing With Python Unittest – Example & Working

Python course with 57 real-time projects - Learn Python

In this Python Unittest tutorial, we will learn how to set up unit tests for our Python code. For this, we will use the module Unittest in Unit Testing with Python.

Right before leaving, we will also introduce you to pytest, another module for the same thing.

Moreover, we will discuss Python Unittest example and the working. Also, we will see Python Unit Testing Framework and assert.

So, let’s start Unit Testing with Python Unittest Tutorial.

Unit Testing With Python Unittest – Example & Working

What is Python Unittest?

Python Unittest is a Python Unit-Testing framework. Inspired by JUnit, it is much like the unit testing frameworks we have with other languages.

Here are some features it supports-

1. Concepts in an object-oriented way for Python Unittest

In this Python Unittest tutorial, we will use the unittest module to demonstrate our examples to you.

Python Unittest Example

In the following example of Unittest in Python, we will take a simple function that calculates the modulus 3 of a value.

>>> import unittest
>>> def modthree(x):                             #defining the function
      return x%3
>>> class Tests(unittest.TestCase):
      def test(self):                                  #test method
               self.assertEqual(modthree(4),1)
>>> if __name__=='__main__':
      unittest.main()

Output

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

Did you see the output?

1. One More Example of Python Unittest

Now let’s try testing for string methods; we won’t need a function for this.

>>> class TestStringMethods(unittest.TestCase):
        def test_lstrip(self): #testing for left stripping
                 self.assertEqual('   hello '.lstrip(),'hello ')
        def test_isupper(self): #testing for isupper
                 self.assertTrue('HELLO'.isupper())
                 self.assertFalse('HELlO'.isupper())
        def test_split(self): #testing for split
                 self.assertEqual('Hello World'.split(),['Hello','World'])
                 with self.assertRaises(TypeError):
                         'Hello World'.split(2)
>>> if __name__=='__main__':
        unittest.main()

Output

….
———————————————————————-
Ran 4 tests in 0.031s
OK

How Python Unittest Works?

So we’ve seen this Unit Testing with Python works without much effort. But how does this happen behind the scenes?

Let’s find out.

1. Subclassing unittest.TestCase

Consider the following line-

class TestStringMethods(unittest.TestCase):

Here, we subclass unittest.TestCase. What we mean is we make our class TestStringMethods inherit from the class unittest.TestCase. Then, we define three methods, the names for which begin with ‘test’:

test_lstrip()
test_isupper()
test_split()

2. Python Unittest Assert Methods

Now, let’s take a look at what methods we can call within Unit testing with Python:

Now that we’ve discussed all these, you can go check the code once again. We used the methods assertEqual(), assertTrue(), assertFalse(), and assertRaises().

3. unittest.main()

This delivers a command-line interface to the test script. The output suggests whether the tests ran okay or failed.

Tests That Fail in Python Unittesting

What happens if a test fails? To make this happen, we refer to a string variable that doesn’t already exist.

>>> class TestStringMethods(unittest.TestCase):
      def test_lstrip(self):
              self.assertEqual('   hello '.lstrip(),'hello ')
      def test_isupper(self):
              self.assertTrue('HELLO'.isupper())
              self.assertFalse('HELlO'.isupper())
      def test_split(self):
              self.assertEqual('Hello World'.split(),['Hello','World'])
              with self.assertRaises(TypeError):
                      s.split(2)
>>> if __name__=='__main__':
      unittest.main()

Output

..E.
======================================================================
ERROR: test_split (__main__.TestStringMethods)
———————————————————————-
Traceback (most recent call last):
File “<pyshell#21>”, line 10, in test_split
NameError: name ‘s’ is not defined
———————————————————————-
Ran 4 tests in 0.016s
FAILED (errors=1)

You can see the error in the output. One of the tests failed and returned an error. It did so because we did not define a string s.

Python Unittest – Testing With pytest

It was fun working with Python Unittest. But before leaving, we want to introduce you to pytest, a framework that makes it fun to write small tests.

But that doesn’t limit it- we can scale it to support complex functional testing for applications and libraries.

First, install pytest with Python pip-
pip install pytest
You don’t have to import this in the IDLE; we create the following Python file on our Desktop-

def modthree(x):
   return x%3
def test_value():
   assert(modthree(4)==1)

We save this as demo.py. Then, we open the command line and get to the desktop. After that, we run a test-

Python Unittest – Testing with pytest

Let’s make a test fail.

def modthree(x):
   return x%3
def test_value():
   assert(modthree(4)==2)

Python Unittest – pytest Testing in Python

So, this was all in Unit Testing with Python Unittest. Hope you like our explanation.

Python Interview Questions on Unittest

  1. What is a Unittest in Python?
  2. How do you write a Unittest in Python? Give an example.
  3. What are the best Python Unittesting frameworks?
  4. What are the best practices for Python unittesting?
  5. What is the difference between Pytest and Unittest?

Conclusion

Hence, in this Python Unittest tutorial, we discussed Unit Testing with Python. Moreover, we saw Python Unittest example and working.

Also, we discussed Python Unit Testing frameworks and test case example with Python Unittest assert.

We hope you can run your own tests for your code. In this tutorial, we saw how to do that with the Python Unittest and pytest modules.

Exit mobile version