You're given a small Python repo. After creating and activating a clean virtual environment, installing requirements, and running "pytest -q", two tests intermittently fail with state leakage. Consider this simplified core function:
file: cart.py
STATE = {}
def add_item(cart=None, item_id=None, qty=1, price=0.0, discounts=[]):
if cart is None:
cart = STATE
if item_id in cart:
cart[item_id]['qty'] += qty
else:
cart[item_id] = {'qty': qty, 'price': price, 'discounts': discounts}
total = sum(v['qty']*v['price'] for v in cart.values())
total -= sum(d for v in cart.values() for d in v['discounts'])
return total
Tasks:
-
Precisely explain what this function does on a single call and over multiple calls; identify at least three concrete design problems that can cause flakiness or poor readability (e.g., shared mutable defaults, hidden global state, mixing state mutation with aggregation).
-
Write a minimal pytest test that reliably exposes the shared-mutable-default bug for discounts (no external files; use plain asserts).
-
Refactor add_item to eliminate global state and mutable defaults, improve readability and type safety (e.g., dataclasses or simple dicts with type hints), and make the function pure where appropriate. Briefly justify API/structure changes.
-
Show how you would organize tests and fixtures (e.g., tmp_path, monkeypatch) and mock time or randomness if needed; explain how you'd make the suite deterministic.
-
List the exact shell commands you would run for environment setup, dependency pinning for reproducibility, and running tests with coverage locally and in CI.