Unit Test

A unit test verifies that one specific aspect of a function’s behavior is correct.

If we have a main file with functions or just a file with functions we want to test different use cases, it is easier to use unittest rather then change the script and run it every time.

Here us a function func_to_print_full_name in the func_file.py file:

def func_to_print_full_name(first, last):
    full_name = first + ' ' + last
    return full_name

Create a file (test_func.py) for testing:

  • import function to test
  • import unittest module
  • create a class (name - any) with must base class - unittest.TestCase
  • def method with test_ and run function with arguments
  • check the output with assert
from func_file import func_to_print_full_name
import unittest

class NamesTestCases(unittest.TestCase):
    """Test function func_to_print_full_name from the func_file"""

    def test_func_to_print_full_name(self):
        """Does it work with Middle name?"""
        full_name = func_to_print_full_name("Dmitry", "Golovach")
        self.assertEqual(full_name, "Dmitry Golovach")

unittest.main()

Run the test file:

  • “.” - one test ran successfully
>python test_func.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

If we run with error:

>python test_func.py
E
======================================================================
ERROR: test_func_to_print_full_name (__main__.NamesTestCases)
Does it work with Middle name?
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_func.py", line 9, in test_func_to_print_full_name
    full_name = func_to_print_full_name("Dmitry", "Golovach", "Wow")
TypeError: func_to_print_full_name() takes 2 positional arguments but 3 were given

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (errors=1)

A test case is a collection of unit tests that together prove that a function behaves as it’s supposed to, within the full range of situations you expect it to handle.

Assert Methods Available from the unittest Module

Method => Use

  • assertEqual(a, b) => Verify that a == b
  • assertNotEqual(a, b) => erify that a != b
  • assertTrue(x) => Verify that x is True
  • assertFalse(x) => Verify that x is False
  • assertIn(item, list) => Verify that item is in list
  • assertNotIn(item, list) => Verify that item is not in list