Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

244 lines · 8.4 KiB

Last changed by

Fixed a refacotring error in the docs. This fixes #100Armin Ronacherbefore adoptiond17b6d7

History of this file

Take it

1.. _testing:23Testing Flask Applications4==========================56   **Something that is untested is broken.**78Not sure where that is coming from, and it's not entirely correct, but9also not that 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 change things, and you will instantly know if your change broke13something.1415Flask gives you a couple of ways to test applications.  It mainly does16that by exposing the Werkzeug test :class:`~werkzeug.Client` class to your17code and handling the context locals for you.  You can then use that with18your favourite testing solution.  In this documentation we will use the19:mod:`unittest` package that comes preinstalled with each Python20installation.2122The Application23---------------2425First we need an application to test for functionality.  For the testing26we will use the application from the :ref:`tutorial`.  If you don't have27that application yet, get the sources from `the examples`_.2829.. _the examples:30   http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/3132The Testing Skeleton33--------------------3435In order to test that, we add a second module (36`flaskr_tests.py`) and create a unittest skeleton there::3738    import os39    import flaskr40    import unittest41    import tempfile4243    class FlaskrTestCase(unittest.TestCase):4445        def setUp(self):46            self.db_fd, self.app.config['DATABASE'] = tempfile.mkstemp()47            self.app = flaskr.app.test_client()48            flaskr.init_db()4950        def tearDown(self):51            os.close(self.db_fd)52            os.unlink(flaskr.app.config['DATABASE'])5354    if __name__ == '__main__':55        unittest.main()5657The code in the :meth:`~unittest.TestCase.setUp` method creates a new test58client and initializes a new database.  That function is called before59each individual test function.  To delete the database after the test, we60close the file and remove it from the filesystem in the61:meth:`~unittest.TestCase.tearDown` method.  What the test client does is62give us a simple interface to the application.  We can trigger test63requests to the application, and the client will also keep track of cookies64for 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 that 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 tests, we already know that our flaskr83application is syntactically valid, otherwise the import would have died84with an exception.8586The First Test87--------------8889Now we can add the first test.  Let's check that the application shows90"No entries here so far" if we access the root of the application (``/``).91For that we modify our created test case class so that it looks like92this::9394    class FlaskrTestCase(unittest.TestCase):9596        def setUp(self):97            self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()98            self.app = flaskr.app.test_client()99            flaskr.init_db()100101        def tearDown(self):102            os.close(self.db_fd)103            os.unlink(flaskr.DATABASE)104105        def test_empty_db(self):106            rv = self.app.get('/')107            assert 'No entries here so far' in rv.data108109Test functions begin with the word `test`.  Every function named like that110will be picked up automatically.  By using `self.app.get` we can send an111HTTP `GET` request to the application with the given path.  The return112value will be a :class:`~flask.Flask.response_class` object.  We can now113use the :attr:`~werkzeug.BaseResponse.data` attribute to inspect the114return value (as string) from the application.  In this case, we ensure115that ``'No entries here so far'`` is part of the output.116117Run it again and you should see one passing test::118119    $ python flaskr_tests.py120    .121    ----------------------------------------------------------------------122    Ran 1 test in 0.034s123124    OK125126Of course you can submit forms with the test client as well, which we will127use now to log our user in.128129Logging 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 to the134application and out of it again.  For that we fire some requests to the135login and logout pages with the required form data (username and136password).  Because the login and logout pages redirect, we tell the137client 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 if 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--------------------165166Now we can 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.  That one contains a larger test193suite.194195196.. _MiniTwit Example:197   http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/198199200Other Testing Tricks201--------------------202203Besides using the test client we used above, there is also the204:meth:`~flask.Flask.test_request_context` method that in combination with205the `with` statement can be used to activate a request context206temporarily.  With that you can access the :class:`~flask.request`,207:class:`~flask.g` and :class:`~flask.session` objects like in view208functions.  Here's a full example that showcases this::209210    app = flask.Flask(__name__)211212    with app.test_request_context('/?name=Peter'):213        assert flask.request.path == '/'214        assert flask.request.args['name'] == 'Peter'215216All the other objects that are context bound can be used the same.217218If you want to test your application with different configurations and219there does not seem to be a good way to do that, consider switching to220application factories (see :ref:`app-factories`).221222223Keeping the Context Around224--------------------------225226.. versionadded:: 0.4227228Sometimes it can be helpful to trigger a regular request but keep the229context around for a little longer so that additional introspection can230happen.  With Flask 0.4 this is possible by using the231:meth:`~flask.Flask.test_client` with a `with` block::232233    app = flask.Flask(__name__)234235    with app.test_client() as c:236        rv = c.get('/?tequila=42')237        assert request.args['tequila'] == '42'238239If you would just be using the :meth:`~flask.Flask.test_client` without240the `with` block, the `assert` would fail with an error because `request`241is no longer available (because used outside of an actual request).242Keep in mind however that :meth:`~flask.Flask.after_request` functions243are already called at that point so your database connection and244everything involved is probably already closed down.