Python - Testing & Quality

Overview

Estimated time: 40–60 minutes

Write tests with pytest, use fixtures/parametrization, and improve code quality with ruff/flake8 and black. Add pre-commit to automate checks.

Learning Objectives

  • Create and run pytest tests; understand discovery and assert rewriting.
  • Use fixtures and parametrization to reduce duplication.
  • Format and lint automatically with black and ruff (or flake8).

Prerequisites

pytest quickstart

pip install pytest
pytest -q

Example

# test_math.py

def add(a, b):
    return a + b

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

Expected Output (example): .\n1 passed

Fixtures and parametrization

import pytest

@pytest.fixture
def samples():
    return [(2, 3, 5), (0, 0, 0), (-1, 1, 0)]

def add(a, b):
    return a + b

@pytest.mark.parametrize("a,b,c", [(2,3,5),(1,4,5)])
def test_add_param(a, b, c):
    assert add(a, b) == c

def test_add_samples(samples):
    for a,b,c in samples:
        assert add(a, b) == c

Quality tools

pip install black ruff pre-commit
black .
ruff .

# .pre-commit-config.yaml (snippet)
# - repo: https://github.com/psf/black
#   rev: 24.3.0
#   hooks:
#     - id: black

Common Pitfalls

  • Relying on print instead of asserts; tests should fail on incorrect behavior.
  • Skipping virtual environments; tools then install globally and conflict.

Checks for Understanding

  1. How does pytest discover tests?
  2. Why use parametrization?
Show answers
  1. It finds files named test_*.py or *_test.py and functions/classes starting with test.
  2. To run the same test logic over multiple inputs without duplication.

Exercises

  1. Write tests for a function that computes factorial; include edge cases.
  2. Add black and ruff to your project and run them; fix any issues.