I'm focused on grasping the user's objective: a Python script showcasing pytest. I'm breaking this down into core elements. I've begun identifying the critical components required to properly illustrate this. Next, I'll flesh out each component necessary.
Outlining the Structure
I'm presently building the structure of the Python script and tests. I'm focusing on simplicity, modularity, and comprehensive test coverage. I'm drafting the math_operations.py module, with addition, division, and an "is_even" function. I'm also preparing the test code, keeping in mind pytest's structure.
Refining the Approach
I'm now honing the script structure. I'm focusing on incorporating the requested features, including handling exceptions, and parametrization. I am also planning to include fixtures. I'm building a Wallet class for the fixture examples. The example will use this class and it's methods within the tests, making it a good example.
Detailing the Implementation
I'm presently building the Python files: my_app.py and test_my_app.py. The former houses the functions to be tested, like add, divide, and get_grade, while the latter contains the associated tests. I'm incorporating various pytest features: basic assertions, boolean assertions, exception handling with pytest.raises, and parametrization for efficient testing. Additionally, I'm integrating fixtures using a Wallet class to demonstrate setup and teardown. My focus is on concise, easily understood code.
Formulating Test Cases
I'm now detailing the various test cases required. I'm focusing on basic assertions, boolean assertions, exception handling using pytest.raises, and parametrization for efficient testing. I will utilize a Wallet fixture, integrating setup and teardown within the test environment. I am organizing the answer into clear steps: installation, application code, test code, execution instructions, and advanced feature explanations.
Here is a complete, step-by-step implementation of unit testing using pytest.
To make this realistic, I have separated the example into two files:
math_lib.py: The actual code (logic) we want to test.
test_math_lib.py: The test script containing the unit tests.
Prerequisites
First, ensure you have pytest installed:
bash
pip install pytest
1. The Application Code (math_lib.py)
Save this code in a file named math_lib.py. This file contains basic math functions and explicit error handling.
python
# math_lib.py
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def divide(a, b):
"""Returns the division of a by b. Raises error if b is zero."""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def is_prime(n):
"""Returns True if n is prime, False otherwise."""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
class Wallet:
"""A simple class to demonstrate testing class methods and state."""
def __init__(self, initial_amount=0):
self.balance = initial_amount
def spend_cash(self, amount):
if amount > self.balance:
raise InsufficientAmount("Not enough money in wallet!")
self.balance -= amount
return self.balance
def add_cash(self, amount):
self.balance += amount
return self.balance
class InsufficientAmount(Exception):
pass
2. The Test Script (test_math_lib.py)
Save this code in a file named test_math_lib.py. Pytest automatically discovers files starting with test_ or ending with _test.py.
This script demonstrates Basic Assertions, Exception Handling, Parametrization, and Fixtures.
python
import pytest
from math_lib import add, divide, is_prime, Wallet, InsufficientAmount
# --- 1. Basic Function Tests ---
def test_add_positive_numbers():
# Standard assertion: checks if left side equals right side
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-1, -1) == -2
def test_add_strings():
# Python's add function works with strings too
assert add("unit", "test") == "unittest"
# --- 2. Exception Handling Tests ---
def test_divide_by_zero_raises_error():
# We expect a ValueError to be raised
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
# Optional: Check if the error message matches
assert str(exc_info.value) == "Cannot divide by zero"
def test_divide_clean():
assert divide(10, 2) == 5
# --- 3. Parametrized Tests (Running same logic with multiple inputs) ---
@pytest.mark.parametrize("number, expected", [
(1, False),
(2, True),
(3, True),
(4, False),
(13, True),
(15, False)
])
def test_is_prime_parametrized(number, expected):
# This will run 6 times as 6 separate tests
assert is_prime(number) is expected
# --- 4. Fixtures (Setup and Teardown) ---
@pytest.fixture
def empty_wallet():
"""Returns a Wallet instance with 0 balance"""
return Wallet()
@pytest.fixture
def wallet_with_cash():
"""Returns a Wallet instance with 20 balance"""
return Wallet(20)
def test_default_initial_amount(empty_wallet):
assert empty_wallet.balance == 0
def test_setting_initial_amount(wallet_with_cash):
assert wallet_with_cash.balance == 20
def test_wallet_add_cash(wallet_with_cash):
wallet_with_cash.add_cash(80)
assert wallet_with_cash.balance == 100
def test_wallet_spend_cash(wallet_with_cash):
wallet_with_cash.spend_cash(10)
assert wallet_with_cash.balance == 10
def test_wallet_spend_too_much(wallet_with_cash):
# Wallet has 20, trying to spend 50
with pytest.raises(InsufficientAmount):
wallet_with_cash.spend_cash(50)
3. How to Run the Tests
Open your terminal (command line) in the directory where you saved the files and run:
bash
pytest
For more detailed output (seeing every test name):
bash
pytest -v
4. Understanding the Output
When you run pytest -v, you will see output similar to this:
assert: Unlike Python's unittest module (which uses self.assertEqual), pytest uses simple Python assert statements. Pytest performs "assertion rewriting" to provide detailed error messages when an assertion fails.
pytest.raises: This is a context manager used to test if your code correctly triggers errors/exceptions (like dividing by zero).
@pytest.mark.parametrize: This prevents code duplication. Instead of writing test_prime_2, test_prime_3, etc., you write one test logic and pass a list of inputs and expected outputs.
@pytest.fixture: Fixtures allow you to set up data (like the Wallet object) before tests run. This ensures each test runs in isolation with fresh data.