testing.rst
This file
Path
docs/testing.rst
354 lines · 12.3 KiB
Last changed by
Merge pull request #2710 from davidism/0.12-docs-themeDavid Lordbefore adoption0ff3f72
History of this fileTake it
1.. _testing:23Testing Flask Applications4==========================56 **Something that is untested is broken.**78The origin of this quote is unknown and while it is not entirely correct, it is also9not far from the truth. Untested applications make it hard to10improve existing code and developers of untested applications tend to11become pretty paranoid. If an application has automated tests, you can12safely make changes and instantly know if anything breaks.1314Flask provides a way to test your application by exposing the Werkzeug15test :class:`~werkzeug.test.Client` and handling the context locals for you.16You can then use that with your favourite testing solution. In this documentation17we will use the :mod:`unittest` package that comes pre-installed with Python.1819The Application20---------------2122First, we need an application to test; we will use the application from23the :ref:`tutorial`. If you don't have that application yet, get the24sources from :gh:`the examples <examples/flaskr>`.2526The Testing Skeleton27--------------------2829In order to test the application, we add a second module30(:file:`flaskr_tests.py`) and create a unittest skeleton there::3132 import os33 import flaskr34 import unittest35 import tempfile3637 class FlaskrTestCase(unittest.TestCase):3839 def setUp(self):40 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()41 flaskr.app.testing = True42 self.app = flaskr.app.test_client()43 with flaskr.app.app_context():44 flaskr.init_db()4546 def tearDown(self):47 os.close(self.db_fd)48 os.unlink(flaskr.app.config['DATABASE'])4950 if __name__ == '__main__':51 unittest.main()5253The code in the :meth:`~unittest.TestCase.setUp` method creates a new test54client and initializes a new database. This function is called before55each individual test function is run. To delete the database after the56test, we close the file and remove it from the filesystem in the57:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the58``TESTING`` config flag is activated. What it does is disable the error59catching during request handling so that you get better error reports when60performing test requests against the application.6162This test client will give us a simple interface to the application. We can63trigger test requests to the application, and the client will also keep track64of cookies for us.6566Because SQLite3 is filesystem-based we can easily use the tempfile module67to create a temporary database and initialize it. The68:func:`~tempfile.mkstemp` function does two things for us: it returns a69low-level file handle and a random file name, the latter we use as70database name. We just have to keep the `db_fd` around so that we can use71the :func:`os.close` function to close the file.7273If we now run the test suite, we should see the following output::7475 $ python flaskr_tests.py7677 ----------------------------------------------------------------------78 Ran 0 tests in 0.000s7980 OK8182Even though it did not run any actual tests, we already know that our flaskr83application is syntactically valid, otherwise the import would have died84with an exception.8586The First Test87--------------8889Now it's time to start testing the functionality of the application.90Let's check that the application shows "No entries here so far" if we91access the root of the application (``/``). To do this, we add a new92test method to our class, like this::9394 class FlaskrTestCase(unittest.TestCase):9596 def setUp(self):97 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()98 flaskr.app.testing = True99 self.app = flaskr.app.test_client()100 with flaskr.app.app_context():101 flaskr.init_db()102103 def tearDown(self):104 os.close(self.db_fd)105 os.unlink(flaskr.app.config['DATABASE'])106107 def test_empty_db(self):108 rv = self.app.get('/')109 assert b'No entries here so far' in rv.data110111Notice that our test functions begin with the word `test`; this allows112:mod:`unittest` to automatically identify the method as a test to run.113114By using `self.app.get` we can send an HTTP ``GET`` request to the application with115the given path. The return value will be a :class:`~flask.Flask.response_class` object.116We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect117the return value (as string) from the application. In this case, we ensure that118``'No entries here so far'`` is part of the output.119120Run it again and you should see one passing test::121122 $ python flaskr_tests.py123 .124 ----------------------------------------------------------------------125 Ran 1 test in 0.034s126127 OK128129Logging In and Out130------------------131132The majority of the functionality of our application is only available for133the administrative user, so we need a way to log our test client in and out134of the application. To do this, we fire some requests to the login and logout135pages with the required form data (username and password). And because the136login and logout pages redirect, we tell the client to `follow_redirects`.137138Add the following two methods to your `FlaskrTestCase` class::139140 def login(self, username, password):141 return self.app.post('/login', data=dict(142 username=username,143 password=password144 ), follow_redirects=True)145146 def logout(self):147 return self.app.get('/logout', follow_redirects=True)148149Now we can easily test that logging in and out works and that it fails with150invalid credentials. Add this new test to the class::151152 def test_login_logout(self):153 rv = self.login('admin', 'default')154 assert b'You were logged in' in rv.data155 rv = self.logout()156 assert b'You were logged out' in rv.data157 rv = self.login('adminx', 'default')158 assert b'Invalid username' in rv.data159 rv = self.login('admin', 'defaultx')160 assert b'Invalid password' in rv.data161162Test Adding Messages163--------------------164165We should also test that adding messages works. Add a new test method166like this::167168 def test_messages(self):169 self.login('admin', 'default')170 rv = self.app.post('/add', data=dict(171 title='<Hello>',172 text='<strong>HTML</strong> allowed here'173 ), follow_redirects=True)174 assert b'No entries here so far' not in rv.data175 assert b'<Hello>' in rv.data176 assert b'<strong>HTML</strong> allowed here' in rv.data177178Here we check that HTML is allowed in the text but not in the title,179which is the intended behavior.180181Running that should now give us three passing tests::182183 $ python flaskr_tests.py184 ...185 ----------------------------------------------------------------------186 Ran 3 tests in 0.332s187188 OK189190For more complex tests with headers and status codes, check out the191`MiniTwit Example`_ from the sources which contains a larger test192suite.193194195.. _MiniTwit Example:196 https://github.com/pallets/flask/tree/0.12.3/examples/minitwit/197198199Other Testing Tricks200--------------------201202Besides using the test client as shown above, there is also the203:meth:`~flask.Flask.test_request_context` method that can be used204in combination with the ``with`` statement to activate a request context205temporarily. With this you can access the :class:`~flask.request`,206:class:`~flask.g` and :class:`~flask.session` objects like in view207functions. Here is a full example that demonstrates this approach::208209 import flask210211 app = flask.Flask(__name__)212213 with app.test_request_context('/?name=Peter'):214 assert flask.request.path == '/'215 assert flask.request.args['name'] == 'Peter'216217All the other objects that are context bound can be used in the same218way.219220If you want to test your application with different configurations and221there does not seem to be a good way to do that, consider switching to222application factories (see :ref:`app-factories`).223224Note however that if you are using a test request context, the225:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`226functions are not called automatically. However227:meth:`~flask.Flask.teardown_request` functions are indeed executed when228the test request context leaves the ``with`` block. If you do want the229:meth:`~flask.Flask.before_request` functions to be called as well, you230need to call :meth:`~flask.Flask.preprocess_request` yourself::231232 app = flask.Flask(__name__)233234 with app.test_request_context('/?name=Peter'):235 app.preprocess_request()236 ...237238This can be necessary to open database connections or something similar239depending on how your application was designed.240241If you want to call the :meth:`~flask.Flask.after_request` functions you242need to call into :meth:`~flask.Flask.process_response` which however243requires that you pass it a response object::244245 app = flask.Flask(__name__)246247 with app.test_request_context('/?name=Peter'):248 resp = Response('...')249 resp = app.process_response(resp)250 ...251252This in general is less useful because at that point you can directly253start using the test client.254255.. _faking-resources:256257Faking Resources and Context258----------------------------259260.. versionadded:: 0.10261262A very common pattern is to store user authorization information and263database connections on the application context or the :attr:`flask.g`264object. The general pattern for this is to put the object on there on265first usage and then to remove it on a teardown. Imagine for instance266this code to get the current user::267268 def get_user():269 user = getattr(g, 'user', None)270 if user is None:271 user = fetch_current_user_from_database()272 g.user = user273 return user274275For a test it would be nice to override this user from the outside without276having to change some code. This can be accomplished with277hooking the :data:`flask.appcontext_pushed` signal::278279 from contextlib import contextmanager280 from flask import appcontext_pushed, g281282 @contextmanager283 def user_set(app, user):284 def handler(sender, **kwargs):285 g.user = user286 with appcontext_pushed.connected_to(handler, app):287 yield288289And then to use it::290291 from flask import json, jsonify292293 @app.route('/users/me')294 def users_me():295 return jsonify(username=g.user.username)296297 with user_set(app, my_user):298 with app.test_client() as c:299 resp = c.get('/users/me')300 data = json.loads(resp.data)301 self.assert_equal(data['username'], my_user.username)302303304Keeping the Context Around305--------------------------306307.. versionadded:: 0.4308309Sometimes it is helpful to trigger a regular request but still keep the310context around for a little longer so that additional introspection can311happen. With Flask 0.4 this is possible by using the312:meth:`~flask.Flask.test_client` with a ``with`` block::313314 app = flask.Flask(__name__)315316 with app.test_client() as c:317 rv = c.get('/?tequila=42')318 assert request.args['tequila'] == '42'319320If you were to use just the :meth:`~flask.Flask.test_client` without321the ``with`` block, the ``assert`` would fail with an error because `request`322is no longer available (because you are trying to use it outside of the actual request).323324325Accessing and Modifying Sessions326--------------------------------327328.. versionadded:: 0.8329330Sometimes it can be very helpful to access or modify the sessions from the331test client. Generally there are two ways for this. If you just want to332ensure that a session has certain keys set to certain values you can just333keep the context around and access :data:`flask.session`::334335 with app.test_client() as c:336 rv = c.get('/')337 assert flask.session['foo'] == 42338339This however does not make it possible to also modify the session or to340access the session before a request was fired. Starting with Flask 0.8 we341provide a so called “session transaction” which simulates the appropriate342calls to open a session in the context of the test client and to modify343it. At the end of the transaction the session is stored. This works344independently of the session backend used::345346 with app.test_client() as c:347 with c.session_transaction() as sess:348 sess['a_key'] = 'a value'349350 # once this is reached the session was stored351352Note that in this case you have to use the ``sess`` object instead of the353:data:`flask.session` proxy. The object however itself will provide the354same interface.