Predict the Mock Behavior
Intermediate · Predict the output · from Python Mocking and Fixtures: Test Code with External Dependencies
From the lesson: Python Mocking and Fixtures: Test Code with External Dependencies
Before car companies test a new vehicle in a real crash, they use a crash test dummy. The dummy is a stand-in for a real person - it behaves similarly enough to be useful, but nobody gets hurt.
Read the lessonRead this code carefully. A mock logger tracks method calls. Predict exactly what gets printed.
class MockLogger:
def __init__(self):
self.messages = []
def log(self, level, message):
self.messages.append(f'[{level}] {message}')
def process_order(logger, item, quantity):
logger.log('INFO', f'Processing {quantity}x {item}')
if quantity > 100:
logger.log('WARNING', 'Large order detected')
logger.log('INFO', 'Order complete')
logger = MockLogger()
process_order(logger, 'Widget', 150)
for msg in logger.messages:
print(msg)
print(f'Total logs: {len(logger.messages)}')
More Mocking exercises
- Create a Mock Email ServiceIntermediate
- Mock the ClockAdvanced
- Build a Test FixtureAdvanced
- Fix the Broken MockAdvanced