unittest

Introduction

Unittest is a testing library that ships with Python by default

It contains both a test framework and a test runner. Unittest has a number of requirements for writing and running tests:

*this means that in unittest, for each type of assertion you need to use its own method, for example:

assertEqual - to assert equality
assertNotEqual - to assert inequality
assertTrue - to assert truth

And so on, see the site for details docs.python.org

This is how unittest differs from, for example, PyTest , where the assertion is always made in the same way - with the help of assert

Let us go through the simplest example of use.

Let us create a working directory app, the file calc.py in the root and the file test_calc.py in the subdirectory tests

Let us also create and activate a virtual environment

python -m venv venv
source venv/bin/activate

Project structure:

app ├── calc.py ├── tests │   └── test_calc.py └── venv ├── bin ├── include ├── lib ├── lib64 -> lib └── pyvenv.cfg

# calc.py def add(x, y): """Add Function""" return x + y + 3 def subtract(x, y): """Subtract Function""" return x - y def multiply(x, y): """Multiply Function""" return x * y def divide(x, y): """Divide Function""" if y == 0: raise ValueError("Can not divide by zero!") return x / y

As you can see, in the function add() an error was deliberately made - instead of adding two variables, the number 3 is also added to them

# test_calc.py import unittest import calc # https://docs.python.org/3/library/unittest.html#unittest.TestCase.debug class TestCalc(unittest.TestCase): def test_add(self): result = calc.add(10, 5) self.assertEqual(result, 15) # python3 -m unittest tests/test_calc.py

To run the test, let us go to the directory with the files and run the following command in the console

python -m unittest tests/test_calc.py

F ====================================================================== FAIL: test_add (tests.test_calc.TestCalc) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/andrei/python/unittest/app/tests/test_calc.py", line 12, in test_add self.assertEqual(result, 15) AssertionError: 18 != 15 ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures=1)

Let us fix the error

# calc.py def add(x, y): """Add Function""" return x + y ...

python3 -m unittest test_calc.py

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

To run this test in PyCharm, or to run it from the console without additionally specifying -m unittest, let us add two lines to the end of the test_calc.py file:

# test_calc.py ... if __name__ == '__main__': unittest.main()

Now the test can be run with the command

python -m tests.test_calc

Let us write tests for all the functions in calc.py

Again let us deliberately make an error, for example in the third test

import unittest import calc class TestCalc(unittest.TestCase): def test_add(self): self.assertEqual(calc.add(10, 5), 15) self.assertEqual(calc.add(-1, 1), 0) self.assertEqual(calc.add(-1, -1), -2) def test_subtract(self): self.assertEqual(calc.subtract(10, 5), 5) self.assertEqual(calc.subtract(-1, 1), -2) self.assertEqual(calc.subtract(-1, -1), 0) def test_multiply(self): self.assertEqual(calc.multiply(10, 5), 70) self.assertEqual(calc.multiply(-1, 1), -1) self.assertEqual(calc.multiply(-1, -1), 1) def test_divide(self): self.assertEqual(calc.divide(10, 5), 2) self.assertEqual(calc.divide(-1, 1), -1) self.assertEqual(calc.divide(-1, -1), 1) if __name__ == '__main__': unittest.main()

Let us run the test

python3 test_calc.py

..F. ====================================================================== FAIL: test_multiply (__main__.TestCalc) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:/Users/username/.PyCharmCE2018.3/config/scratches/test_calc.py", line 17, in test_multiply self.assertEqual(calc.multiply(10, 5), 70) AssertionError: 50 != 70 ---------------------------------------------------------------------- Ran 4 tests in 0.001s FAILED (failures=1) Process finished with exit code 1

Note the first line: dots mean the test ran successfully. F - test failure.

..F. means that the first, second and fourth tests passed successfully, while the third has an error

The assertion that returned FALSE is also visible

self.assertEqual(calc.multiply(10, 5), 70)

And the error AssertionError: 50 != 70

With such a detailed result we easily fix the error

self.assertEqual(calc.multiply(10, 5), 70)

We change it to

self.assertEqual(calc.multiply(10, 5), 50)

Let us run the test

python3 test_calc.py

.... ---------------------------------------------------------------------- Ran 4 tests in 0.001s OK Process finished with exit code 0

Testing the solution of a quadratic equation

Let us create two more files quadratic.py and test_quadratic.py

Project structure

app ├── calc.py ├── __pycache__ ├── quadratic.py ├── tests │   ├── __pycache__ │   ├── test_calc.py │   └── test_quadratic.py └── venv ├── bin ├── include ├── lib ├── lib64 -> lib └── pyvenv.cfg

Quadratic equations are equations of the form

a*x^2 + b*x + c

x^2 and x are implied by default, so it is enough to specify a, b and c - and it immediately becomes clear what the quadratic equation looks like.

First of all let us check that a, b and c are numbers

def quadratic_solve(a ,b, c): if not all( map( lambda p: isinstance(p, (int, float)), (a, b, c) ) ): raise TypeError("Not valid argument type") print("Types are OK")

Here I used the functions: all() , map() and lambda function

If something is unclear, follow the links to the functions or visit the section «Functions»

An example test

# test_quadratic.py import unittest from quadratic import quadratic_solve class TestQuadratic(unittest.TestCase): def test_raises_type_error(self): try: # Deliberately passing a string quadratic_solve("", 1, 1.5) except TypeError as err: print("\nOK, caught type error", err) else: self.fail("NOK, missed type error")

python -m unittest -v tests/test_quadratic.py

test_raises_type_error (tests.test_quadratic.TestQuadratic) ... OK, caught type error Not valid argument type ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OK

The test can be rewritten in a more native form - without try and except. unittest has already thought through this situation

def test_raises_type_error(self): with self.assertRaises(TypeError): quadratic_solve("", 1, 1.5)

Now the code for solving the quadratic equation can be written

from math import sqrt def quadratic_solve(a ,b, c): if not all( map( lambda p: isinstance(p, (int, float)), (a, b, c) ) ): raise TypeError("Not valid argument type") print("Types are OK") if a == 0: if b == 0: # a and b are 0: no solution return None, None return -c / b, None d = b ** 2 - 4 * a * c if d < 0: return None, None d_root = sqrt(d) divider = 2 * a x1 = (-b + d_root) / divider x2 = (-b - d_root) / divider if d == 0: x2 = None elif x2 > x1: x1, x2 = x2, x1 return x1, x2

And write tests for the solution itself

# test_quadratic.py import unittest from quadratic import quadratic_solve class TestQuadratic(unittest.TestCase): def test_raises_type_error(self): with self.assertRaises(TypeError): quadratic_solve("", 1, 1.5) def test_result_is_tuple(self): res = quadratic_solve(0, 0, 0) self.assertIsInstance(res, tuple) def test_zero_a_and_b(self): res = quadratic_solve(0, 0, 1) self.assertEqual(res, (None, None)) def test_two_roots(self): res = quadratic_solve(1, -1, -2) self.assertEqual(res, (2.0, -1.0)) def test_single_root(self): res = quadratic_solve(1, -2, 1) self.assertEqual(res, (2.0, None))

test_raises_type_error (tests.test_quadratic.TestQuadratic) ... ok test_result_is_tuple (tests.test_quadratic.TestQuadratic) ... Types are OK ok test_single_root (tests.test_quadratic.TestQuadratic) ... Types are OK ok test_two_roots (tests.test_quadratic.TestQuadratic) ... Types are OK ok test_zero_a_and_b (tests.test_quadratic.TestQuadratic) ... Types are OK ok ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK

All the tests pass successfully. Nevertheless such a set of tests has redundant code.

Several tests consist in passing some value to the same function and then comparing the result with a reference. Parameterization of tests will help get rid of the extra code. This is handled well by PyTest

Theory for unittest

For those who wonder whether unittest is outdated or not, my humble opinion is that it is not.

In the Python world the more fashionable choice is considered to be PyTest one of the reasons is the simpler syntax.

Nevertheless unittest is convenient because it is built into the standard library and because other programming languages have similar frameworks too.

Test Fixture

A single test is called a test case (Test Case).

It is often necessary to run several test cases that need the same thing to run.

For example, to get the same object or to start Selenium Webdriver or something else.

To avoid writing the same thing in every test case, you can use the methods setUp and tearDown, which are created once for each class and will run before each test case.

Such a combination setUp + tearDown is called Test Fixture

Test Fixture = setUp + tearDown

The components of any test

The order in which a test is executed is usually as follows:

Preparing for the test

The action itself, for example running a particular function

Checking the result against the expectation.

Arrange → Act → Assert

Long tests in which many alternating actions and checks take place should be avoided where possible.

It is better to write several small tests than one long one. Then when one of the well-structured tests fails it will be easier to understand what exactly is not working.

Article author: Andrei Olegovich