Unit testing
Contents
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.
Tools for writing unit-tests#
Following is a set of tool recommendations for different code projects:
PyTest, UnitTest
GoogleTest
MSTest, NUnit, xUnit
JUnit
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#
cd <PROJECT_DIR>
py -m pytest <PATH_TO_TESTS>
Finding code coverage with PyTest#
cd <PROJECT_DIR>
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:
(Demonstration) Write a unit test to test the function
solve
injacobi_solver.py
Write 3 unit tests to test the functions
add, matrix_vector_multipy, matrix_inverse
implemented indense_matrix.py
(Optional) Write additional tests where matrix entries are float values and use
pytest.approx
Python cheat sheet#
Create a matrix with numpy 2D array: |
|
\(\begin{bmatrix} 1 &2 \\ 3 &4 \end{bmatrix}\) |
Create a vector with numpy 1D array: |
|
\(\begin{bmatrix} 1, 2 \end{bmatrix}\) |