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: |
|
|---|
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.
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 body is empty or 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, json=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: | |
|---|---|
| |
| 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: | |
|---|---|
| Keyword Arguments: | |
| |
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: | |
|---|---|
| Keyword Arguments: | |
| |
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: | |
|---|---|
| Keyword Arguments: | |
| |
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: | |
|---|---|
| Keyword Arguments: | |
| |
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: | |
|---|---|
| Keyword Arguments: | |
| |
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: | |
|---|---|
| Keyword Arguments: | |
| |
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: | |
|---|---|
| Keyword Arguments: | |
| |
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 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: | |
|---|---|
| |
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:
falcon.testing.rand_string(min, max) [source]
Returns a randomly-generated string, of a random length.
| Parameters: |
|---|
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: | |
|---|---|
| |
falcon.testing.redirected(*args, **kwds) [source]
A context manager to temporarily redirect stdout or stderr
e.g.:
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: | |
| |
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 bool – True 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: |
|
|---|
© 2012–2017 by Rackspace Hosting, Inc. and other contributors
Licensed under the Apache License, Version 2.0.
https://falcon.readthedocs.io/en/1.4.1/api/testing.html