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, headers=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')

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

The app that this client instance was configured to use.

simulate_delete(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a DELETE request to a WSGI application.

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

simulate_get(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a GET request to a WSGI application.

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

simulate_head(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a HEAD request to a WSGI application.

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

simulate_options(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate an OPTIONS request to a WSGI application.

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

simulate_patch(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a PATCH request to a WSGI application.

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

simulate_post(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a POST request to a WSGI application.

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

simulate_put(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a PUT request to a WSGI application.

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

simulate_request(*args, **kwargs) → falcon.testing.client._ResultBase[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, headers=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.

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

The app that this client instance was configured to use.

async simulate_delete(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a DELETE request to an ASGI application.

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

async simulate_get(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a GET request to an ASGI application.

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

simulate_get_stream(path='/', **kwargs)[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='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a HEAD request to an ASGI application.

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

async simulate_options(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate an OPTIONS request to an ASGI application.

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

async simulate_patch(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a PATCH request to an ASGI application.

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

async simulate_post(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a POST request to an ASGI application.

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

async simulate_put(path='/', **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a PUT request to an ASGI application.

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

async simulate_request(*args, **kwargs) → falcon.testing.client._ResultBase[source]

Simulate a request to an ASGI 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)
simulate_ws(path='/', **kwargs)[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()
class falcon.testing.Result(iterable, status, headers)[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

status

HTTP status string given in the response

Type

str

status_code

The code portion of the HTTP status string

Type

int

headers

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.

Type

CaseInsensitiveDict

cookies

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

Type

dict

encoding

Text encoding of the response body, or None if the encoding can not be determined.

Type

str

content

Raw response body, or bytes if the response body was empty.

Type

bytes

text

Decoded response body of type str. If the content type does not specify an encoding, UTF-8 is assumed.

Type

str

json

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.

Type

JSON serializable

class falcon.testing.StreamedResult(body_chunks, status, headers, task, req_event_emitter)[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.

status

HTTP status string given in the response

Type

str

status_code

The code portion of the HTTP status string

Type

int

headers

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.

Type

CaseInsensitiveDict

cookies

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

Type

dict

encoding

Text encoding of the response body, or None if the encoding can not be determined.

Type

str

stream

Raw response body, as a byte stream.

Type

ResultStream

async finalize()[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.

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().

ready

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

Type

bool

closed

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

Type

bool

close_code

The WebSocket close code provided by the app if the connection is closed, or None if the connection is open.

Type

int

subprotocol

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

Type

str

headers

An iterable of [name, value] two-item iterables, 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.

Type

Iterable[Iterable[bytes]]

async close(code: Optional[int] = 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).

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()object[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()object[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: Union[bytes, bytearray, memoryview])[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)[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)[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)[source]

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

Parameters

payload (str) – The string to send.

async wait_ready(timeout: Optional[int] = 5)[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)[source]

Represents a cookie returned by a simulated request.

Parameters

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

name

The cookie’s name.

Type

str

value

The value of the cookie.

Type

str

expires

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

Type

datetime.datetime

path

The path prefix to which this cookie is restricted, or None if not specified.

Type

str

domain

The domain to which this cookie is restricted, or None if not specified.

Type

str

max_age

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

Type

int

secure

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

Type

bool

http_only

Whether or not the cookie may only be included in unscripted requests from the client.

Type

bool

Standalone Methods

falcon.testing.simulate_get(app, path, **kwargs) → falcon.testing.client._ResultBase[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, path, **kwargs) → falcon.testing.client._ResultBase[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, path, **kwargs) → falcon.testing.client._ResultBase[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, path, **kwargs) → falcon.testing.client._ResultBase[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, path, **kwargs) → falcon.testing.client._ResultBase[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, path, **kwargs) → falcon.testing.client._ResultBase[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, path, **kwargs) → falcon.testing.client._ResultBase[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, method='GET', path='/', query_string=None, headers=None, content_type=None, body=None, json=None, file_wrapper=None, wsgierrors=None, params=None, params_csv=False, protocol='http', host='falconframework.org', remote_addr=None, extras=None, http_version='1.1', port=None, root_path=None, cookies=None, asgi_chunk_size=4096, asgi_disconnect_ttl=300) → falcon.testing.client._ResultBase[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, resp, resource, params)[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, resp, resource, params)[source]

Before hook for capturing responder arguments.

An asynchronous version of capture_responder_args().

falcon.testing.set_resp_defaults(req, resp, resource, params)[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, resp, resource, params)[source]

Wrap set_resp_defaults() in a coroutine.

Low-Level Utils

class falcon.testing.StartResponseMock[source]

Mock object representing a WSGI start_response callable.

call_count

Number of times start_response was called.

Type

int

status

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

Type

str

headers

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

Type

list

headers_dict

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

Type

dict

class falcon.testing.ASGIRequestEventEmitter(body: Optional[Union[str, bytes]] = None, chunk_size: Optional[int] = None, disconnect_at: Optional[Union[int, float]] = 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).

disconnected

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

Type

bool

disconnect(exhaust_body: Optional[bool] = 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.

class falcon.testing.ASGILifespanEventEmitter(shutting_down)[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.

events

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

Type

iterable

headers

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

Type

iterable

status

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

Type

int

body_chunks

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

Type

iterable

more_body

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.)

Type

bool

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

  • ValueError – Invalid event name or field value.

falcon.testing.create_environ(path='/', query_string='', http_version='1.1', scheme='http', host='falconframework.org', port=None, headers=None, app=None, body='', method='GET', wsgierrors=None, file_wrapper=None, remote_addr=None, root_path=None, cookies=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-333: ‘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='/', query_string='', method='GET', headers=None, host='falconframework.org', scheme=None, port=None, http_version='1.1', remote_addr=None, root_path=None, content_length=None, include_server=True, cookies=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 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='/', query_string='', headers=None, host='falconframework.org', scheme=None, port=None, http_version='1.1', remote_addr=None, root_path=None, include_server=True, subprotocols=None, spec_version='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 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=None, **kwargs) → falcon.request.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=None, req_type=None, options=None, **kwargs) → falcon.request.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)[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

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)
Type

object

setUp()[source]

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

class falcon.testing.SimpleTestResource(status=None, body=None, json=None, headers=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

called

Whether or not a req/resp was captured.

Type

bool

captured_req

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

Type

falcon.Request

captured_resp

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

Type

falcon.Response

captured_kwargs

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

Type

dict

Functions

falcon.testing.rand_string(min, max)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=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)[source]

Redirect stdout or stderr temporarily.

e.g.:

with redirected(stderr=os.devnull):

falcon.testing.get_encoding_from_headers(headers)[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.