Skip to main content

Testing & Edge Cases

Editorial

Testing Strategy

Our testing strategy follows the class structure — we test bottom-up, starting with the smallest units (enums, spots) and building up to the orchestrator (ParkingLot). Each test targets a single class and a single behavior.

What to test for each class:

ClassWhat to Test
ParkingSpotCompatibility checks, park/unpark state transitions, double-park rejection
FloorFinding available spots, full-floor detection, spot counting
PricingStrategy (each impl)Fee calculation for various durations, boundary values
ParkingTicketCorrect initialization, entry time recording
ParkingLotEnd-to-end park/unpark, lot-full handling, invalid ticket handling

Testing principle: We don't test private internals. We test the public API — the methods that other classes call. If ParkingSpot.park() sets is_occupied = True, we verify it through is_available(), not by inspecting the private field.

Unit Tests — ParkingSpot

The ParkingSpot tests verify the compatibility rules and state management — the foundation of correct parking behavior.

import pytest
from parking_lot import ParkingSpot, SpotType, Car, Truck, Motorcycle


class TestParkingSpot:
    """Tests for ParkingSpot — compatibility and state transitions."""

    # --- Compatibility Tests ---

    def test_compact_spot_allows_motorcycle(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        bike = Motorcycle("MOTO-001")
        assert spot.can_fit(bike) is True

    def test_compact_spot_allows_car(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        car = Car("CAR-001")
        assert spot.can_fit(car) is True

    def test_compact_spot_rejects_truck(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        truck = Truck("TRK-001")
        assert spot.can_fit(truck) is False

    def test_large_spot_allows_all_vehicle_types(self):
        spot = ParkingSpot("F1-L1", SpotType.LARGE)
        assert spot.can_fit(Motorcycle("M1")) is True
        assert spot.can_fit(Car("C1")) is True
        assert spot.can_fit(Truck("T1")) is True

    def test_regular_spot_rejects_truck(self):
        spot = ParkingSpot("F1-R1", SpotType.REGULAR)
        assert spot.can_fit(Truck("T1")) is False

    # --- State Transition Tests ---

    def test_new_spot_is_available(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        assert spot.is_available() is True

    def test_park_makes_spot_unavailable(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        car = Car("CAR-001")
        spot.park(car)
        assert spot.is_available() is False

    def test_unpark_makes_spot_available_again(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        car = Car("CAR-001")
        spot.park(car)
        spot.unpark()
        assert spot.is_available() is True

    def test_park_stores_correct_vehicle(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        car = Car("CAR-001")
        spot.park(car)
        assert spot.vehicle == car

    def test_unpark_clears_vehicle(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        car = Car("CAR-001")
        spot.park(car)
        spot.unpark()
        assert spot.vehicle is None

    # --- Edge Cases ---

    def test_park_on_occupied_spot_raises_error(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        spot.park(Car("CAR-001"))
        with pytest.raises(ValueError, match="already occupied"):
            spot.park(Car("CAR-002"))

    def test_unpark_on_empty_spot_raises_error(self):
        spot = ParkingSpot("F1-C1", SpotType.COMPACT)
        with pytest.raises(ValueError, match="already empty"):
            spot.unpark()
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import static org.junit.jupiter.api.Assertions.*;

class ParkingSpotTest {

    // --- Compatibility Tests ---

    @Test
    @DisplayName("Compact spot allows motorcycle")
    void compactSpotAllowsMotorcycle() {
        ParkingSpot spot = new ParkingSpot("F1-C1", SpotType.COMPACT);
        assertTrue(spot.canFit(new Motorcycle("MOTO-001")));
    }

    @Test
    @DisplayName("Compact spot rejects truck")
    void compactSpotRejectsTruck() {
        ParkingSpot spot = new ParkingSpot("F1-C1", SpotType.COMPACT);
        assertFalse(spot.canFit(new Truck("TRK-001")));
    }

    @Test
    @DisplayName("Large spot accepts all vehicle types")
    void largeSpotAcceptsAll() {
        ParkingSpot spot = new ParkingSpot("F1-L1", SpotType.LARGE);
        assertAll(
            () -> assertTrue(spot.canFit(new Motorcycle("M1"))),
            () -> assertTrue(spot.canFit(new Car("C1"))),
            () -> assertTrue(spot.canFit(new Truck("T1")))
        );
    }

    // --- State Transition Tests ---

    @Test
    @DisplayName("Park on occupied spot throws exception")
    void parkOnOccupiedSpotThrows() {
        ParkingSpot spot = new ParkingSpot("F1-C1", SpotType.COMPACT);
        spot.park(new Car("CAR-001"));

        assertThrows(IllegalStateException.class,
            () -> spot.park(new Car("CAR-002")));
    }

    @Test
    @DisplayName("Unpark on empty spot throws exception")
    void unparkOnEmptySpotThrows() {
        ParkingSpot spot = new ParkingSpot("F1-C1", SpotType.COMPACT);
        assertThrows(IllegalStateException.class, spot::unpark);
    }
}

Unit Tests — PricingStrategy

Pricing tests verify fee calculations for boundary durations — these are the most common source of bugs in real parking systems.

import pytest
from datetime import timedelta
from parking_lot import HourlyPricing, FlatRatePricing


class TestHourlyPricing:
    """Tests for HourlyPricing — charges per hour, rounds up."""

    def test_exactly_one_hour(self):
        pricing = HourlyPricing(hourly_rate=10.0)
        fee = pricing.calculate_fee(timedelta(hours=1))
        assert fee == 10.0

    def test_partial_hour_rounds_up(self):
        pricing = HourlyPricing(hourly_rate=10.0)
        fee = pricing.calculate_fee(timedelta(hours=1, minutes=1))
        assert fee == 20.0  # 1h1m → rounds up to 2 hours

    def test_exactly_two_hours(self):
        pricing = HourlyPricing(hourly_rate=10.0)
        fee = pricing.calculate_fee(timedelta(hours=2))
        assert fee == 20.0

    def test_zero_duration(self):
        pricing = HourlyPricing(hourly_rate=10.0)
        fee = pricing.calculate_fee(timedelta(seconds=0))
        assert fee == 0.0

    def test_less_than_one_hour(self):
        pricing = HourlyPricing(hourly_rate=10.0)
        fee = pricing.calculate_fee(timedelta(minutes=30))
        assert fee == 10.0  # Any partial hour → 1 hour

    def test_24_hours(self):
        pricing = HourlyPricing(hourly_rate=10.0)
        fee = pricing.calculate_fee(timedelta(hours=24))
        assert fee == 240.0


class TestFlatRatePricing:
    """Tests for FlatRatePricing — fixed fee regardless of duration."""

    def test_flat_rate_for_short_duration(self):
        pricing = FlatRatePricing(flat_rate=50.0)
        fee = pricing.calculate_fee(timedelta(minutes=30))
        assert fee == 50.0

    def test_flat_rate_for_long_duration(self):
        pricing = FlatRatePricing(flat_rate=50.0)
        fee = pricing.calculate_fee(timedelta(hours=24))
        assert fee == 50.0  # Same fee regardless

    def test_flat_rate_for_zero_duration(self):
        pricing = FlatRatePricing(flat_rate=50.0)
        fee = pricing.calculate_fee(timedelta(seconds=0))
        assert fee == 50.0  # Still charges flat rate
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;

class HourlyPricingTest {

    @Test
    void exactlyOneHour() {
        HourlyPricing pricing = new HourlyPricing(10.0);
        assertEquals(10.0, pricing.calculateFee(Duration.ofHours(1)));
    }

    @Test
    void partialHourRoundsUp() {
        HourlyPricing pricing = new HourlyPricing(10.0);
        assertEquals(20.0, pricing.calculateFee(Duration.ofMinutes(61)));
    }

    @Test
    void zeroDuration() {
        HourlyPricing pricing = new HourlyPricing(10.0);
        assertEquals(0.0, pricing.calculateFee(Duration.ZERO));
    }
}

class FlatRatePricingTest {

    @Test
    void sameRateRegardlessOfDuration() {
        FlatRatePricing pricing = new FlatRatePricing(50.0);
        assertEquals(50.0, pricing.calculateFee(Duration.ofMinutes(30)));
        assertEquals(50.0, pricing.calculateFee(Duration.ofHours(24)));
    }
}

Unit Tests — ParkingLot Integration

These tests verify the end-to-end parking flow — from parkVehicle through ticket creation to unparkVehicle and fee calculation. They test ParkingLot as the orchestrator, which exercises the interaction between all classes.

import pytest
from datetime import datetime, timedelta
from unittest.mock import patch
from parking_lot import (
    ParkingLot, Floor, ParkingSpot, SpotType,
    Car, Truck, Motorcycle, HourlyPricing
)


def create_small_lot() -> ParkingLot:
    """Helper: Creates a minimal lot for testing.
    Floor 1: 1 compact, 1 regular, 1 large spot.
    """
    spots = [
        ParkingSpot("F1-C1", SpotType.COMPACT),
        ParkingSpot("F1-R1", SpotType.REGULAR),
        ParkingSpot("F1-L1", SpotType.LARGE),
    ]
    floor = Floor(floor_number=1, spots=spots)
    return ParkingLot(
        name="Test Lot",
        floors=[floor],
        pricing_strategy=HourlyPricing(hourly_rate=10.0)
    )


class TestParkingLotPark:
    """Tests for the park vehicle flow."""

    def test_park_car_returns_ticket(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        assert ticket is not None
        assert ticket.vehicle.license_plate == "CAR-001"

    def test_park_assigns_compatible_spot(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        # Car should get COMPACT or REGULAR, not necessarily LARGE
        assert ticket.spot.spot_type in (SpotType.COMPACT, SpotType.REGULAR, SpotType.LARGE)

    def test_park_truck_skips_compact_and_regular(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Truck("TRK-001"))
        assert ticket.spot.spot_type == SpotType.LARGE

    def test_park_marks_spot_as_occupied(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        assert ticket.spot.is_available() is False


class TestParkingLotUnpark:
    """Tests for the unpark vehicle flow."""

    def test_unpark_returns_fee(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        fee = lot.unpark_vehicle(ticket.ticket_id)
        assert isinstance(fee, float)
        assert fee >= 0

    def test_unpark_frees_spot(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        spot = ticket.spot
        lot.unpark_vehicle(ticket.ticket_id)
        assert spot.is_available() is True

    def test_unpark_with_known_duration(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        # Mock the entry time to exactly 2 hours ago
        ticket.entry_time = datetime.now() - timedelta(hours=2)
        fee = lot.unpark_vehicle(ticket.ticket_id)
        assert fee == 20.0  # 2 hours × $10/hour

    def test_unpark_removes_ticket_from_active(self):
        lot = create_small_lot()
        ticket = lot.park_vehicle(Car("CAR-001"))
        ticket_id = ticket.ticket_id
        lot.unpark_vehicle(ticket_id)
        with pytest.raises(ValueError):
            lot.unpark_vehicle(ticket_id)  # Second unpark should fail
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;

class ParkingLotTest {

    private ParkingLot lot;

    @BeforeEach
    void setUp() {
        List<ParkingSpot> spots = List.of(
            new ParkingSpot("F1-C1", SpotType.COMPACT),
            new ParkingSpot("F1-R1", SpotType.REGULAR),
            new ParkingSpot("F1-L1", SpotType.LARGE)
        );
        Floor floor = new Floor(1, spots);
        lot = new ParkingLot("Test Lot", List.of(floor), new HourlyPricing(10.0));
    }

    @Test
    void parkCarReturnsTicket() {
        ParkingTicket ticket = lot.parkVehicle(new Car("CAR-001"));
        assertNotNull(ticket);
        assertEquals("CAR-001", ticket.getVehicle().getLicensePlate());
    }

    @Test
    void truckOnlyGetsLargeSpot() {
        ParkingTicket ticket = lot.parkVehicle(new Truck("TRK-001"));
        assertEquals(SpotType.LARGE, ticket.getSpot().getSpotType());
    }

    @Test
    void unparkFreesSpotAndReturnsFee() {
        ParkingTicket ticket = lot.parkVehicle(new Car("CAR-001"));
        ParkingSpot spot = ticket.getSpot();
        double fee = lot.unparkVehicle(ticket.getTicketId());
        assertTrue(spot.isAvailable());
        assertTrue(fee >= 0);
    }

    @Test
    void doubleUnparkThrowsException() {
        ParkingTicket ticket = lot.parkVehicle(new Car("CAR-001"));
        lot.unparkVehicle(ticket.getTicketId());
        assertThrows(IllegalArgumentException.class,
            () -> lot.unparkVehicle(ticket.getTicketId()));
    }
}

Edge Cases

Edge cases are where designs break. In interviews, identifying these proactively shows system-level thinking. Here are the critical edge cases for the Parking Lot, organized by severity.

Edge Case 1: Lot Full — No Compatible Spot Available

Scenario: A truck arrives, but all LARGE spots are taken. COMPACT and REGULAR spots exist but can't fit a truck.

Expected behavior: parkVehicle() raises an exception or returns None — NOT silently assigning an incompatible spot.

Why it matters: If we assign a COMPACT spot to a truck, the compatibility invariant is broken. Downstream code (fee calculation, spot counting) assumes valid assignments. This would be a data integrity bug.

Test:

def test_lot_full_for_truck_but_not_for_car(self):
    lot = create_small_lot()  # 1 compact, 1 regular, 1 large
    lot.park_vehicle(Truck("T1"))  # Takes the only LARGE spot
    
    # Car can still park (compact or regular available)
    ticket = lot.park_vehicle(Car("C1"))
    assert ticket is not None
    
    # Another truck has no compatible spot
    with pytest.raises(ParkingFullError):
        lot.park_vehicle(Truck("T2"))

Edge Case 2: Double Unpark — Same Ticket Used Twice

Scenario: Client calls unparkVehicle(ticketId) twice with the same ticket ID.

Expected behavior: First call succeeds. Second call raises an error — the ticket no longer exists in activeTickets.

Why it matters: Without this check, the second call would try to access a deleted ticket, causing a KeyError (Python) or NullPointerException (Java). The spot would be "double-freed" — potentially allowing it to be unparked when empty.

Edge Case 3: Concurrent Access to Last Spot

Scenario: Two vehicles arrive simultaneously. Only one COMPACT spot remains. Both threads call parkVehicle() at the same time.

Expected behavior: Only one vehicle gets the spot. The other receives a "lot full" response.

Why it matters: Without synchronization, both threads could see the spot as available, both assign it, and the spot ends up with two vehicles — violating the single-occupancy invariant.

Our scope: In this Easy-level problem, we don't implement concurrency control. But you should mention this in interviews:

"In a production system, parkVehicle would need synchronization — either a lock on the spot or an optimistic concurrency check. For this design, I'm assuming single-threaded access."

Edge Case 4: Vehicle Already Parked

Scenario: A car with license plate "ABC-123" is already parked. The same license plate tries to park again.

Expected behavior: The system should reject the second parking attempt. The same vehicle cannot occupy two spots.

Implementation consideration: We'd need a lookup by license plate — a Set<String> of parked plates that's checked on entry. This is a minor enhancement to our current design:

def park_vehicle(self, vehicle: Vehicle) -> ParkingTicket:
    if vehicle.license_plate in self._parked_plates:
        raise ValueError(f"Vehicle {vehicle.license_plate} is already parked")
    # ... find spot and create ticket
    self._parked_plates.add(vehicle.license_plate)
    return ticket

Edge Case 5: Zero-Duration Parking

Scenario: A vehicle parks and immediately unparks (entry time ≈ exit time).

Expected behavior: With HourlyPricing, zero duration → $0 fee. With FlatRatePricing, zero duration → full flat rate (you still used the service).

Why it matters: This is a business decision, not a bug. But the implementation must handle timedelta(0) without errors. Our ceil(hours) calculation for hourly pricing correctly returns 0 for zero duration.

Edge Case 6: Pricing Strategy Not Set

Scenario: ParkingLot is constructed without a PricingStrategy (or it's set to None).

Expected behavior: unparkVehicle() should fail fast with a clear error — NOT return None or silently charge $0.

Implementation: Validate in the constructor:

def __init__(self, name, floors, pricing_strategy):
    if pricing_strategy is None:
        raise ValueError("PricingStrategy is required")
    self.pricing_strategy = pricing_strategy

Interview Follow-Up Questions

After presenting your Parking Lot design, interviewers typically probe with extension questions to test flexibility. Here are the most common ones and how to answer them.

Q1: "How would you add reservation support?"

Add a Reservation class that holds a time slot and a spot reference. ParkingLot gets a reserveSpot(vehicleType, startTime, endTime) method that marks the spot as reserved (but not occupied). On arrival, the reserved vehicle is directed to their specific spot. This requires a new state for ParkingSpot: AVAILABLE → RESERVED → OCCUPIED → AVAILABLE.

Q2: "What if different floors have different pricing?"

Move the PricingStrategy reference from ParkingLot to Floor. Each floor can have its own pricing — premium floors near the entrance charge more. The unparkVehicle method calls ticket.spot.floor.pricingStrategy.calculateFee(duration) instead of self.pricingStrategy.calculateFee(duration).

Q3: "How would you handle electric vehicle charging spots?"

Add ELECTRIC to SpotType and ElectricVehicle to the vehicle hierarchy. Electric spots have a ChargingStation component (composition). The compatibility map is updated: electric vehicles can park in electric spots AND regular spots, but non-electric vehicles cannot use electric spots. This requires no changes to the core park/unpark flow — only the compatibility rules expand.

Q4: "How would you add a display board showing available spots per floor?"

This is the Observer Pattern (Fundamentals S12). A DisplayBoard subscribes to spot status changes. When ParkingSpot.park() or unpark() is called, it notifies all observers. The display board updates its counters without polling.

Q5: "What about payment integration — credit cards, mobile payments?"

This is another Strategy Pattern application. Create a PaymentStrategy interface with implementations like CreditCardPayment, MobilePayment, CashPayment. The unparkVehicle method calculates the fee (via PricingStrategy) and then processes payment (via PaymentStrategy). Two separate strategies for two separate concerns — SRP in action.