Interview Prep/Python for DevOps/Testing, services & metrics

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.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics