PythiloLesson 8 of 12 · progress kept in this browser

monkeypatch

Code that reads the clock, draws random numbers or looks at environment variables gives a different answer on every run. pytest's monkeypatch fixture replaces those sources for one test and undoes every change when the test ends, pass or fail.

import random
import pytest

def roll():
    return random.randint(1, 6)

# In a test, ask for monkeypatch instead.
with pytest.MonkeyPatch.context() as mp:
    mp.setattr(random, "randint",
               lambda low, high: 6)
    print(roll(), roll())
print(1 <= roll() <= 6)
Your task

make_token and api_base are written for you. Write test_token_uses_clock_and_random(monkeypatch), fixing time.time at 1700000000.9 and random.randint at 4242 and checking the whole token; test_api_base_from_environment(monkeypatch), setting API_BASE to http://localhost:8000/; and test_api_base_default(monkeypatch), removing API_BASE.

The first run loads pytest into this browser.