Editor

Mock the Clock

Advanced · Write the code · 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 lesson

The get_greeting function uses get_current_hour() to decide the greeting. Monkey-patch get_current_hour to test all three cases: morning (hour=9), afternoon (hour=14), and evening (hour=20). Use try/finally to restore the original. Print each greeting on its own line, then print Time mock test passed!.

def get_current_hour():
# In real code, this would use datetime
return 12
def get_greeting():
hour = get_current_hour()
if hour < 12:
return 'Good morning!'
elif hour < 17:
return 'Good afternoon!'
else:
return 'Good evening!'
# Monkey-patch get_current_hour to test all 3 greetings
# Remember to restore the original!

More Mocking exercises

All Python exercises · 50 practice problems · Testing quiz