Testing with fakes

Code that reads the clock, the network or a file is hard to test. The answer changes every run, or needs a real server.

The fix is dependency injection: pass the thing in instead of reaching out for it. A function that takes now as an argument can be tested with any time you like. A function that takes a fetch function can be tested with a fake that returns canned data from a dict.

def greeting() -> str:                   # hard to test
    hour = datetime.now().hour
    ...
def greeting(hour: int) -> str:          # easy to test
    ...

In design interviews this is how you answer "how would you test this?": the parts that talk to the outside world sit behind a small interface, and tests swap in fakes.

Run it. Then add a fake user to FAKE_USERS and look them up.