smartyfy.mrindigi.com

Python Master Course V2 — 113. Testing Exceptions, Classes and Object State

What you will be able to do

  • Explain try/except, raise and exception contracts through a short bridge
  • Define a minimal class with __init__, methods and instance attributes
  • Test state transitions, invalid input and independent instances

Prerequisites: 051–060: functions; 112: pytest fixtures; no formal OOP or exception-handling course is assumed.

Your local workspace

Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson113, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.

Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.

python -m pip install pytest

The examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.

Bridge: exceptions are explicit failure paths

A normal return gives a caller a result. An exception interrupts that path and travels outward until a matching handler catches it. int("many") cannot return an integer, so it raises ValueError. A syntax error prevents a program from being parsed; a runtime exception occurs while syntactically valid code is executing. Read the final traceback line for the exception type and message, then follow the file and line information to the responsible call.

Use try around the operation that may fail and except for the specific condition you know how to handle. A handler is not a command to ignore every error. If a reservation cannot be accepted, a user interface might display a useful message; the reservation object should report failure without silently pretending that the booking succeeded. raise ValueError("message") creates that failure deliberately. Assertions belong in tests, while production validation needs explicit condition checks because optimized Python can remove assert statements.

try:
    requested = int("many")
except ValueError:
    print("Enter a whole number")

Expected output

Enter a whole number

The except block handles only the failed conversion. An unrelated TypeError would remain visible. In a larger program, preserve unexpected exceptions for diagnosis rather than converting every problem into an empty result.

Bridge: a class gives state an owner

A class describes a kind of object. Calling ReservationCounter(3) makes an instance, then __init__ establishes its initial attributes. The conventional parameter self refers to that instance. When you call counter.reserve(2), Python supplies counter as self; you supply only 2. An attribute such as self.reserved belongs to this instance, while a method is a function accessed through the object.

State is the information that survives between calls. Our capacity stays fixed by convention, and reserved changes after a successful operation. The invariant is 0 <= reserved <= capacity. Every public operation should preserve that rule. Separate instances must remain independent; a mutable list placed directly in the class body would instead be shared unless replaced on each instance. No inheritance, decorators or advanced object model is required for this example.

Validation order matters. Check type, range and available capacity before changing reserved. This gives the operation a simple failure guarantee: a rejected request leaves the count unchanged. bool is a subclass of int in Python, so isinstance(True, int) is true. This contract deliberately requires type(value) is int to reject booleans as reservation counts. That strict choice is appropriate here, but should not become an unexplained universal rule.

Build a reservation counter

def positive_integer(value, label):
    if type(value) is not int:
        raise TypeError(f"{label} must be an integer")
    if value <= 0:
        raise ValueError(f"{label} must be positive")


class ReservationCounter:
    def __init__(self, capacity):
        positive_integer(capacity, "capacity")
        self.capacity = capacity
        self.reserved = 0

    def reserve(self, amount):
        positive_integer(amount, "amount")
        if self.reserved + amount > self.capacity:
            raise ValueError("insufficient capacity")
        self.reserved += amount
        return self.reserved

    def cancel(self, amount):
        positive_integer(amount, "amount")
        if amount > self.reserved:
            raise ValueError("cannot cancel unreserved places")
        self.reserved -= amount
        return self.reserved

Save the following independent demonstration as demo.py in the same folder. Both a successful transition and a rejected transition have observable behavior. The last print is important: merely catching the exception would not prove state integrity.

from reservations import ReservationCounter

counter = ReservationCounter(3)
print(counter.reserve(2))
try:
    counter.reserve(2)
except ValueError as error:
    print(error)
print(counter.reserved)
print(counter.cancel(1))

Expected output

2
insufficient capacity
2
1

Guided lab: test the transition, rejection and independence

Save the suite below as test_reservations.py. Arrange a fresh counter per test. Use pytest.raises to assert a failure contract, then make a separate assertion about post-failure state. Assertions after the failing call must be outside the raises block: code after the exception inside that block would never run.

Run python -m pytest -q test_reservations.py. The expected outcome is three passing tests, with elapsed time varying. Add constructor tests before adding more methods: an object that starts in an invalid state is difficult to repair reliably. Then write cancellation tests for partial cancellation, cancellation of all reserved places and rejection of excessive cancellation.

import pytest
from reservations import ReservationCounter


def test_reserve_and_cancel():
    counter = ReservationCounter(3)
    assert counter.reserve(2) == 2
    assert counter.cancel(1) == 1
    assert counter.reserved == 1


def test_failed_reservation_does_not_mutate():
    counter = ReservationCounter(3)
    counter.reserve(2)
    with pytest.raises(ValueError, match="insufficient capacity"):
        counter.reserve(2)
    assert counter.reserved == 2


def test_instances_are_independent():
    first = ReservationCounter(3)
    second = ReservationCounter(3)
    first.reserve(1)
    assert (first.reserved, second.reserved) == (1, 0)

Debug a state bug by recording before, requested operation and after. If a test fails only after another case, inspect shared state or reused fixtures first. This object is educational and single-threaded: it does not provide durable reservations or protection against concurrent requests. A real booking service would need atomic storage rules rather than trusting this in-memory check.

Questions worth asking

What does self actually contain?

It refers to the instance receiving the method call. first.reserve(1) and second.reserve(1) invoke the same method definition with different objects as self. Accessing self.reserved therefore selects the count belonging to the receiving object.

Does __init__ return the new instance?

No. Normal construction creates the instance and then invokes __init__ to initialize it. The initializer should not return a non-None value. Treat it as the place to establish valid initial attributes, not as a factory that manually returns its object.

Why test state after an expected exception?

A method can raise the correct exception after corrupting data. Testing only its error type would miss that defect. The separate assertion verifies the promised failure guarantee, making the contract cover both the visible error and the absence of a state change.

Why distinguish TypeError from ValueError?

An unsupported kind of input, such as a string or boolean, violates the type contract. A supported integer with an unacceptable value, such as zero, violates the range contract. The distinction helps callers respond appropriately and makes debugging more specific.

Can a caller directly change reserved?

Yes; these attributes are accessible. The class expresses a contract, not a security boundary. More controlled interfaces can reduce accidental mutation, but tests should still focus on documented public operations. Protecting real shared inventory requires persistence and concurrency controls.

Should every function be converted into a class?

No. Use a plain function when inputs fully describe the computation and no identity or ongoing state is needed. This example benefits from a class because capacity and reservations belong together across a sequence of operations.

Practice, then compare your solution

1. Invalid construction

Test that capacity zero is rejected.

Worked solution and reasoning

Construction itself is the action that should raise. There is no usable counter to inspect afterward.

def test_zero_capacity():
    import pytest
    from reservations import ReservationCounter
    with pytest.raises(ValueError, match="capacity must be positive"):
        ReservationCounter(0)

2. Cancellation guarantee

A counter has one reserved place. Test cancel(2).

Worked solution and reasoning

Arrange reserve(1), expect ValueError with the cancellation message, then assert reserved == 1. This catches a common mistake: subtracting first and validating afterward.

Mastery checkpoint

Explain construction, self, attributes and methods using the two independent counters. Trace a successful call and a rejected call line by line. Your finished suite must cover initial state, both transitions, both boundaries, invalid types and unchanged state after failure. You now have the exception and object vocabulary needed for the testing lessons ahead.

Official documentation and next steps

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.