testing.rst
This file
Path
docs/testing.rst
244 lines · 8.4 KiB
Last changed by
Added support for deferred context cleanup. test_client users can now access the context locals after the actual request if the client is used with a with-block. This fixes #59.Armin Ronacherbefore adoptionbc00fd1
History of this fileTake it
The walk stopped after 200 commits: lines older than 26f86b1 point at it.
Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 1–10why, one step back1.. _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 toProofreading the documentationChris Edgemonbefore adoptiona7ff9db
lines 11–12why, one step back11become pretty paranoid. If an application however has automated tests, you12can safely change things and you will instantly know if your change brokeRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 13–17why, one step back13something.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 withProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 18why, one step back18your favourite testing solution. In this documentation we will use theRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 19–37why, one step back19: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::37Added missing os import.Armin Ronacherbefore adoptionf6b9efc
line 38why, one step back38 import osRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
line 39why, one step back39 import flaskrAdded missing os import.Armin Ronacherbefore adoptionf6b9efc
line 40why, one step back40 import unittestRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 41–45why, one step back41 import tempfile4243 class FlaskrTestCase(unittest.TestCase):4445 def setUp(self):Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
line 46why, one step back46 self.db_fd, flaskr.DATABASE = tempfile.mkstemp()Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 47–49why, one step back47 self.app = flaskr.app.test_client()48 flaskr.init_db()49Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 50–53why, one step back50 def tearDown(self):51 os.close(self.db_fd)52 os.unlink(flaskr.DATABASE)53Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 54–56why, one step back54 if __name__ == '__main__':55 unittest.main()56Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 57–64why, one step back57The 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.Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
line 65why, one step back65Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 66why, one step back66Because SQLite3 is filesystem-based we can easily use the tempfile moduleMake the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 67–70why, one step back67to 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 useFix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2
line 71why, one step back71the :func:`os.close` function to close the file.Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
line 72why, one step back72More typo fixes.Georg Brandlbefore adoptiona224fec
line 73why, one step back73If we now run that test suite, we should see the following output::Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 74–78why, one step back7475 $ python flaskr_tests.py7677 ----------------------------------------------------------------------78 Ran 0 tests in 0.000sFix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2
line 79why, one step back79Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 80–96why, one step back80 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):Ported examples over to new config. documented upgradingArmin Ronacherbefore adoptiondfecc86
line 97why, one step back97 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 98–99why, one step back98 self.app = flaskr.app.test_client()99 flaskr.init_db()Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 100–103why, one step back100101 def tearDown(self):102 os.close(self.db_fd)103 os.unlink(flaskr.DATABASE)Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 104–125why, one step back104105 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 OK125Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 126why, one step back126Of course you can submit forms with the test client as well, which we willRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 127–132why, one step back127use now to log our user in.128129Logging In and Out130------------------131132The majority of the functionality of our application is only available forProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 133why, one step back133the administration user. So we need a way to log our test client in to theRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 134–138why, one step back134application 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`.138Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 139why, one step back139Add the following two methods to your `FlaskrTestCase` class::Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 140–150why, one step back140141 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 withProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 151why, one step back151invalid credentials. Add this new test to the class::Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 152–153why, one step back152153 def test_login_logout(self):Ported examples over to new config. documented upgradingArmin Ronacherbefore adoptiondfecc86
line 154why, one step back154 rv = self.login('admin', 'default')Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 155–157why, one step back155 assert 'You were logged in' in rv.data156 rv = self.logout()157 assert 'You were logged out' in rv.dataPorted examples over to new config. documented upgradingArmin Ronacherbefore adoptiondfecc86
line 158why, one step back158 rv = self.login('adminx', 'default')Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
line 159why, one step back159 assert 'Invalid username' in rv.dataPorted examples over to new config. documented upgradingArmin Ronacherbefore adoptiondfecc86
line 160why, one step back160 rv = self.login('admin', 'defaultx')Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 161–169why, one step back161 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):Ported examples over to new config. documented upgradingArmin Ronacherbefore adoptiondfecc86
line 170why, one step back170 self.login('admin', 'default')Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 171–178why, one step back171 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 '<Hello>' in rv.data177 assert '<strong>HTML</strong> allowed here' in rv.data178Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 179why, one step back179Here we check that HTML is allowed in the text but not in the title,Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 180–183why, one step back180which is the intended behavior.181182Running that should now give us three passing tests::183More typo fixes.Georg Brandlbefore adoptiona224fec
line 184why, one step back184 $ python flaskr_tests.pyRestructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 185–187why, one step back185 ...186 ----------------------------------------------------------------------187 Ran 3 tests in 0.332sMore typo fixes.Georg Brandlbefore adoptiona224fec
line 188why, one step back188Restructured documentation a bit.Armin Ronacherbefore adoption26f86b1
lines 189–197why, one step back189 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/Fixed merging confictArmin Ronacherbefore adoptioneeb0e94
lines 198–216why, one step back198199200Other 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 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.Ported examples over to new config. documented upgradingArmin Ronacherbefore adoptiondfecc86
lines 217–220why, one step back217218If 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`).Added support for deferred context cleanup. test_client users can now access the context locals after the actual request if the client is used with a with-block. This fixes #59.Armin Ronacherbefore adoptionbc00fd1
lines 221–244why, one step back221222223Keeping 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('/?foo=42')237 assert request.args['foo'] == '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.