### Patching Client with unittest setUp Source: https://lundberg.github.io/respx/migrate Migrate 'unittest setUp' for 'responses.RequestsMock' to 'respx.mock'. ```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 Source: https://lundberg.github.io/respx Install Respx using pip. Requires Python 3.8+ and HTTPX 0.25+. ```bash $ pip install respx ``` -------------------------------- ### Mock HTTPX Response with return_value Source: https://lundberg.github.io/respx/guide Mock a GET request to example.org with a 204 No Content response. ```python respx.get("https://example.org/").mock(return_value=Response(204)) ``` -------------------------------- ### Add a GET Route Source: https://lundberg.github.io/respx/api Helper to add a GET route. Matches the specified URL and optional lookups. ```python respx.get("https://example.org/", params={"foo": "bar"}, ...) ``` -------------------------------- ### Mock a Response Source: https://lundberg.github.io/respx/migrate Migrate 'responses.add' for mocking a GET request 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"}) ``` -------------------------------- ### HTTP Method Helpers Source: https://lundberg.github.io/respx/guide Use HTTP method helpers like get(), post(), etc., to shortcut the route API for defining routes. Ensure the mocked route is called and the response is as expected. ```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 ``` -------------------------------- ### Creating Reusable Patterns with M Source: https://lundberg.github.io/respx/api The M pattern allows combining multiple matching arguments with an AND operator to create reusable patterns. This example demonstrates creating a pattern that matches requests to 'example.org'. ```python import respx from respx.patterns import M pattern = M(host="example.org") respx.route(pattern) ``` -------------------------------- ### Configure Router with Base URL Source: https://lundberg.github.io/respx/guide Set a 'base_url' when configuring the router to share a common domain or prefix for added routes. This example demonstrates its use with an async client. ```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" ``` -------------------------------- ### Pytest Custom Fixture Setup Source: https://lundberg.github.io/respx/examples Define a custom pytest fixture in `conftest.py` to manage mocked API routes. ```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 ``` -------------------------------- ### HTTP Method Helpers (get, post, etc.) Source: https://lundberg.github.io/respx/api HTTP method helpers to add routes, mimicking the HTTPX Helper Functions. These allow for quick route definition based on common HTTP methods. ```APIDOC ## HTTP Method Helpers (get, post, ...) ### Description HTTP method helpers to add routes, mimicking the HTTPX Helper Functions. ### Methods - `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 #### Keyword 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 `__=value`. ### Returns `Route` ### Example ```python respx.get("https://example.org/", params={"foo": "bar"}, ...) ``` ``` -------------------------------- ### Combining Route Patterns with M() Source: https://lundberg.github.io/respx/guide Combine multiple route patterns using the M() object and bitwise operators (&, |, ~) for advanced matching. This example combines host and path patterns. ```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 ``` -------------------------------- ### Reusable Routers with Decorator Source: https://lundberg.github.io/respx/guide Create and use isolated routers with respx.mock for managing multiple APIs. This example uses the router as a decorator to mock a specific API endpoint. ```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 ``` -------------------------------- ### Mocking with Async App (ASGIHandler) Source: https://lundberg.github.io/respx/guide Mock responses from an asynchronous ASGI application by passing an ASGIHandler instance as the side effect. This example uses Starlette. ```python import httpx import respx from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route from respx.mock import ASGIHandler 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 ``` -------------------------------- ### Mocking with SetCookie Source: https://lundberg.github.io/respx/api Use respx.SetCookie to generate 'Set-Cookie' headers for mocked responses. This example shows how to mock a POST request and return a response with a SetCookie header. ```python import respx respx.post("https://example.org/").mock( return_value=httpx.Response(200, headers=[SetCookie("foo", "bar")]) ) ``` -------------------------------- ### Route API with Lookups Source: https://lundberg.github.io/respx/guide Specify a lookup type for a route pattern by adding a '__' suffix to the pattern key. This example uses 'method__in' to match multiple HTTP methods. ```python respx.route(method__in=["PUT", "PATCH"]) ``` -------------------------------- ### Mock HTTPX Response with Side Effect Placeholder Source: https://lundberg.github.io/respx/guide Illustrates mocking a GET request with a side effect, where '...' represents a function, exception, or iterable. ```python respx.get("https://example.org/").mock(side_effect=...) ``` -------------------------------- ### Mock GET request with a Response object using modulo Source: https://lundberg.github.io/respx/guide Provide an `httpx.Response` object directly to the modulo operator to mock a response with a specific status code and other properties. ```python respx.get("https://example.org/") % Response(418) response = httpx.get("https://example.org/") assert response.status_code == httpx.codes.IM_A_TEAPOT ``` -------------------------------- ### Mocking with Sync App (WSGIHandler) Source: https://lundberg.github.io/respx/guide Mock responses from a synchronous WSGI application by passing a WSGIHandler instance as the side effect to the route's mock method. This example uses Flask. ```python import httpx import respx from flask import Flask from respx.mock import WSGIHandler 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 GET request with status code 204 using modulo Source: https://lundberg.github.io/respx/guide The modulo operator (%) can be used with an integer to mock a response with the specified status code. This is a concise way to set up simple mocks. ```python respx.get("https://example.org/") % 204 response = httpx.get("https://example.org/") assert response.status_code == 204 ``` -------------------------------- ### Set HTTPX Response return_value via Setter Source: https://lundberg.github.io/respx/guide Set the return value for a GET request route to a 200 OK response with JSON data. ```python route = respx.get("https://example.org/") route.return_value = Response(200, json={"foo": "bar"}) ``` -------------------------------- ### Mock GET request with JSON response using modulo Source: https://lundberg.github.io/respx/guide A dictionary can be used with the modulo operator 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"} ``` -------------------------------- ### Set Side Effect via Setter Placeholder Source: https://lundberg.github.io/respx/guide Demonstrates setting a side effect for a GET request route using the setter, where '...' represents a function, exception, or iterable. ```python route = respx.get("https://example.org/") route.side_effect = ... ``` -------------------------------- ### Configure Context Manager with Settings Source: https://lundberg.github.io/respx/guide Pass configuration arguments to the respx.mock context manager. The configured router instance will be yielded. ```python with respx.mock(...) as respx_mock: ... ``` -------------------------------- ### Using respx.mock() instead of MockTransport Source: https://lundberg.github.io/respx/upgrade Demonstrates the updated way to initialize a mock router, using `respx.mock(...)` directly instead of instantiating `respx.MockTransport`. ```python # Previously my_mock = respx.MockTransport(assert_all_called=False) ``` ```python # Now my_mock = respx.mock(assert_all_called=False) ``` -------------------------------- ### Route.respond() Source: https://lundberg.github.io/respx/api A shortcut for creating and mocking an HTTPX Response with specified status code, headers, and content. ```APIDOC ## Route.respond() ### Description Shortcut for creating and mocking a `HTTPX` Response. ### Method `route.respond(_status_code=200, headers=None, cookies=None, content=None, text=None, html=None, json=None, stream=None, content_type=None)` ### Parameters #### Keyword 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 as `Set-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) Any_ - Response _JSON_ content to mock, with automatic content-type header added. - **stream** - _(optional) Iterable[bytes]_ - Response _stream_ to mock. - **content_type** - _(optional) str_ - Response `Content-Type` header to mock. ### Returns `Route` ``` -------------------------------- ### Unittest Mixin SetupClass Source: https://lundberg.github.io/respx/examples Use a mixin class to set up and tear down respx mocks for `unittest.TestCase` 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) ``` -------------------------------- ### Enable Assert All Mocked Source: https://lundberg.github.io/respx/guide Configure the router with 'assert_all_mocked=True' to ensure all sent HTTPX requests are routed and mocked. Unmocked requests will raise an error. ```python @respx.mock(assert_all_mocked=True) def test_something(respx_mock): response = httpx.get("https://example.org/") # Not mocked, will raise ``` -------------------------------- ### Patching Client with Context Manager Source: https://lundberg.github.io/respx/migrate Migrate from 'responses.RequestsMock()' context manager to 'respx.mock()' context manager. ```python import responses def test_foo(): with responses.RequestsMock() as rsps: ... ``` ```python import respx def test_foo(): with respx.mock() as respx_mock: ... ``` -------------------------------- ### respx.mock() Source: https://lundberg.github.io/respx/api Creates a mock Router instance, ready to be used as a decorator or manager for activation. It allows configuration for asserting all requests are mocked and all routes are called. ```APIDOC ## respx.mock() ### Description Creates a mock `Router` instance, ready to be used as decorator/manager for activation. ### Method `respx.mock(assert_all_mocked=True, _assert_all_called=True, base_url=None)` ### Parameters #### Keyword Parameters - **assert_all_mocked** (bool) - Optional - default:`True` - 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 - default:`True` - 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` ### Note When using the _default_ mock router `respx.mock`, _without settings_ , `assert_all_called` is **disabled**. ``` -------------------------------- ### Mock HTTPX client using MockTransport and Router Source: https://lundberg.github.io/respx/guide Instantiate an `httpx.Client` with `httpx.MockTransport` and a Respx router to mock requests without patching the global HTTPX module. ```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: ... ``` -------------------------------- ### Mock HTTPX with Context Manager Source: https://lundberg.github.io/respx/guide Use the 'with respx.mock:' context manager to activate Respx for a specific block of code. This is useful for more granular control over mocking. ```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 ``` -------------------------------- ### Configure Respx Mock Router Source: https://lundberg.github.io/respx/api Creates a mock Router instance. Use assert_all_mocked=False to auto-mock non-routed requests with status 200. assert_all_called=False disables assertion that all mocked routes were called. ```python respx.mock(assert_all_mocked=True, _assert_all_called=True, base_url=None_) ``` -------------------------------- ### Basic Mocking with respx.mock decorator Source: https://lundberg.github.io/respx Use the @respx.mock decorator to enable mocking for a function. Define routes using respx.get and mock responses with httpx.Response. ```python import httpx import respx from httpx import Response @respx.mock def test_example(): my_route = respx.get("https://foo.bar/").mock(return_value=Response(204)) response = httpx.get("https://foo.bar/") assert my_route.called assert response.status_code == 204 ``` -------------------------------- ### Mocking with Context Manager (requests-mock) Source: https://lundberg.github.io/respx/migrate Migrate '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) ``` -------------------------------- ### Configure Decorator with Settings Source: https://lundberg.github.io/respx/guide Pass configuration arguments directly to the @respx.mock decorator. The test function will receive the configured router instance. ```python @respx.mock(...) def test_something(respx_mock): ... ``` -------------------------------- ### Patching Client with Decorator Source: https://lundberg.github.io/respx/migrate Migrate from 'responses.activate' decorator to 'respx.mock' decorator. ```python import responses @responses.activate def test_foo(): ... ``` ```python import respx @respx.mock def test_foo(): ... ``` -------------------------------- ### Match Path with StartsWith Source: https://lundberg.github.io/respx/api Use the `startswith` lookup for a case-sensitive prefix match on the request path. ```python M(path__startswith="/api/") ``` -------------------------------- ### Respond with HTTPX Response Source: https://lundberg.github.io/respx/api A shortcut for creating and mocking an HTTPX Response with specified status code, headers, cookies, and content. ```python route.respond(_status_code=200, headers=None, cookies=None, content=None, text=None, html=None, json=None, stream=None, content_type=None_) ``` -------------------------------- ### Stacking Mock Responses in Respx Source: https://lundberg.github.io/respx/upgrade Explains how to stack multiple mock responses for the same route using the `side_effect` argument with a list of `Response` objects. Note that repeating a route pattern replaces existing ones. ```python # Previously respx.post("https://some.url/", status_code=404) respx.post("https://some.url/", status_code=200) ``` ```python # Now respx.post("https://some.url/").mock( side_effect=[ Response(404), Response(200), ], ) ``` -------------------------------- ### Mocking Responses in Respx Source: https://lundberg.github.io/respx/upgrade Demonstrates the updated API for mocking HTTP responses, separating request patterns from response details. Use `.respond()` or the `%` operator for simpler cases. ```python # Previously respx.post("https://some.url/", status_code=200, content={"x": 1}) ``` ```python # Now respx.post("https://some.url/").mock(return_value=Response(200, json={"x": 1})) ``` ```python respx.post("https://some.url/").respond(200, json={"x": 1}) ``` ```python respx.post("https://some.url/") % dict(json={"x": 1}) ``` -------------------------------- ### Define a POST response with status code 201 Source: https://lundberg.github.io/respx/guide Use `.respond()` as a shortcut for `return_value` to define a mock response for a specific HTTP method and URL. ```python respx.post("https://example.org/").respond(201) ``` -------------------------------- ### Match Path with Regex Source: https://lundberg.github.io/respx/api Use the `regex` lookup to match the request path against a regular expression. ```python M(path__regex=r"^/api/(?P\w+)/" ) ``` -------------------------------- ### Specifying a List of Responses (requests-mock) Source: https://lundberg.github.io/respx/migrate Migrate 'requests_mock.mock.get(..., responses)' to 'respx.get().side_effect = responses'. ```python import requests_mock m.get(requests_mock.ANY, responses) ``` ```python import respx respx.get().side_effect = responses ``` -------------------------------- ### Mocking with Decorator (requests-mock) Source: https://lundberg.github.io/respx/migrate Migrate '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={}) ``` -------------------------------- ### Exact Path Match Source: https://lundberg.github.io/respx/api Use the `eq` lookup for an exact match on the request path. Alternatively, use the `path__eq` syntax. ```python M(path="/foo/bar/") M(path__eq="/foo/bar/") ``` -------------------------------- ### Raising an Exception (requests-mock) Source: https://lundberg.github.io/respx/migrate Migrate 'requests_mock.mock.post(..., exc=...)' to 'respx.post().side_effect = ...'. ```python import requests_mock from json import JSONDecodeError m.post(requests_mock.ANY, exc=JSONDecodeError("nope", "ok", 1)) ``` ```python import respx from json import JSONDecodeError respx.post().side_effect = JSONDecodeError("nope", "ok", 1) ``` -------------------------------- ### Path Pattern Source: https://lundberg.github.io/respx/api Matches the request URL path. Supports 'eq', 'regex', 'startswith', and 'in' lookups. ```APIDOC ## Path ### Description Matches request _URL path_, using `eq` as default lookup. ### Key: `path` ### Lookups: eq, regex, startswith, in ### Example: ```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/"]) ``` ``` -------------------------------- ### Host Pattern Source: https://lundberg.github.io/respx/api Matches the request URL host. Supports 'eq', 'regex', and 'in' lookups. ```APIDOC ## Host ### Description Matches request _URL host_, using `eq` as default lookup. ### Key: `host` ### Lookups: eq, regex, in ### Example: ```python respx.route(host="example.org") respx.route(host__regex=r"example\.(org|com)") respx.route(host__in=["example.org", "example.com"]) ``` ``` -------------------------------- ### Enable Pass Through Source: https://lundberg.github.io/respx/api Marks a route to pass through, sending matched requests to the real server instead of mocking them. ```python route.pass_through(_value=True_) ``` -------------------------------- ### Handling Callbacks and Errors in Respx Source: https://lundberg.github.io/respx/upgrade Illustrates how callbacks and exceptions are now handled as side effects using the `.mock(side_effect=...)` method. This applies to both direct request mocks and route definitions. ```python # Previously respx.post("https://some.url/", content=callback) respx.post("https://some.url/", content=Exception()) ``` ```python # Now respx.post("https://some.url/").mock(side_effect=callback) ``` ```python respx.post("https://some.url/").mock(side_effect=Exception) ``` ```python respx.route().mock(side_effect=callback) ``` -------------------------------- ### Port Pattern Source: https://lundberg.github.io/respx/api Matches the request URL port. Supports 'eq' and 'in' lookups. ```APIDOC ## Port ### Description Matches request _URL port_, using `eq` as default lookup. ### Key: `port` ### Lookups: eq, in ### Example: ```python respx.route(port=8000) respx.route(port__in=[2375, 2376]) ``` ``` -------------------------------- ### Defining Routes in Respx Source: https://lundberg.github.io/respx/upgrade Shows the change from the `.add` API to the `.route` API for defining request routes. The `.route` method allows specifying method and URL explicitly. ```python # Previously respx.add("POST", "https://some.url/", content="foobar") ``` ```python # Now respx.route(method="POST", url="https://some.url/").respond(content="foobar") ``` -------------------------------- ### Reusable Routers with Context Manager Source: https://lundberg.github.io/respx/guide Use an isolated router instance as a context manager to activate routes within a specific block of code. This allows for scoped mocking. ```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: ... ``` -------------------------------- ### Unittest Async Context Manager Mock Source: https://lundberg.github.io/respx/examples Manage mocks for asynchronous tests in `unittest.TestCase` using `async with respx.mock:`. ```python async def test_async_ctx_manager(self): 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 ``` -------------------------------- ### Subsequent Responses Source: https://lundberg.github.io/respx/migrate Migrate multiple 'responses.add' calls for the same URL to 'respx.get().mock(side_effect=[...])' with Response objects. ```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 import Response respx.get("https://example.org/").mock( side_effect=[Response(200), Response(500)] ) ``` -------------------------------- ### Unittest Mixin Usage Source: https://lundberg.github.io/respx/examples Integrate the `MockedAPIMixin` into a `unittest.TestCase` to leverage pre-configured mocks. ```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) ``` -------------------------------- ### respx.route() Source: https://lundberg.github.io/respx/api Adds a new, optionally named, Route with given patterns and/or lookups combined using the AND operator. ```APIDOC ## respx.route() ### Description Adds a new, _optionally named_ , `Route` with given patterns _and/or_ lookups combined, using the AND operator. ### Method `respx.route(_*patterns, name=None, **lookups)` ### Parameters #### Positional Parameters - **patterns** - _(optional) args_ - One or more pattern objects. #### Keyword Parameters - **lookups** - _(optional) kwargs_ - One or more pattern keyword lookups, given as `__=value`. - **name** - _(optional) str_ - Name this route. ### Returns `Route` ``` -------------------------------- ### Method Pattern Source: https://lundberg.github.io/respx/api Matches the request HTTP method. Supports 'eq' and 'in' lookups. ```APIDOC ## Method ### Description Matches request _HTTP method_, using `eq` as default lookup. ### Key: `method` ### Lookups: eq, in ### Example: ```python respx.route(method="GET") respx.route(method__in=["PUT", "PATCH"]) ``` ``` -------------------------------- ### Callbacks Source: https://lundberg.github.io/respx/migrate Migrate '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 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) ``` -------------------------------- ### Configure Pytest Fixture with Marker Source: https://lundberg.github.io/respx/guide Use the '@pytest.mark.respx(...)' marker on a test case to configure the router when using the 'respx_mock' pytest fixture. ```python @pytest.mark.respx(...) def test_something(respx_mock): ... ``` -------------------------------- ### Mock HTTPX with Decorator Source: https://lundberg.github.io/respx/guide Use the @respx.mock decorator to activate Respx for a test function. This automatically patches HTTPX and enables request routing. ```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 ``` -------------------------------- ### Pytest Built-in Marker Source: https://lundberg.github.io/respx/examples Configure the `respx_mock` fixture using the `respx` marker for base URL settings. ```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 ``` -------------------------------- ### respx.request() Source: https://lundberg.github.io/respx/api A generic method to add a route for any HTTP method. It requires the method and URL to be specified. ```APIDOC ## respx.request() ### Description Adds a route for a specific HTTP method and URL. ### Method `respx.request(_method, url, name=None, **lookups)` ### Parameters #### Keyword 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 `__=value`. ### Returns `Route` ### Example ```python respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...) ``` ``` -------------------------------- ### Enable Assert All Called Source: https://lundberg.github.io/respx/guide Configure the router with 'assert_all_called=True' to ensure all added routes are called when the mock scope exits. This helps verify that all intended mocks were used. ```python @respx.mock(assert_all_called=True) def test_something(respx_mock): respx_mock.get("https://example.org/") respx_mock.get("https://some.url/") # Not called, will fail the test response = httpx.get("https://example.org/") ``` -------------------------------- ### URL Pattern Source: https://lundberg.github.io/respx/api Matches the entire request URL. Can combine individual URL parts or match the full URL string. Supports 'eq', 'regex', and 'startswith' lookups. ```APIDOC ## URL ### Description 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 ### Example: ```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/") ``` ``` -------------------------------- ### Pytest Session Scoped Fixture (Async) Source: https://lundberg.github.io/respx/examples Configure a session-scoped respx fixture for async tests, ensuring proper event loop handling with `pytest-asyncio`. ```python # conftest.py import pytest import respx from respx.fixtures import session_event_loop as event_loop # noqa: F401 @pytest.fixture(scope="session") async def mocked_api(event_loop): # noqa: F811 async with respx.mock(base_url="https://foo.bar") as respx_mock: ... yield respx_mock ``` -------------------------------- ### Add a Request Route Source: https://lundberg.github.io/respx/api Adds a route for a specific HTTP method and URL. Supports optional name and lookups. ```python respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...) ``` -------------------------------- ### Set Route Return Value Source: https://lundberg.github.io/respx/api Sets the HTTPX Response to be returned when the route is matched. ```python route.return_value = Response(204) ``` -------------------------------- ### History and Assertions: All Called Source: https://lundberg.github.io/respx/migrate Migrate 'assert_all_requests_are_fired=False' in 'responses.RequestsMock' to 'assert_all_called=False' in 'respx.mock'. ```python import responses with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: ... ``` ```python import respx with respx.mock(assert_all_called=False) as respx_mock: ... ``` -------------------------------- ### Matching URL Path Source: https://lundberg.github.io/respx/api Match requests based on the URL path. Supports exact matching ('eq'), regular expressions ('regex'), prefix matching ('startswith'), and matching against a list ('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/"]) ``` -------------------------------- ### Pytest Mocking with respx_mock fixture Source: https://lundberg.github.io/respx Utilize the respx_mock fixture provided by Respx for cleaner pytest integration. Mock responses using the fixture's methods. ```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 ``` -------------------------------- ### Matching HTTP Method Source: https://lundberg.github.io/respx/api Match requests based on their HTTP method. The 'eq' lookup is the default. You can also use 'in' to match against a list of methods. ```python respx.route(method="GET") respx.route(method__in=["PUT", "PATCH"]) ``` -------------------------------- ### History and Assertions: Call History Source: https://lundberg.github.io/respx/migrate Migrate accessing call history from 'responses.calls' to 'respx.calls'. ```python import responses responses.calls[0].request responses.calls[0].response ``` ```python import respx respx.calls[0].request respx.calls[0].response request, response = respx.calls[0] respx.calls.last.response ``` -------------------------------- ### Route.return_value Source: https://lundberg.github.io/respx/api Setter for the HTTPX Response to return when the route is matched. ```APIDOC ## Route.return_value ### Description Setter for the `HTTPX` Response to return. ### Example ```python route.return_value = Response(204) ``` ``` -------------------------------- ### Matching Full URL Source: https://lundberg.github.io/respx/api Match requests based on the full URL. When no lookup is given, 'url' acts as a shorthand for combining host and path. Supports 'eq', 'regex', and 'startswith' lookups. ```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/") ``` -------------------------------- ### Route.pass_through() Source: https://lundberg.github.io/respx/api Marks a route to pass through, sending matched requests to the real server instead of mocking them. ```APIDOC ## Route.pass_through() ### Description Marks route to pass through, sending matched requests to real server, _e.g. don't mock_. ### Method `route.pass_through(_value=True)` ### Parameters #### Keyword Parameters - **value** - _(optional) bool - default:`True`_ - Mark route to pass through. ### Returns `Route` ``` -------------------------------- ### Route.mock() Source: https://lundberg.github.io/respx/api Mock a route's response or side effect. This can be a direct response or a callable/exception to handle the request. ```APIDOC ## Route.mock() ### Description Mock a route's response or side effect. ### Method `route.mock(_return_value=None, side_effect=None)` ### Parameters #### Keyword 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` ``` -------------------------------- ### Mocking Route Response with return_value Source: https://lundberg.github.io/respx/guide Mock a route's response by setting the return_value of the mock interface to an httpx.Response object. This directly specifies the response to be returned. ```python .mock(return_value=httpx.Response(200, json={"name": "baz"})) ``` -------------------------------- ### Pytest Mocking with respx marker and base_url Source: https://lundberg.github.io/respx Configure Respx mocks within pytest using the @pytest.mark.respx marker to specify a base URL for routes. ```python import httpx import pytest @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 ``` -------------------------------- ### Pass Through Requests Source: https://lundberg.github.io/respx/migrate Migrate '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() ``` -------------------------------- ### Route API with Patterns Source: https://lundberg.github.io/respx/guide Define a combined pattern using the route API to match and capture incoming requests. Verify the route was called and the response status code. ```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 ``` -------------------------------- ### Mock an Exception Source: https://lundberg.github.io/respx/migrate Migrate 'responses.add' with an exception body 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) ``` -------------------------------- ### Content Pattern Source: https://lundberg.github.io/respx/api Matches the raw request content (body). Supports 'eq' and 'contains' lookups. ```APIDOC ## Content ### Description Matches request raw _content_, using eq as default lookup. ### Key: `content` ### Lookups: eq, contains ### 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") ``` ``` -------------------------------- ### Matching URL Scheme Source: https://lundberg.github.io/respx/api Match requests based on the URL scheme (e.g., http, https). The 'eq' lookup is the default, and 'in' can be used for multiple schemes. ```python respx.route(scheme="https") respx.route(scheme__in=["http", "https"]) ``` -------------------------------- ### Unittest Regular Decoration Mock Source: https://lundberg.github.io/respx/examples Apply the `@respx.mock` decorator to test methods within a `unittest.TestCase` subclass. ```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) ``` -------------------------------- ### Scheme Pattern Source: https://lundberg.github.io/respx/api Matches the request URL scheme (e.g., 'http', 'https'). Supports 'eq' and 'in' lookups. ```APIDOC ## Scheme ### Description Matches request _URL scheme_, using `eq` as default lookup. ### Key: `scheme` ### Lookups: eq, in ### Example: ```python respx.route(scheme="https") respx.route(scheme__in=["http", "https"]) ``` ``` -------------------------------- ### M() - Combined Patterns Source: https://lundberg.github.io/respx/api Creates a reusable pattern by combining multiple arguments using the AND operator. This is useful for defining complex matching criteria. ```APIDOC ## M() ### Description Creates a reusable pattern, combining multiple arguments using the AND operator. ### Parameters: * **patterns** - _(optional) args_ One or more pattern objects. * **lookups** - _(optional) kwargs_ One or more pattern keyword lookups, given as `__=value`. ### Returns: `Pattern` ### Example: ```python import respx from respx.patterns import M pattern = M(host="example.org") respx.route(pattern) ``` ``` -------------------------------- ### Assertions (requests-mock) Source: https://lundberg.github.io/respx/migrate Migrate assertions from 'requests_mock.mock' object to 'respx.calls'. ```python self.assertTrue(m.called_once) self.assertEqual(m.last_request.url, "https://api.io/example/endpoint") self.assertEqual(m.last_request.json(), {"key": "value"}) ``` ```python respx.calls.assert_called_once() self.assertEqual( str(respx.calls.last.request.url), "https://api.io/example/endpoint", ) self.assertEqual(json.loads(respx.calls.last.request.content), {"key": "value"}) ``` -------------------------------- ### Params Pattern Source: https://lundberg.github.io/respx/api Matches request URL query parameters. Supports 'contains' and 'eq' lookups. ```APIDOC ## Params ### Description Matches request _URL query params_, using `contains` as default lookup. ### Key: `params` ### Lookups: contains, eq ### 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") ``` **Note:** A request querystring with multiple parameters of the same name is treated as an ordered list when matching. Use `mock.ANY` as value to only match on parameter presence, e.g. `respx.route(params={"foo": ANY})`. ``` -------------------------------- ### Combine Patterns with AND Source: https://lundberg.github.io/respx/api Combine two patterns using the bitwise AND operator (`&`) to create a more specific match. ```python M(scheme="http") & M(host="example.org") ``` -------------------------------- ### Match HTTP Method with In Source: https://lundberg.github.io/respx/api Use the `in` lookup to match if the HTTP method is one of the specified values. ```python M(method__in=["PUT", "PATCH"]) ``` -------------------------------- ### SetCookie Utility Source: https://lundberg.github.io/respx/api A utility to render a `("Set-Cookie", )` tuple. Useful for setting cookies in responses. ```APIDOC ## SetCookie ### Description A utility to render a `("Set-Cookie", )` tuple. See route respond shortcut for alternative use. ### Parameters: * **name** * **value** * **path** - _(optional)_ * **domain** - _(optional)_ * **expires** - _(optional)_ * **max_age** - _(optional)_ * **http_only** - _(optional, default=False)_ * **same_site** - _(optional)_ * **secure** - _(optional, default=False)_ * **partitioned** - _(optional, default=False)_ ### Example: ```python import respx respx.post("https://example.org/").mock( return_value=httpx.Response(200, headers=[SetCookie("foo", "bar")]) ) ``` ``` -------------------------------- ### Manually Resetting Call History Source: https://lundberg.github.io/respx/guide Demonstrates how to manually reset call statistics within a test case using `respx.reset()`. This is useful for isolating test steps and ensuring accurate call counts. ```python import httpx import respx @respx.mock def test_reset(): respx.post("https://foo.bar/baz/") httpx.post("https://foo.bar/baz/") assert respx.calls.call_count == 1 respx.calls.assert_called_once() respx.reset() assert len(respx.calls) == 0 assert respx.calls.call_count == 0 respx.calls.assert_not_called() ``` -------------------------------- ### Matching URL Query Parameters Source: https://lundberg.github.io/respx/api Match requests based on URL query parameters. The default lookup is 'contains'. You can provide parameters as a dictionary, list of tuples, or a query string. Note that 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") ``` -------------------------------- ### Unittest Async Decorator Mock Source: https://lundberg.github.io/respx/examples Mock asynchronous HTTP requests within `unittest.TestCase` using the `@respx.mock` decorator. ```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 ``` -------------------------------- ### Modify Mocked Response Source: https://lundberg.github.io/respx/migrate Migrate 'responses.replace' to 'respx.get().respond()' for modifying a mocked response. ```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}) ```