Installing pytest

Install pytest:

pip install pytest

Basic Test

Write simple test:

# test_math.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

Running Tests

Run with pytest:

# Run all tests
pytest

# Run specific file
pytest test_math.py

# Verbose output
pytest -v

Test Fixtures

Use fixtures for setup:

import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3, 4, 5]

def test_sum(sample_data):
    assert sum(sample_data) == 15

Parametrized Tests

Test multiple inputs:

import pytest

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),
    (0, 0, 0),
    (-1, 1, 0),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

Testing Exceptions

Test that exceptions are raised:

import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

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

Best Practices

  • Write tests first: Test-driven development
  • Test edge cases: Boundary conditions
  • Keep tests simple: One assertion per test when possible
  • Use descriptive names: test_what_it_does format

Next Steps

Learn about packaging to distribute tested code.