Skip to content
Myr

Merge pull request #2307 from neilvictorgrey/master

Before adoption: this commit came in with the history the project adopted, so no landing records it.

For Issue #2286: Update unittest references

authored by David Lord · committed by GitHub · parents 54a18a5, 8858135 · Browse files · 4 files+117 added−101 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+117 added−101 removed

  • tests:+3 added−7 removed
  • other:+114 added−94 removed

4 files+117 added−101 removed

modified:docs/signals.rst+2 added-2 removed
25 unmodified lines
26executed in undefined order and do not modify any data.2728The big advantage of signals over handlers is that you can safely29subscribe to them for just a split second. These temporary30subscriptions are helpful for unittesting for example. Say you want to30subscriptions are helpful for unit testing for example. Say you want to31know what templates were rendered as part of a request: signals allow you32to do exactly that.3334Subscribing to Signals
9 unmodified lines
44signal. When you subscribe to a signal, be sure to also provide a sender45unless you really want to listen for signals from all applications. This is46especially true if you are developing an extension.4748For example, here is a helper context manager that can be used in a unittest48For example, here is a helper context manager that can be used in a unit test49to determine which templates were rendered and what variables were passed50to the template::5152 from flask import template_rendered
138 unmodified lines
modified:docs/testing.rst+111 added-91 removed
3 unmodified lines
4==========================56 **Something that is untested is broken.**78The origin of this quote is unknown and while it is not entirely correct, it is also9not far from the truth. Untested applications make it hard to8The origin of this quote is unknown and while it is not entirely correct, it9is also not far from the truth. Untested applications make it hard to10improve existing code and developers of untested applications tend to11become pretty paranoid. If an application has automated tests, you can12safely make changes and instantly know if anything breaks.1314Flask provides a way to test your application by exposing the Werkzeug15test :class:`~werkzeug.test.Client` and handling the context locals for you.16You can then use that with your favourite testing solution. In this documentation17we will use the :mod:`unittest` package that comes pre-installed with Python.16You can then use that with your favourite testing solution.1718In this documentation we will use the `pytest`_ package as the base19framework for our tests. You can install it with ``pip``, like so::2021 pip install pytest2223.. _pytest:24 https://pytest.org2526The Application27---------------2829First, we need an application to test; we will use the application from30the :ref:`tutorial`. If you don't have that application yet, get the24sources from `the examples`_.31source code from `the examples`_.3233.. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/3536The Testing Skeleton37--------------------3832In order to test the application, we add a second module33(:file:`flaskr_tests.py`) and create a unittest skeleton there::39We begin by adding a tests directory under the application root. Then40create a Python file to store our tests (:file:`test_flaskr.py`). When we41format the filename like ``test_*.py``, it will be auto-discoverable by42pytest.4344Next, we create a `pytest fixture`_ called45:func:`client` that configures46the application for testing and initializes a new database.::4748 import os36 from flaskr import flaskr37 import unittest49 import tempfile5040 class FlaskrTestCase(unittest.TestCase):51 import pytest5242 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44 flaskr.app.testing = True45 self.app = flaskr.app.test_client()46 with flaskr.app.app_context():47 flaskr.init_db()53 from flaskr import flaskr5449 def tearDown(self):50 os.close(self.db_fd)51 os.unlink(flaskr.app.config['DATABASE'])5553 if __name__ == '__main__':54 unittest.main()56 @pytest.fixture57 def client(request):58 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()59 flaskr.app.config['TESTING'] = True60 client = flaskr.app.test_client()6156The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57client and initializes a new database. This function is called before58each individual test function is run. To delete the database after the59test, we close the file and remove it from the filesystem in the60:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the61``TESTING`` config flag is activated. What it does is disable the error62catching during request handling so that you get better error reports when63performing test requests against the application.62 with flaskr.app.app_context():63 flaskr.init_db()6465This test client will give us a simple interface to the application. We can66trigger test requests to the application, and the client will also keep track67of cookies for us.65 yield client6667 os.close(db_fd)68 os.unlink(flaskr.app.config['DATABASE'])6970This client fixture will be called by each individual test. It gives us a71simple interface to the application, where we can trigger test requests to the72application. The client will also keep track of cookies for us.7374During setup, the ``TESTING`` config flag is activated. What75this does is disable error catching during request handling, so that76you get better error reports when performing test requests against the77application.7869Because SQLite3 is filesystem-based we can easily use the tempfile module79Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module80to create a temporary database and initialize it. The81:func:`~tempfile.mkstemp` function does two things for us: it returns a82low-level file handle and a random file name, the latter we use as83database name. We just have to keep the `db_fd` around so that we can use84the :func:`os.close` function to close the file.8586To delete the database after the test, the fixture closes the file and removes87it from the filesystem.8889If we now run the test suite, we should see the following output::9078 $ python flaskr_tests.py91 $ pytest9280 ----------------------------------------------------------------------81 Ran 0 tests in 0.000s93 ================ test session starts ================94 rootdir: ./flask/examples/flaskr, inifile: setup.cfg95 collected 0 items9683 OK97 =========== no tests ran in 0.07 seconds ============9885Even though it did not run any actual tests, we already know that our flaskr99Even though it did not run any actual tests, we already know that our ``flaskr``100application is syntactically valid, otherwise the import would have died101with an exception.102103.. _pytest fixture:104 https://docs.pytest.org/en/latest/fixture.html105106The First Test107--------------108109Now it's time to start testing the functionality of the application.110Let's check that the application shows "No entries here so far" if we94access the root of the application (``/``). To do this, we add a new95test method to our class, like this::111access the root of the application (``/``). To do this, we add a new112test function to :file:`test_flaskr.py`, like this::11397 class FlaskrTestCase(unittest.TestCase):114 def test_empty_db(client):115 """Start with a blank database."""11699 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101 flaskr.app.testing = True102 self.app = flaskr.app.test_client()103 with flaskr.app.app_context():104 flaskr.init_db()117 rv = client.get('/')118 assert b'No entries here so far' in rv.data119106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])109110 def test_empty_db(self):111 rv = self.app.get('/')112 assert b'No entries here so far' in rv.data113120Notice that our test functions begin with the word `test`; this allows115:mod:`unittest` to automatically identify the method as a test to run.121`pytest`_ to automatically identify the function as a test to run.122117By using `self.app.get` we can send an HTTP ``GET`` request to the application with123By using ``client.get`` we can send an HTTP ``GET`` request to the application with124the given path. The return value will be a :class:`~flask.Flask.response_class` object.125We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126the return value (as string) from the application. In this case, we ensure that127``'No entries here so far'`` is part of the output.128129Run it again and you should see one passing test::130125 $ python flaskr_tests.py126 .127 ----------------------------------------------------------------------128 Ran 1 test in 0.034s131 $ pytest -v132130 OK133 ================ test session starts ================134 rootdir: ./flask/examples/flaskr, inifile: setup.cfg135 collected 1 items136137 tests/test_flaskr.py::test_empty_db PASSED138139 ============= 1 passed in 0.10 seconds ==============140141Logging In and Out142------------------143144The majority of the functionality of our application is only available for
1 unmodified line
146of the application. To do this, we fire some requests to the login and logout147pages with the required form data (username and password). And because the148login and logout pages redirect, we tell the client to `follow_redirects`.149141Add the following two methods to your `FlaskrTestCase` class::150Add the following two functions to your :file:`test_flaskr.py` file::151143 def login(self, username, password):144 return self.app.post('/login', data=dict(145 username=username,146 password=password147 ), follow_redirects=True)152 def login(client, username, password):153 return client.post('/login', data=dict(154 username=username,155 password=password156 ), follow_redirects=True)157149 def logout(self):150 return self.app.get('/logout', follow_redirects=True)158159 def logout(client):160 return client.get('/logout', follow_redirects=True)161162Now we can easily test that logging in and out works and that it fails with153invalid credentials. Add this new test to the class::163invalid credentials. Add this new test function::164155 def test_login_logout(self):156 rv = self.login('admin', 'default')157 assert b'You were logged in' in rv.data158 rv = self.logout()159 assert b'You were logged out' in rv.data160 rv = self.login('adminx', 'default')161 assert b'Invalid username' in rv.data162 rv = self.login('admin', 'defaultx')163 assert b'Invalid password' in rv.data165 def test_login_logout(client):166 """Make sure login and logout works."""167168 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])169 assert b'You were logged in' in rv.data170171 rv = logout(client)172 assert b'You were logged out' in rv.data173174 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])175 assert b'Invalid username' in rv.data176177 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')178 assert b'Invalid password' in rv.data179180Test Adding Messages181--------------------182168We should also test that adding messages works. Add a new test method183We should also test that adding messages works. Add a new test function184like this::185171 def test_messages(self):172 self.login('admin', 'default')173 rv = self.app.post('/add', data=dict(186 def test_messages(client):187 """Test that messages work."""188189 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])190 rv = client.post('/add', data=dict(191 title='<Hello>',192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)194 assert b'No entries here so far' not in rv.data
4 unmodified lines
199which is the intended behavior.200201Running that should now give us three passing tests::202186 $ python flaskr_tests.py187 ...188 ----------------------------------------------------------------------189 Ran 3 tests in 0.332s203 $ pytest -v204191 OK205 ================ test session starts ================206 rootdir: ./flask/examples/flaskr, inifile: setup.cfg207 collected 3 items208209 tests/test_flaskr.py::test_empty_db PASSED210 tests/test_flaskr.py::test_login_logout PASSED211 tests/test_flaskr.py::test_messages PASSED212213 ============= 3 passed in 0.23 seconds ==============214215For more complex tests with headers and status codes, check out the216`MiniTwit Example`_ from the sources which contains a larger test217suite.218197219.. _MiniTwit Example:220 https://github.com/pallets/flask/tree/master/examples/minitwit/221201222Other Testing Tricks223--------------------224225Besides using the test client as shown above, there is also the
152 unmodified lines
modified:examples/flaskr/tests/test_flaskr.py+3 added-7 removed
20 unmodified lines
21 flaskr.app.config['TESTING'] = True22 client = flaskr.app.test_client()23 with flaskr.app.app_context():24 flaskr.init_db()25 yield client26 os.close(db_fd)27 os.unlink(flaskr.app.config['DATABASE'])2826 def teardown():27 os.close(db_fd)28 os.unlink(flaskr.app.config['DATABASE'])29 request.addfinalizer(teardown)2931 return client323330def login(client, username, password):31 return client.post('/login', data=dict(32 username=username,33 password=password
39 unmodified lines
modified:flask/app.py+1 added-1 removed
218 unmodified lines
219 debug = ConfigAttribute('DEBUG')220221 #: The testing flag. Set this to ``True`` to enable the test mode of222 #: Flask extensions (and in the future probably also Flask itself).223 #: For example this might activate unittest helpers that have an223 #: For example this might activate test helpers that have an224 #: additional runtime cost which should not be enabled by default.225 #:226 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the227 #: default it's implicitly enabled.
1853 unmodified lines