Skip to content
Myr

For Issue #2286: Replaces references to unittest in the documentation with pytest

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

authored by Neil Grey · committed by Neil Grey · parent 0c94908 · Browse files · 3 files+111 added−93 removed
This commit

State

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

Diff stats

3 files+111 added−93 removed

  • other:+111 added−93 removed

3 files+111 added−93 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+108 added-90 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 tempfile50 import pytest51 from flaskr import flaskr5240 class FlaskrTestCase(unittest.TestCase):53 @pytest.fixture54 def client(request):55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True57 client = flaskr.app.test_client()58 with flaskr.app.app_context():59 flaskr.init_db()6042 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()4849 def tearDown(self):50 os.close(self.db_fd)61 def teardown():62 os.close(db_fd)63 os.unlink(flaskr.app.config['DATABASE'])64 request.addfinalizer(teardown)6553 if __name__ == '__main__':54 unittest.main()66 return client6756The 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.68This client fixture will be called by each individual test. It gives us a69simple interface to the application, where we can trigger test requests to the70application. The client will also keep track of cookies for us.7165This 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.72During setup, the ``TESTING`` config flag is activated. What73this does is disable error catching during request handling, so that74you get better error reports when performing test requests against the75application.7669Because SQLite3 is filesystem-based we can easily use the tempfile module77Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module78to create a temporary database and initialize it. The79:func:`~tempfile.mkstemp` function does two things for us: it returns a80low-level file handle and a random file name, the latter we use as81database name. We just have to keep the `db_fd` around so that we can use82the :func:`os.close` function to close the file.8384To delete the database after the test, we close the file and remove it85from the filesystem in the86:func:`teardown` function.8788If we now run the test suite, we should see the following output::8978 $ python flaskr_tests.py90 $ pytest9180 ----------------------------------------------------------------------81 Ran 0 tests in 0.000s92 ================ test session starts ================93 rootdir: ./flask/examples/flaskr, inifile: setup.cfg94 collected 0 items9583 OK96 =========== no tests ran in 0.07 seconds ============9785Even though it did not run any actual tests, we already know that our flaskr98Even though it did not run any actual tests, we already know that our ``flaskr``99application is syntactically valid, otherwise the import would have died100with an exception.101102.. _pytest fixture:103 https://docs.pytest.org/en/latest/fixture.html104105The First Test106--------------107108Now it's time to start testing the functionality of the application.109Let'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::110access the root of the application (``/``). To do this, we add a new111test function to :file:`test_flaskr.py`, like this::11297 class FlaskrTestCase(unittest.TestCase):113 def test_empty_db(client):114 """Start with a blank database."""115 rv = client.get('/')116 assert b'No entries here so far' in rv.data11799 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()105106 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.data113118Notice that our test functions begin with the word `test`; this allows115:mod:`unittest` to automatically identify the method as a test to run.119`pytest`_ to automatically identify the function as a test to run.120117By using `self.app.get` we can send an HTTP ``GET`` request to the application with121By using `client.get` we can send an HTTP ``GET`` request to the application with122the given path. The return value will be a :class:`~flask.Flask.response_class` object.123We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect124the return value (as string) from the application. In this case, we ensure that125``'No entries here so far'`` is part of the output.126127Run it again and you should see one passing test::128125 $ python flaskr_tests.py126 .127 ----------------------------------------------------------------------128 Ran 1 test in 0.034s129 $ pytest -v130130 OK131 ================ test session starts ================132 rootdir: ./flask/examples/flaskr, inifile: setup.cfg133 collected 1 items134135 tests/test_flaskr.py::test_empty_db PASSED136137 ============= 1 passed in 0.10 seconds ==============138139Logging In and Out140------------------141142The majority of the functionality of our application is only available for
1 unmodified line
144of the application. To do this, we fire some requests to the login and logout145pages with the required form data (username and password). And because the146login and logout pages redirect, we tell the client to `follow_redirects`.147141Add the following two methods to your `FlaskrTestCase` class::148Add the following two functions to your :file:`test_flaskr.py` file::149143 def login(self, username, password):144 return self.app.post('/login', data=dict(145 username=username,146 password=password147 ), follow_redirects=True)150 def login(client, username, password):151 return client.post('/login', data=dict(152 username=username,153 password=password154 ), follow_redirects=True)155149 def logout(self):150 return self.app.get('/logout', follow_redirects=True)156 def logout(client):157 return client.get('/logout', follow_redirects=True)158159Now we can easily test that logging in and out works and that it fails with153invalid credentials. Add this new test to the class::160invalid credentials. Add this new test function::161155 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.data162 def test_login_logout(client):163 """Make sure login and logout works"""164 rv = login(client, flaskr.app.config['USERNAME'],165 flaskr.app.config['PASSWORD'])166 assert b'You were logged in' in rv.data167 rv = logout(client)168 assert b'You were logged out' in rv.data169 rv = login(client, flaskr.app.config['USERNAME'] + 'x',170 flaskr.app.config['PASSWORD'])171 assert b'Invalid username' in rv.data172 rv = login(client, flaskr.app.config['USERNAME'],173 flaskr.app.config['PASSWORD'] + 'x')174 assert b'Invalid password' in rv.data175176Test Adding Messages177--------------------178168We should also test that adding messages works. Add a new test method179We should also test that adding messages works. Add a new test function180like this::181171 def test_messages(self):172 self.login('admin', 'default')173 rv = self.app.post('/add', data=dict(182 def test_messages(client):183 """Test that messages work"""184 login(client, flaskr.app.config['USERNAME'],185 flaskr.app.config['PASSWORD'])186 rv = client.post('/add', data=dict(187 title='<Hello>',188 text='<strong>HTML</strong> allowed here'189 ), follow_redirects=True)190 assert b'No entries here so far' not in rv.data
4 unmodified lines
195which is the intended behavior.196197Running that should now give us three passing tests::198186 $ python flaskr_tests.py187 ...188 ----------------------------------------------------------------------189 Ran 3 tests in 0.332s199 $ pytest -v200191 OK201 ================ test session starts ================202 rootdir: ./flask/examples/flaskr, inifile: setup.cfg203 collected 3 items204205 tests/test_flaskr.py::test_empty_db PASSED206 tests/test_flaskr.py::test_login_logout PASSED207 tests/test_flaskr.py::test_messages PASSED208209 ============= 3 passed in 0.23 seconds ==============210211For more complex tests with headers and status codes, check out the212`MiniTwit Example`_ from the sources which contains a larger test213suite.214
161 unmodified lines
modified:flask/app.py+1 added-1 removed
220 unmodified lines
221 debug = ConfigAttribute('DEBUG')222223 #: The testing flag. Set this to ``True`` to enable the test mode of224 #: Flask extensions (and in the future probably also Flask itself).225 #: For example this might activate unittest helpers that have an225 #: For example this might activate test helpers that have an226 #: additional runtime cost which should not be enabled by default.227 #:228 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the229 #: default it's implicitly enabled.
1853 unmodified lines