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
Provenance
- Commit
cd593bf- Tree
d44b1df- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
54a18a5- Parent 2
8858135
4 files changed+117 added−101 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+111 added-91 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 40- class FlaskrTestCase(unittest.TestCase):51+ import pytest52 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()53+ from flaskr import flaskr54 49- def tearDown(self):50- os.close(self.db_fd)51- os.unlink(flaskr.app.config['DATABASE'])55 53- 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()61 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.62+ with flaskr.app.app_context():63+ flaskr.init_db()64 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.65+ yield client66 67+ os.close(db_fd)68+ os.unlink(flaskr.app.config['DATABASE'])69+70+This client fixture will be called by each individual test. It gives us a71+simple interface to the application, where we can trigger test requests to the72+application. The client will also keep track of cookies for us.73+74+During setup, the ``TESTING`` config flag is activated. What75+this does is disable error catching during request handling, so that76+you get better error reports when performing test requests against the77+application.78+69-Because SQLite3 is filesystem-based we can easily use the tempfile module79+Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module80 to create a temporary database and initialize it. The81 :func:`~tempfile.mkstemp` function does two things for us: it returns a82 low-level file handle and a random file name, the latter we use as83 database name. We just have to keep the `db_fd` around so that we can use84 the :func:`os.close` function to close the file.85 86+To delete the database after the test, the fixture closes the file and removes87+it from the filesystem.88+89 If we now run the test suite, we should see the following output::90 78- $ python flaskr_tests.py91+ $ pytest92 80- ----------------------------------------------------------------------81- Ran 0 tests in 0.000s93+ ================ test session starts ================94+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg95+ collected 0 items96 83- OK97+ =========== no tests ran in 0.07 seconds ============98 85-Even though it did not run any actual tests, we already know that our flaskr99+Even though it did not run any actual tests, we already know that our ``flaskr``100 application is syntactically valid, otherwise the import would have died101 with an exception.102 103+.. _pytest fixture:104+ https://docs.pytest.org/en/latest/fixture.html105+106 The First Test107 --------------108 109 Now it's time to start testing the functionality of the application.110 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::111+access the root of the application (``/``). To do this, we add a new112+test function to :file:`test_flaskr.py`, like this::113 97- class FlaskrTestCase(unittest.TestCase):114+ def test_empty_db(client):115+ """Start with a blank database."""116 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()117+ rv = client.get('/')118+ assert b'No entries here so far' in rv.data119 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-120 Notice 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.122 117-By using `self.app.get` we can send an HTTP ``GET`` request to the application with123+By using ``client.get`` we can send an HTTP ``GET`` request to the application with124 the given path. The return value will be a :class:`~flask.Flask.response_class` object.125 We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126 the return value (as string) from the application. In this case, we ensure that127 ``'No entries here so far'`` is part of the output.128 129 Run it again and you should see one passing test::130 125- $ python flaskr_tests.py126- .127- ----------------------------------------------------------------------128- Ran 1 test in 0.034s131+ $ pytest -v132 130- OK133+ ================ test session starts ================134+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg135+ collected 1 items136 137+ tests/test_flaskr.py::test_empty_db PASSED138+139+ ============= 1 passed in 0.10 seconds ==============140+141 Logging In and Out142 ------------------143 144 The majority of the functionality of our application is only available for1 unmodified line146 of the application. To do this, we fire some requests to the login and logout147 pages with the required form data (username and password). And because the148 login and logout pages redirect, we tell the client to `follow_redirects`.149 141-Add the following two methods to your `FlaskrTestCase` class::150+Add the following two functions to your :file:`test_flaskr.py` file::151 143- 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)157 149- def logout(self):150- return self.app.get('/logout', follow_redirects=True)158 159+ def logout(client):160+ return client.get('/logout', follow_redirects=True)161+162 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::163+invalid credentials. Add this new test function::164 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.data165+ def test_login_logout(client):166+ """Make sure login and logout works."""167 168+ rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])169+ assert b'You were logged in' in rv.data170+171+ rv = logout(client)172+ assert b'You were logged out' in rv.data173+174+ rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])175+ assert b'Invalid username' in rv.data176+177+ rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')178+ assert b'Invalid password' in rv.data179+180 Test Adding Messages181 --------------------182 168-We should also test that adding messages works. Add a new test method183+We should also test that adding messages works. Add a new test function184 like this::185 171- 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."""188+189+ 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.data4 unmodified lines199 which is the intended behavior.200 201 Running that should now give us three passing tests::202 186- $ python flaskr_tests.py187- ...188- ----------------------------------------------------------------------189- Ran 3 tests in 0.332s203+ $ pytest -v204 191- OK205+ ================ test session starts ================206+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg207+ collected 3 items208 209+ tests/test_flaskr.py::test_empty_db PASSED210+ tests/test_flaskr.py::test_login_logout PASSED211+ tests/test_flaskr.py::test_messages PASSED212+213+ ============= 3 passed in 0.23 seconds ==============214+215 For more complex tests with headers and status codes, check out the216 `MiniTwit Example`_ from the sources which contains a larger test217 suite.218 197-219 .. _MiniTwit Example:220 https://github.com/pallets/flask/tree/master/examples/minitwit/221 201-222 Other Testing Tricks223 --------------------224 225 Besides using the test client as shown above, there is also the152 unmodified linesmodified:examples/flaskr/tests/test_flaskr.py+3 added-7 removed
20 unmodified lines21 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'])28 26- def teardown():27- os.close(db_fd)28- os.unlink(flaskr.app.config['DATABASE'])29- request.addfinalizer(teardown)29 31- return client32-33-30 def login(client, username, password):31 return client.post('/login', data=dict(32 username=username,33 password=password39 unmodified linesmodified:flask/app.py+1 added-1 removed
218 unmodified lines219 debug = ConfigAttribute('DEBUG')220 221 #: 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