Unit testing

Unit testing checks a code at its basic level by isolating the code into smaller units. The behaviour of the functional units is compared against an expected outcome.

Unit testing is more of an act of design than of verification. It is more of an act of documentation than of verification.
- R. C. Martin and M. Martin: Agile Principles, Patterns and Practices in C#. 2006.

Illustration of unit testing concept: A long snippet of code is broken into unit-testable units.

Tools for writing unit-tests

Following is a set of tool recommendations for different code projects:


Writing unit tests for python projects

We use PyTest for unit-testing in our hands-on exercises. Following are the commands to perform tests with PyTest which can be used once you have tests implemented in the code project.

Running PyTest

py -m pytest <PATH_TO_TESTS>

Finding code coverage with PyTest

py -m coverage run --source=<PATH_TO_SOURCECODE> -m pytest <PATH_TO_TESTS>
py -m coverage report -m

Hands-on exercise

The python project we use for the hands-on exercise is a Matrix Calculator. See preparation page for the project link. The main features of the project are:

  • Perform basic matrix operations: Add, Multiply, Inverse
  • Can handle different matrix formats: Dense
  • Can handle user-defined linear solvers: Jacobi iterative solver

Write your first unit test

Perform the following tasks and observe the code coverage after each step:

  1. (Demonstration) Write a unit test to test the function solve in jacobi_solver.py
  2. Write 3 unit tests to test the functions add, matrix_vector_multipy, matrix_inverse implemented in dense_matrix.py
  3. (Optional) Write additional tests where matrix entries are float values and use pytest.approx

Python cheat sheet

Create a matrix with numpy 2D array:

np.array( [[1,2], [3,4]] )

Create a vector with numpy 1D array:

np.array( [1,2] )