
Code
Pass the Clock In
How do you test this?
def greeting():
hour = datetime.datetime.now().hour
...
The answer changes depending on when you run the test! The function reaches out and grabs the real clock itself, so a test can't control it.
Dependency injection
Dependency injection is a fancy name for a simple idea: pass the things a function depends on in as parameters. A sensible default keeps normal calls easy:
def greeting(clock=datetime.datetime.now):
hour = clock().hour
...
greeting() # real clock
greeting(lambda: datetime.datetime(2026, 1, 1, 9)) # fake 9am
Now tests can pass a fake clock for any time they want. No mocks
or patching needed. The same trick works for random generators,
file systems, databases and notifiers (like warn_dark earlier).
Assignment
- Refactor
lantern_greetingto take aclockparameter that defaults todatetime.datetime.now, and callclock(). Hours 5–11 give"Good morning", 12–17 give"Good afternoon", anything else gives"Good evening". - Write
test_greeting()using fake clocks for the boundary hours (at least 5, 11, 12, 17, 18 and 4). It must pass now and catch bugs.
- Refactor
lantern_greetingto take aclockparameter that defaults todatetime.datetime.now, and callclock(). Hours 5–11 give"Good morning", 12–17 give"Good afternoon", anything else gives"Good evening". - Write
test_greeting()using fake clocks for the boundary hours (at least 5, 11, 12, 17, 18 and 4). It must pass now and catch bugs.
main.py Python sleeping
Press Run to try your code, then Check to test it.