|
|
|
@ -8,8 +8,8 @@ Testing Flask Applications
|
|
|
|
|
Not sure where that is coming from, and it's not entirely correct, but |
|
|
|
|
also not that far from the truth. Untested applications make it hard to |
|
|
|
|
improve existing code and developers of untested applications tend to |
|
|
|
|
become pretty paranoid. If an application however has automated tests, you |
|
|
|
|
can safely change things and you will instantly know if your change broke |
|
|
|
|
become pretty paranoid. If an application has automated tests, you can |
|
|
|
|
safely change things, and you will instantly know if your change broke |
|
|
|
|
something. |
|
|
|
|
|
|
|
|
|
Flask gives you a couple of ways to test applications. It mainly does |
|
|
|
@ -60,7 +60,7 @@ each individual test function. To delete the database after the test, we
|
|
|
|
|
close the file and remove it from the filesystem in the |
|
|
|
|
:meth:`~unittest.TestCase.tearDown` method. What the test client does is |
|
|
|
|
give us a simple interface to the application. We can trigger test |
|
|
|
|
requests to the application and the client will also keep track of cookies |
|
|
|
|
requests to the application, and the client will also keep track of cookies |
|
|
|
|
for us. |
|
|
|
|
|
|
|
|
|
Because SQLite3 is filesystem-based we can easily use the tempfile module |
|
|
|
@ -130,7 +130,7 @@ Logging In and Out
|
|
|
|
|
------------------ |
|
|
|
|
|
|
|
|
|
The majority of the functionality of our application is only available for |
|
|
|
|
the administration user. So we need a way to log our test client in to the |
|
|
|
|
the administrative user, so we need a way to log our test client in to the |
|
|
|
|
application and out of it again. For that we fire some requests to the |
|
|
|
|
login and logout pages with the required form data (username and |
|
|
|
|
password). Because the login and logout pages redirect, we tell the |
|
|
|
@ -200,12 +200,12 @@ suite.
|
|
|
|
|
Other Testing Tricks |
|
|
|
|
-------------------- |
|
|
|
|
|
|
|
|
|
Besides using the test client we used above there is also the |
|
|
|
|
Besides using the test client we used above, there is also the |
|
|
|
|
:meth:`~flask.Flask.test_request_context` method that in combination with |
|
|
|
|
the `with` statement can be used to activate a request context |
|
|
|
|
temporarily. With that you can access the :class:`~flask.request`, |
|
|
|
|
:class:`~flask.g` and :class:`~flask.session` objects like in view |
|
|
|
|
functions. Here a full example that showcases this:: |
|
|
|
|
functions. Here's a full example that showcases this:: |
|
|
|
|
|
|
|
|
|
app = flask.Flask(__name__) |
|
|
|
|
|
|
|
|
|