### Patch Client with unittest setUp Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate 'unittest' setup for 'responses' to 'respx'. ```python import responses def setUp(self): self.responses = responses.RequestsMock() self.responses.start() self.addCleanup(self.responses.stop) ``` ```python import respx def setUp(self): self.respx_mock = respx.mock() self.respx_mock.start() self.addCleanup(self.respx_mock.stop) ``` -------------------------------- ### Install RESPX via pip Source: https://github.com/lundberg/respx/blob/master/README.md Command to install the library using pip. ```console $ pip install respx ``` -------------------------------- ### Configure Router Settings Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Examples of passing configuration arguments to decorators, context managers, and fixtures. ```python @respx.mock(...) def test_something(respx_mock): ... ``` ```python with respx.mock(...) as respx_mock: ... ``` ```python @pytest.mark.respx(...) def test_something(respx_mock): ... ``` -------------------------------- ### Lookup Examples Source: https://github.com/lundberg/respx/blob/master/docs/api.md Provides examples of different lookup types used for matching request parameters. ```APIDOC ## Lookups ### eq #### Description Exact match lookup. #### Example ```python M(path__eq="/foo/bar/") ``` ### contains #### Description Case-sensitive containment test. #### Example ```python M(params__contains={"id": "123"}) ``` ### in #### Description Case-sensitive within test. #### Example ```python M(method__in=["PUT", "PATCH"]) ``` ### regex #### Description Regular expression match. #### Example ```python M(path__regex=r"^/api/(?P\\w+)/$") ``` ### startswith #### Description Case-sensitive starts-with match. #### Example ```python M(path__startswith="/api/") ``` ``` -------------------------------- ### Operator Examples Source: https://github.com/lundberg/respx/blob/master/docs/api.md Demonstrates how to combine multiple patterns using logical operators. ```APIDOC ## Operators ### AND (&) #### Description Combines two patterns using the AND operator. #### Example ```python M(scheme="http") & M(host="example.org") ``` ### OR (|) #### Description Combines two patterns using the OR operator. #### Example ```python M(method="PUT") | M(method="PATCH") ``` ### INVERT (~) #### Description Inverts a pattern match. #### Example ```python ~M(params={"foo": "bar"}) ``` ``` -------------------------------- ### Unittest: Reuse Setup & Teardown - MockedAPIMixin Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Create a mixin class for unittest to manage Respx mocking setup and teardown. This allows for reusable mocking configurations across multiple test classes. ```python # testcases.py import respx from httpx import Response class MockedAPIMixin: @classmethod def setUpClass(cls): cls.mocked_api = respx.mock( base_url="https://foo.bar", assert_all_called=False ) users_route = cls.mocked_api.get("/users/", name="list_users") users_route.return_value = Response(200, json=[]) ... def setUp(self): self.mocked_api.start() self.addCleanup(self.mocked_api.stop) ``` ```python # test_api.py import httpx import unittest from .testcases import MockedAPIMixin class APITestCase(MockedAPIMixin, unittest.TestCase): def test_list_users(self): response = httpx.get("https://foo.bar/users/") self.assertEqual(response.status_code, 200) self.assertListEqual(response.json(), []) self.assertTrue(self.mocked_api["list_users"].called ``` -------------------------------- ### Define GET Route with Parameters Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use HTTP method helpers like `respx.get` for a concise way to define routes. Ensure the route pattern matches the request parameters. ```python my_route = respx.get("https://example.org/", params={"foo": "bar"}) response = httpx.get("https://example.org/", params={"foo": "bar"}) assert my_route.called assert response.status_code == 200 ``` -------------------------------- ### Mock a GET Response Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate mocking a GET request with a JSON response from 'responses.add' to 'respx.get().respond()'. ```python import responses responses.add( responses.GET, "https://example.org/", json={"foo": "bar"}, status=200, ) ``` ```python import respx respx.get("https://example.org/").respond(200, json={"foo": "bar"}) ``` -------------------------------- ### Mock List of Responses (requests-mock) Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate specifying a list of responses for a GET request from 'm.get(..., responses=...)' to 'respx.get().side_effect = responses'. ```python import requests_mock m.get(requests_mock.ANY, responses=responses) ``` ```python import respx respx.get().side_effect = responses ``` -------------------------------- ### Mock an Exception Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate mocking an exception for a GET request from 'responses.add' with 'body=Exception' to 'respx.get().mock(side_effect=ConnectError)'. ```python import responses responses.add( responses.GET, "https://example.org/", body=Exception("..."), ) ``` ```python import respx from httpx import ConnectError respx.get("https://example.org/").mock(side_effect=ConnectError) ``` -------------------------------- ### Unittest: Async Test Cases with Decorator Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Mock HTTP requests in asynchronous unittest tests using the `@respx.mock` decorator. This is suitable for async tests that do not require a custom fixture setup. ```python import asynctest import httpx import respx class MyTestCase(asynctest.TestCase): @respx.mock async def test_async_decorator(self): async with httpx.AsyncClient() as client: route = respx.get("https://example.org/") response = await client.get("https://example.org/") assert route.called assert response.status_code == 200 ``` -------------------------------- ### Pytest: Use respx_mock Fixture Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Use the `respx_mock` fixture provided by Respx in your pytest tests to mock HTTP requests. Ensure `httpx` is installed. ```python import httpx def test_fixture(respx_mock): respx_mock.get("https://foo.bar/").mock(return_value=httpx.Response(204)) response = httpx.get("https://foo.bar/") assert response.status_code == 204 ``` -------------------------------- ### Pytest: Async Test Cases with Decorator Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Mock HTTP requests in asynchronous pytest tests using the `@respx.mock` decorator. This is suitable for tests that do not require a custom fixture setup. ```python import httpx import respx @respx.mock async def test_async_decorator(): async with httpx.AsyncClient() as client: route = respx.get("https://example.org/") response = await client.get("https://example.org/") assert route.called assert response.status_code == 200 ``` -------------------------------- ### Run tests with Task Source: https://github.com/lundberg/respx/blob/master/CONTRIBUTING.md Executes the project test suite using the Task tool. ```bash task test ``` -------------------------------- ### Mock with Context Manager (requests-mock) Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate from 'requests_mock.mock()' context manager to 'respx.mock()'. ```python import requests_mock with requests_mock.mock() as m: m.get(requests_mock.ANY, json=json) ``` ```python import respx with respx.mock() as respx_mock: respx_mock.get().respond(json=json) ``` -------------------------------- ### Define Route with Method, Host, and Path Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the `respx.route` API for full control over request pattern matching, specifying method, host, and path. ```python my_route = respx.route(method="GET", host="example.org", path="/foobar/") response = httpx.get("https://example.org/foobar/") assert my_route.called assert response.status_code == 200 ``` -------------------------------- ### Stacked Responses with Iterables Source: https://github.com/lundberg/respx/blob/master/docs/guide.md When side_effect is an iterable, each request gets the next Response or exception. StopIteration is raised when the iterable is exhausted. ```python import httpx import respx @respx.mock def test_stacked_responses(): route = respx.get("https://example.org/") route.side_effect = [ httpx.Response(404), httpx.Response(200), ] response1 = httpx.get("https://example.org/") response2 = httpx.get("https://example.org/") assert response1.status_code == 404 assert response2.status_code == 200 assert route.call_count == 2 ``` -------------------------------- ### Decorate Function as Side Effect Source: https://github.com/lundberg/respx/blob/master/docs/guide.md A route can directly decorate a function to be used as its side effect, simplifying the setup for named routes. ```python import httpx import rexpx @respx.route(url__regex=r"https://example.org/(?P\w+)/", name="user") def user_api(request, user): return httpx.Response(200, json={"user": user}) @respx.mock def test_user_api(): response = httpx.get("https://example.org/lundberg/") assert response.status_code == 200 assert response.json() == {"user": "lundberg"} assert respx.routes["user"].called ``` -------------------------------- ### Patch Client with Context Manager Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate from 'responses.RequestsMock()' context manager to 'respx.mock()'. ```python import responses def test_foo(): with responses.RequestsMock() as rsps: ... ``` ```python import respx def test_foo(): with respx.mock() as respx_mock: ... ``` -------------------------------- ### Initializing MockTransport Source: https://github.com/lundberg/respx/blob/master/docs/upgrade.md Use respx.mock() instead of the deprecated MockTransport class. ```python # Previously my_mock = respx.MockTransport(assert_all_called=False) # Now my_mock = respx.mock(assert_all_called=False) ``` -------------------------------- ### Shortcut: Respond with Status Code Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use .respond() as a shortcut for return_value to mock a response with a specific status code. ```python respx.post("https://example.org/").respond(201) ``` -------------------------------- ### Shortcut: Mock with Response Object Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the modulo operator (%) with an httpx.Response object to mock a response. ```python respx.get("https://example.org/") % Response(418) response = httpx.get("https://example.org/") assert response.status_code == httpx.codes.IM_A_TEAPOT ``` -------------------------------- ### Patch Client with Decorator Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate from 'responses.activate' decorator to 'respx.mock'. ```python import responses @responses.activate def test_foo(): ... ``` ```python import respx @respx.mock def test_foo(): ... ``` -------------------------------- ### Lookup: Startswith Source: https://github.com/lundberg/respx/blob/master/docs/api.md Performs a case-sensitive starts-with test. ```python M(path__startswith="/api/") ``` -------------------------------- ### Router Configuration Source: https://github.com/lundberg/respx/blob/master/docs/api.md Configure the Respx mock router for controlling request mocking behavior. ```APIDOC ## respx.mock() ### Description Creates a mock `Router` instance, ready to be used as decorator/manager for activation. ### Method `respx.mock()` ### Parameters #### Keyword Arguments - **assert_all_mocked** (bool) - Optional - Asserts that all sent and captured `HTTPX` requests are routed and mocked. If disabled, all non-routed requests will be auto mocked with status code `200`. - **assert_all_called** (bool) - Optional - Asserts that all added and mocked routes were called when exiting context. - **base_url** (str) - Optional - Base URL to match, on top of each route specific pattern *and/or* side effect. ### Returns `Router` ### Notes When using the *default* mock router `respx.mock`, *without settings*, `assert_all_called` is **disabled**. ### Pytest Integration Use the `@pytest.mark.respx(...)` marker with these parameters to configure the `respx_mock` [pytest fixture](examples.md#built-in-marker). ``` -------------------------------- ### Combine Host and Path Patterns Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the `M()` object and bitwise operators to create reusable, combined patterns for matching multiple hosts and specific paths. ```python hosts_pattern = M(host="example.org") | M(host="example.com") my_route = respx.route(hosts_pattern, method="GET", path="/foo/") response = httpx.get("http://example.org/foo/") assert response.status_code == 200 assert my_route.called response = httpx.get("https://example.com/foo/") assert response.status_code == 200 assert my_route.call_count == 2 ``` -------------------------------- ### Define HTTP Method Routes Source: https://github.com/lundberg/respx/blob/master/docs/api.md Use HTTP method helpers to define routes with specific URL patterns and lookups. ```python respx.get("https://example.org/", params={"foo": "bar"}, ...) ``` ```python respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...) ``` -------------------------------- ### Configure Base URL Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Set a base URL for routes to simplify path definitions. ```python import httpx import respx from httpx import Response @respx.mock(base_url="https://example.org/api/") async def test_something(respx_mock): async with httpx.AsyncClient(base_url="https://example.org/api/") as client: respx_mock.get("/baz/").mock(return_value=Response(200, text="Baz")) response = await client.get("/baz/") assert response.text == "Baz" ``` -------------------------------- ### Mock with Decorator (requests-mock) Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate from 'requests_mock.mock()' decorator to 'respx.mock()'. ```python import requests_mock @requests_mock.mock() def test_some_call(self, m: requests_mock.mock): m.get(requests_mock.ANY, json={}) ``` ```python import respx @respx.mock() def test_some_call(self, respx_mock: respx.Router): respx_mock.get().respond(json={}) ``` -------------------------------- ### Run linters with Task Source: https://github.com/lundberg/respx/blob/master/CONTRIBUTING.md Executes the project linters using the Task tool to ensure code quality. ```bash task lint ``` -------------------------------- ### Route Definition Source: https://github.com/lundberg/respx/blob/master/docs/api.md Define and configure individual routes for mocking specific HTTP requests. ```APIDOC ## respx.route() ### Description Adds a new, *optionally named*, `Route` with given [patterns](#patterns) *and/or* [lookups](#lookups) combined, using the [AND](#and) operator. ### Method `respx.route(*patterns, name=None, **lookups)` ### Parameters #### Positional Arguments - **patterns** (args) - Optional - One or more [pattern](#patterns) objects. #### Keyword Arguments - **name** (str) - Optional - Name this route. - **lookups** (kwargs) - Optional - One or more [pattern](#patterns) keyword [lookups](#lookups), given as `__=value`. ### Returns `Route` ``` ```APIDOC ## respx.get(), respx.post(), ... ### Description HTTP method helpers to add routes, mimicking the [HTTPX Helper Functions](https://www.python-httpx.org/api/#helper-functions). ### Method `respx.get(*url, name=None, **lookups)` `respx.options(*url, name=None, **lookups)` `respx.head(*url, name=None, **lookups)` `respx.post(*url, name=None, **lookups)` `respx.put(*url, name=None, **lookups)` `respx.patch(*url, name=None, **lookups)` `respx.delete(*url, name=None, **lookups)` ### Parameters #### Arguments - **url** (str | compiled regex | tuple (httpcore) | httpx.URL) - Optional - Request URL to match, *full or partial*, turned into a [URL](#url) pattern. #### Keyword Arguments - **name** (str) - Optional - Name this route. - **lookups** (kwargs) - Optional - One or more [pattern](#patterns) keyword [lookups](#lookups), given as `__=value`. ### Returns `Route` ### Example ```python respx.get("https://example.org/", params={"foo": "bar"}, ...) ``` ``` ```APIDOC ## respx.request() ### Description Generic method to add a route for any HTTP method. ### Method `respx.request(*method, url, name=None, **lookups)` ### Parameters #### Arguments - **method** (str) - Required - Request HTTP method to match. - **url** (str | compiled regex | tuple (httpcore) | httpx.URL) - Optional - Request URL to match, *full or partial*, turned into a [URL](#url) pattern. #### Keyword Arguments - **name** (str) - Optional - Name this route. - **lookups** (kwargs) - Optional - One or more [pattern](#patterns) keyword [lookups](#lookups), given as `__=value`. ### Returns `Route` ### Example ```python respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...) ``` ``` -------------------------------- ### Pytest: Custom Fixture with Context Manager Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Define a custom pytest fixture using `respx.mock` as a context manager to set up routes and mock responses. This allows for reusable mocking configurations. ```python # conftest.py import pytest import respx from httpx import Response @pytest.fixture def mocked_api(): with respx.mock( base_url="https://foo.bar", assert_all_called=False ) as respx_mock: users_route = respx_mock.get("/users/", name="list_users") users_route.return_value = Response(200, json=[]) ... yield respx_mock ``` ```python # test_api.py import httpx def test_list_users(mocked_api): response = httpx.get("https://foo.bar/users/") assert response.status_code == 200 assert response.json() == [] assert mocked_api["list_users"].called ``` -------------------------------- ### Mock HTTPX with Context Manager Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the respx.mock context manager to scope mocking to a specific block of code. ```python import httpx import respx def test_ctx_manager(): with respx.mock: my_route = respx.get("https://example.org/") response = httpx.get("https://example.org/") assert my_route.called assert response.status_code == 200 ``` -------------------------------- ### Mock with Callback Function Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate using a callback function for dynamic response generation from 'responses.add_callback' to 'respx.get().mock(side_effect=...)'. ```python import responses import json def my_callback(request): headers = {"Content-Type": "application/json"} body = {"foo": "bar"} return (200, headers, json.dumps(body)) responses.add_callback( responses.GET, "http://example.org/", callback=my_callback, ) ``` ```python import respx from respx.mock import Response def my_side_effect(request, route): return Response(200, json={"foo": "bar"}) respx.get("https://example.org/").mock(side_effect=my_side_effect) ``` -------------------------------- ### Match URL Path Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request paths using equality, regex, prefix, or inclusion lookups. ```python respx.route(path="/api/foobar/") respx.route(path__regex=r"^/api/(?P\w+)/") respx.route(path__startswith="/api/") respx.route(path__in=["/api/v1/foo/", "/api/v2/foo/"]) ``` -------------------------------- ### Route Responding Methods Source: https://github.com/lundberg/respx/blob/master/docs/api.md Methods for defining how a route should respond to a request. ```APIDOC ## Route.respond() Shortcut for creating and mocking a `HTTPX` [Response](#response). ### Method Signature route.respond(*status_code=200, headers=None, cookies=None, content=None, text=None, html=None, json=None, stream=None, content_type=None*) ### Parameters #### Optional Parameters - **status_code** (int) - default: `200` - Response status code to mock. - **headers** (dict | Sequence[tuple[str, str]]) - Response headers to mock. - **cookies** (dict | Sequence[tuple[str, str]] | Sequence[SetCookie]) - Response cookies to mock as `Set-Cookie` headers. See [SetCookie](#setcookie). - **content** (bytes | str | Iterable[bytes]) - Response raw content to mock. - **text** (str) - Response *text* content to mock, with automatic content-type header added. - **html** (str) - Response *HTML* content to mock, with automatic content-type header added. - **json** (Any) - Response *JSON* content to mock, with automatic content-type header added. - **stream** (Iterable[bytes]) - Response *stream* to mock. - **content_type** (str) - Response `Content-Type` header to mock. ### Returns `Route` ## Route.pass_through() Marks a route to pass through, sending matched requests to the real server (i.e., don't mock). ### Method Signature route.pass_through(*value=True*) ### Parameters #### Optional Parameters - **value** (bool) - default: `True` - Mark route to pass through. ### Returns `Route` ``` -------------------------------- ### Configure Route Response Source: https://github.com/lundberg/respx/blob/master/docs/api.md Set the response for a route using the return_value property. ```python route.return_value = Response(204) ``` -------------------------------- ### Routing Requests in RESPX Source: https://github.com/lundberg/respx/blob/master/docs/upgrade.md Replaces the .add API with the .route method for defining request handlers. ```python # Previously respx.add("POST", "https://some.url/", content="foobar") # Now respx.route(method="POST", url="https://some.url/").respond(content="foobar") ``` -------------------------------- ### Pattern Matching Utilities Source: https://github.com/lundberg/respx/blob/master/docs/api.md Utilities for creating reusable request patterns. ```APIDOC ## Patterns ### M() Creates a reusable pattern, combining multiple arguments using the [AND](#and) operator. #### Method Signature > M(*patterns, **lookups*) #### Parameters - **patterns** (*args) - Optional. One or more [pattern](#patterns) objects. - **lookups** (*kwargs) - Optional. One or more [pattern](#patterns) keyword [lookups](#lookups), given as `__=value`. #### Returns `Pattern` #### Example ```python import respx from respx.patterns import M pattern = M(host="example.org") respx.route(pattern) ``` > See [operators](#operators) for advanced usage. ### Method Matches request *HTTP method*, using `[eq](#eq)` as default lookup. > Key: `method` > Lookups: [eq](#eq), [in](#in) ```python respx.route(method="GET") respx.route(method__in=["PUT", "PATCH"]) ``` ### Scheme Matches request *URL scheme*, using `[eq](#eq)` as default lookup. > Key: `scheme` > Lookups: [eq](#eq), [in](#in) ```python respx.route(scheme="https") respx.route(scheme__in=["http", "https"]) ``` ### Host Matches request *URL host*, using `[eq](#eq)` as default lookup. > Key: `host` > Lookups: [eq](#eq), [regex](#regex), [in](#in) ```python respx.route(host="example.org") respx.route(host__regex=r"example\.(org|com)") respx.route(host__in=["example.org", "example.com"]) ``` ### Port Matches request *URL port*, using `[eq](#eq)` as default lookup. > Key: `port` > Lookups: [eq](#eq), [in](#in) ```python respx.route(port=8000) respx.route(port__in=[2375, 2376]) ``` ### Path Matches request *URL path*, using `[eq](#eq)` as default lookup. > Key: `path` > Lookups: [eq](#eq), [regex](#regex), [startswith](#startswith), [in](#in) ```python respx.route(path="/api/foobar/") respx.route(path__regex=r"^/api/(?P\w+)/") respx.route(path__startswith="/api/") respx.route(path__in=["/api/v1/foo/", "/api/v2/foo/"]) ``` ``` -------------------------------- ### Reusable Router with Context Manager Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use an isolated router instance as a context manager to activate mocking for a block of code. This allows for managing mock behavior within specific scopes. ```python import httpx import respx api_mock = respx.mock(base_url="https://api.foo.bar/", assert_all_called=False) api_mock.get("/baz/", name="baz").mock( return_value=httpx.Response(200, json={"name": "baz"}), ) def test_ctx_manager(): with api_mock: ... ``` -------------------------------- ### Mock HTTPX without patching Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use httpx.MockTransport with a RESPX router to mock requests without globally patching HTTPX. ```python import httpx import respx router = respx.Router() router.post("https://example.org/") % 404 def test_client(): mock_transport = httpx.MockTransport(router.handler) with httpx.Client(transport=mock_transport) as client: response = client.post("https://example.org/") assert response.status_code == 404 def test_client(): mock_transport = httpx.MockTransport(router.async_handler) with httpx.AsyncClient(transport=mock_transport) as client: ... ``` -------------------------------- ### Reusable Router with Decorator Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Create an isolated router using `respx.mock` to group routes for specific APIs. Use the router instance as a decorator to activate mocking for a test function. ```python import httpx import respx api_mock = respx.mock(base_url="https://api.foo.bar/", assert_all_called=False) api_mock.get("/baz/", name="baz").mock( return_value=httpx.Response(200, json={"name": "baz"}), ) @api_mock def test_decorator(): response = httpx.get("https://api.foo.bar/baz/") assert response.status_code == 200 assert response.json() == {"name": "baz"} assert api_mock["baz"].called ``` -------------------------------- ### Mock Async App Response with ASGIHandler Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use ASGIHandler to mock responses from an asynchronous Starlette application. Ensure the base URL matches the application's routing. ```python import httpx import respx from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route async def baz(request): return JSONResponse({"ham": "spam"}) app = Starlette(routes=[Route("/baz/", baz)]) @respx.mock(base_url="https://foo.bar/") async def test_baz(respx_mock): app_route = respx_mock.route().mock(side_effect=ASGIHandler(app)) response = await httpx.AsyncClient().get("https://foo.bar/baz/") assert response.json() == {"ham": "spam"} assert app_route.called ``` -------------------------------- ### Set Cookie Header Source: https://github.com/lundberg/respx/blob/master/docs/api.md Demonstrates using SetCookie to generate a header for an HTTPX response. ```python import respx respx.post("https://example.org/").mock( return_value=httpx.Response(200, headers=[SetCookie("foo", "bar")]) ) ``` -------------------------------- ### Shortcut: Mock with Integer Status Code Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the modulo operator (%) with an integer to mock a response with that status code. ```python respx.get("https://example.org/") % 204 response = httpx.get("https://example.org/") assert response.status_code == 204 ``` -------------------------------- ### Create Reusable Pattern Source: https://github.com/lundberg/respx/blob/master/docs/api.md Creates a reusable pattern object using the M helper to combine lookups. ```python import respx from respx.patterns import M pattern = M(host="example.org") respx.route(pattern) ``` -------------------------------- ### Match Request Content Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches raw request content using eq or contains lookups. ```python respx.post("https://example.org/", content="foobar") respx.post("https://example.org/", content=b"foobar") respx.post("https://example.org/", content__contains="bar") ``` -------------------------------- ### Match URL Port Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request ports using equality or inclusion lookups. ```python respx.route(port=8000) respx.route(port__in=[2375, 2376]) ``` -------------------------------- ### Route with Method Lookup Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Specify multiple methods for a route using the `__in` lookup suffix with the `method` parameter in `respx.route`. ```python respx.route(method__in=["PUT", "PATCH"]) ``` -------------------------------- ### Operator: AND Source: https://github.com/lundberg/respx/blob/master/docs/api.md Combines two patterns using the bitwise AND operator. ```python M(scheme="http") & M(host="example.org") ``` -------------------------------- ### Pytest: Configure respx_mock with Marker Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Configure the `respx_mock` fixture using the `respx` marker to set a base URL for your tests. This simplifies mocking relative paths. ```python import httpx import pytest @pytest.mark.respx(base_url="https://foo.bar") def test_configured_fixture(respx_mock): respx_mock.get("/baz/").mock(return_value=httpx.Response(204)) response = httpx.get("https://foo.bar/baz/") assert response.status_code == 204 ``` -------------------------------- ### Route Mocking Source: https://github.com/lundberg/respx/blob/master/docs/api.md Configure the response or side effect for a defined route. ```APIDOC ## route.mock() ### Description Mock a route's response or side effect. ### Method `route.mock(*return_value=None, side_effect=None)` ### Parameters #### Arguments - **return_value** (Response) - Optional - HTTPX Response to mock and return. - **side_effect** (Callable | Exception | Iterable of httpx.Response/Exception) - Optional - [Side effect](guide.md#mock-with-a-side-effect) to call, exception to raise or stacked responses to respond with in order. ### Returns `Route` ``` ```APIDOC ## route.return_value ### Description Setter for the `HTTPX` [Response](#response) to return. ### Usage ```python route.return_value = Response(204) ``` ``` ```APIDOC ## route.side_effect ### Description Setter for the [side effect](guide.md#mock-with-a-side-effect) to trigger. ### Usage ```python route.side_effect = ... ``` See [route.mock()](#mock) for valid side effect types. ``` -------------------------------- ### Match Request Query Parameters Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches URL query parameters using various input formats. Multiple parameters with the same name are treated as an ordered list. ```python 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") ``` -------------------------------- ### Match Request URL Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches the request URL using shorthand patterns or specific lookups like eq, regex, or startswith. ```python 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\w+)/") respx.get(url__startswith="https://example.org/api/") respx.get("all://*.example.org/foo/") ``` -------------------------------- ### Match URL Host Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request hosts using equality, regex, or inclusion lookups. ```python respx.route(host="example.org") respx.route(host__regex=r"example\.(org|com)") respx.route(host__in=["example.org", "example.com"]) ``` -------------------------------- ### Match HTTP Method Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request methods using equality or inclusion lookups. ```python respx.route(method="GET") respx.route(method__in=["PUT", "PATCH"]) ``` -------------------------------- ### Unittest: Regular Decoration Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Mock HTTP requests in unittest test methods using the `@respx.mock` decorator. This is a straightforward way to enable Respx for a single test. ```python # test_api.py import httpx import respx import unittest class APITestCase(unittest.TestCase): @respx.mock def test_some_endpoint(self): respx.get("https://example.org/") % 202 response = httpx.get("https://example.org/") self.assertEqual(response.status_code, 202) ``` -------------------------------- ### Mock HTTPX with Pytest Fixture Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the respx_mock pytest fixture for clean integration with test suites. ```python import httpx def test_fixture(respx_mock): my_route = respx_mock.get("https://example.org/") response = httpx.get("https://example.org/") assert my_route.called assert response.status_code == 200 ``` -------------------------------- ### Request Matching Parameters Source: https://github.com/lundberg/respx/blob/master/docs/api.md Defines how to match requests based on their URL query parameters. Supports 'contains' (default) and 'eq' lookups. ```APIDOC ## POST /api/users ### Description Matches request URL query parameters. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **params** (dict or list or str) - Required - Query parameters to match. Supports lookups like `contains` and `eq`. ### Request Example ```python 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") ``` ### Response #### Success Response (200) - **status** (str) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Mocking Responses in RESPX Source: https://github.com/lundberg/respx/blob/master/docs/upgrade.md Updates to response mocking syntax, separating request patterns from response details. ```python # Previously respx.post("https://some.url/", status_code=200, content={"x": 1}) # Now respx.post("https://some.url/").mock(return_value=Response(200, json={"x": 1})) respx.post("https://some.url/").respond(200, json={"x": 1}) respx.post("https://some.url/") % dict(json={"x": 1}) ``` -------------------------------- ### Shortcut: Mock with JSON Response Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the modulo operator (%) with a dictionary to mock a JSON response. The default status code is 200. ```python respx.get("https://example.org/") % dict(json={"foo": "bar"}) response = httpx.get("https://example.org/") assert response.status_code == 200 assert response.json() == {"foo": "bar"} ``` -------------------------------- ### Define and Assert Named Routes Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Name routes when adding them to access and assert their calls later via the `respx.routes` mapping. This is useful for routes defined outside the test case. ```python import httpx import respx # Added somewhere else respx.get("https://example.org/", name="home") @respx.mock def test_route_call(): httpx.get("https://example.org/") assert respx.routes["home"].called assert respx.routes["home"].call_count == 1 last_home_response = respx.routes["home"].calls.last.response assert last_home_response.status_code == 200 ``` -------------------------------- ### Mock Raising Exception (requests-mock) Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate raising an exception during a POST request from 'm.post(..., exc=...)' to 'respx.post().side_effect = ...'. ```python import requests_mock m.post(requests_mock.ANY, exc=JSONDecodeError("nope", "ok", 1)) ``` ```python import respx respx.post().side_effect = JSONDecodeError("nope", "ok", 1) ``` -------------------------------- ### Mock Sync App Response with WSGIHandler Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use WSGIHandler to mock responses from a synchronous Flask application. Ensure the base URL matches the application's routing. ```python import httpx import respx from flask import Flask app = Flask("foobar") @app.route("/baz/") def baz(): return {"ham": "spam"} @respx.mock(base_url="https://foo.bar/") def test_baz(respx_mock): app_route = respx_mock.route().mock(side_effect=WSGIHandler(app)) response = httpx.get("https://foo.bar/baz/") assert response.json() == {"ham": "spam"} assert app_route.called ``` -------------------------------- ### Mock Subsequent Responses Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate handling subsequent responses for the same URL from multiple 'responses.add' calls to 'respx.get().mock(side_effect=[...])'. ```python import responses responses.add(responses.GET, "https://example.org/", status=200) responses.add(responses.GET, "https://example.org/", status=500) ``` ```python import respx from respx.mock import Response respx.get("https://example.org/").mock( side_effect=[Response(200), Response(500)] ) ``` -------------------------------- ### HTTPX Response Class Source: https://github.com/lundberg/respx/blob/master/docs/api.md Details of the `httpx.Response` class used for mocking. ```APIDOC ## Response !!! note "NOTE" This is a partial reference for how to instantiate the **HTTPX** `Response` class, e.g. *not* a RESPX class. ### Constructor > httpx.Response(*status_code, headers=None, content=None, text=None, html=None, json=None, stream=None*) ### Parameters #### Required Parameters - **status_code** (int) - HTTP status code. #### Optional Parameters - **headers** (dict | httpx.Headers) - HTTP headers. - **content** (bytes | str | Iterable[bytes]) - Raw content. - **text** (str) - Text content, with automatic content-type header added. - **html** (str) - HTML content, with automatic content-type header added. - **json** (Any) - JSON content, with automatic content-type header added. - **stream** (Iterable[bytes]) - Content *stream*. !!! tip "Cookies" Use [respx.SetCookie(...)](#setcookie) to produce `Set-Cookie` headers. ``` -------------------------------- ### Pytest: Async Test Cases with Context Manager Source: https://github.com/lundberg/respx/blob/master/docs/examples.md Use `respx.mock` as an asynchronous context manager within your async pytest tests to mock HTTP requests. This provides a clear scope for mocking. ```python async def test_async_ctx_manager(): async with respx.mock: async with httpx.AsyncClient() as client: route = respx.get("https://example.org/") response = await client.get("https://example.org/") assert route.called assert response.status_code == 200 ``` -------------------------------- ### Pass Through Requests Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate enabling pass-through for specific URLs from 'responses.add_passthru' to 'respx.route().pass_through()'. ```python import responses responses.add_passthru("https://example.org/") ``` ```python import respx respx.route(url="https://example.org/").pass_through() ``` -------------------------------- ### Mock HTTPX requests with pytest fixture Source: https://github.com/lundberg/respx/blob/master/README.md Utilizes the respx_mock fixture and optional respx marker for cleaner integration with pytest. ```python import httpx import pytest def test_default(respx_mock): respx_mock.get("https://foo.bar/").mock(return_value=httpx.Response(204)) response = httpx.get("https://foo.bar/") assert response.status_code == 204 @pytest.mark.respx(base_url="https://foo.bar") def test_with_marker(respx_mock): respx_mock.get("/baz/").mock(return_value=httpx.Response(204)) response = httpx.get("https://foo.bar/baz/") assert response.status_code == 204 ``` -------------------------------- ### Mock HTTPX requests with respx.mock decorator Source: https://github.com/lundberg/respx/blob/master/README.md Uses the respx.mock decorator to intercept HTTPX requests and define mock responses. ```python import httpx import respx from httpx import Response @respx.mock def test_example(): my_route = respx.get("https://example.org/").mock(return_value=Response(204)) response = httpx.get("https://example.org/") assert my_route.called assert response.status_code == 204 ``` -------------------------------- ### Mock HTTPX with Decorator Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use the respx.mock decorator to patch HTTPX for a specific test function. ```python import httpx import respx @respx.mock def test_decorator(): my_route = respx.get("https://example.org/") response = httpx.get("https://example.org/") assert my_route.called assert response.status_code == 200 ``` -------------------------------- ### Match URL Scheme Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request URL schemes using equality or inclusion lookups. ```python respx.route(scheme="https") respx.route(scheme__in=["http", "https"]) ``` -------------------------------- ### Match Request Headers Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request headers using contains or eq lookups. ```python respx.route(headers={"foo": "bar", "ham": "spam"}) respx.route(headers=[("foo", "bar"), ("ham", "spam")]) ``` -------------------------------- ### Mock Response with return_value Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Set a specific httpx.Response object to be returned for a mocked route. This is useful for static responses. ```python respx.get("https://example.org/").mock(return_value=Response(204)) ``` ```python route = respx.get("https://example.org/") route.return_value = Response(200, json={"foo": "bar"}) ``` -------------------------------- ### Lookup: Regex Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches a request attribute against a regular expression. ```python M(path__regex=r"^/api/(?P\w+)/") ``` -------------------------------- ### Match Request Files Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches files within form data using contains or eq lookups. ```python 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)}) ``` -------------------------------- ### Match Request JSON Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches JSON content, supporting direct equality or path traversal. ```python respx.post("https://example.org/", json={"foo": "bar"}) ``` ```python respx.post("https://example.org/", json__foobar__0__ham="spam") httpx.post("https://example.org/", json={"foobar": [{"ham": "spam"}]}) ``` -------------------------------- ### Headers Matching Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches request headers. Supports 'contains' (default) and 'eq' lookups. ```APIDOC ## ROUTE /api/resource ### Description Matches request headers. ### Method ANY ### Endpoint /api/resource ### Parameters #### Headers - **headers** (dict or list) - Required - The headers to match. Supports `contains` and `eq` lookups. ### Request Example ```python respx.route(headers={"foo": "bar", "ham": "spam"}) respx.route(headers=[("foo", "bar"), ("ham", "spam")]) ``` ### Response #### Success Response (200) - **headers** (dict) - The matched headers. #### Response Example ```json { "headers": { "foo": "bar", "ham": "spam" } } ``` ``` -------------------------------- ### URL Matching Source: https://github.com/lundberg/respx/blob/master/docs/api.md Allows matching requests based on the entire URL or parts of it. Supports 'eq', 'regex', and 'startswith' lookups. ```APIDOC ## GET /example.org/ ### Description Matches request URLs. ### Method GET ### Endpoint /example.org/ ### Parameters #### Query Parameters - **url** (str) - Required - The URL to match. Supports lookups like `eq`, `regex`, `startswith`. ### Request Example ```python respx.get("//example.org/foo/") respx.get(url__eq="https://example.org:8080/foobar/?ham=spam") respx.get(url__regex=r"https://example.org/(?P\\w+)/") respx.get(url__startswith="https://example.org/api/") respx.get("all://*.example.org/foo/") ``` ### Response #### Success Response (200) - **url** (str) - The matched URL. #### Response Example ```json { "url": "https://example.org/foo/" } ``` ``` -------------------------------- ### Replace Mocked Response Source: https://github.com/lundberg/respx/blob/master/docs/migrate.md Migrate replacing an existing mocked response from 'responses.replace' to re-defining the route in 'respx'. ```python import responses responses.add(responses.GET, "http://example.org/", json={"data": 1}) responses.replace(responses.GET, "http://example.org/", json={"data": 2}) ``` ```python import respx respx.get("https://example.org/").respond(json={"data": 1}) respx.get("https://example.org/").respond(json={"data": 2}) ``` -------------------------------- ### Infinite Stacked Responses with itertools Source: https://github.com/lundberg/respx/blob/master/docs/guide.md Use itertools.chain and itertools.repeat to create a side effect that repeats the last response indefinitely. ```python from itertools import chain, repeat import httpx import respx @respx.mock def test_stacked_responses(): respx.post("https://example.org/").mock( side_effect=chain( [httpx.Response(201)], repeat(httpx.Response(200)), ) ) response1 = httpx.post("https://example.org/") response2 = httpx.post("https://example.org/") response3 = httpx.post("https://example.org/") assert response1.status_code == 201 assert response2.status_code == 200 assert response3.status_code == 200 ``` -------------------------------- ### Content Matching Source: https://github.com/lundberg/respx/blob/master/docs/api.md Matches the raw content of the request body. Supports 'eq' (default) and 'contains' lookups. ```APIDOC ## POST /example.org/ ### Description Matches the raw content of the request body. ### Method POST ### Endpoint /example.org/ ### Parameters #### Request Body - **content** (str or bytes) - Required - The raw content to match. Supports `eq` and `contains` lookups. ### Request Example ```python respx.post("https://example.org/", content="foobar") respx.post("https://example.org/", content=b"foobar") respx.post("https://example.org/", content__contains="bar") ``` ### Response #### Success Response (200) - **content** (str) - The matched content. #### Response Example ```json { "content": "foobar" } ``` ```