Exercise 2: An Upper-Bound Contract Check — Possible Solution ==================================================================== THE EXTENDED CONTRACT TEST ------------------------------ def contract_test_discount_strategy(strategy): result = strategy.apply(DISCOUNT_CONTRACT_INPUT) errors = [] if not isinstance(result, (int, float)): errors.append(f"apply() must return a number, got {type(result).__name__}") else: if result < 0: errors.append("apply() must not return a negative total") if result > DISCOUNT_CONTRACT_INPUT: errors.append(f"apply() must not return a total GREATER than the input, " f"got {result} > {DISCOUNT_CONTRACT_INPUT}") return errors class InflatingDiscount(DiscountStrategy): # deliberately broken def apply(self, total): return total * 1.1 # INCREASES the price RESULTS ------------------------------ NoDiscount: PASS GoldDiscount: PASS PlatinumDiscount: PASS InflatingDiscount: FAIL: ['apply() must not return a total GREATER than the input, got 110.00000000000001 > 100.0'] All three existing, legitimate strategies still pass the extended contract - none of them was ever close to violating the new upper- bound rule. The deliberately broken InflatingDiscount is caught immediately. WHY THIS WORKS AS AN ANSWER ------------------------------ This demonstrates a contract can be extended over time as new assumptions about "correct" become explicit, the same way Chapter 5's own contract test evolved when a new required field was added. It also reinforces Step 3's own real value: InflatingDiscount is exactly the kind of bug (a genuinely wrong new DiscountStrategy implementation) that a contract test catches in isolation, before it's ever wired into a real checkout flow where the consequence would be a customer charged more than the subtotal they started with.