Testing

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. Simply inherit from this class in your test case classes instead of unittest.TestCase or testtools.TestCase.

api_class

class – An API class to use when instantiating the api instance (default: falcon.API)

api

object – An API instance to target when simulating requests (default: self.api_class())

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

Simulates a DELETE request to a WSGI application.

Equivalent to simulate_request('DELETE', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • headers (dict) – Additional headers to include in the request (default: None)
simulate_get(path='/', **kwargs)[source]

Simulates a GET request to a WSGI application.

Equivalent to simulate_request('GET', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • headers (dict) – Additional headers to include in the request (default: None)
simulate_head(path='/', **kwargs)[source]

Simulates a HEAD request to a WSGI application.

Equivalent to simulate_request('HEAD', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • headers (dict) – Additional headers to include in the request (default: None)
simulate_options(path='/', **kwargs)[source]

Simulates an OPTIONS request to a WSGI application.

Equivalent to simulate_request('OPTIONS', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • headers (dict) – Additional headers to include in the request (default: None)
simulate_patch(path='/', **kwargs)[source]

Simulates a PATCH request to a WSGI application.

Equivalent to simulate_request('PATCH', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • 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.
simulate_post(path='/', **kwargs)[source]

Simulates a POST request to a WSGI application.

Equivalent to simulate_request('POST', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • 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.
simulate_put(path='/', **kwargs)[source]

Simulates a PUT request to a WSGI application.

Equivalent to simulate_request('PUT', ...)

Parameters:

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

Keyword Arguments:
 
  • query_string (str) – A raw query string to include in the request (default: None)
  • 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.
simulate_request(method='GET', path='/', query_string=None, headers=None, body=None, file_wrapper=None)[source]

Simulates a request to a WSGI application.

Performs a WSGI request directly against self.api.

Keyword Arguments:
 
  • method (str) – The HTTP method to use in the request (default: ‘GET’)
  • path (str) – The URL path to request (default: ‘/’)
  • query_string (str) – A raw query string to include in the request (default: None)
  • 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).
Returns:

The result of the request

Return type:

Result

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

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. Raises an error if the response encoding can not be determined.

json

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

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 the on_get() responder is implemented; when 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
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.

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.
  • decode (str, optional) – 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.