Menu

Test Driven Development with Pytest

Introduction

Testing is a crucial skill for professional developers. Python's pytest framework makes writing tests simple and enjoyable. In this lesson, you'll learn the fundamentals of test-driven development (TDD).

Writing tests with pytest

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

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

# test_calculator.py
import pytest
from calculator import add, divide

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

def test_divide():
    assert divide(10, 2) == 5
    assert divide(7, 2) == 3.5

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

# Run with: pytest test_calculator.py -v

The TDD workflow

  1. Red: Write a failing test.
  2. Green: Write the minimum code to make it pass.
  3. Refactor: Clean up the code while keeping tests green.

Assignment

  1. Install pytest: pip install pytest.
  2. Write tests for a StringCalculator class that can add comma-separated numbers.
  3. Use TDD to build a simple Stack class.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!