RESPX supports side_effect mocking, which behaves similarly to Python's built-in Mock object. side_effect takes precedence over return_value.
Function side effects
Functions are called with the captured request argument. They can:
- Return an
httpx.Response. - Raise an
Exception. - Return
None to treat the route as a non-match (continuing to the next route). - Return the input
Request to pass the request through. - Advanced: If the route uses regex with named groups, those groups are passed as
kwargs to the function. You can also include a route argument to access call stats or modify the route.
Exception side effects
Pass an httpx.HTTPError subclass or any Exception to simulate request errors.
Iterable side effects
Pass an iterable (like a list) to return/raise different responses for repeated requests in order. Once the iterable is exhausted, a StopIteration is raised. You can use itertools to create infinite sequences.
import httpx
import respx
# 1. Function side effect with request and route
def my_side_effect(request, route):
return httpx.Response(201, json={"id": route.call_count + 1})
@respx.mock
def test_side_effect():
respx.post("https://example.org/").mock(side_effect=my_side_effect)
response = httpx.post("https://example.org/")
assert response.json() == {"id": 1}
# 2. Regex named groups passed as kwargs
def my_side_effect_kwargs(request, slug):
return httpx.Response(200, json={"slug": slug})
@respx.mock
def test_regex_kwargs():
route = respx.route(url__regex=r"https://example.org/(?P<slug>\w+)/")
route.side_effect = my_side_effect_kwargs
response = httpx.get("https://example.org/foobar/")
assert response.json() == {"slug": "foobar"}
# 3. Exception side effect
@respx.mock
def test_connection_error():
respx.get("https://example.org/").mock(side_effect=httpx.ConnectError)
# ... triggers error
# 4. Iterable side effect
@respx.mock
def test_stacked_responses():
route = respx.get("https://example.org/")
route.side_effect = [httpx.Response(404), httpx.Response(200)]
# First call returns 404, second returns 200