# Example: Simple unit testing with pytest
# =======================================
#
# This is a complete example demonstrating unit testing with pytest.
#
# Prerequisites:
# 1. Install pytest: `pip install pytest`
# 2. Save the code below into two files:
# - `calc.py` (the module to test)
# - `test_calc.py` (the test file)
# 3. Run the tests: `pytest test_calc.py -v` (or just `pytest` if in the same directory)
#
# pytest will discover and run all test functions automatically.
# Use `-v` for verbose output.
# File: calc.py
"""
A simple calculator module.
"""
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
def subtract(a: int, b: int) -> int:
"""Subtract two integers."""
return a - b
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
def divide(a: float, b: float) -> float:
"""Divide two numbers, raises ValueError if b is zero."""
if b == 0:
raise ValueError("Division by zero is not allowed!")
return a / b
# File: test_calc.py
"""
Unit tests for calc.py using pytest.
"""
import pytest
from calc import add, subtract, multiply, divide
def test_add():
"""Test addition of positive numbers."""
assert add(2, 3) == 5
def test_add_negative():
"""Test addition with negative numbers."""
assert add(-1, 1) == 0
assert add(-5, -3) == -8
def test_subtract():
"""Test subtraction."""
assert subtract(5, 3) == 2
def test_subtract_negative():
"""Test subtraction with negatives."""
assert subtract(3, 5) == -2
def test_multiply():
"""Test multiplication."""
assert multiply(4, 5) == 20
assert multiply(-2, 3) == -6
assert multiply(0, 10) == 0
def test_divide():
"""Test division."""
assert divide(10.0, 2.0) == 5.0
assert divide(7.0, 2.0) == 3.5
def test_divide_by_zero():
"""Test division by zero raises ValueError."""
with pytest.raises(ValueError, match="Division by zero"):
divide(10.0, 0.0)
# Advanced pytest features example (add to test_calc.py if desired):
# def test_parametrized():
# """Parametrized test example."""
# test_cases = [(2, 3, 5), (-1, 1, 0), (0, 0, 0)]
# for a, b, expected in test_cases:
# assert add(a, b) == expected
#
# Use pytest.mark.parametrize for cleaner version:
#
# import pytest
#
# @pytest.mark.parametrize("a, b, expected", [(2, 3, 5), (-1, 1, 0), (0, 0, 0)])
# def test_add_parametrized(a, b, expected):
# assert add(a, b) == expected
#
# Run with: pytest test_calc.py::test_add_parametrized -v
Running the Tests
# Install pytest if needed
pip install pytest
# Run all tests
pytest -v
# Run specific test file
pytest test_calc.py -v
# Expected output:
# test_calc.py::test_add PASSED
# test_calc.py::test_add_negative PASSED
# ...
# ====================== 7 passed in 0.01s ======================
This script setup demonstrates core pytest features: assertions, exception testing (pytest.raises), and can be extended with fixtures, parametrization, or mocking for more complex scenarios. All tests should pass! 🧪