Testing Helpers#

Functional testing framework for Falcon apps and Falcon itself.

Falcon’s testing module contains various test classes and utility functions to support functional testing for both Falcon-based apps and the Falcon framework itself.

The testing framework supports both unittest and pytest:

# -----------------------------------------------------------------
# unittest
# -----------------------------------------------------------------

from falcon import testing
import myapp


class MyTestCase(testing.TestCase):
    def setUp(self):
        super(MyTestCase, self).setUp()

        # Assume the hypothetical `myapp` package has a
        # function called `create()` to initialize and
        # return a `falcon.App` instance.
        self.app = myapp.create()


class TestMyApp(MyTestCase):
    def test_get_message(self):
        doc = {'message': 'Hello world!'}

        result = self.simulate_get('/messages/42')
        self.assertEqual(result.json, doc)


# -----------------------------------------------------------------
# pytest
# -----------------------------------------------------------------

from falcon import testing
import pytest

import myapp


# Depending on your testing strategy and how your application
# manages state, you may be able to broaden the fixture scope
# beyond the default 'function' scope used in this example.

@pytest.fixture()
def client():
    # Assume the hypothetical `myapp` package has a function called
    # `create()` to initialize and return a `falcon.App` instance.
    return testing.TestClient(myapp.create())


def test_get_message(client):
    doc = {'message': 'Hello world!'}

    result = client.simulate_get('/messages/42')
    assert result.json == doc

Simulating Requests#

Main Interface#

class falcon.testing.TestClient(app: Callable[[...], Any], headers: Mapping[str, str] | None = None)[source]#

Simulate requests to a WSGI or ASGI application.

This class provides a contextual wrapper for Falcon’s simulate_*() test functions. It lets you replace this:

simulate_get(app, '/messages')
simulate_head(app, '/messages')

with this:

client = TestClient(app)
client.simulate_get('/messages')
client.simulate_head('/messages')

For convenience, TestClient also exposes shorthand aliases without the simulate_ prefix. Just as with a typical Python HTTP client, it is possible to simply call:

client = TestClient(app)
client.get('/messages')
client.request('LOCK', '/files/first')

Note

The methods all call self.simulate_request() for convenient overriding of request preparation by child classes.

Note

In the case of an ASGI request, this class will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

An instance of ASGIConductor may be instantiated directly, or obtained from an instance of TestClient using the context manager pattern, as per the following example:

client = falcon.testing.TestClient(app)

# -- snip --

async with client as conductor:
    async with conductor.simulate_get_stream('/events') as result:
        pass
Parameters:

app (callable) – A WSGI or ASGI application to target when simulating requests

Keyword Arguments:

headers (dict) – Default headers to set on every request (default None). These defaults may be overridden by passing values for the same headers to one of the simulate_*() methods.

app: falcon.App#

The app that this client instance was configured to use.

delete(*args: Any, **kwargs: Any) Any#

Simulate a DELETE request to a WSGI application.

(See also: falcon.testing.simulate_delete())

Added in version 3.1.

get(*args: Any, **kwargs: Any) Any#

Simulate a GET request to a WSGI application.

(See also: falcon.testing.simulate_get())

Added in version 3.1.

head(*args: Any, **kwargs: Any) Any#

Simulate a HEAD request to a WSGI application.

(See also: falcon.testing.simulate_head())

Added in version 3.1.

options(*args: Any, **kwargs: Any) Any#

Simulate an OPTIONS request to a WSGI application.

(See also: falcon.testing.simulate_options())

Added in version 3.1.

patch(*args: Any, **kwargs: Any) Any#

Simulate a PATCH request to a WSGI application.

(See also: falcon.testing.simulate_patch())

Added in version 3.1.

post(*args: Any, **kwargs: Any) Any#

Simulate a POST request to a WSGI application.

(See also: falcon.testing.simulate_post())

Added in version 3.1.

put(*args: Any, **kwargs: Any) Any#

Simulate a PUT request to a WSGI application.

(See also: falcon.testing.simulate_put())

Added in version 3.1.

request(*args: Any, **kwargs: Any) Any#

Simulate a request to a WSGI application.

Wraps falcon.testing.simulate_request() to perform a WSGI request directly against self.app. Equivalent to:

falcon.testing.simulate_request(self.app, *args, **kwargs)

Added in version 3.1.

simulate_delete(path: str = '/', **kwargs: Any) Result[source]#

Simulate a DELETE request to a WSGI application.

(See also: falcon.testing.simulate_delete())

simulate_get(path: str = '/', **kwargs: Any) Result[source]#

Simulate a GET request to a WSGI application.

(See also: falcon.testing.simulate_get())

simulate_head(path: str = '/', **kwargs: Any) Result[source]#

Simulate a HEAD request to a WSGI application.

(See also: falcon.testing.simulate_head())

simulate_options(path: str = '/', **kwargs: Any) Result[source]#

Simulate an OPTIONS request to a WSGI application.

(See also: falcon.testing.simulate_options())

simulate_patch(path: str = '/', **kwargs: Any) Result[source]#

Simulate a PATCH request to a WSGI application.

(See also: falcon.testing.simulate_patch())

simulate_post(path: str = '/', **kwargs: Any) Result[source]#

Simulate a POST request to a WSGI application.

(See also: falcon.testing.simulate_post())

simulate_put(path: str = '/', **kwargs: Any) Result[source]#

Simulate a PUT request to a WSGI application.

(See also: falcon.testing.simulate_put())

simulate_request(*args: Any, **kwargs: Any) Result[source]#

Simulate a request to a WSGI application.

Wraps falcon.testing.simulate_request() to perform a WSGI request directly against self.app. Equivalent to:

falcon.testing.simulate_request(self.app, *args, **kwargs)
class falcon.testing.ASGIConductor(app: Callable[[...], Any], headers: Mapping[str, str] | None = None)[source]#

Test conductor for ASGI apps.

This class provides more control over the lifecycle of a simulated request as compared to TestClient. In addition, the conductor’s asynchronous interface affords interleaved requests and the testing of streaming protocols such as Server-Sent Events (SSE) and WebSocket.

ASGIConductor is implemented as a context manager. Upon entering and exiting the context, the appropriate ASGI lifespan events will be simulated.

Within the context, HTTP requests can be simulated using an interface that is similar to TestClient, except that all simulate_*() methods are coroutines:

async with testing.ASGIConductor(some_app) as conductor:
    async def post_events():
        for i in range(100):
            await conductor.simulate_post('/events', json={'id': i}):
            await asyncio.sleep(0.01)

    async def get_events_sse():
        # Here, we will get only some of the single server-sent events
        # because the non-streaming method is "single-shot". In other
        # words, simulate_get() will emit a client disconnect event
        # into the app before returning.
        result = await conductor.simulate_get('/events')

        # Alternatively, we can use simulate_get_stream() as a context
        # manager to perform a series of reads on the result body that
        # are interleaved with the execution of the post_events()
        # coroutine.
        async with conductor.simulate_get_stream('/events') as sr:
            while some_condition:
                # Read next body chunk that was received (if any).
                chunk = await sr.stream.read()

                if chunk:
                    # TODO: Do something with the chunk
                    pass

            # Exiting the context causes the request event emitter to
            # begin emitting ``'http.disconnect'`` events and then awaits
            # the completion of the asyncio task that is running the
            # simulated ASGI request.

    asyncio.gather(post_events(), get_events_sse())

Note

Because the ASGIConductor interface uses coroutines, it cannot be used directly with synchronous testing frameworks such as pytest.

As a workaround, the test can be adapted by wrapping it in an inline async function and then invoking it via falcon.async_to_sync() or decorating the test function with falcon.runs_sync().

Alternatively, you can try searching PyPI to see if an async plugin is available for your testing framework of choice. For example, the pytest-asyncio plugin is available for pytest users.

Similar to the TestClient, ASGIConductor also exposes convenience aliases without the simulate_ prefix. Just as with a typical asynchronous HTTP client, it is possible to simply invoke:

await conductor.get('/messages')
await conductor.request('LOCK', '/files/first')
Parameters:

app (callable) – An ASGI application to target when simulating requests.

Keyword Arguments:

headers (dict) – Default headers to set on every request (default None). These defaults may be overridden by passing values for the same headers to one of the simulate_*() methods.

app: asgi.App#

The app that this client instance was configured to use.

async delete(*args: Any, **kwargs: Any) Any#

Simulate a DELETE request to an ASGI application.

(See also: falcon.testing.simulate_delete())

Added in version 3.1.

async get(*args: Any, **kwargs: Any) Any#

Simulate a GET request to an ASGI application.

(See also: falcon.testing.simulate_get())

Added in version 3.1.

get_stream(*args: Any, **kwargs: Any) Any#

Simulate a GET request to an ASGI application with a streamed response.

(See also: falcon.testing.simulate_get() for a list of supported keyword arguments.)

This method returns an async context manager that can be used to obtain a managed StreamedResult instance. Exiting the context will automatically finalize the result object, causing the request event emitter to begin emitting 'http.disconnect' events and then await the completion of the task that is running the simulated ASGI request.

In the following example, a series of streamed body chunks are read from the response:

async with conductor.get_stream('/events') as sr:
    while some_condition:
        # Read next body chunk that was received (if any).
        chunk = await sr.stream.read()

        if chunk:
            # TODO: Do something with the chunk. For example,
            #   a series of server-sent events could be validated
            #   by concatenating the chunks and splitting on
            #   double-newlines to obtain individual events.
            pass

Added in version 3.1.

async head(*args: Any, **kwargs: Any) Any#

Simulate a HEAD request to an ASGI application.

(See also: falcon.testing.simulate_head())

Added in version 3.1.

async options(*args: Any, **kwargs: Any) Any#

Simulate an OPTIONS request to an ASGI application.

(See also: falcon.testing.simulate_options())

Added in version 3.1.

async patch(*args: Any, **kwargs: Any) Any#

Simulate a PATCH request to an ASGI application.

(See also: falcon.testing.simulate_patch())

Added in version 3.1.

async post(*args: Any, **kwargs: Any) Any#

Simulate a POST request to an ASGI application.

(See also: falcon.testing.simulate_post())

Added in version 3.1.

async put(*args: Any, **kwargs: Any) Any#

Simulate a PUT request to an ASGI application.

(See also: falcon.testing.simulate_put())

Added in version 3.1.

async request(*args: Any, **kwargs: Any) Any#

Simulate a request to an ASGI application.

Wraps falcon.testing.simulate_request() to perform an ASGI request directly against self.app. Equivalent to:

falcon.testing.simulate_request(self.app, *args, **kwargs)

Added in version 3.1.

async simulate_delete(path: str = '/', **kwargs: Any) Result[source]#

Simulate a DELETE request to an ASGI application.

(See also: falcon.testing.simulate_delete())

async simulate_get(path: str = '/', **kwargs: Any) Result[source]#

Simulate a GET request to an ASGI application.

(See also: falcon.testing.simulate_get())

simulate_get_stream(path: str = '/', **kwargs: Any) _AsyncContextManager[source]#

Simulate a GET request to an ASGI application with a streamed response.

(See also: falcon.testing.simulate_get() for a list of supported keyword arguments.)

This method returns an async context manager that can be used to obtain a managed StreamedResult instance. Exiting the context will automatically finalize the result object, causing the request event emitter to begin emitting 'http.disconnect' events and then await the completion of the task that is running the simulated ASGI request.

In the following example, a series of streamed body chunks are read from the response:

async with conductor.simulate_get_stream('/events') as sr:
    while some_condition:
        # Read next body chunk that was received (if any).
        chunk = await sr.stream.read()

        if chunk:
            # TODO: Do something with the chunk. For example,
            #   a series of server-sent events could be validated
            #   by concatenating the chunks and splitting on
            #   double-newlines to obtain individual events.
            pass
async simulate_head(path: str = '/', **kwargs: Any) Result[source]#

Simulate a HEAD request to an ASGI application.

(See also: falcon.testing.simulate_head())

async simulate_options(path: str = '/', **kwargs: Any) Result[source]#

Simulate an OPTIONS request to an ASGI application.

(See also: falcon.testing.simulate_options())

async simulate_patch(path: str = '/', **kwargs: Any) Result[source]#

Simulate a PATCH request to an ASGI application.

(See also: falcon.testing.simulate_patch())

async simulate_post(path: str = '/', **kwargs: Any) Result[source]#

Simulate a POST request to an ASGI application.

(See also: falcon.testing.simulate_post())

async simulate_put(path: str = '/', **kwargs: Any) Result[source]#

Simulate a PUT request to an ASGI application.

(See also: falcon.testing.simulate_put())

async simulate_request(*args: Any, _stream_result: Literal[True], **kwargs: Any) StreamedResult[source]#
async simulate_request(*args: Any, **kwargs: Any) Result

Simulate a request to an ASGI application.

Wraps falcon.testing.simulate_request() to perform an ASGI request directly against self.app. Equivalent to:

falcon.testing.simulate_request(self.app, *args, **kwargs)
simulate_ws(path: str = '/', **kwargs: Any) _WSContextManager[source]#

Simulate a WebSocket connection to an ASGI application.

All keyword arguments are passed through to falcon.testing.create_scope_ws().

This method returns an async context manager that can be used to obtain a managed falcon.testing.ASGIWebSocketSimulator instance. Exiting the context will simulate a close on the WebSocket (if not already closed) and await the completion of the task that is running the simulated ASGI request.

In the following example, a series of WebSocket TEXT events are received from the ASGI app:

async with conductor.simulate_ws('/events') as ws:
    while some_condition:
        message = await ws.receive_text()
websocket(*args: Any, **kwargs: Any) Any#

Simulate a WebSocket connection to an ASGI application.

All keyword arguments are passed through to falcon.testing.create_scope_ws().

This method returns an async context manager that can be used to obtain a managed falcon.testing.ASGIWebSocketSimulator instance. Exiting the context will simulate a close on the WebSocket (if not already closed) and await the completion of the task that is running the simulated ASGI request.

In the following example, a series of WebSocket TEXT events are received from the ASGI app:

async with conductor.websocket('/events') as ws:
    while some_condition:
        message = await ws.receive_text()

Added in version 3.1.

class falcon.testing.Result(iterable: Iterable[bytes], status: str, headers: Iterable[Tuple[str, str]])[source]#

Encapsulates the result of a simulated request.

Parameters:
  • iterable (iterable) – An iterable that yields zero or more bytestrings, per PEP-3333

  • status (str) – An HTTP status string, including status code and reason string

  • headers (list) – A list of (header_name, header_value) tuples, per PEP-3333

property content: bytes#

Raw response body, or an b'' if the response body was empty.

property content_type: str | None#

Return the Content-Type header or None if missing.

property cookies: Dict[str, Cookie]#

A dictionary of falcon.testing.Cookie values parsed from the response, by name.

The cookies dictionary can be used directly in subsequent requests:

client = testing.TestClient(app)
response_one = client.simulate_get('/')
response_two = client.simulate_post('/', cookies=response_one.cookies)
property encoding: str | None#

Text encoding of the response body.

Returns None if the encoding can not be determined.

property headers: Dict[str, str]#

A case-insensitive dictionary containing all the headers in the response, except for cookies, which may be accessed via the cookies attribute.

Note

Multiple instances of a header in the response are currently not supported; it is unspecified which value will “win” and be represented in headers.

property json: Any#

Deserialized JSON body.

Will be None if the body has no content to deserialize. Otherwise, raises an error if the response is not valid JSON.

property status: str#

HTTP status string given in the response.

property status_code: int#

The code portion of the HTTP status string.

property text: str#

Decoded response body of type str.

If the content type does not specify an encoding, UTF-8 is assumed.

class falcon.testing.StreamedResult(body_chunks: Sequence[bytes], status: str, headers: Iterable[Tuple[str, str]], task: Task, req_event_emitter: ASGIRequestEventEmitter)[source]#

Encapsulates the streamed result of an ASGI request.

Parameters:
  • body_chunks (list) – A list of body chunks. This list may be appended to after a result object has been instantiated.

  • status (str) – An HTTP status string, including status code and reason string

  • headers (list) – A list of (header_name, header_value) tuples, per PEP-3333

  • task (asyncio.Task) – The scheduled simulated request which may or may not have already finished. finalize() will await the task before returning.

  • req_event_emitter (ASGIRequestEventEmitter) – A reference to the event emitter used to simulate events sent to the ASGI application via its receive() method. finalize() will cause the event emitter to simulate an 'http.disconnect' event before returning.

property content_type: str | None#

Return the Content-Type header or None if missing.

property cookies: Dict[str, Cookie]#

A dictionary of falcon.testing.Cookie values parsed from the response, by name.

The cookies dictionary can be used directly in subsequent requests:

client = testing.TestClient(app)
response_one = client.simulate_get('/')
response_two = client.simulate_post('/', cookies=response_one.cookies)
property encoding: str | None#

Text encoding of the response body.

Returns None if the encoding can not be determined.

async finalize() None[source]#

Finalize the encapsulated simulated request.

This method causes the request event emitter to begin emitting 'http.disconnect' events and then awaits the completion of the asyncio task that is running the simulated ASGI request.

property headers: Dict[str, str]#

A case-insensitive dictionary containing all the headers in the response, except for cookies, which may be accessed via the cookies attribute.

Note

Multiple instances of a header in the response are currently not supported; it is unspecified which value will “win” and be represented in headers.

property status: str#

HTTP status string given in the response.

property status_code: int#

The code portion of the HTTP status string.

property stream: ResultBodyStream#

Raw response body, as a byte stream.

class falcon.testing.ResultBodyStream(chunks: Sequence[bytes])[source]#

Simple forward-only reader for a streamed test result body.

Parameters:

chunks (list) – Reference to a list of body chunks that may continue to be appended to as more body events are collected.

async read() bytes[source]#

Read any data that has been collected since the last call.

Returns:

data that has been collected since the last call, or an empty byte string if no additional data is available.

Return type:

bytes

class falcon.testing.ASGIWebSocketSimulator[source]#

Simulates a WebSocket client for testing a Falcon ASGI app.

This class provides a way to test WebSocket endpoints in a Falcon ASGI app without having to interact with an actual ASGI server. While it is certainly important to test against a real server, a number of functional tests can be satisfied more efficiently and transparently with a simulated connection.

Note

The ASGIWebSocketSimulator class is not designed to be instantiated directly; rather it should be obtained via simulate_ws().

async close(code: int | None = None, reason: str | None = None) None[source]#

Close the simulated connection.

Keyword Arguments:
  • code (int) – The WebSocket close code to send to the application per the WebSocket spec (default: 1000).

  • reason (str) – The WebSocket close reason to send to the application per the WebSocket spec (default: empty string).

property close_code: int | None#

The WebSocket close code provided by the app if the connection is closed.

Returns None if the connection is still open.

property close_reason: str | None#

The WebSocket close reason provided by the app if the connection is closed.

Returns None if the connection is still open.

property closed: bool#

True if the WebSocket connection has been denied or closed by the app, or the client has disconnected.

property headers: List[Tuple[bytes, bytes]] | None#

An iterable of [name, value] two-item tuples, where name is the header name, and value is the header value for each header returned by the app when it accepted the WebSocket connection. This property resolves to None if the connection has not been accepted.

property ready: bool#

True if the WebSocket connection has been accepted and the client is still connected, False otherwise.

async receive_data() bytes[source]#

Receive a message from the app with a binary data payload.

Awaiting this coroutine will block until a message is available or the WebSocket is disconnected.

async receive_json() Any[source]#

Receive a message from the app with a JSON-encoded TEXT payload.

Awaiting this coroutine will block until a message is available or the WebSocket is disconnected.

async receive_msgpack() Any[source]#

Receive a message from the app with a MessagePack-encoded BINARY payload.

Awaiting this coroutine will block until a message is available or the WebSocket is disconnected.

async receive_text() str[source]#

Receive a message from the app with a Unicode string payload.

Awaiting this coroutine will block until a message is available or the WebSocket is disconnected.

async send_data(payload: bytes | bytearray | memoryview) None[source]#

Send a message to the app with a binary data payload.

Parameters:

payload (Union[bytes, bytearray, memoryview]) – The binary data to send.

async send_json(media: object) None[source]#

Send a message to the app with a JSON-encoded payload.

Parameters:

media – A JSON-encodable object to send as a TEXT (0x01) payload.

async send_msgpack(media: object) None[source]#

Send a message to the app with a MessagePack-encoded payload.

Parameters:

media – A MessagePack-encodable object to send as a BINARY (0x02) payload.

async send_text(payload: str) None[source]#

Send a message to the app with a Unicode string payload.

Parameters:

payload (str) – The string to send.

property subprotocol: str | None#

The subprotocol the app wishes to accept, or None if not specified.

async wait_ready(timeout: int | None = None) None[source]#

Wait until the connection has been accepted or denied.

This coroutine can be awaited in order to pause execution until the app has accepted or denied the connection. In the latter case, an error will be raised to the caller.

Keyword Arguments:

timeout (int) – Number of seconds to wait before giving up and raising an error (default: 5).

class falcon.testing.Cookie(morsel: Morsel)[source]#

Represents a cookie returned by a simulated request.

Parameters:

morsel – A Morsel object from which to derive the cookie data.

property domain: str#

The domain to which this cookie is restricted.

An empty string if not specified.

property expires: datetime | None#

Expiration timestamp for the cookie, or None if not specified.

Changed in version 4.0: This property now returns timezone-aware datetime objects (or None).

property http_only: bool#

Whether or not the cookie will be visible from JavaScript in the client.

property max_age: int | None#

The lifetime of the cookie in seconds, or None if not specified.

property name: str#

The cookie’s name.

property partitioned: bool#

Indicates if the cookie has the Partitioned flag set.

property path: str#

The path prefix to which this cookie is restricted.

An empty string if not specified.

property same_site: str | None#

Specifies whether cookies are send in cross-site requests.

Possible values are ‘Lax’, ‘Strict’ and ‘None’. None if not specified.

property secure: bool#

Whether or not the cookie may only only be transmitted from the client via HTTPS.

property value: str#

The value of the cookie.

Standalone Methods#

falcon.testing.simulate_get(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate a GET request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'GET', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) –

    The URL path to request

    Note

    The path may contain a query string. However, neither query_string nor params may be specified in this case.

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • file_wrapper (callable) – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the WSGI environ (default: None). This can be used to test high-performance file transmission when resp.stream is set to a file-like object.

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_head(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate a HEAD request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'HEAD', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) –

    The URL path to request

    Note

    The path may contain a query string. However, neither query_string nor params may be specified in this case.

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_post(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate a POST request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'POST', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) – The URL path to request

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • content_type (str) – The value to use for the Content-Type header in the request. If specified, this value will take precedence over any value set for the Content-Type header in the headers keyword argument. The falcon module provides a number of constants for common media types.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • body (str) – The body of the request (default ‘’). The value will be encoded as UTF-8 in the WSGI environ. Alternatively, a byte string may be passed, in which case it will be used as-is.

  • json (JSON serializable) – A JSON document to serialize as the body of the request (default: None). If specified, overrides body and sets the Content-Type header to 'application/json', overriding any value specified by either the content_type or headers arguments.

  • file_wrapper (callable) – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the WSGI environ (default: None). This can be used to test high-performance file transmission when resp.stream is set to a file-like object.

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_put(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate a PUT request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'PUT', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) – The URL path to request

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • content_type (str) – The value to use for the Content-Type header in the request. If specified, this value will take precedence over any value set for the Content-Type header in the headers keyword argument. The falcon module provides a number of constants for common media types.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • body (str) – The body of the request (default ‘’). The value will be encoded as UTF-8 in the WSGI environ. Alternatively, a byte string may be passed, in which case it will be used as-is.

  • json (JSON serializable) – A JSON document to serialize as the body of the request (default: None). If specified, overrides body and sets the Content-Type header to 'application/json', overriding any value specified by either the content_type or headers arguments.

  • file_wrapper (callable) – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the WSGI environ (default: None). This can be used to test high-performance file transmission when resp.stream is set to a file-like object.

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_options(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate an OPTIONS request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'OPTIONS', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) – The URL path to request

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_patch(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate a PATCH request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'PATCH', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) – The URL path to request

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • content_type (str) – The value to use for the Content-Type header in the request. If specified, this value will take precedence over any value set for the Content-Type header in the headers keyword argument. The falcon module provides a number of constants for common media types.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • body (str) – The body of the request (default ‘’). The value will be encoded as UTF-8 in the WSGI environ. Alternatively, a byte string may be passed, in which case it will be used as-is.

  • json (JSON serializable) – A JSON document to serialize as the body of the request (default: None). If specified, overrides body and sets the Content-Type header to 'application/json', overriding any value specified by either the content_type or headers arguments.

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_delete(app: Callable[[...], Any], path: str, **kwargs: Any) Result[source]#

Simulate a DELETE request to a WSGI or ASGI application.

Equivalent to:

simulate_request(app, 'DELETE', path, **kwargs)

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Parameters:
  • app (callable) – The application to call

  • path (str) – The URL path to request

Keyword Arguments:
  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • content_type (str) – The value to use for the Content-Type header in the request. If specified, this value will take precedence over any value set for the Content-Type header in the headers keyword argument. The falcon module provides a number of constants for common media types.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • body (str) – The body of the request (default ‘’). The value will be encoded as UTF-8 in the WSGI environ. Alternatively, a byte string may be passed, in which case it will be used as-is.

  • json (JSON serializable) – A JSON document to serialize as the body of the request (default: None). If specified, overrides body and sets the Content-Type header to 'application/json', overriding any value specified by either the content_type or headers arguments.

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300). Set to 0 to simulate an immediate disconnection without first emitting 'http.request'.

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_request(app: Callable[[...], Any], method: str = 'GET', path: str = '/', query_string: str | None = None, headers: Mapping[str, str] | Iterable[Tuple[str, str]] | None = None, content_type: str | None = None, body: str | bytes | None = None, json: Any | None = None, file_wrapper: Callable[[...], Any] | None = None, wsgierrors: TextIO | None = None, params: Mapping[str, Any] | None = None, params_csv: bool = False, protocol: str = 'http', host: str = 'falconframework.org', remote_addr: str | None = None, extras: Mapping[str, Any] | None = None, http_version: str = '1.1', port: int | None = None, root_path: str | None = None, cookies: Mapping[str, str | Cookie] | None = None, asgi_chunk_size: int = 4096, asgi_disconnect_ttl: int = 300) Result[source]#

Simulate a request to a WSGI or ASGI application.

Performs a request against a WSGI or ASGI application. In the case of WSGI, uses wsgiref.validate to ensure the response is valid.

Note

In the case of an ASGI request, this method will simulate the entire app lifecycle in a single shot, including lifespan and client disconnect events. In order to simulate multiple interleaved requests, or to test a streaming endpoint (such as one that emits server-sent events), ASGIConductor can be used to more precisely control the app lifecycle.

Keyword Arguments:
  • app (callable) – The WSGI or ASGI application to call

  • method (str) – An HTTP method to use in the request (default: ‘GET’)

  • path (str) –

    The URL path to request (default: ‘/’).

    Note

    The path may contain a query string. However, neither query_string nor params may be specified in this case.

  • root_path (str) – The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This defaults to the empty string, indicating that the application corresponds to the “root” of the server.

  • protocol – The protocol to use for the URL scheme (default: ‘http’)

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’). A string may also be passed, as long as it can be parsed as an int.

  • params (dict) – A dictionary of query string parameters, where each key is a parameter name, and each value is either a str or something that can be converted into a str, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).

  • params_csv (bool) – Set to True to encode list values in query string params as comma-separated values (e.g., ‘thing=1,2,3’). Otherwise, parameters will be encoded by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Defaults to False.

  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.

  • content_type (str) – The value to use for the Content-Type header in the request. If specified, this value will take precedence over any value set for the Content-Type header in the headers keyword argument. The falcon module provides a number of constants for common media types.

  • headers (dict) –

    Extra headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • body (str) – The body of the request (default ‘’). The value will be encoded as UTF-8 in the WSGI environ. Alternatively, a byte string may be passed, in which case it will be used as-is.

  • json (JSON serializable) – A JSON document to serialize as the body of the request (default: None). If specified, overrides body and sets the Content-Type header to 'application/json', overriding any value specified by either the content_type or headers arguments.

  • file_wrapper (callable) – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the WSGI environ (default: None). This can be used to test high-performance file transmission when resp.stream is set to a file-like object.

  • host (str) – A string to use for the hostname part of the fully qualified request URL (default: ‘falconframework.org’)

  • remote_addr (str) – A string to use as the remote IP address for the request (default: ‘127.0.0.1’). For WSGI, this corresponds to the ‘REMOTE_ADDR’ environ variable. For ASGI, this corresponds to the IP address used for the ‘client’ field in the connection scope.

  • http_version (str) – The HTTP version to simulate. Must be either ‘2’, ‘2.0’, 1.1’, ‘1.0’, or ‘1’ (default ‘1.1’). If set to ‘1.0’, the Host header will not be added to the scope.

  • wsgierrors (io) – The stream to use as wsgierrors in the WSGI environ (default sys.stderr)

  • asgi_chunk_size (int) – The maximum number of bytes that will be sent to the ASGI app in a single 'http.request' event (default 4096).

  • asgi_disconnect_ttl (int) – The maximum number of seconds to wait since the request was initiated, before emitting an 'http.disconnect' event when the app calls the receive() function (default 300).

  • extras (dict) – Additional values to add to the WSGI environ dictionary or the ASGI scope for the request (default: None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

Returns:

The result of the request

Return type:

Result

falcon.testing.capture_responder_args(req: wsgi.Request, resp: wsgi.Response, resource: object, params: Mapping[str, str]) None[source]#

Before hook for capturing responder arguments.

Adds the following attributes to the hooked responder’s resource class:

  • captured_req

  • captured_resp

  • captured_kwargs

In addition, if the capture-req-body-bytes header is present in the request, the following attribute is added:

  • captured_req_body

Including the capture-req-media header in the request (set to any value) will add the following attribute:

  • capture-req-media

async falcon.testing.capture_responder_args_async(req: asgi.Request, resp: asgi.Response, resource: Resource, params: Mapping[str, str]) None[source]#

Before hook for capturing responder arguments.

An asynchronous version of capture_responder_args().

falcon.testing.set_resp_defaults(req: wsgi.Request, resp: wsgi.Response, resource: Resource, params: Mapping[str, str]) None[source]#

Before hook for setting default response properties.

This hook simply sets the the response body, status, and headers to the _default_status, _default_body, and _default_headers attributes that are assumed to be defined on the resource object.

async falcon.testing.set_resp_defaults_async(req: asgi.Request, resp: asgi.Response, resource: Resource, params: Mapping[str, str]) None[source]#

Wrap set_resp_defaults() in a coroutine.

Low-Level Utils#

class falcon.testing.StartResponseMock[source]#

Mock object representing a WSGI start_response callable.

property call_count: int#

Number of times start_response was called.

headers: Iterable[Tuple[str, str]] | None#

Raw headers list passed to start_response, per PEP-3333.

headers_dict: Dict[str, str]#

Headers as a case-insensitive dict-like object, instead of a list.

status: str | None#

HTTP status line, e.g. ‘785 TPS Cover Sheet not attached’.

class falcon.testing.ASGIRequestEventEmitter(body: str | bytes | None = None, chunk_size: int | None = None, disconnect_at: int | float | None = None)[source]#

Emits events on-demand to an ASGI app.

This class can be used to drive a standard ASGI app callable in order to perform functional tests on the app in question.

Note

In order to ensure the app is able to handle subtle variations in the ASGI events that are allowed by the specification, such variations are applied to the emitted events at unspecified intervals. This includes whether or not the more_body field is explicitly set, or whether or not the request body chunk in the event is occasionally empty,

Keyword Arguments:
  • body (str) – The body content to use when emitting http.request events. May be an empty string. If a byte string, it will be used as-is; otherwise it will be encoded as UTF-8 (default b'').

  • chunk_size (int) – The maximum number of bytes to include in a single http.request event (default 4096).

  • disconnect_at (float) – The Unix timestamp after which to begin emitting 'http.disconnect' events (default now + 30s). The value may be either an int or a float, depending on the precision required. Setting disconnect_at to 0 is treated as a special case, and will result in an 'http.disconnect' event being immediately emitted (rather than first emitting an 'http.request' event).

disconnect(exhaust_body: bool | None = None) None[source]#

Set the client connection state to disconnected.

Call this method to simulate an immediate client disconnect and begin emitting 'http.disconnect' events.

Parameters:

exhaust_body (bool) – Set to False in order to begin emitting 'http.disconnect' events without first emitting at least one 'http.request' event.

property disconnected: bool#

Returns True if the simulated client connection is in a “disconnected” state.

class falcon.testing.ASGILifespanEventEmitter(shutting_down: Condition)[source]#

Emits ASGI lifespan events to an ASGI app.

This class can be used to drive a standard ASGI app callable in order to perform functional tests on the app in question.

When simulating both lifespan and per-request events, each event stream will require a separate invocation of the ASGI callable; one with a lifespan event emitter, and one with a request event emitter. An asyncio Condition can be used to pause the lifespan emitter until all of the desired request events have been emitted.

Keyword Arguments:

shutting_down (asyncio.Condition) – An instance of asyncio.Condition that will be awaited before emitting the final shutdown event ('lifespan.shutdown).

class falcon.testing.ASGIResponseEventCollector[source]#

Collects and validates ASGI events returned by an app.

Raises:
  • TypeError – An event field emitted by the app was of an unexpected type.

  • ValueError – Invalid event name or field value.

body_chunks: List[bytes]#

An iterable of bytes objects emitted by the app via 'http.response.body' events.

events: List[Mapping[str, Any]]#

An iterable of events that were emitted by the app, collected as-is from the app.

headers: List[Tuple[str, str]]#

An iterable of (str, str) tuples representing the ISO-8859-1 decoded headers emitted by the app in the body of the 'http.response.start' event.

more_body: bool | None#

Whether or not the app expects to emit more body chunks.

Will be None if unknown (i.e., the app has not yet emitted any 'http.response.body' events.)

status: HTTPStatus | str | int | None#

HTTP status code emitted by the app in the body of the 'http.response.start' event.

falcon.testing.create_environ(path: str = '/', query_string: str = '', http_version: str = '1.1', scheme: str = 'http', host: str = 'falconframework.org', port: int | None = None, headers: Mapping[str, str] | Iterable[Tuple[str, str]] | None = None, app: str | None = None, body: str | bytes = b'', method: str = 'GET', wsgierrors: TextIO | None = None, file_wrapper: Callable[[...], Any] | None = None, remote_addr: str | None = None, root_path: str | None = None, cookies: Mapping[str, str | Cookie] | None = None) Dict[str, Any][source]#

Create a mock PEP-3333 environ dict for simulating WSGI requests.

Keyword Arguments:
  • path (str) – The path for the request (default '/')

  • query_string (str) – The query string to simulate, without a leading '?' (default ''). The query string is passed as-is (it will not be percent-encoded).

  • http_version (str) – The HTTP version to simulate. Must be either '2', '2.0', '1.1', '1.0', or '1' (default '1.1'). If set to '1.0', the Host header will not be added to the scope.

  • scheme (str) – URL scheme, either 'http' or 'https' (default 'http')

  • host (str) – Hostname for the request (default 'falconframework.org')

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for 'http' and 443 for 'https'). A string may also be passed, as long as it can be parsed as an int.

  • headers (dict) –

    Headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • root_path (str) – Value for the SCRIPT_NAME environ variable, described in PEP-3333: ‘The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This may be an empty string, if the application corresponds to the “root” of the server.’ (default '')

  • app (str) – Deprecated alias for root_path. If both kwargs are passed, root_path takes precedence.

  • body (str) – The body of the request (default ''). The value will be encoded as UTF-8 in the WSGI environ. Alternatively, a byte string may be passed, in which case it will be used as-is.

  • method (str) – The HTTP method to use (default 'GET')

  • wsgierrors (io) – The stream to use as wsgierrors (default sys.stderr)

  • file_wrapper – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the environ.

  • remote_addr (str) – Remote address for the request to use as the 'REMOTE_ADDR' environ variable (default None)

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the Set-Cookie header.

falcon.testing.create_scope(path: str = '/', query_string: str = '', method: str = 'GET', headers: Mapping[str, str] | Iterable[Tuple[str, str]] | None = None, host: str = 'falconframework.org', scheme: str | None = None, port: int | None = None, http_version: str = '1.1', remote_addr: str | None = None, root_path: str | None = None, content_length: int | None = None, include_server: bool = True, cookies: Mapping[str, str | Cookie] | None = None) Dict[str, Any][source]#

Create a mock ASGI scope dict for simulating HTTP requests.

Keyword Arguments:
  • path (str) – The path for the request (default '/')

  • query_string (str) – The query string to simulate, without a leading '?' (default ''). The query string is passed as-is (it will not be percent-encoded).

  • method (str) – The HTTP method to use (default 'GET')

  • headers (dict) –

    Headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). When the request will include a body, the Content-Length header should be included in this list. Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • host (str) – Hostname for the request (default 'falconframework.org'). This also determines the value of the Host header in the request.

  • scheme (str) – URL scheme, either 'http' or 'https' (default 'http')

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for 'http' and 443 for 'https'). A string may also be passed, as long as it can be parsed as an int.

  • http_version (str) – The HTTP version to simulate. Must be either '2', '2.0', '1.1', '1.0', or '1' (default '1.1'). If set to '1.0', the Host header will not be added to the scope.

  • remote_addr (str) – Remote address for the request to use for the ‘client’ field in the connection scope (default None)

  • root_path (str) – The root path this application is mounted at; same as SCRIPT_NAME in WSGI (default '').

  • content_length (int) – The expected content length of the request body (default None). If specified, this value will be used to set the Content-Length header in the request.

  • include_server (bool) – Set to False to not set the ‘server’ key in the scope dict (default True).

  • cookies (dict) – Cookies as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of items provides the name and value for the ‘Set-Cookie’ header.

falcon.testing.create_scope_ws(path: str = '/', query_string: str = '', headers: Mapping[str, str] | Iterable[Tuple[str, str]] | None = None, host: str = 'falconframework.org', scheme: str | None = None, port: int | None = None, http_version: str = '1.1', remote_addr: str | None = None, root_path: str | None = None, include_server: bool = True, subprotocols: str | None = None, spec_version: str = '2.1') Dict[str, Any][source]#

Create a mock ASGI scope dict for simulating WebSocket requests.

Keyword Arguments:
  • path (str) – The path for the request (default '/')

  • query_string (str) – The query string to simulate, without a leading '?' (default ''). The query string is passed as-is (it will not be percent-encoded).

  • headers (dict) –

    Headers as a dict-like (Mapping) object, or an iterable yielding a series of two-member (name, value) iterables. Each pair of strings provides the name and value for an HTTP header. If desired, multiple header values may be combined into a single (name, value) pair by joining the values with a comma when the header in question supports the list format (see also RFC 7230 and RFC 7231). When the request will include a body, the Content-Length header should be included in this list. Header names are not case-sensitive.

    Note

    If a User-Agent header is not provided, it will default to:

    f'falcon-client/{falcon.__version__}'
    

  • host (str) – Hostname for the request (default 'falconframework.org'). This also determines the value of the Host header in the request.

  • scheme (str) – URL scheme, either 'ws' or 'wss' (default 'ws')

  • port (int) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for 'ws' and 443 for 'wss'). A string may also be passed, as long as it can be parsed as an int.

  • http_version (str) – The HTTP version to simulate. Must be either '2', '2.0', or '1.1' (default '1.1').

  • remote_addr (str) – Remote address for the request to use for the ‘client’ field in the connection scope (default None)

  • root_path (str) – The root path this application is mounted at; same as SCRIPT_NAME in WSGI (default '').

  • include_server (bool) – Set to False to not set the ‘server’ key in the scope dict (default True).

  • spec_version (str) – The ASGI spec version to emulate (default '2.1').

  • subprotocols (Iterable[str]) – Subprotocols the client wishes to advertise to the server (default []).

falcon.testing.create_req(options: RequestOptions | None = None, **kwargs: Any) Request[source]#

Create and return a new Request instance.

This function can be used to conveniently create a WSGI environ and use it to instantiate a falcon.Request object in one go.

The arguments for this function are identical to those of falcon.testing.create_environ(), except an additional options keyword argument may be set to an instance of falcon.RequestOptions to configure certain aspects of request parsing in lieu of the defaults.

falcon.testing.create_asgi_req(body: bytes | None = None, req_type: Type[Request] | None = None, options: RequestOptions | None = None, **kwargs: Any) Request[source]#

Create and return a new ASGI Request instance.

This function can be used to conveniently create an ASGI scope and use it to instantiate a falcon.asgi.Request object in one go.

The arguments for this function are identical to those of falcon.testing.create_scope(), with the addition of body, req_type, and options arguments as documented below.

Keyword Arguments:
falcon.testing.closed_wsgi_iterable(iterable: Iterable[bytes]) Iterable[bytes][source]#

Wrap an iterable to ensure its close() method is called.

Wraps the given iterable in an iterator utilizing a for loop as illustrated in the PEP-3333 server/gateway side example. Finally, if the iterable has a close() method, it is called upon exception or exhausting iteration.

Furthermore, the first bytestring yielded from iteration, if any, is prefetched before returning the wrapped iterator in order to ensure the WSGI start_response function is called even if the WSGI application is a generator.

Parameters:

iterable (iterable) – An iterable that yields zero or more bytestrings, per PEP-3333

Returns:

An iterator yielding the same bytestrings as iterable

Return type:

iterator

Other Helpers#

Test Cases#

class falcon.testing.TestCase(methodName='runTest')[source]#

Extends unittest to support WSGI/ASGI functional testing.

Note

If available, uses testtools in lieu of unittest.

This base class provides some extra plumbing for unittest-style test cases, to help simulate WSGI or ASGI requests without having to spin up an actual web server. Various simulation methods are derived from falcon.testing.TestClient.

Simply inherit from this class in your test case classes instead of unittest.TestCase or testtools.TestCase.

app: App#

A WSGI or ASGI application to target when simulating requests (defaults to falcon.App()). When testing your application, you will need to set this to your own instance of falcon.App or falcon.asgi.App. For example:

from falcon import testing
import myapp


class MyTestCase(testing.TestCase):
    def setUp(self):
        super(MyTestCase, self).setUp()

        # Assume the hypothetical `myapp` package has a
        # function called `create()` to initialize and
        # return a `falcon.App` instance.
        self.app = myapp.create()


class TestMyApp(MyTestCase):
    def test_get_message(self):
        doc = {'message': 'Hello world!'}

        result = self.simulate_get('/messages/42')
        self.assertEqual(result.json, doc)
setUp() None[source]#

Hook method for setting up the test fixture before exercising it.

class falcon.testing.SimpleTestResource(status: Optional[str] = None, body: Optional[str] = None, json: Optional[dict[str, str]] = None, headers: Optional[HeaderArg] = None)[source]#

Mock resource for functional testing of framework components.

This class implements a simple test resource that can be extended as needed to test middleware, hooks, and the Falcon framework itself.

Only noop on_get() and on_post() responders are implemented; when overriding these, or adding additional responders in child classes, they can be decorated with the falcon.testing.capture_responder_args() hook in order to capture the req, resp, and params arguments that are passed to the responder. Responders may also be decorated with the falcon.testing.set_resp_defaults() hook in order to set resp properties to default status, body, and header values.

Keyword Arguments:
  • status (str) – Default status string to use in responses

  • body (str) – Default body string to use in responses

  • json (JSON serializable) – Default JSON document to use in responses. Will be serialized to a string and encoded as UTF-8. Either json or body may be specified, but not both.

  • headers (dict) – Default set of additional headers to include in responses

property called: bool#

Whether or not a req/resp was captured.

captured_kwargs: Optional[Any]#

The last dictionary of kwargs, beyond req and resp, that were passed into any one of the responder methods.

captured_req: Optional[Union[wsgi.Request, asgi.Request]]#

The last Request object passed into any one of the responder methods.

captured_req_body: Optional[bytes]#

The last Request body provided to any one of the responder methods.

This value is only captured when the 'capture-req-body-bytes' header is set on the request. The value of the header is the number of bytes to read.

captured_req_media: Optional[Any]#

The last Request media provided to any one of the responder methods.

This value is only captured when the 'capture-req-media' header is set on the request.

captured_resp: Optional[Union[wsgi.Response, asgi.Response]]#

The last Response object passed into any one of the responder methods.

Functions#

falcon.testing.rand_string(min: int, max: int) str[source]#

Return a randomly-generated string, of a random length.

Parameters:
  • min (int) – Minimum string length to return, inclusive

  • max (int) – Maximum string length to return, inclusive

falcon.testing.get_unused_port() int[source]#

Get an unused localhost port for use by a test server.

Warning

It is possible for a third party to bind to the returned port before the caller is able to do so. The caller will need to retry with a different port in that case.

Warning

This method has only be tested on POSIX systems and may not work elsewhere.

falcon.testing.redirected(stdout: ~typing.TextIO = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, stderr: ~typing.TextIO = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>) Iterator[None][source]#

Redirect stdout or stderr temporarily.

e.g.:

with redirected(stderr=os.devnull):

falcon.testing.get_encoding_from_headers(headers: Mapping[str, str]) str | None[source]#

Return encoding from given HTTP Header Dict.

Parameters:

headers (dict) – Dictionary from which to extract encoding. Header names must either be lowercase or the dict must support case-insensitive lookups.