testing.rst
This file
Path
docs/testing.rst
186 lines · 6.4 KiB
Last changed by
Removed useless codeArmin Ronacherbefore adoptionbf52a17
History of this fileTake 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 however has automated tests you12can savely 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 us 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 unittest39 import flaskr40 import tempfile4142 class FlaskrTestCase(unittest.TestCase):4344 def setUp(self):45 self.db = tempfile.NamedTemporaryFile()46 self.app = flaskr.app.test_client()47 flaskr.DATABASE = self.db.name48 flaskr.init_db()4950 if __name__ == '__main__':51 unittest.main()5253The code in the `setUp` function creates a new test client and initialize54a new database. That function is called before each individual test function.55What the test client does for us is giving us a simple interface to the56application. We can trigger test requests to the application and the57client will also keep track of cookies for us.5859Because SQLite3 is filesystem based we can easily use the tempfile module60to create a temporary database and initialize it. Just make sure that you61keep a reference to the :class:`~tempfile.NamedTemporaryFile` around (we62store it as `self.db` because of that) so that the garbage collector does63not remove that object and with it the database from the filesystem.6465If we now run that testsuite, we should see the following output::6667 $ python flaskr_tests.py6869 ----------------------------------------------------------------------70 Ran 0 tests in 0.000s71 72 OK7374Even though it did not run any tests, we already know that our flaskr75application is syntactically valid, otherwise the import would have died76with an exception.7778The First Test79--------------8081Now we can add the first test. Let's check that the application shows82"No entries here so far" if we access the root of the application (``/``).83For that we modify our created test case class so that it looks like84this::8586 class FlaskrTestCase(unittest.TestCase):8788 def setUp(self):89 self.db = tempfile.NamedTemporaryFile()90 self.app = flaskr.app.test_client()91 flaskr.DATABASE = self.db.name92 flaskr.init_db()9394 def test_empty_db(self):95 rv = self.app.get('/')96 assert 'No entries here so far' in rv.data9798Test functions begin with the word `test`. Every function named like that99will be picked up automatically. By using `self.app.get` we can send an100HTTP `GET` request to the application with the given path. The return101value will be a :class:`~flask.Flask.response_class` object. We can now102use the :attr:`~werkzeug.BaseResponse.data` attribute to inspect the103return value (as string) from the application. In this case, we ensure104that ``'No entries here so far'`` is part of the output.105106Run it again and you should see one passing test::107108 $ python flaskr_tests.py109 .110 ----------------------------------------------------------------------111 Ran 1 test in 0.034s112113 OK114115Of course you can submit forms with the test client as well which we will116use now to log our user in.117118Logging In and Out119------------------120121The majority of the functionality of our application is only available for122the administration user. So we need a way to log our test client into the123application and out of it again. For that we fire some requests to the124login and logout pages with the required form data (username and125password). Because the login and logout pages redirect, we tell the126client to `follow_redirects`.127128Add the following two methods do your `FlaskrTestCase` class::129130 def login(self, username, password):131 return self.app.post('/login', data=dict(132 username=username,133 password=password134 ), follow_redirects=True)135136 def logout(self):137 return self.app.get('/logout', follow_redirects=True)138139Now we can easily test if logging in and out works and that it fails with140invalid credentials. Add this as new test to the class::141142 def test_login_logout(self):143 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)144 assert 'You were logged in' in rv.data145 rv = self.logout()146 assert 'You were logged out' in rv.data147 rv = self.login(flaskr.USERNAME + 'x', flaskr.PASSWORD)148 assert 'Invalid username' in rv.data149 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD + 'x')150 assert 'Invalid password' in rv.data151152Test Adding Messages153--------------------154155Now we can also test that adding messages works. Add a new test method156like this::157158 def test_messages(self):159 self.login(flaskr.USERNAME, flaskr.PASSWORD)160 rv = self.app.post('/add', data=dict(161 title='<Hello>',162 text='<strong>HTML</strong> allowed here'163 ), follow_redirects=True)164 assert 'No entries here so far' not in rv.data165 assert '<Hello>' in rv.data166 assert '<strong>HTML</strong> allowed here' in rv.data167168Here we also check that HTML is allowed in the text but not in the title169which is the intended behavior.170171Running that should now give us three passing tests::172173 $ python flaskr_tests.py 174 ...175 ----------------------------------------------------------------------176 Ran 3 tests in 0.332s177 178 OK179180For more complex tests with headers and status codes, check out the181`MiniTwit Example`_ from the sources. That one contains a larger test182suite.183184185.. _MiniTwit Example:186 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/