testing.rst
This file
Path
docs/testing.rst
197 lines · 6.8 KiB
Last changed by
Fix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2
History of this fileTake it
Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 1–10why, one step back1.. _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 toProofreading the documentationChris Edgemonbefore adoptiona7ff9db
lines 11–12why, one step back11become pretty paranoid. If an application however has automated tests, you12can safely change things and you will instantly know if your change brokeDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 13–17why, one step back13something.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 withProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 18why, one step back18your favourite testing solution. In this documentation we will use theDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 19–24why, one step back19:mod:`unittest` package that comes preinstalled with each Python20installation.2122The Application23---------------24Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 25–27why, one step back25First 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`_.Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 28why, one step back28Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 29–30why, one step back29.. _the examples:30 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 31–35why, one step back3132The Testing Skeleton33--------------------3435In order to test that, we add a second module (Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 36why, one step back36`flaskr_tests.py`) and create a unittest skeleton there::Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 37why, one step back37Added missing os import.Armin Ronacherbefore adoptionf6b9efc
line 38why, one step back38 import osBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 39why, one step back39 import flaskrAdded missing os import.Armin Ronacherbefore adoptionf6b9efc
line 40why, one step back40 import unittestBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 41why, one step back41 import tempfileDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 42why, one step back42Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 43why, one step back43 class FlaskrTestCase(unittest.TestCase):Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 44–45why, one step back4445 def setUp(self):Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
line 46why, one step back46 self.db_fd, flaskr.DATABASE = tempfile.mkstemp()Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 47–48why, one step back47 self.app = flaskr.app.test_client()48 flaskr.init_db()Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 49why, one step back49Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 50–53why, one step back50 def tearDown(self):51 os.close(self.db_fd)52 os.unlink(flaskr.DATABASE)53Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 54–56why, one step back54 if __name__ == '__main__':55 unittest.main()56Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 57–64why, one step back57The code in the :meth:`~unittest.TestCase.setUp` method creates a new test58client 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 back65Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 66why, one step back66Because SQLite3 is filesystem-based we can easily use the tempfile moduleMake the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
lines 67–70why, one step back67to create a temporary database and initialize it. The68: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 useFix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2
line 71why, one step back71the :func:`os.close` function to close the file.Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 72why, one step back72Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 73–74why, one step back73If we now run that testsuite, we should see the following output::74Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 75why, one step back75 $ python flaskr_tests.pyDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 76–78why, one step back7677 ----------------------------------------------------------------------78 Ran 0 tests in 0.000sFix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2
line 79why, one step back79Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 80–81why, one step back80 OK81Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 82why, one step back82Even though it did not run any tests, we already know that our flaskrDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 83–88why, one step back83application is syntactically valid, otherwise the import would have died84with an exception.8586The First Test87--------------88Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 89–92why, one step back89Now we can add the first test. Let's check that the application shows90"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 back93Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 94why, one step back94 class FlaskrTestCase(unittest.TestCase):Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 95–96why, one step back9596 def setUp(self):Make the example tests pass on Windows.Armin Ronacherbefore adoption3053fcd
line 97why, one step back97 self.db_fd, flaskr.DATABASE = tempfile.mkstemp()Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 98–99why, one step back98 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 back100101 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 back104Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 105why, one step back105 def test_empty_db(self):Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 106why, one step back106 rv = self.app.get('/')Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 107why, one step back107 assert 'No entries here so far' in rv.dataDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 108–114why, one step back108109Test 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 ensureBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 115why, one step back115that ``'No entries here so far'`` is part of the output.Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 116why, one step back116Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 117why, one step back117Run it again and you should see one passing test::Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 118why, one step back118Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 119–122why, one step back119 $ python flaskr_tests.py120 .121 ----------------------------------------------------------------------122 Ran 1 test in 0.034sDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 123why, one step back123Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 124why, one step back124 OKDoc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
line 125why, one step back125Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 126why, one step back126Of course you can submit forms with the test client as well, which we willBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 127–132why, one step back127use now to log our user in.128129Logging In and Out130------------------131132The majority of the functionality of our application is only available forProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 133why, one step back133the administration user. So we need a way to log our test client in to theBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 134–138why, one step back134application and out of it again. For that we fire some requests to the135login and logout pages with the required form data (username and136password). Because the login and logout pages redirect, we tell the137client to `follow_redirects`.138Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 139why, one step back139Add the following two methods to your `FlaskrTestCase` class::Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 140–150why, one step back140141 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 withProofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 151why, one step back151invalid credentials. Add this new test to the class::Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 152–178why, one step back152153 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 '<Hello>' in rv.data177 assert '<strong>HTML</strong> allowed here' in rv.data178Proofreading the documentationChris Edgemonbefore adoptiona7ff9db
line 179why, one step back179Here 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 back180which 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.194Doc updates and typo fixesArmin Ronacherbefore adoption2f5a4f8
lines 195–197why, one step back195196.. _MiniTwit Example:197 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/