Pytest

Learn how to use the Pytest library.

There are various libraries and frameworks that help us unit test Python code, such as pytest and nose2. Python even comes with a module called unittest. The choice of testing framework is up to the developer. In this lesson, we’ll familiarize ourselves with the pytest library.

The pytest library

The pytest library, along with auxiliary libraries like pytest-cov and coverage, help us unit test code and allow us to gain insights into how much of the code has been tested.

Test cases

Consider the following example module:

Press + to interact
def conditional_add(x: int) -> int:
"""Adds 4 if the input is negative, else adds 8."""
if x < 0:
return x + 4
else:
return x + 8

In the code snippet, we have a single function, conditional_add, that takes an integer argument. If the number is negative, it returns that number added to 8, or added to 4 if it's positive or 0. There’s an if-else branch in the code, and line 4 runs only if the input is negative. Line 6 runs if the input is 0 or a positive number. In unit testing, ...