Why Pytest is the Industry Standard Testing Framework
Modern Python engineering teams use Pytest for its concise syntax, powerful fixture dependency injection system, and rich plugin ecosystem. Unlike standard unittest, Pytest avoids boilerplate class hierarchies.
1. Pytest Fixtures with Yield Teardown
import pytest
@pytest.fixture
def sample_database():
# Setup connection
db = {"users": [], "connected": True}
print("
[Setup] Connected to mock DB")
yield db
# Teardown
db["connected"] = False
print("[Teardown] Closed mock DB connection")
def test_insert_user(sample_database):
sample_database["users"].append("Kashinath")
assert len(sample_database["users"]) == 1
assert "Kashinath" in sample_database["users"]
2. Test Parametrization (`@pytest.mark.parametrize`)
import pytest
def calculate_discount(price: float, is_student: bool) -> float:
return price * 0.8 if is_student else price
@pytest.mark.parametrize("price, is_student, expected", [
(100.0, True, 80.0),
(100.0, False, 100.0),
(50.0, True, 40.0),
(0.0, True, 0.0),
])
def test_discounts(price, is_student, expected):
assert calculate_discount(price, is_student) == expected