Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

186 lines · 6.4 KiB

Last changed by

Removed useless codeArmin Ronacherbefore adoptionbf52a17

History of this file

Take it

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 1–24why, one step back
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---------------24

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 25–27why, one step back
25First we need an application to test for functionality. For the testing
26we will use the application from the :ref:`tutorial`. If you don't have27that application yet, get the sources from `the examples`_.

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 28why, one step back
28

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 29–30why, one step back
29.. _the examples:
30 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 31–35why, one step back
31
32The Testing Skeleton33--------------------3435In order to test that, we add a second module (

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 36why, one step back
36`flaskr_tests.py`) and create a unittest skeleton there::

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 37–38why, one step back
37
38 import unittest

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 39–40why, one step back
39 import flaskr
40 import tempfile

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 41why, one step back
41

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 42why, one step back
42 class FlaskrTestCase(unittest.TestCase):

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 43–44why, one step back
43
44 def setUp(self):

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 45–48why, one step back
45 self.db = tempfile.NamedTemporaryFile()
46 self.app = flaskr.app.test_client()47 flaskr.DATABASE = self.db.name48 flaskr.init_db()

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 49–52why, one step back
49
50 if __name__ == '__main__':51 unittest.main()52

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 53–57why, one step back
53The code in the `setUp` function creates a new test client and initialize
54a 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.

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 58why, one step back
58

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 59–64why, one step back
59Because SQLite3 is filesystem based we can easily use the tempfile module
60to 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.64

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 65–66why, one step back
65If we now run that testsuite, we should see the following output::
66

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 67why, one step back
67 $ python flaskr_tests.py

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 68–73why, one step back
68
69 ----------------------------------------------------------------------70 Ran 0 tests in 0.000s71 72 OK73

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 74why, one step back
74Even though it did not run any tests, we already know that our flaskr

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 75–80why, one step back
75application is syntactically valid, otherwise the import would have died
76with an exception.7778The First Test79--------------80

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 81–84why, one step back
81Now we can add the first test. Let's check that the application shows
82"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::

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 85why, one step back
85

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 86why, one step back
86 class FlaskrTestCase(unittest.TestCase):

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 87–88why, one step back
87
88 def setUp(self):

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 89–92why, one step back
89 self.db = tempfile.NamedTemporaryFile()
90 self.app = flaskr.app.test_client()91 flaskr.DATABASE = self.db.name92 flaskr.init_db()

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 93why, one step back
93

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 94why, one step back
94 def test_empty_db(self):

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 95why, one step back
95 rv = self.app.get('/')

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 96why, one step back
96 assert 'No entries here so far' in rv.data

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 97–103why, one step back
97
98Test 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 ensure

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 104why, one step back
104that ``'No entries here so far'`` is part of the output.

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 105why, one step back
105

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 106why, one step back
106Run it again and you should see one passing test::

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 107why, one step back
107

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 108–111why, one step back
108 $ python flaskr_tests.py
109 .110 ----------------------------------------------------------------------111 Ran 1 test in 0.034s

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 112why, one step back
112

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 113why, one step back
113 OK

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 114why, one step back
114

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 115–183why, one step back
115Of course you can submit forms with the test client as well which we will
116use 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 '&lt;Hello&gt' 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.183

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 184–186why, one step back
184
185.. _MiniTwit Example:186 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/