Skip to content
Myr

fixing some wording issues on the testing page

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by matt swanson · committed by Armin Ronacher · parent 04e70bd · Browse files · 1 file+54 added−57 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Armin Ronacher <armin.ronacher@active-4.com>

Diff stats

1 file+54 added−57 removed

  • other:+54 added−57 removed

1 file+54 added−57 removed

modified:docs/testing.rst+54 added-57 removed
3 unmodified lines
4==========================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 to8The 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 change things, and you will instantly know if your change broke13something.12safely make changes and instantly know if anything breaks.1315Flask gives you a couple of ways to test applications. It mainly does16that by exposing the Werkzeug test :class:`~werkzeug.test.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.14Flask provides a way to test your application by exposing the Werkzeug 15test :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---------------2125First 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`_.22First, we need an application to test; we will use the application from 23the :ref:`tutorial`. If you don't have that application yet, get the 24sources from `the examples`_.2526.. _the examples:27 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/2829The Testing Skeleton30--------------------3135In order to test that, we add a second module (36`flaskr_tests.py`) and create a unittest skeleton there::32In order to test the application, we add a second module 33(`flaskr_tests.py`) and create a unittest skeleton there::3435 import os36 import flaskr37 import unittest
13 unmodified lines
51 if __name__ == '__main__':52 unittest.main()5354The 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.55client and initializes a new database. This function is called before56each individual test function is run. To delete the database after the 57test, we close the file and remove it from the filesystem in the58:meth:`~unittest.TestCase.tearDown` method. 5960This test client will give us a simple interface to the application. We can 61trigger test requests to the application, and the client will also keep track 62of cookies for us.6364Because SQLite3 is filesystem-based we can easily use the tempfile module65to create a temporary database and initialize it. The66:func:`~tempfile.mkstemp` function does two things for us: it returns a67low-level file handle and a random file name, the latter we use as68database name. We just have to keep the `db_fd` around so that we can use69the :func:`os.close` function to close the file.7073If we now run that test suite, we should see the following output::71If we now run the test suite, we should see the following output::7273 $ python flaskr_tests.py7475 ----------------------------------------------------------------------76 Ran 0 tests in 0.000s7778 OK7982Even though it did not run any tests, we already know that our flaskr80Even though it did not run any actual tests, we already know that our flaskr81application is syntactically valid, otherwise the import would have died82with an exception.8384The First Test85--------------8689Now 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::87Now it's time to start testing the functionality of the application. 88Let's check that the application shows "No entries here so far" if we 89access the root of the application (``/``). To do this, we add a new90test method to our class, like this::9192 class FlaskrTestCase(unittest.TestCase):9394 def setUp(self):
8 unmodified lines
103 def test_empty_db(self):104 rv = self.app.get('/')105 assert 'No entries here so far' in rv.data106109Test 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.wrappers.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.107Notice that our test functions begin with the word `test`; this allows 108:mod:`unittest` to automatically identify the method as a test to run. 109110By using `self.app.get` we can send an HTTP `GET` request to the application with 111the given path. The return value will be a :class:`~flask.Flask.response_class` object. 112We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect113the return value (as string) from the application. In this case, we ensure that 114``'No entries here so far'`` is part of the output.115116Run it again and you should see one passing test::117118 $ python flaskr_tests.py119 .
1 unmodified line
121 Ran 1 test in 0.034s122123 OK124126Of course you can submit forms with the test client as well, which we will127use now to log our user in.128125Logging In and Out126------------------127128The 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`.129the administrative user, so we need a way to log our test client in and out130of the application. To do this, we fire some requests to the login and logout 131pages with the required form data (username and password). And because the 132login and logout pages redirect, we tell the client to `follow_redirects`.133134Add the following two methods to your `FlaskrTestCase` class::135136 def login(self, username, password):
4 unmodified lines
141142 def logout(self):143 return self.app.get('/logout', follow_redirects=True)144150Now we can easily test if logging in and out works and that it fails with145Now we can easily test that logging in and out works and that it fails with146invalid credentials. Add this new test to the class::147148 def test_login_logout(self):149 rv = self.login('admin', 'default')
7 unmodified lines
157158Test Adding Messages159--------------------160166Now we can also test that adding messages works. Add a new test method161We should also test that adding messages works. Add a new test method162like this::163164 def test_messages(self):165 self.login('admin', 'default')
17 unmodified lines
183184 OK185186For more complex tests with headers and status codes, check out the192`MiniTwit Example`_ from the sources. That one contains a larger test187`MiniTwit Example`_ from the sources which contains a larger test188suite.189190191.. _MiniTwit Example:
2 unmodified lines
194195Other Testing Tricks196--------------------197203Besides 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`,198Besides using the test client as shown above, there is also the199:meth:`~flask.Flask.test_request_context` method that can be used200in combination with the `with` statement to activate a request context201temporarily. With this you can access the :class:`~flask.request`,202:class:`~flask.g` and :class:`~flask.session` objects like in view208functions. Here's a full example that showcases this::203functions. Here is a full example that demonstrates this approach::204205 app = flask.Flask(__name__)206207 with app.test_request_context('/?name=Peter'):208 assert flask.request.path == '/'209 assert flask.request.args['name'] == 'Peter'210216All the other objects that are context bound can be used the same.211All the other objects that are context bound can be used in the same212way.213214If you want to test your application with different configurations and215there does not seem to be a good way to do that, consider switching to216application factories (see :ref:`app-factories`).
3 unmodified lines
220--------------------------221222.. versionadded:: 0.4223228Sometimes it can be helpful to trigger a regular request but keep the224Sometimes it is helpful to trigger a regular request but still keep the225context around for a little longer so that additional introspection can226happen. With Flask 0.4 this is possible by using the227:meth:`~flask.Flask.test_client` with a `with` block::228
2 unmodified lines
231 with app.test_client() as c:232 rv = c.get('/?tequila=42')233 assert request.args['tequila'] == '42'234239If you would just be using the :meth:`~flask.Flask.test_client` without235If you were to use just the :meth:`~flask.Flask.test_client` without236the `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 and237is no longer available (because you are trying to use it outside of the actual request).238However, keep in mind that any :meth:`~flask.Flask.after_request` functions239are already called at this point so your database connection and240everything involved is probably already closed down.241