Programming, Python
How to Test Your Python Code with Pytest
Simplify your testing process and enhance code quality with Pytest

Are you tired of spending hours debugging your code and fixing errors that could have easily been prevented? We know how frustrating it can be to have code that doesn’t work correctly, especially when you’re under pressure to deliver results. But fear not! There’s a solution: Pytest.
Pytest is a robust testing framework that helps ensure your code works as expected, even under different scenarios and conditions. Integrating Pytest into your code allows you to identify and fix bugs before they become problems, saving you time and effort in the long run.
In this article, we’ll show you how to start with Pytest. From setting up your environment to writing tests that cover all your code, we’ve got you covered. So why wait? Let’s start testing and ensure your code works flawlessly every time.
We’ll cover:
- An Overview of Pytest
- A Practical Example
Let’s start by describing an overview of Pytest.
An Overview of Pytest
Pytest is a testing framework for Python that focuses on simplicity and ease of use. To install Pytest, run the following command:
$ pip install pytest
Pytest follows a modular and extensible architecture, allowing developers to organize tests into individual test functions or classes.
When you build your test using Pytest, you must follow the steps described below:
- Create a new script
test_<mytest>.pyfor your tests. Import Pytest into the script. - Define Your Test Functions: A test function is a Python function that verifies a specific aspect of your code’s behavior. Each test function should be self-contained, focusing on a single test case. Pytest automatically discovers and executes these test functions.
- Test Naming Convention: Each test function must start with
test_to make Pytest recognize it correctly. - Test Assertions: Use test assertions to define the function's behavior. Pytest provides a wide range of powerful assertion functions.
- Test Fixtures: Fixtures are functions that provide reusable and preconfigured resources or test data to your test functions.
A List of Some Assets Functions
Here are some of the main assertions provided by Pytest:
assert: Make simple assertions by checking if a given condition is trueassertEqual: Compare two values for equality. It checks if the expected value is equal to the actual valueassertTrueandassertFalse: Verify if a given condition is true or false.assertRaises: Check if a specific exception is raised when executing a code.assertInandassertNotIn: Verify if a value is present or absent in a given collection or sequenceassertAlmostEqual: Compare floating-point values to a specified degree of precision.assertDictEqual: Check if two dictionaries have the same set of key-value pairs.assertRaisesRegex: Verify if a specific exception is raised and the exception message matches a regular expression pattern.
Now that you have seen the basic concepts behind Pytest let’s move on to a practical example.
A Practical Example
Let’s imagine we want to build a calculator and test if we have implemented it correctly. First, we define the core functions, and then we write tests.
Core Functions
The core functions implement the calculator's operations. For example, we can write the following simple code to implement the primary operations:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / bSave the file as calculator.py.
Test Functions
In the same directory where we save the core functions, add another script for the tests named test_calculator.py. First, import the core functions and the Pytest library:
import pytest
from calculator import addThen, add a test for each function in the calculator.py file. For each function, add a separate test. For example, to test the add() function, write the following test:
def test_addition():
result = add(2, 4)
assert result == 6
result = add(-1, 3)
assert result == 2
result = add(0, 0)
assert result == 0Similarly, you can write tests for the other functions. You can find the complete example in this GitHub repository.
To run tests, open a terminal and run the following command from the folder where there are the two scripts:
pytest
You should obtain the following output:
% pytest
================================================== test session starts ===================================================
platform darwin -- Python 3.8.10, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/angelica/CNR/Git/data-science/Tests/Calculator
plugins: typeguard-2.13.3, anyio-3.3.4
collected 4 items
test_calculator.py .... [100%]
=================================================== 4 passed in 0.02s ====================================================Using Test Fixtures
Let’s modify the previous example to support test fixtures. First, create a new directory and a new file named calculator.py. Wrap the calculation functions in a class:
class Calculator:
def __init__(self):
self.result = 0
def add(self, a, b):
self.result = a + b
return self.result
def subtract(self, a, b):
self.result = a - b
return self.result
def multiply(self, a, b):
self.result = a * b
return self.result
def divide(self, a, b):
self.result = a / b
return self.resultThen, create another script called test_calculator.py in the same directory. Import Pytest and the Calculator class at the beginning of the script:
import pytest
from calculator import *Use the @pytest.fixture decorator to define a fixture named calculator. Fixtures are functions that provide reusable resources or setup actions for tests. In this case, the calculator fixture creates an instance of the Calculator class and returns it.
@pytest.fixture
def calculator():
# Create an instance of the calculator
calc = Calculator()
return calcNow we can use the test fixture calculator in our tests:
def test_multiplication(calculator):
result = calculator.multiply(4, 3)
assert result == 12
def test_division(calculator):
result = calculator.divide(10, 2)
assert result == 5Finally, run the test:
pytest
You should obtain the following output:
pytest
================================================== test session starts ===================================================
platform darwin -- Python 3.8.10, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/angelica/CNR/Git/data-science/Tests/CalculatorFixture
plugins: typeguard-2.13.3, anyio-3.3.4
collected 4 items
test_calculator.py .... [100%]
=================================================== 4 passed in 0.01s ====================================================You can find the complete example in this GitHub repository.
Summary
Congratulations! You have just learned how to add tests to your Python code using Pytest! Embracing Pytest as your testing framework ensures the reliability and longevity of your Python code!
Using Pytest is simple: you need to write intuitive test functions!






