Use responses as a context manager
masterIf you don't want to decorate the entire function, use responses.RequestsMock() as a context manager. Requests made inside the with block are mocked, while requests made outside the block will hit the real server.
import responses
import requests
def test_my_api():
with responses.RequestsMock() as rsps:
rsps.add(
responses.GET,
"http://twitter.com/api/1/foobar",
body="{}",
status=200,
content_type="application/json",
)
resp = requests.get("http://twitter.com/api/1/foobar")
assert resp.status_code == 200
# Outside the context manager, requests hit the real server
resp = requests.get("http://twitter.com/api/1/foobar")
# This will likely return a 404 from the real server