Creates a mock Router
instance, ready to be used as decorator/manager for activation.
respx.mock(assert_all_mocked=True, assert_all_called=True, base_url=None)
Parameters:
- assert_all_mocked - (optional) bool - default:
True
Asserts that all sent and capturedHTTPX
requests are routed and mocked.
If disabled, all non-routed requests will be auto mocked with status code200
.- assert_all_called - (optional) bool - default:
True
Asserts that all added and mocked routes were called when exiting context.- base_url - (optional) str
Base URL to match, on top of each route specific pattern and/or side effect.Returns:
Router
!!! note "NOTE"
When using the default mock router respx.mock
, without settings, assert_all_called
is disabled.
!!! tip "pytest"
Use the @pytest.mark.respx(...)
marker with these parameters to configure the respx_mock
pytest fixture.
Adds a new, optionally named, Route
with given patterns and/or lookups combined, using the AND operator.
respx.route(*patterns, name=None, **lookups)
Parameters:
- patterns - (optional) args
One or more pattern objects.- lookups - (optional) kwargs
One or more pattern keyword lookups, given as<pattern>__<lookup>=value
.- name - (optional) str
Name this route.Returns:
Route
HTTP method helpers to add routes, mimicking the HTTPX Helper Functions.
respx.get(url, name=None, **lookups)
respx.options(...)
respx.head(...)
respx.post(...)
respx.put(...)
respx.patch(...)
respx.delete(...)
Parameters:
- url - (optional) str | compiled regex | tuple (httpcore) | httpx.URL
Request URL to match, full or partial, turned into a URL pattern.- name - (optional) str
Name this route.- lookups - (optional) kwargs
One or more pattern keyword lookups, given as<pattern>__<lookup>=value
.Returns:
Route
respx.get("https://example.org/", params={"foo": "bar"}, ...)
respx.request(method, url, name=None, **lookups)
Parameters:
- method - str
Request HTTP method to match.- url - (optional) str | compiled regex | tuple (httpcore) | httpx.URL
Request URL to match, full or partial, turned into a URL pattern.- name - (optional) str
Name this route.- lookups - (optional) kwargs
One or more pattern keyword lookups, given as<pattern>__<lookup>=value
.Returns:
Route
respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...)
Mock a route's response or side effect.
route.mock(return_value=None, side_effect=None)
Parameters:
- return_value - (optional) Response
HTTPX Response to mock and return.- side_effect - (optional) Callable | Exception | Iterable of httpx.Response/Exception
Side effect to call, exception to raise or stacked responses to respond with in order.Returns:
Route
Setter for the HTTPX
Response to return.
route.return_value = Response(204)
Setter for the side effect to trigger.
route.side_effect = ...
See route.mock() for valid side effect types.
Shortcut for creating and mocking a HTTPX
Response.
route.respond(status_code=200, headers=None, cookies=None, content=None, text=None, html=None, json=None, stream=None, content_type=None)
Parameters:
- status_code - (optional) int - default:
200
Response status code to mock.- headers - (optional) dict | Sequence[tuple[str, str]]
Response headers to mock.- cookies - (optional) dict | Sequence[tuple[str, str]] | Sequence[SetCookie]
Response cookies to mock asSet-Cookie
headers. See SetCookie.- content - (optional) bytes | str | Iterable[bytes]
Response raw content to mock.- text - (optional) str
Response text content to mock, with automatic content-type header added.- html - (optional) str
Response HTML content to mock, with automatic content-type header added.- json - (optional) str | list | dict
Response JSON content to mock, with automatic content-type header added.- stream - (optional) Iterable[bytes]
Response stream to mock.- content_type - (optional) str
ResponseContent-Type
header to mock.Returns:
Route
route.pass_through(value=True)
Parameters:
- value - (optional) bool - default:
True
Mark route to pass through, sending matched requests to real server, e.g. don't mock.Returns:
Route
!!! note "NOTE"
This is a partial reference for how to the instantiate the HTTPX Response
class, e.g. not a RESPX class.
httpx.Response(status_code, headers=None, content=None, text=None, html=None, json=None, stream=None)
Parameters:
- status_code - int
HTTP status code.- headers - (optional) dict | httpx.Headers
HTTP headers.- content - (optional) bytes | str | Iterable[bytes]
Raw content.- text - (optional) str
Text content, with automatic content-type header added.- html - (optional) str
HTML content, with automatic content-type header added.- json - (optional) str | list | dict
JSON content, with automatic content-type header added.- stream - (optional) Iterable[bytes]
Content stream.
!!! tip "Cookies"
Use respx.SetCookie(...) to produce Set-Cookie
headers.
A utility to render a ("Set-Cookie", <cookie header value>)
tuple. See route respond shortcut for alternative use.
respx.SetCookie(name, value, path=None, domain=None, expires=None, max_age=None, http_only=False, same_site=None, secure=False, partitioned=False)
import respx
respx.post("https://example.org/").mock(
return_value=httpx.Response(200, headers=[SetCookie("foo", "bar")])
)
Creates a reusable pattern, combining multiple arguments using the AND operator.
M(*patterns, **lookups)
Parameters:
- patterns - (optional) args
One or more pattern objects.- lookups - (optional) kwargs
One or more pattern keyword lookups, given as<pattern>__<lookup>=value
.Returns:
Pattern
import respx
from respx.patterns import M
pattern = M(host="example.org")
respx.route(pattern)
See operators for advanced usage.
Matches request HTTP method, using eq
as default lookup.
respx.route(method="GET")
respx.route(method__in=["PUT", "PATCH"])
Matches request URL scheme, using eq
as default lookup.
respx.route(scheme="https")
respx.route(scheme__in=["http", "https"])
Matches request URL host, using eq
as default lookup.
respx.route(host="example.org")
respx.route(host__regex=r"example\.(org|com)")
respx.route(host__in=["example.org", "example.com"])
Matches request URL port, using eq
as default lookup.
respx.route(port=8000)
respx.route(port__in=[2375, 2376])
Matches request URL path, using eq
as default lookup.
Key:
path
Lookups: eq, regex, startswith, in
respx.route(path="/api/foobar/")
respx.route(path__regex=r"^/api/(?P<slug>\w+)/")
respx.route(path__startswith="/api/")
respx.route(path__in=["/api/v1/foo/", "/api/v2/foo/"])
Matches request URL query params, using contains
as default lookup.
respx.route(params={"foo": "bar", "ham": "spam"})
respx.route(params=[("foo", "bar"), ("ham", "spam")])
respx.route(params=(("foo", "bar"), ("ham", "spam")))
respx.route(params="foo=bar&ham=spam")
!!! note "NOTE"
A request querystring with multiple parameters of the same name is treated as an ordered list when matching.
!!! tip "ANY value"
Use mock.ANY
as value to only match on parameter presence, e.g. respx.route(params={"foo": ANY})
.
Matches request URL.
When no lookup is given, url
works as a shorthand pattern, combining individual request URL parts, using the AND operator.
Key:
url
Lookups: eq, regex, startswith
respx.get("//example.org/foo/") # == M(host="example.org", path="/foo/")
respx.get(url__eq="https://example.org:8080/foobar/?ham=spam")
respx.get(url__regex=r"https://example.org/(?P<slug>\w+)/")
respx.get(url__startswith="https://example.org/api/")
respx.get("all://*.example.org/foo/")
Matches request raw content, using eq as default lookup.
respx.post("https://example.org/", content="foobar")
respx.post("https://example.org/", content=b"foobar")
respx.post("https://example.org/", content__contains="bar")
Matches request form data, excluding files, using eq as default lookup.
respx.post("https://example.org/", data={"foo": "bar"})
Matches files within request form data, using contains as default lookup.
respx.post("https://example.org/", files={"some_file": b"..."})
respx.post("https://example.org/", files={"some_file": ANY})
respx.post("https://example.org/", files={"some_file": ("filename.txt", b"...")})
respx.post("https://example.org/", files={"some_file": ("filename.txt", ANY)})
Matches request json content, using eq as default lookup.
Key:
json
Lookups: eq
respx.post("https://example.org/", json={"foo": "bar"})
The json
pattern also supports path traversing, i.e. json__<path>=<value>
.
respx.post("https://example.org/", json__foobar__0__ham="spam")
httpx.post("https://example.org/", json={"foobar": [{"ham": "spam"}]})
Matches request headers, using contains as default lookup.
respx.route(headers={"foo": "bar", "ham": "spam"})
respx.route(headers=[("foo", "bar"), ("ham", "spam")])
Matches request cookie header, using contains as default lookup.
respx.route(cookies={"foo": "bar", "ham": "spam"})
respx.route(cookies=[("foo", "bar"), ("ham", "spam")])
M(path="/foo/bar/")
M(path__eq="/foo/bar/")
Case-sensitive containment test.
M(params__contains={"id": "123"})
Case-sensitive within test.
M(method__in=["PUT", "PATCH"])
M(path__regex=r"^/api/(?P<slug>\w+)/")
Case-sensitive starts-with.
M(path__startswith="/api/")
Patterns can be combined using bitwise operators, creating new patterns.
Combines two Pattern
s using and
operator.
M(scheme="http") & M(host="example.org")
Combines two Pattern
s using or
operator.
M(method="PUT") | M(method="PATCH")
Inverts a Pattern
match.
~M(params={"foo": "bar"})