15 Automating Tests#

Goal#

Here you’ll learn to write and run tests for Python using the pytest library. With this you will automatise software tests and focus on solving the issues behind failed tests.

Prerequisites#

Steps#

1. Introduction#

Pytest is a Python pacakge that simplifies running tests and create stardarised tests, without to manually check your files after each itereataion. Additioanlly, you can configuring GitHub CI/CD to automatically run these tests, perhaps using a dockerfile (see 16_docker). It is a common way to sync tests and criteria among a group of developers and to automate them, saving time and mistakes,

2. Setup#

Before starting using pytest you will have to install it using pip:

pip install pytest

Also, in the repository where you want to conduct tests, you should create a new directory named tests in the root directory.

mkdir tests/

Inside that directory, you can create as many files for tests. For pytest to recognise them, they must start with "test":

touch tests/test_<name>.py

3. Execution#

3.1 Import Required Packages#

import pytest
import <package-name> # to import your full package
from build.lib.<package-name> import <function> # to import a specific function

3.2 Write a Function#

Testing functions must start with test_

def test_<function-name>():
    # your function goes here

3.3 Example Usage#

import pytest
import my_package as mp

def test_addition_function():
	inp = (1,1) # input
	expected = 2
	out = mp.sum_function(inp) # output
	assert out == expected # assert evaluates the tested result with the expected result

def test_addition_function():
	inps = [(1,1), (2,5), (4,5), (3,8), (10,10)]
	expected = [2, 7, 9, 11, 20]
	for inp, result in zip(inps, expected):
		assert mp.sum_function(inp) == result

def test_addition_function():
	inp = ('1',3.5)
	with pytest.raises(ValueError, match="Both values must be integers."):
		mp.addition_function(inp)
		# pytest.raises enables to run a function and check the correct error is raised

4. Verification#

To run the test, enter the following command to the shell:

pytest

You’ll see if ‘all test passed’ or which tests failed and where.

You can ses an example of pytest usage in the capibara3/capicr-software repository.

Troubleshooting#

Check the official pytest documentation.

Next Steps#

Great you can now automatically test your code and share your tests with others! Next step is learning about 16_docker to also share your code’s dependencies.