2 min read

Python Pytest Module

pytest is a framework that makes building simple and scalable tests easy. Tests are expressive and readable—no boilerplate code required. It is often preferred over the standard unittest module for its simpler syntax and powerful features.

Installation

pip install pytest

Basic Usage

Create a file named test_sample.py. Pytest identifies files starting with test_ or ending with _test.py as test files. Unlike unittest, you do not need to create a class.

def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

Running Tests

Run the tests from the command line:

pytest

Fixtures

Fixtures provide a fixed baseline upon which tests can reliably and repeatedly execute. They are defined using the @pytest.fixture decorator.

import pytest

@pytest.fixture
def input_value():
    return 39

def test_divisible_by_3(input_value):
    assert input_value % 3 == 0

def test_divisible_by_6(input_value):
    assert input_value % 6 == 0

Parametrization

Parametrization allows you to run a test function multiple times with different arguments.

import pytest

@pytest.mark.parametrize("num, output", [(1, 11), (2, 22), (3, 33)])
def test_multiplication_11(num, output):
    assert 11 * num == output

Markers

Markers allow you to categorize tests (e.g., slow, smoke).

import pytest

@pytest.mark.slow
def test_slow_function():
    import time
    time.sleep(1)
    assert True

Run with pytest -m slow.

Testing Exceptions

Use pytest.raises() to assert that a block of code raises a specific exception.

import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

programming/python/python