Intro to Pytest



This content originally appeared on DEV Community and was authored by ThatMLGuy

The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.

To install pytest, run:

pip install pytest

In this post, we’ll create a simple division function and then write tests that validate its behavior.

Step 1: Create Your Code File

Let’s create a file called methods.py with a simple method that divides two integer numbers and returns a floating number:

# methods.py
def division(a: int, b: int) -> float:
    return a / b

Step 2: Create Your Test File

Next, create a file named tests.py, which will contain all the tests.

We’ll use @pytest.mark.parametrize to run the test function multiple times with different inputs.

# tests.py
import pytest
from methods import division

@pytest.mark.parametrize(
    "a,b,expected",
    [
        (10, 20, 0.5),                  
        (20, 0, ZeroDivisionError),
        ("10", "hello", TypeError),
    ],
)
def test_division(a, b, expected):
    # If expected is an exception type, assert that the error is raised
    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
            division(a, b)
    else:
        # Otherwise, assert the result matches
        assert division(a, b) == expected

Our Test Cases:

a b expected result
10 20 0.5
20 0 ZeroDivisionError raised
“10” “hello” TypeError raised

Step 3: Run Your Tests

From your terminal, run:

pytest tests.py

Pytest will automatically:

  • execute all the test methods in the file
  • display which tests passed or failed
  • show helpful tracebacks when something goes wrong

Output:

collected 3 items                                                                                          

tests.py ...                                                                                         [100%]

============================================ 3 passed in 0.02s =============================================

All the test cases have passes as we are aware what errors would be raised.

I know this is a short post, but I felt it was cool and just wanted to share it with you all. If you know any other tools or frameworks worth checking out, feel free to share them in the comments.

If you want to explore more, check out the official documentation at PyTest Docs


This content originally appeared on DEV Community and was authored by ThatMLGuy