🌱 Junior Track 25 of 25

25. Testing & Quality Assurance

Write robust unit and integration tests using `pytest`, master crisp `assert` statements, reuse test state with `@pytest.fixture`, isolate external systems with `unittest.mock`, execute matrix tests with `@pytest.mark.parametrize`, and verify error paths with `pytest.raises()`.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 25 — TESTING & QUALITY ASSURANCE
# ==============================================================================
import pytest
from unittest.mock import Mock, patch

# ------------------------------------------------------------------------------
# 1. Functions & Classes under test
# ------------------------------------------------------------------------------
def add(a: int, b: int) -> int:
    return a + b

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

class BankAccount:
    def __init__(self, balance: float = 0.0):
        self.balance = balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.balance += amount

    def withdraw(self, amount: float) -> None:
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount

def fetch_user_role(user_id: int, api_client: object) -> str:
    # Simulates calling an external payment / user service
    response = api_client.get_user(user_id)
    return response.get("role", "guest")


# ------------------------------------------------------------------------------
# 2. Pytest Unit Tests, Fixtures, Parametrization, Exception & Mock Testing
# ------------------------------------------------------------------------------

# A. Simple Assertion Test
def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

# B. Testing Exceptions with pytest.raises
def test_divide_by_zero():
    with pytest.raises(ValueError) as exc_info:
        divide(10.0, 0.0)
    assert "Cannot divide by zero" in str(exc_info.value)

# C. Reusable State via @pytest.fixture
@pytest.fixture
def account():
    """Fixture providing a fresh BankAccount with $100 initial balance."""
    return BankAccount(balance=100.0)

def test_account_deposit(account):
    account.deposit(50.0)
    assert account.balance == 150.0

def test_account_withdraw_insufficient(account):
    with pytest.raises(ValueError, match="Insufficient funds"):
        account.withdraw(500.0)

# D. Parametrized Matrix Testing
@pytest.mark.parametrize("a, b, expected", [
    (1, 1, 2),
    (10, 20, 30),
    (-5, 5, 0),
    (100, 250, 350),
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

# E. Mocking External Dependencies
def test_fetch_user_role_with_mock():
    mock_api = Mock()
    mock_api.get_user.return_value = {"id": 42, "role": "admin"}

    role = fetch_user_role(42, mock_api)
    assert role == "admin"
    mock_api.get_user.assert_called_once_with(42)
🌱 Junior Track 25 Master Reference

25. Testing, Pytest, Fixtures & Mocking Guide

📊 Pytest & Testing Utilities Summary

Feature Syntax / Construct Primary Purpose
Basic Assertion assert add(2, 3) == 5 Verifies boolean condition; pytest rewrites expressions for detailed failure output.
Test Fixtures @pytest.fixture Provides reusable setup data, mock database handles, or pre-configured objects.
Parametrization @pytest.mark.parametrize Runs a single test function against multiple parameter sets without repeating code.
Exception Testing with pytest.raises(...) Verifies that functions fail safely by raising expected exceptions under bad inputs.
Mocking & Patching Mock(), patch() Simulates third-party network APIs, databases, or slow filesystem functions.

⭐ Rate Track 25: Unit Testing with unittest & pytest (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 24. Dataclasses & Field Config 🌱 Junior Hub (25 Modules Complete!) 26. Debugging & Troubleshooting →