Migrate from requests
responses
Here's a few examples on how to migrate your code from the responses
library to respx
.
Patching the Client
Decorator
@responses.activate
def test_foo():
...
@respx.mock
def test_foo():
...
See Router Settings for more details.
Context Manager
def test_foo():
with responses.RequestsMock() as rsps:
...
def test_foo():
with respx.mock() as respx_mock:
...
See Router Settings for more details.
unittest setUp
def setUp(self):
self.responses = responses.RequestsMock()
self.responses.start()
self.addCleanup(self.responses.stop)
def setUp(self):
self.respx_mock = respx.mock()
self.respx_mock.start()
self.addCleanup(self.respx_mock.stop)
See unittest examples for more details.
Mock a Response
responses.add(
responses.GET, "https://example.org/",
json={"foo": "bar"},
status=200,
)
respx.get("https://example.org/").respond(200, json={"foo": "bar"})
See Routing Requests and Mocking Responses for more details.
Mock an Exception
responses.add(
responses.GET, "https://example.org/",
body=Exception("..."),
)
respx.get("https://example.org/").mock(side_effect=ConnectError)
See Exception Side Effect for more details.
Subsequent Responses
responses.add(responses.GET, "https://example.org/", status=200)
responses.add(responses.GET, "https://example.org/", status=500)
respx.get("https://example.org/").mock(
side_effect=[Response(200), Response(500)]
)
See Iterable Side Effect for more details.
Callbacks
def my_callback(request):
headers = {"Content-Type": "application/json"}
body = {"foo": "bar"}
return (200, headers, json.dumps(resp_body))
responses.add_callback(
responses.GET, "http://example.org/",
callback=my_callback,
)
def my_side_effect(request, route):
return Response(200, json={"foo": "bar"})
respx.get("https://example.org/").mock(side_effect=my_side_effect)
See Mock with a Side Effect for more details.
History and Assertions
History
responses.calls[0].request
responses.calls[0].response
respx.calls[0].request
respx.calls[0].response
request, response = respx.calls[0]
respx.calls.last.response
See Call History for more details.
Call Count
responses.assert_call_count("http://example.org/", 1)
route = respx.get("https://example.org/")
assert route.call_count == 1
See Call History for more details.
All Called
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
...
with respx.mock(assert_all_called=False) as respx_mock:
...
See Assert all Called for more details.
Modify Mocked Response
responses.add(responses.GET, "http://example.org/", json={"data": 1})
responses.replace(responses.GET, "http://example.org/", json={"data": 2})
respx.get("https://example.org/").respond(json={"data": 1})
respx.get("https://example.org/").respond(json={"data": 2})
Pass Through Requests
responses.add_passthru("https://example.org/")
respx.route(url="https://example.org/").pass_through()
See Pass Through for more details.
requests-mock
todo ... contribution welcome ;-)