Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

355 lines · 12.3 KiB

Last changed by

Merge pull request #1491 from nvie/patch-1Markus Unterwaditzerbefore adoption3e07b9c

History of this file

Take 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 `the examples`_.2526.. _the examples:27   https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/2829The Testing Skeleton30--------------------3132In order to test the application, we add a second module33(:file:`flaskr_tests.py`) and create a unittest skeleton there::3435    import os36    import flaskr37    import unittest38    import tempfile3940    class FlaskrTestCase(unittest.TestCase):4142        def setUp(self):43            self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44            flaskr.app.config['TESTING'] = True45            self.app = flaskr.app.test_client()46            with flaskr.app.app_context():47                flaskr.init_db()4849        def tearDown(self):50            os.close(self.db_fd)51            os.unlink(flaskr.app.config['DATABASE'])5253    if __name__ == '__main__':54        unittest.main()5556The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57client and initializes a new database.  This function is called before58each individual test function is run.  To delete the database after the59test, we close the file and remove it from the filesystem in the60:meth:`~unittest.TestCase.tearDown` method.  Additionally during setup the61``TESTING`` config flag is activated.  What it does is disable the error62catching during request handling so that you get better error reports when63performing test requests against the application.6465This test client will give us a simple interface to the application.  We can66trigger test requests to the application, and the client will also keep track67of cookies for us.6869Because SQLite3 is filesystem-based we can easily use the tempfile module70to create a temporary database and initialize it.  The71:func:`~tempfile.mkstemp` function does two things for us: it returns a72low-level file handle and a random file name, the latter we use as73database name.  We just have to keep the `db_fd` around so that we can use74the :func:`os.close` function to close the file.7576If we now run the test suite, we should see the following output::7778    $ python flaskr_tests.py7980    ----------------------------------------------------------------------81    Ran 0 tests in 0.000s8283    OK8485Even though it did not run any actual tests, we already know that our flaskr86application is syntactically valid, otherwise the import would have died87with an exception.8889The First Test90--------------9192Now it's time to start testing the functionality of the application.93Let's check that the application shows "No entries here so far" if we94access the root of the application (``/``). To do this, we add a new95test method to our class, like this::9697    class FlaskrTestCase(unittest.TestCase):9899        def setUp(self):100            self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101            self.app = flaskr.app.test_client()102            flaskr.init_db()103104        def tearDown(self):105            os.close(self.db_fd)106            os.unlink(flaskr.app.config['DATABASE'])107108        def test_empty_db(self):109            rv = self.app.get('/')110            assert b'No entries here so far' in rv.data111112Notice that our test functions begin with the word `test`; this allows113:mod:`unittest` to automatically identify the method as a test to run.114115By using `self.app.get` we can send an HTTP ``GET`` request to the application with116the given path.  The return value will be a :class:`~flask.Flask.response_class` object.117We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect118the return value (as string) from the application.  In this case, we ensure that119``'No entries here so far'`` is part of the output.120121Run it again and you should see one passing test::122123    $ python flaskr_tests.py124    .125    ----------------------------------------------------------------------126    Ran 1 test in 0.034s127128    OK129130Logging In and Out131------------------132133The majority of the functionality of our application is only available for134the administrative user, so we need a way to log our test client in and out135of the application.  To do this, we fire some requests to the login and logout136pages with the required form data (username and password).  And because the137login and logout pages redirect, we tell the client to `follow_redirects`.138139Add the following two methods to your `FlaskrTestCase` class::140141   def login(self, username, password):142       return self.app.post('/login', data=dict(143           username=username,144           password=password145       ), follow_redirects=True)146147   def logout(self):148       return self.app.get('/logout', follow_redirects=True)149150Now we can easily test that logging in and out works and that it fails with151invalid credentials.  Add this new test to the class::152153   def test_login_logout(self):154       rv = self.login('admin', 'default')155       assert 'You were logged in' in rv.data156       rv = self.logout()157       assert 'You were logged out' in rv.data158       rv = self.login('adminx', 'default')159       assert 'Invalid username' in rv.data160       rv = self.login('admin', 'defaultx')161       assert 'Invalid password' in rv.data162163Test Adding Messages164--------------------165166We should also test that adding messages works.  Add a new test method167like this::168169    def test_messages(self):170        self.login('admin', 'default')171        rv = self.app.post('/add', data=dict(172            title='<Hello>',173            text='<strong>HTML</strong> allowed here'174        ), follow_redirects=True)175        assert 'No entries here so far' not in rv.data176        assert '&lt;Hello&gt;' in rv.data177        assert '<strong>HTML</strong> allowed here' in rv.data178179Here we check that HTML is allowed in the text but not in the title,180which is the intended behavior.181182Running that should now give us three passing tests::183184    $ python flaskr_tests.py185    ...186    ----------------------------------------------------------------------187    Ran 3 tests in 0.332s188189    OK190191For more complex tests with headers and status codes, check out the192`MiniTwit Example`_ from the sources which contains a larger test193suite.194195196.. _MiniTwit Example:197   https://github.com/mitsuhiko/flask/tree/master/examples/minitwit/198199200Other Testing Tricks201--------------------202203Besides using the test client as shown above, there is also the204:meth:`~flask.Flask.test_request_context` method that can be used205in combination with the ``with`` statement to activate a request context206temporarily.  With this you can access the :class:`~flask.request`,207:class:`~flask.g` and :class:`~flask.session` objects like in view208functions.  Here is a full example that demonstrates this approach::209210    import flask211    212    app = flask.Flask(__name__)213214    with app.test_request_context('/?name=Peter'):215        assert flask.request.path == '/'216        assert flask.request.args['name'] == 'Peter'217218All the other objects that are context bound can be used in the same219way.220221If you want to test your application with different configurations and222there does not seem to be a good way to do that, consider switching to223application factories (see :ref:`app-factories`).224225Note however that if you are using a test request context, the226:meth:`~flask.Flask.before_request` functions are not automatically called227same for :meth:`~flask.Flask.after_request` functions.  However228:meth:`~flask.Flask.teardown_request` functions are indeed executed when229the test request context leaves the ``with`` block.  If you do want the230:meth:`~flask.Flask.before_request` functions to be called as well, you231need to call :meth:`~flask.Flask.preprocess_request` yourself::232233    app = flask.Flask(__name__)234235    with app.test_request_context('/?name=Peter'):236        app.preprocess_request()237        ...238239This can be necessary to open database connections or something similar240depending on how your application was designed.241242If you want to call the :meth:`~flask.Flask.after_request` functions you243need to call into :meth:`~flask.Flask.process_response` which however244requires that you pass it a response object::245246    app = flask.Flask(__name__)247248    with app.test_request_context('/?name=Peter'):249        resp = Response('...')250        resp = app.process_response(resp)251        ...252253This in general is less useful because at that point you can directly254start using the test client.255256.. _faking-resources:257258Faking Resources and Context259----------------------------260261.. versionadded:: 0.10262263A very common pattern is to store user authorization information and264database connections on the application context or the :attr:`flask.g`265object.  The general pattern for this is to put the object on there on266first usage and then to remove it on a teardown.  Imagine for instance267this code to get the current user::268269    def get_user():270        user = getattr(g, 'user', None)271        if user is None:272            user = fetch_current_user_from_database()273            g.user = user274        return user275276For a test it would be nice to override this user from the outside without277having to change some code.  This can be accomplished with278hooking the :data:`flask.appcontext_pushed` signal::279280    from contextlib import contextmanager281    from flask import appcontext_pushed, g282283    @contextmanager284    def user_set(app, user):285        def handler(sender, **kwargs):286            g.user = user287        with appcontext_pushed.connected_to(handler, app):288            yield289290And then to use it::291292    from flask import json, jsonify293294    @app.route('/users/me')295    def users_me():296        return jsonify(username=g.user.username)297298    with user_set(app, my_user):299        with app.test_client() as c:300            resp = c.get('/users/me')301            data = json.loads(resp.data)302            self.assert_equal(data['username'], my_user.username)303304305Keeping the Context Around306--------------------------307308.. versionadded:: 0.4309310Sometimes it is helpful to trigger a regular request but still keep the311context around for a little longer so that additional introspection can312happen.  With Flask 0.4 this is possible by using the313:meth:`~flask.Flask.test_client` with a ``with`` block::314315    app = flask.Flask(__name__)316317    with app.test_client() as c:318        rv = c.get('/?tequila=42')319        assert request.args['tequila'] == '42'320321If you were to use just the :meth:`~flask.Flask.test_client` without322the ``with`` block, the ``assert`` would fail with an error because `request`323is no longer available (because you are trying to use it outside of the actual request).324325326Accessing and Modifying Sessions327--------------------------------328329.. versionadded:: 0.8330331Sometimes it can be very helpful to access or modify the sessions from the332test client.  Generally there are two ways for this.  If you just want to333ensure that a session has certain keys set to certain values you can just334keep the context around and access :data:`flask.session`::335336    with app.test_client() as c:337        rv = c.get('/')338        assert flask.session['foo'] == 42339340This however does not make it possible to also modify the session or to341access the session before a request was fired.  Starting with Flask 0.8 we342provide a so called “session transaction” which simulates the appropriate343calls to open a session in the context of the test client and to modify344it.  At the end of the transaction the session is stored.  This works345independently of the session backend used::346347    with app.test_client() as c:348        with c.session_transaction() as sess:349            sess['a_key'] = 'a value'350351        # once this is reached the session was stored352353Note that in this case you have to use the ``sess`` object instead of the354:data:`flask.session` proxy.  The object however itself will provide the355same interface.