Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

197 lines · 6.8 KiB

Last changed by

Added missing os import.Armin Ronacherbefore adoptionf6b9efc

History of this file

Take it

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 1–10why, 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 to

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

lines 11–12why, one step back
11become pretty paranoid. If an application however has automated tests, you
12can safely change things and you will instantly know if your change broke

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 13–17why, one step back
13something.
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 with

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 18why, one step back
18your favourite testing solution. In this documentation we will use the

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 19–24why, one step back
19:mod:`unittest` package that comes preinstalled with each Python
20installation.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

line 37why, one step back
37

Added missing os import.Armin Ronacherbefore adoptionf6b9efc

line 38why, one step back
38 import os

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 39why, one step back
39 import flaskr

Added missing os import.Armin Ronacherbefore adoptionf6b9efc

line 40why, one step back
40 import unittest

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 41why, one step back
41 import tempfile

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 42why, one step back
42

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

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

Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd

line 46why, one step back
46 self.db_fd, flaskr.DATABASE = tempfile.mkstemp()

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 47–48why, one step back
47 self.app = flaskr.app.test_client()
48 flaskr.init_db()

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 49why, one step back
49

Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd

lines 50–53why, one step back
50 def tearDown(self):
51 os.close(self.db_fd)52 os.unlink(flaskr.DATABASE)53

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 54–56why, one step back
54 if __name__ == '__main__':
55 unittest.main()56

Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd

lines 57–64why, one step back
57The code in the :meth:`~unittest.TestCase.setUp` method creates a new test
58client 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.

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 65why, one step back
65

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 66why, one step back
66Because SQLite3 is filesystem-based we can easily use the tempfile module

Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd

lines 67–71why, one step back
67to create a temporary database and initialize it. The
68: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 function.

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 72why, one step back
72

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

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

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 76–81why, one step back
76
77 ----------------------------------------------------------------------78 Ran 0 tests in 0.000s79 80 OK81

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 83–88why, one step back
83application is syntactically valid, otherwise the import would have died
84with an exception.8586The First Test87--------------88

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

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 class FlaskrTestCase(unittest.TestCase):

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 95–96why, one step back
95
96 def setUp(self):

Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd

line 97why, one step back
97 self.db_fd, flaskr.DATABASE = tempfile.mkstemp()

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 98–99why, one step back
98 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 back
100
101 def tearDown(self):102 os.close(self.db_fd)103 os.unlink(flaskr.DATABASE)

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 104why, one step back
104

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

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

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 108–114why, one step back
108
109Test 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 ensure

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 116why, one step back
116

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

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

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 118why, one step back
118

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 119–122why, one step back
119 $ python flaskr_tests.py
120 .121 ----------------------------------------------------------------------122 Ran 1 test in 0.034s

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 123why, one step back
123

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

line 124why, one step back
124 OK

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

line 125why, one step back
125

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 126why, one step back
126Of course you can submit forms with the test client as well, which we will

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 127–132why, one step back
127use now to log our user in.
128129Logging In and Out130------------------131132The majority of the functionality of our application is only available for

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 133why, one step back
133the administration user. So we need a way to log our test client in to the

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 134–138why, one step back
134application and out of it again. For that we fire some requests to the
135login and logout pages with the required form data (username and136password). Because the login and logout pages redirect, we tell the137client to `follow_redirects`.138

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 139why, one step back
139Add the following two methods to your `FlaskrTestCase` class::

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 140–150why, one step back
140
141 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 with

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 151why, one step back
151invalid credentials. Add this new test to the class::

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 152–178why, one step back
152
153 def test_login_logout(self):154 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)155 assert 'You were logged in' in rv.data156 rv = self.logout()157 assert 'You were logged out' in rv.data158 rv = self.login(flaskr.USERNAME + 'x', flaskr.PASSWORD)159 assert 'Invalid username' in rv.data160 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD + 'x')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(flaskr.USERNAME, flaskr.PASSWORD)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.data178

Proofreading the documentationChris Edgemonbefore adoptiona7ff9db

line 179why, one step back
179Here we check that HTML is allowed in the text but not in the title,

Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae

lines 180–194why, one step back
180which is the intended behavior.
181182Running that should now give us three passing tests::183184 $ python flaskr_tests.py 185 ...186 ----------------------------------------------------------------------187 Ran 3 tests in 0.332s188 189 OK190191For more complex tests with headers and status codes, check out the192`MiniTwit Example`_ from the sources. That one contains a larger test193suite.194

Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8

lines 195–197why, one step back
195
196.. _MiniTwit Example:197 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/