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
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 type str
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: | |
---|---|
| |
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
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)
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: | |
---|---|
|
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 |
---|
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 |
---|
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, remote_addr=None)
[source]
Creates a mock PEP-3333 environ dict
for simulating WSGI requests.
Keyword Arguments: | |
---|---|
|
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.:
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 a close()
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 |
© 2019 by Falcon contributors
Licensed under the Apache License, Version 2.0.
https://falcon.readthedocs.io/en/2.0.0/api/testing.html