Unit Testing in Python — Unittest

Python Methods and Functions

White box method is used for unit testing.

OOP concepts supported by the unittest framework:

  • test fixture:
    The test fixture is used as the basis for running tests to ensure there is a fixed environment in which tests are run so that results can be repeated. 
    • create temporary databases.
    • start the server process.
  • use case:
    Test suite — it is a set of conditions that is used to determine whether the system under test is working properly.
  • testing:
    A test suite is a set of test cases that are used to test a program to show that that it has a specific set of behaviors by running the merged tests together.
  • test runner:
    Test run — it is the component that configures test execution and provides the result to the user.

Basic test structure:
unittest defines tests in the following two ways:

  • Manage test "fixtures" using code.
  • test yourself.

import unittest


class SimpleTest (unittest.TestCase):


# Returns True or False.

  def test ( self ) : 

  self . assertTrue ( True )


if __ name__ = = '__main__' :

unittest.main ()

This is basic test code using the unittest framework which has one test. This test () method will fail if TRUE is ever FALSE.

Running tests

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

The last block helps to run the test by running the file through the command line.

. -------------------------------------------------- -------------------- Ran 1 test in 0.000s OK 

Here in the output "." The first line of output means the test passed. 
The "-v" parameter is added to the command line during test execution to get more detailed test results.

 test (__main __. SimpleTest) ... ok --------- -------------------------------------------------- ----------- Ran 1 test in 0.000s OK 

Possible results:
There are three types of possible test results:

  • OK — this means that all tests passed.
  • FAIL — this means that the test failed and an AssertionError is thrown.
  • ERROR — this means that the test is throwing an exception other than AssertionError.

Let's take an example to understand the implementation of the unittest framework.


# Python code to demonstrate how unittest works

import unittest


class TestStringMethods (unittest.TestCase):


def setUp ( self ):



  # Returns True if the string contains 4 a.

def test_strings_a ( self ):

self . assertEqual ( 'a' * 4 , 'aaaa' )


# Returns True if the string is uppercase.

def test_upper ( self ): 

self . assertEqual ( 'foo' . upper (), ' FOO' )


# Returns TRUE if the string is uppercase

# else returns False.

def test_isupper ( self ): 

self . assertTrue ( 'FOO' . Isupper ())

  self . assertFalse ( ' Foo' . isupper () )


# Returns true if the line is removed and

# matches the given output.

def test_strip ( self ): 

s = 'pythonengineering'

  self . assertEqual (s.strip ( 'geek' ), 'sforgeeks' )


# Returns true if string p Separates and matches

# given output.

def test_split ( self ): 

s = 'hello world'

  self . assertEqual (s.split (), [ 'hello' , 'world' ])

with self . assertRaises (TypeError) :

s.split ( 2 ) < / code>


if __ name__ = = '__main__' :

unittest.main ()

The above code is a short script for testing 5 string methods.  unittest.TestCase is used to create test cases by subclassing it. The final block of code at the bottom allows us to run all tests by simply running the file.

Key terms used in the code:

  • assertEqual ( ) — this operator is used to check if the result is equal to the expected result.
  • assertTrue () / assertFalse () — this operator is used to check if a given statement is true or false.
  • assertRaises () — this statement is used to raise a specific exception.

Test description:

  • test_strings_a
    This test is used to test the property of a string where the character "a" is multiplied a number such as "x" gives the result as x times "a". The assertEqual () statement returns true in this case if the result matches the given output.
  • test_upper
    This test is used to check if a given string is converted to uppercase or not ... The assertEqual () statement returns true if the returned string is uppercase.
  • test_isupper
    This test is used to validate a property of a string that returns TRUE if the string is uppercase register, otherwise returns False. The assertTrue () / assertFalse () statement is used for this check.
  • test_strip
    This test is used to check if all characters passed to the function have been removed from the string ... The assertEqual () statement returns true if the line is deleted and matches the given output.
  • test_split
    This test is used to test a line splitting function that splits a line by an argument passed into a function, and returns the result as a list. The assertEqual () statement returns true in this case if the output matches the specified output.

unittest.main () provides a command line interface for a test script. Running the above script from the command line produces the following output:

 ..... --------------------------- ------------------------------------------- Ran 5 tests in 0.000s OK 

This article is courtesy of Aditi Gupta . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.