@@ -5,35 +5,32 @@ Testing Flask Applications
5
5
6
6
**Something that is untested is broken. **
7
7
8
- Not sure where that is coming from, and it's not entirely correct, but
9
- also not that far from the truth. Untested applications make it hard to
8
+ The origin of this quote is unknown and while it is not entirely correct, it is also
9
+ not far from the truth. Untested applications make it hard to
10
10
improve existing code and developers of untested applications tend to
11
11
become pretty paranoid. If an application has automated tests, you can
12
- safely change things, and you will instantly know if your change broke
13
- something.
12
+ safely make changes and instantly know if anything breaks.
14
13
15
- Flask gives you a couple of ways to test applications. It mainly does
16
- that by exposing the Werkzeug test :class: `~werkzeug.test.Client ` class to your
17
- code and handling the context locals for you. You can then use that with
18
- your favourite testing solution. In this documentation we will use the
19
- :mod: `unittest ` package that comes preinstalled with each Python
20
- installation.
14
+ Flask provides a way to test your application by exposing the Werkzeug
15
+ test :class: `~werkzeug.test.Client ` and handling the context locals for you.
16
+ You can then use that with your favourite testing solution. In this documentation
17
+ we will use the :mod: `unittest ` package that comes pre-installed with Python.
21
18
22
19
The Application
23
20
---------------
24
21
25
- First we need an application to test for functionality. For the testing
26
- we will use the application from the :ref: `tutorial `. If you don't have
27
- that application yet, get the sources from `the examples `_.
22
+ First, we need an application to test; we will use the application from
23
+ the :ref: `tutorial `. If you don't have that application yet, get the
24
+ sources from `the examples `_.
28
25
29
26
.. _the examples :
30
27
http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/
31
28
32
29
The Testing Skeleton
33
30
--------------------
34
31
35
- In order to test that , we add a second module (
36
- `flaskr_tests.py `) and create a unittest skeleton there::
32
+ In order to test the application , we add a second module
33
+ ( `flaskr_tests.py `) and create a unittest skeleton there::
37
34
38
35
import os
39
36
import flaskr
@@ -55,13 +52,14 @@ In order to test that, we add a second module (
55
52
unittest.main()
56
53
57
54
The code in the :meth: `~unittest.TestCase.setUp ` method creates a new test
58
- client and initializes a new database. That function is called before
59
- each individual test function. To delete the database after the test, we
60
- close the file and remove it from the filesystem in the
61
- :meth: `~unittest.TestCase.tearDown ` method. What the test client does is
62
- give us a simple interface to the application. We can trigger test
63
- requests to the application, and the client will also keep track of cookies
64
- for us.
55
+ client and initializes a new database. This function is called before
56
+ each individual test function is run. To delete the database after the
57
+ test, we close the file and remove it from the filesystem in the
58
+ :meth: `~unittest.TestCase.tearDown ` method.
59
+
60
+ This test client will give us a simple interface to the application. We can
61
+ trigger test requests to the application, and the client will also keep track
62
+ of cookies for us.
65
63
66
64
Because SQLite3 is filesystem-based we can easily use the tempfile module
67
65
to create a temporary database and initialize it. The
@@ -70,7 +68,7 @@ low-level file handle and a random file name, the latter we use as
70
68
database name. We just have to keep the `db_fd ` around so that we can use
71
69
the :func: `os.close ` function to close the file.
72
70
73
- If we now run that test suite, we should see the following output::
71
+ If we now run the test suite, we should see the following output::
74
72
75
73
$ python flaskr_tests.py
76
74
@@ -79,17 +77,17 @@ If we now run that test suite, we should see the following output::
79
77
80
78
OK
81
79
82
- Even though it did not run any tests, we already know that our flaskr
80
+ Even though it did not run any actual tests, we already know that our flaskr
83
81
application is syntactically valid, otherwise the import would have died
84
82
with an exception.
85
83
86
84
The First Test
87
85
--------------
88
86
89
- Now 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 (`` / ``).
91
- For that we modify our created test case class so that it looks like
92
- this::
87
+ Now it's time to start testing the functionality of the application.
88
+ Let's check that the application shows "No entries here so far" if we
89
+ access the root of the application (`` / ``). To do this, we add a new
90
+ test method to our class, like this::
93
91
94
92
class FlaskrTestCase(unittest.TestCase):
95
93
@@ -106,13 +104,14 @@ this::
106
104
rv = self.app.get('/')
107
105
assert 'No entries here so far' in rv.data
108
106
109
- Test functions begin with the word `test `. Every function named like that
110
- will be picked up automatically. By using `self.app.get ` we can send an
111
- HTTP `GET ` request to the application with the given path. The return
112
- value will be a :class: `~flask.Flask.response_class ` object. We can now
113
- use the :attr: `~werkzeug.wrappers.BaseResponse.data ` attribute to inspect the
114
- return value (as string) from the application. In this case, we ensure
115
- that ``'No entries here so far' `` is part of the output.
107
+ Notice that our test functions begin with the word `test `; this allows
108
+ :mod: `unittest ` to automatically identify the method as a test to run.
109
+
110
+ By using `self.app.get ` we can send an HTTP `GET ` request to the application with
111
+ the given path. The return value will be a :class: `~flask.Flask.response_class ` object.
112
+ We can now use the :attr: `~werkzeug.wrappers.BaseResponse.data ` attribute to inspect
113
+ the return value (as string) from the application. In this case, we ensure that
114
+ ``'No entries here so far' `` is part of the output.
116
115
117
116
Run it again and you should see one passing test::
118
117
@@ -123,18 +122,14 @@ Run it again and you should see one passing test::
123
122
124
123
OK
125
124
126
- Of course you can submit forms with the test client as well, which we will
127
- use now to log our user in.
128
-
129
125
Logging In and Out
130
126
------------------
131
127
132
128
The majority of the functionality of our application is only available for
133
- the administrative user, so we need a way to log our test client in to the
134
- application and out of it again. For that we fire some requests to the
135
- login and logout pages with the required form data (username and
136
- password). Because the login and logout pages redirect, we tell the
137
- client to `follow_redirects `.
129
+ the administrative user, so we need a way to log our test client in and out
130
+ of the application. To do this, we fire some requests to the login and logout
131
+ pages with the required form data (username and password). And because the
132
+ login and logout pages redirect, we tell the client to `follow_redirects `.
138
133
139
134
Add the following two methods to your `FlaskrTestCase ` class::
140
135
@@ -147,7 +142,7 @@ Add the following two methods to your `FlaskrTestCase` class::
147
142
def logout(self):
148
143
return self.app.get('/logout', follow_redirects=True)
149
144
150
- Now we can easily test if logging in and out works and that it fails with
145
+ Now we can easily test that logging in and out works and that it fails with
151
146
invalid credentials. Add this new test to the class::
152
147
153
148
def test_login_logout(self):
@@ -163,7 +158,7 @@ invalid credentials. Add this new test to the class::
163
158
Test Adding Messages
164
159
--------------------
165
160
166
- Now we can also test that adding messages works. Add a new test method
161
+ We should also test that adding messages works. Add a new test method
167
162
like this::
168
163
169
164
def test_messages(self):
@@ -189,7 +184,7 @@ Running that should now give us three passing tests::
189
184
OK
190
185
191
186
For more complex tests with headers and status codes, check out the
192
- `MiniTwit Example `_ from the sources. That one contains a larger test
187
+ `MiniTwit Example `_ from the sources which contains a larger test
193
188
suite.
194
189
195
190
@@ -200,20 +195,21 @@ suite.
200
195
Other Testing Tricks
201
196
--------------------
202
197
203
- Besides using the test client we used above, there is also the
204
- :meth: `~flask.Flask.test_request_context ` method that in combination with
205
- the `with ` statement can be used to activate a request context
206
- temporarily. With that you can access the :class: `~flask.request `,
198
+ Besides using the test client as shown above, there is also the
199
+ :meth: `~flask.Flask.test_request_context ` method that can be used
200
+ in combination with the `with ` statement to activate a request context
201
+ temporarily. With this you can access the :class: `~flask.request `,
207
202
:class: `~flask.g ` and :class: `~flask.session ` objects like in view
208
- functions. Here's a full example that showcases this::
203
+ functions. Here is a full example that demonstrates this approach ::
209
204
210
205
app = flask.Flask(__name__)
211
206
212
207
with app.test_request_context('/?name=Peter'):
213
208
assert flask.request.path == '/'
214
209
assert flask.request.args['name'] == 'Peter'
215
210
216
- All the other objects that are context bound can be used the same.
211
+ All the other objects that are context bound can be used in the same
212
+ way.
217
213
218
214
If you want to test your application with different configurations and
219
215
there does not seem to be a good way to do that, consider switching to
@@ -225,7 +221,7 @@ Keeping the Context Around
225
221
226
222
.. versionadded :: 0.4
227
223
228
- Sometimes it can be helpful to trigger a regular request but keep the
224
+ Sometimes it is helpful to trigger a regular request but still keep the
229
225
context around for a little longer so that additional introspection can
230
226
happen. With Flask 0.4 this is possible by using the
231
227
:meth: `~flask.Flask.test_client ` with a `with ` block::
@@ -236,9 +232,10 @@ happen. With Flask 0.4 this is possible by using the
236
232
rv = c.get('/?tequila=42')
237
233
assert request.args['tequila'] == '42'
238
234
239
- If you would just be using the :meth: `~flask.Flask.test_client ` without
235
+ If you were to use just the :meth: `~flask.Flask.test_client ` without
240
236
the `with ` block, the `assert ` would fail with an error because `request `
241
- is no longer available (because used outside of an actual request).
242
- Keep in mind however that :meth: `~flask.Flask.after_request ` functions
243
- are already called at that point so your database connection and
237
+ is no longer available (because you are trying to use it outside of the actual request).
238
+ However, keep in mind that any :meth: `~flask.Flask.after_request ` functions
239
+ are already called at this point so your database connection and
244
240
everything involved is probably already closed down.
241
+
0 commit comments