Testing with pytest

Testing is critical for production software. While Python has a built-inunittest module, most professionals prefer pytestfor its simpler syntax and powerful features.

1. Installation

pip install pytest

2. Writing Your First Test

Create a file named test_logic.py. Functions must start with test_.

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

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

3. Running Tests

Simply run pytest in your terminal. It will discover and run all tests automatically.

pytest

4. Advanced Features

  • Fixtures: Setup and teardown code (e.g., creating a temporary database).
  • Parametrization: Testing multiple inputs for the same function.
  • Markers: Categorizing tests (e.g., @pytest.mark.slow).
Red-Green-Refactor: Following the TDD (Test Driven Development) cycle with pytest ensures your logic remains sound as your project grows.