Testing

Reference

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.API` instance.
        self.app = myapp.create()


class TestMyApp(MyTestCase):
    def test_get_message(self):
        doc = {u'message': u'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.API` instance.
    return testing.TestClient(myapp.create())


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

    result = client.simulate_get('/messages/42')
    assert result.json == doc
class falcon.testing.Result(iterable, status, headers)[source]

Encapsulates the result of a simulated WSGI 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

str – HTTP status string given in the response

status_code

int – The code portion of the HTTP status string

headers

CaseInsensitiveDict – 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.

cookies

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

encoding

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

content

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

text

str – Decoded response body of type unicode under Python 2.6 and 2.7, and of type str otherwise. If the content type does not specify an encoding, UTF-8 is assumed.

json

dict – Deserialized JSON body. Raises an error if the response is not JSON.

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

str – The cookie’s name.

value

str – The value of the cookie.

expires

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

path

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

domain

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

max_age

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

secure

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

http_only

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

falcon.testing.simulate_request(app, method='GET', path='/', query_string=None, headers=None, body=None, file_wrapper=None, wsgierrors=None, params=None, params_csv=True, protocol='http')[source]

Simulates a request to a WSGI application.

Performs a request against a WSGI application. Uses wsgiref.validate to ensure the response is valid WSGI.

Keyword Arguments:
 
  • app (callable) – The WSGI application to call
  • method (str) – An HTTP method to use in the request (default: ‘GET’)
  • path (str) – The URL path to request (default: ‘/’)
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.
  • headers (dict) – Additional headers to include in the request (default: None)
  • body (str) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: None). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
  • file_wrapper (callable) – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the environ (default: None). This can be used to test high-performance file transmission when resp.stream is set to a file-like object.
  • wsgierrors (io) – The stream to use as wsgierrors (default sys.stderr)
Returns:

The result of the request

Return type:

Result

falcon.testing.simulate_get(app, path, **kwargs)[source]

Simulates a GET request to a WSGI application.

Equivalent to:

simulate_request(app, 'GET', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.
  • headers (dict) – Additional headers to include in the request (default: None)
  • file_wrapper (callable) – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the environ (default: None). This can be used to test high-performance file transmission when resp.stream is set to a file-like object.
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
falcon.testing.simulate_head(app, path, **kwargs)[source]

Simulates a HEAD request to a WSGI application.

Equivalent to:

simulate_request(app, 'HEAD', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • query_string (str) – A raw query string to include in the request (default: None). If specified, overrides params.
  • headers (dict) – Additional headers to include in the request (default: None)
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
falcon.testing.simulate_post(app, path, **kwargs)[source]

Simulates a POST request to a WSGI application.

Equivalent to:

simulate_request(app, 'POST', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • headers (dict) – Additional headers to include in the request (default: None)
  • body (str) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: None). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
falcon.testing.simulate_put(app, path, **kwargs)[source]

Simulates a PUT request to a WSGI application.

Equivalent to:

simulate_request(app, 'PUT', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • headers (dict) – Additional headers to include in the request (default: None)
  • body (str) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: None). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
falcon.testing.simulate_options(app, path, **kwargs)[source]

Simulates an OPTIONS request to a WSGI application.

Equivalent to:

simulate_request(app, 'OPTIONS', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • headers (dict) – Additional headers to include in the request (default: None)
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
falcon.testing.simulate_patch(app, path, **kwargs)[source]

Simulates a PATCH request to a WSGI application.

Equivalent to:

simulate_request(app, 'PATCH', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • headers (dict) – Additional headers to include in the request (default: None)
  • body (str) – A string to send as the body of the request. Accepts both byte strings and Unicode strings (default: None). If a Unicode string is provided, it will be encoded as UTF-8 in the request.
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
falcon.testing.simulate_delete(app, path, **kwargs)[source]

Simulates a DELETE request to a WSGI application.

Equivalent to:

simulate_request(app, 'DELETE', path, **kwargs)
Parameters:
  • app (callable) – The WSGI application to call
  • path (str) – The URL path to request
Keyword Arguments:
 
  • 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 False to encode list values in query string params by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • headers (dict) – Additional headers to include in the request (default: None)
  • protocol – The protocol to use for the URL scheme (default: ‘http’)
class falcon.testing.TestClient(app)[source]

Simulates requests to a WSGI 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')

The methods all call simulate_request for convenient overriding of requests like this:

class AuthenticatedClient(TestClient):

    def simulate_request(self, *args, **kwargs):
        original_headers = kwargs.get('headers', {})
        kwargs['headers'] = original_headers.update(
            {'Authorization': 'Bearer API_KEY'}
        )
        return super().simulate_request(self, *args, **kwargs)
Parameters:app (callable) – A WSGI application to target when simulating requests
simulate_delete(path='/', **kwargs)[source]

Simulates a DELETE request to a WSGI application.

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

simulate_get(path='/', **kwargs)[source]

Simulates a GET request to a WSGI application.

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

simulate_head(path='/', **kwargs)[source]

Simulates a HEAD request to a WSGI application.

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

simulate_options(path='/', **kwargs)[source]

Simulates an OPTIONS request to a WSGI application.

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

simulate_patch(path='/', **kwargs)[source]

Simulates a PATCH request to a WSGI application.

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

simulate_post(path='/', **kwargs)[source]

Simulates a POST request to a WSGI application.

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

simulate_put(path='/', **kwargs)[source]

Simulates a PUT request to a WSGI application.

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

simulate_request(*args, **kwargs)[source]

Simulates 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.TestCase(methodName='runTest')[source]

Extends unittest to support WSGI 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 calls 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

object – A WSGI application to target when simulating requests (default: falcon.API()). When testing your application, you will need to set this to your own instance of falcon.API. 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.API` instance.
        self.app = myapp.create()


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

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

object – Deprecated alias for app

api_class

callable – Deprecated class variable; will be removed in a future release.

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 (dict) – 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

bool – Whether or not a req/resp was captured.

captured_req

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

captured_resp

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

captured_kwargs

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

class falcon.testing.StartResponseMock[source]

Mock object representing a WSGI start_response callable.

call_count

int – Number of times start_response was called.

status

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

headers

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

headers_dict

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

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
falcon.testing.rand_string(min, max)[source]

Returns 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.create_environ(path='/', query_string='', protocol='HTTP/1.1', scheme='http', host='falconframework.org', port=None, headers=None, app='', body='', method='GET', wsgierrors=None, file_wrapper=None)[source]

Creates 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 ‘’)
  • protocol (str) – The HTTP protocol to simulate (default ‘HTTP/1.1’). If set to ‘HTTP/1.0’, the Host header will not be added to the environment.
  • scheme (str) – URL scheme, either ‘http’ or ‘https’ (default ‘http’)
  • host (str) – Hostname for the request (default ‘falconframework.org’)
  • port (str) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’).
  • headers (dict) – Headers as a dict or an iterable yielding (key, value) tuple‘s
  • app (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 ‘’)
  • body (str) – The body of the request (default ‘’). Accepts both byte strings and Unicode strings. Unicode strings are encoded as UTF-8 in the request.
  • 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.
falcon.testing.redirected(*args, **kwds)[source]

A context manager to temporarily redirect stdout or stderr

e.g.:

with redirected(stderr=os.devnull):
...

Deprecated

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

Extends unittest to support WSGI functional testing.

Warning

This class has been deprecated and will be removed in a future release. Please use TestCase instead.

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 calls without having to spin up an actual web server. Simply inherit from this class in your test case classes instead of unittest.TestCase or testtools.TestCase.

api

falcon.API – An API instance to target when simulating requests. Defaults to falcon.API().

srmock

falcon.testing.StartResponseMock – Provides a callable that simulates the behavior of the start_response argument that the server would normally pass into the WSGI app. The mock object captures various information from the app’s response to the simulated request.

test_route

str – A simple, generated path that a test can use to add a route to the API.

api_class

alias of API

setUp()[source]

Initializer, unittest-style

simulate_request(path, decode=None, **kwargs)[source]

Simulates a request to self.api.

Parameters:

path (str) – The path to request.

Keyword Arguments:
 
  • decode (str) – If this is set to a character encoding, such as ‘utf-8’, simulate_request will assume the response is a single byte string, and will decode it as the result of the request, rather than simply returning the standard WSGI iterable.
  • kwargs (optional) – Same as those defined for falcon.testing.create_environ.
srmock_class

alias of StartResponseMock

tearDown()[source]

Destructor, unittest-style

class falcon.testing.TestResource[source]

Mock resource for functional testing.

Warning

This class is deprecated and will be removed in a future release. Please use SimpleTestResource instead.

This class implements the on_get responder, captures request data, and sets response body and headers.

Child classes may add additional methods and attributes as needed.

sample_status

str – HTTP status to set in the response

sample_body

str – Random body string to set in the response

resp_headers

dict – Sample headers to use in the response

req

falcon.Request – Request object passed into the on_get responder.

resp

falcon.Response – Response object passed into the on_get responder.

kwargs

dict – Keyword arguments passed into the on_get responder, if any.

called

boolTrue if on_get was ever called; False otherwise.

on_get(req, resp, **kwargs)[source]

GET responder.

Captures req, resp, and kwargs. Also sets up a sample response.

Parameters:
  • req – Falcon Request instance.
  • resp – Falcon Response instance.
  • kwargs – URI template name=value pairs, if any, along with any extra args injected by middleware.