Using WebTest

WebTest (http://webtest.readthedocs.io) has been around for a long time. It was written by Ian Bicking back in the days of the Paste project, and is based on the WebOb (http://docs.webob.org) project, which provides a Request and Response class similar (but not compatible) to Flask's.

WebTest wraps call to a WSGI application like FlaskTest does, and lets you interact with it. WebTest is somewhat similar to FlaskTest, with a few extra helpers when dealing with JSON, and a neat feature to call non-WSGI applications.

To use it with Flask, you can install the flask-webtest package (https://flask-webtest.readthedocs.io/), and you will get a similar integration level as Flask's native tool:

    import unittest 
from flask_basic import app as tested_app
from flask_webtest import TestApp

class TestMyApp(unittest.TestCase):
def test_help(self):
# creating a client to interact with the app
app = TestApp(tested_app)

# calling /api/ endpoint
hello = app.get('/api')

# asserting the body
self.assertEqual(hello.json['Hello'], 'World!')

if __name__ == '__main__':
unittest.main()

We've said earlier that integration tests were similar to functional tests except that they called a real server instead of instantiating a local WSGI app.

WebTest leverages the WSGIProxy2 library (https://pypi.python.org/pypi/WSGIProxy2), which converts calls that are made to the Python application to HTTP requests made to a real HTTP application.

The previous script can be slightly modified to become an integration test if you set an HTTP_SERVER variable in the environ function, as follows:

    import unittest 
import os

class TestMyApp(unittest.TestCase):

def setUp(self):
# if HTPP_SERVER is set, we use it as an endpoint
http_server = os.environ.get('HTTP_SERVER')
if http_server is not None:
from webtest import TestApp
self.app = TestApp(http_server)
else:
# fallbacks to the wsgi app
from flask_basic import app
from flask_webtest import TestApp
self.app = TestApp(app)

def test_help(self):
# calling /api/ endpoint
hello = self.app.get('/api')

# asserting the body
self.assertEqual(hello.json['Hello'], 'World!')

if __name__ == '__main__':
unittest.main()

When this last test is executed with HTTP_SERVER=http://myservice/, it performs all its calls to that service.

That trick is pretty handy to turn some of your functional tests into integration tests without having to write two distinct tests. As we said earlier, it has some limitations, since you can't interact locally with the application instance. But it's extremely useful to validate that a deployed service works as expected directly from your test suite, just by flipping an option.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset