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
Provenance
- Commit
65fc888- Tree
dd0bede- Author
Neil Grey <neil.grey@shotgunsoftware.com>- Committer
Neil Grey <neil.grey@shotgunsoftware.com>- Parent
0c94908
3 files changed+111 added−93 removed
modified:docs/signals.rst+2 added-2 removed
25 unmodified lines26 executed in undefined order and do not modify any data.27 28 The big advantage of signals over handlers is that you can safely29 subscribe to them for just a split second. These temporary30-subscriptions are helpful for unittesting for example. Say you want to30+subscriptions are helpful for unit testing for example. Say you want to31 know what templates were rendered as part of a request: signals allow you32 to do exactly that.33 34 Subscribing to Signals9 unmodified lines44 signal. When you subscribe to a signal, be sure to also provide a sender45 unless you really want to listen for signals from all applications. This is46 especially true if you are developing an extension.47 48-For example, here is a helper context manager that can be used in a unittest48+For example, here is a helper context manager that can be used in a unit test49 to determine which templates were rendered and what variables were passed50 to the template::51 52 from flask import template_rendered138 unmodified linesmodified:docs/testing.rst+108 added-90 removed
3 unmodified lines4 ==========================5 6 **Something that is untested is broken.**7 8-The origin of this quote is unknown and while it is not entirely correct, it is also9-not far from the truth. Untested applications make it hard to8+The origin of this quote is unknown and while it is not entirely correct, it9+is also not far from the truth. Untested applications make it hard to10 improve existing code and developers of untested applications tend to11 become pretty paranoid. If an application has automated tests, you can12 safely make changes and instantly know if anything breaks.13 14 Flask provides a way to test your application by exposing the Werkzeug15 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 documentation17-we will use the :mod:`unittest` package that comes pre-installed with Python.16+You can then use that with your favourite testing solution.17 18+In this documentation we will use the `pytest`_ package as the base19+framework for our tests. You can install it with ``pip``, like so::20+21+ pip install pytest22+23+.. _pytest:24+ https://pytest.org25+26 The Application27 ---------------28 29 First, we need an application to test; we will use the application from30 the :ref:`tutorial`. If you don't have that application yet, get the24-sources from `the examples`_.31+source code from `the examples`_.32 33 .. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/35 36 The Testing Skeleton37 --------------------38 32-In order to test the application, we add a second module33-(:file:`flaskr_tests.py`) and create a unittest skeleton there::39+We begin by adding a tests directory under the application root. Then40+create a Python file to store our tests (:file:`test_flaskr.py`). When we41+format the filename like ``test_*.py``, it will be auto-discoverable by42+pytest.43 44+Next, we create a `pytest fixture`_ called45+:func:`client` that configures46+the application for testing and initializes a new database.::47+48 import os36- from flaskr import flaskr37- import unittest49 import tempfile50+ import pytest51+ from flaskr import flaskr52 40- 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()60 42- 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()48-49- 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)65 53- if __name__ == '__main__':54- unittest.main()66+ return client67 56-The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57-client and initializes a new database. This function is called before58-each individual test function is run. To delete the database after the59-test, 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 error62-catching during request handling so that you get better error reports when63-performing test requests against the application.68+This client fixture will be called by each individual test. It gives us a69+simple interface to the application, where we can trigger test requests to the70+application. The client will also keep track of cookies for us.71 65-This test client will give us a simple interface to the application. We can66-trigger test requests to the application, and the client will also keep track67-of cookies for us.72+During setup, the ``TESTING`` config flag is activated. What73+this does is disable error catching during request handling, so that74+you get better error reports when performing test requests against the75+application.76 69-Because SQLite3 is filesystem-based we can easily use the tempfile module77+Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module78 to create a temporary database and initialize it. The79 :func:`~tempfile.mkstemp` function does two things for us: it returns a80 low-level file handle and a random file name, the latter we use as81 database name. We just have to keep the `db_fd` around so that we can use82 the :func:`os.close` function to close the file.83 84+To delete the database after the test, we close the file and remove it85+from the filesystem in the86+:func:`teardown` function.87+88 If we now run the test suite, we should see the following output::89 78- $ python flaskr_tests.py90+ $ pytest91 80- ----------------------------------------------------------------------81- Ran 0 tests in 0.000s92+ ================ test session starts ================93+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg94+ collected 0 items95 83- OK96+ =========== no tests ran in 0.07 seconds ============97 85-Even though it did not run any actual tests, we already know that our flaskr98+Even though it did not run any actual tests, we already know that our ``flaskr``99 application is syntactically valid, otherwise the import would have died100 with an exception.101 102+.. _pytest fixture:103+ https://docs.pytest.org/en/latest/fixture.html104+105 The First Test106 --------------107 108 Now it's time to start testing the functionality of the application.109 Let's check that the application shows "No entries here so far" if we94-access the root of the application (``/``). To do this, we add a new95-test method to our class, like this::110+access the root of the application (``/``). To do this, we add a new111+test function to :file:`test_flaskr.py`, like this::112 97- 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.data117 99- 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()105-106- def tearDown(self):107- os.close(self.db_fd)108- os.unlink(flaskr.app.config['DATABASE'])109-110- def test_empty_db(self):111- rv = self.app.get('/')112- assert b'No entries here so far' in rv.data113-118 Notice 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.120 117-By using `self.app.get` we can send an HTTP ``GET`` request to the application with121+By using `client.get` we can send an HTTP ``GET`` request to the application with122 the given path. The return value will be a :class:`~flask.Flask.response_class` object.123 We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect124 the return value (as string) from the application. In this case, we ensure that125 ``'No entries here so far'`` is part of the output.126 127 Run it again and you should see one passing test::128 125- $ python flaskr_tests.py126- .127- ----------------------------------------------------------------------128- Ran 1 test in 0.034s129+ $ pytest -v130 130- OK131+ ================ test session starts ================132+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg133+ collected 1 items134 135+ tests/test_flaskr.py::test_empty_db PASSED136+137+ ============= 1 passed in 0.10 seconds ==============138+139 Logging In and Out140 ------------------141 142 The majority of the functionality of our application is only available for1 unmodified line144 of the application. To do this, we fire some requests to the login and logout145 pages with the required form data (username and password). And because the146 login and logout pages redirect, we tell the client to `follow_redirects`.147 141-Add the following two methods to your `FlaskrTestCase` class::148+Add the following two functions to your :file:`test_flaskr.py` file::149 143- 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)155 149- def logout(self):150- return self.app.get('/logout', follow_redirects=True)156+ def logout(client):157+ return client.get('/logout', follow_redirects=True)158 159 Now we can easily test that logging in and out works and that it fails with153-invalid credentials. Add this new test to the class::160+invalid credentials. Add this new test function::161 155- 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.data175 176 Test Adding Messages177 --------------------178 168-We should also test that adding messages works. Add a new test method179+We should also test that adding messages works. Add a new test function180 like this::181 171- 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.data4 unmodified lines195 which is the intended behavior.196 197 Running that should now give us three passing tests::198 186- $ python flaskr_tests.py187- ...188- ----------------------------------------------------------------------189- Ran 3 tests in 0.332s199+ $ pytest -v200 191- OK201+ ================ test session starts ================202+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg203+ collected 3 items204 205+ tests/test_flaskr.py::test_empty_db PASSED206+ tests/test_flaskr.py::test_login_logout PASSED207+ tests/test_flaskr.py::test_messages PASSED208+209+ ============= 3 passed in 0.23 seconds ==============210+211 For more complex tests with headers and status codes, check out the212 `MiniTwit Example`_ from the sources which contains a larger test213 suite.214 161 unmodified linesmodified:flask/app.py+1 added-1 removed
220 unmodified lines221 debug = ConfigAttribute('DEBUG')222 223 #: 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