How do you test HTTP-calling code without hitting the network?
IntermediateConceptTesting, services & metrics
Answer
Use responses (for requests) or respx (for httpx) to register fake responses:
import responses
@responses.activate
def test_latest_release():
responses.get("https://api.github.com/repos/acme/app/releases/latest",
json={"tag_name": "v1.4.2"}, status=200)
assert latest_release("acme/app") == "v1.4.2"
Unregistered calls raise ConnectionError, which also guarantees tests never leak to real services. Also test the failure paths (500, timeout, 429 with Retry-After) since retry logic is where bugs hide.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner