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
¶ 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
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
unicode
under Python 2.7, and of typestr
otherwise. 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.
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
-
falcon.testing.
simulate_request
(app, method='GET', path='/', query_string=None, headers=None, body=None, json=None, file_wrapper=None, wsgierrors=None, params=None, params_csv=True, protocol='http', host='falconframework.org', remote_addr=None, extras=None)[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: ‘/’).
Note
The path may contain a query string. However, neither query_string nor params may be specified in this case.
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 astr
, or a list of such values. If alist
, 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 toTrue
.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.json (JSON serializable) – A JSON document to serialize as the body of the request (default:
None
). If specified, overrides body and the Content-Type header in headers.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.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’)
wsgierrors (io) – The stream to use as wsgierrors (default
sys.stderr
)extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
- Returns
The result of the request
- Return type
-
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.
Note
The path may contain a query string. However, neither query_string nor params may be specified in this case.
- 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 astr
, or a list of such values. If alist
, 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 toTrue
.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’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
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.
Note
The path may contain a query string. However, neither query_string nor params may be specified in this case.
- 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 astr
, or a list of such values. If alist
, 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 toTrue
.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’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
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 astr
, or a list of such values. If alist
, 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 toTrue
.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.json (JSON serializable) – A JSON document to serialize as the body of the request (default:
None
). If specified, overrides body and the Content-Type header in headers.protocol – The protocol to use for the URL scheme (default: ‘http’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
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 astr
, or a list of such values. If alist
, 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 toTrue
.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.json (JSON serializable) – A JSON document to serialize as the body of the request (default:
None
). If specified, overrides body and the Content-Type header in headers.protocol – The protocol to use for the URL scheme (default: ‘http’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
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 astr
, or a list of such values. If alist
, 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 toTrue
.headers (dict) – Additional headers to include in the request (default:
None
)protocol – The protocol to use for the URL scheme (default: ‘http’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
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 astr
, or a list of such values. If alist
, 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 toTrue
.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.json (JSON serializable) – A JSON document to serialize as the body of the request (default:
None
). If specified, overrides body and the Content-Type header in headers.protocol – The protocol to use for the URL scheme (default: ‘http’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
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 astr
, or a list of such values. If alist
, 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 toTrue
.headers (dict) – Additional headers to include in the request (default:
None
)protocol – The protocol to use for the URL scheme (default: ‘http’)
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’)
extras (dict) – Additional CGI variables to add to the WSGI
environ
dictionary for the request (default:None
)
-
class
falcon.testing.
TestClient
(app, headers=None)[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')
Note
The methods all call
self.simulate_request()
for convenient overriding of request preparation by child classes.- Parameters
app (callable) – A WSGI 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.
-
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 againstself.app
. Equivalent to:falcon.testing.simulate_request(self.app, *args, **kwargs)
-
class
falcon.testing.
TestCase
(*args, **kwargs)[source]¶ Extends
unittest
to support WSGI functional testing.Note
If available, uses
testtools
in lieu ofunittest
.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
ortesttools.TestCase
.-
app
¶ 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 offalcon.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)
- Type
object
-
-
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()
andon_post()
responders are implemented; when overriding these, or adding additional responders in child classes, they can be decorated with thefalcon.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 thefalcon.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
-
captured_resp
¶ The last Response object passed into any one of the responder methods.
- Type
-
captured_kwargs
¶ The last dictionary of kwargs, beyond
req
andresp
, that were passed into any one of the responder methods.- Type
dict
-
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 alist
.- Type
dict
-
-
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, remote_addr=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
’sapp (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.
remote_addr (str) – Remote address for the request (default ‘127.0.0.1’)
-
falcon.testing.
redirected
(stdout=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stderr=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)[source]¶ A context manager to temporarily redirect stdout or stderr
e.g.:
- with redirected(stderr=os.devnull):
…
-
falcon.testing.
closed_wsgi_iterable
(iterable)[source]¶ Wraps 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 aclose()
method, it is called upon exception or exausting 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