Pytest Testing: Python Test Framework Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Pytest: The Complete Guide to Testing in Python

Introduction to Pytest

Testing is a critical part of software development. Without quality tests, it's hard to guarantee code reliability and stable behavior when making changes. Pytest is a modern, powerful, and user-friendly framework for automated testing in Python that greatly simplifies writing and running tests.

Pytest has gained popularity among developers thanks to its concise syntax, rich extension capabilities, and powerful fixture system. It significantly outperforms the standard unittest module in ease of use and test development speed.

Installing and Setting Up Pytest

Installation via pip

pip install pytest

Verifying the Installation

pytest --version

Your First Simple Test

Create a file called test_example.py:

def test_addition():
    assert 2 + 2 == 4

def test_string_operations():
    text = "Hello, World!"
    assert "Hello" in text
    assert len(text) == 13

Running Tests

pytest

Pytest automatically discovers all test files and functions that follow the naming conventions.

Test Structure and Organization

Naming Conventions

Pytest uses the following conventions for automatic test discovery:

  • Test files: test_*.py or *_test.py
  • Test functions: def test_...()
  • Test classes: class Test... (without an __init__ method)
  • Test methods in classes: def test_...()

Organizing Your Test Structure

project/
├── src/
│   ├── calculator.py
│   └── utils.py
├── tests/
│   ├── test_calculator.py
│   ├── test_utils.py
│   └── conftest.py
└── pytest.ini

Running Tests with Different Options

# Run all tests
pytest

# Run tests in a specific directory
pytest tests/

# Run a specific file
pytest test_calculator.py

# Run a specific test
pytest test_calculator.py::test_add

# Run tests in a class
pytest test_calculator.py::TestCalculator

# Run a specific class method
pytest test_calculator.py::TestCalculator::test_multiply

Writing Tests: The Basics

Using assert for Checks

Pytest uses Python's standard assert statement to check conditions:

def test_basic_assertions():
    # Check equality
    assert 2 + 2 == 4
    
    # Check inequality
    assert 3 * 3 != 8
    
    # Check membership
    assert "Python" in "Python testing"
    
    # Check types
    assert isinstance(42, int)
    
    # Check truthiness
    assert bool([1, 2, 3])
    
    # Check falsiness
    assert not bool([])

Testing Exceptions

import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero is not allowed")
    return a / b

def test_division_by_zero():
    with pytest.raises(ValueError):
        divide(10, 0)

def test_exception_message():
    with pytest.raises(ValueError, match="Division by zero"):
        divide(10, 0)

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

Organizing Tests into Classes

class TestCalculator:
    def test_addition(self):
        assert 2 + 3 == 5
    
    def test_subtraction(self):
        assert 10 - 4 == 6

Recommendations