Skip to content
Myr

tests.rst

This file

Path

docs/tutorial/tests.rst

559 lines · 17.8 KiB

Last changed by

Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9

History of this file

Take it

1.. currentmodule:: flask23Test Coverage4=============56Writing unit tests for your application lets you check that the code7you wrote works the way you expect. Flask provides a test client that8simulates requests to the application and returns the response data.910You should test as much of your code as possible. Code in functions only11runs when the function is called, and code in branches, such as ``if``12blocks, only runs when the condition is met. You want to make sure that13each function is tested with data that covers each branch.1415The closer you get to 100% coverage, the more comfortable you can be16that making a change won't unexpectedly change other behavior. However,17100% coverage doesn't guarantee that your application doesn't have bugs.18In particular, it doesn't test how the user interacts with the19application in the browser. Despite this, test coverage is an important20tool to use during development.2122.. note::23    This is being introduced late in the tutorial, but in your future24    projects you should test as you develop.2526You'll use `pytest`_ and `coverage`_ to test and measure your code.27Install them both:2829.. code-block:: none3031    $ pip install pytest coverage3233.. _pytest: https://pytest.readthedocs.io/34.. _coverage: https://coverage.readthedocs.io/353637Setup and Fixtures38------------------3940The test code is located in the ``tests`` directory. This directory is41*next to* the ``flaskr`` package, not inside it. The42``tests/conftest.py`` file contains setup functions called *fixtures*43that each test will use. Tests are in Python modules that start with44``test_``, and each test function in those modules also starts with45``test_``.4647Each test will create a new temporary database file and populate some48data that will be used in the tests. Write a SQL file to insert that49data.5051.. code-block:: sql52    :caption: ``tests/data.sql``5354    INSERT INTO user (username, password)55    VALUES56      ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),57      ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');5859    INSERT INTO post (title, body, author_id, created)60    VALUES61      ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');6263The ``app`` fixture will call the factory and pass ``test_config`` to64configure the application and database for testing instead of using your65local development configuration.6667.. code-block:: python68    :caption: ``tests/conftest.py``6970    import os71    import tempfile7273    import pytest74    from flaskr import create_app75    from flaskr.db import get_db, init_db7677    with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:78        _data_sql = f.read().decode('utf8')798081    @pytest.fixture82    def app():83        db_fd, db_path = tempfile.mkstemp()8485        app = create_app({86            'TESTING': True,87            'DATABASE': db_path,88        })8990        with app.app_context():91            init_db()92            get_db().executescript(_data_sql)9394        yield app9596        os.close(db_fd)97        os.unlink(db_path)9899100    @pytest.fixture101    def client(app):102        return app.test_client()103104105    @pytest.fixture106    def runner(app):107        return app.test_cli_runner()108109:func:`tempfile.mkstemp` creates and opens a temporary file, returning110the file descriptor and the path to it. The ``DATABASE`` path is111overridden so it points to this temporary path instead of the instance112folder. After setting the path, the database tables are created and the113test data is inserted. After the test is over, the temporary file is114closed and removed.115116:data:`TESTING` tells Flask that the app is in test mode. Flask changes117some internal behavior so it's easier to test, and other extensions can118also use the flag to make testing them easier.119120The ``client`` fixture calls121:meth:`app.test_client() <Flask.test_client>` with the application122object created by the ``app`` fixture. Tests will use the client to make123requests to the application without running the server.124125The ``runner`` fixture is similar to ``client``.126:meth:`app.test_cli_runner() <Flask.test_cli_runner>` creates a runner127that can call the Click commands registered with the application.128129Pytest uses fixtures by matching their function names with the names130of arguments in the test functions. For example, the ``test_hello``131function you'll write next takes a ``client`` argument. Pytest matches132that with the ``client`` fixture function, calls it, and passes the133returned value to the test function.134135136Factory137-------138139There's not much to test about the factory itself. Most of the code will140be executed for each test already, so if something fails the other tests141will notice.142143The only behavior that can change is passing test config. If config is144not passed, there should be some default configuration, otherwise the145configuration should be overridden.146147.. code-block:: python148    :caption: ``tests/test_factory.py``149150    from flaskr import create_app151152153    def test_config():154        assert not create_app().testing155        assert create_app({'TESTING': True}).testing156157158    def test_hello(client):159        response = client.get('/hello')160        assert response.data == b'Hello, World!'161162You added the ``hello`` route as an example when writing the factory at163the beginning of the tutorial. It returns "Hello, World!", so the test164checks that the response data matches.165166167Database168--------169170Within an application context, ``get_db`` should return the same171connection each time it's called. After the context, the connection172should be closed.173174.. code-block:: python175    :caption: ``tests/test_db.py``176177    import sqlite3178179    import pytest180    from flaskr.db import get_db181182183    def test_get_close_db(app):184        with app.app_context():185            db = get_db()186            assert db is get_db()187188        with pytest.raises(sqlite3.ProgrammingError) as e:189            db.execute('SELECT 1')190191        assert 'closed' in str(e.value)192193The ``init-db`` command should call the ``init_db`` function and output194a message.195196.. code-block:: python197    :caption: ``tests/test_db.py``198199    def test_init_db_command(runner, monkeypatch):200        class Recorder(object):201            called = False202203        def fake_init_db():204            Recorder.called = True205206        monkeypatch.setattr('flaskr.db.init_db', fake_init_db)207        result = runner.invoke(args=['init-db'])208        assert 'Initialized' in result.output209        assert Recorder.called210211This test uses Pytest's ``monkeypatch`` fixture to replace the212``init_db`` function with one that records that it's been called. The213``runner`` fixture you wrote above is used to call the ``init-db``214command by name.215216217Authentication218--------------219220For most of the views, a user needs to be logged in. The easiest way to221do this in tests is to make a ``POST`` request to the ``login`` view222with the client. Rather than writing that out every time, you can write223a class with methods to do that, and use a fixture to pass it the client224for each test.225226.. code-block:: python227    :caption: ``tests/conftest.py``228229    class AuthActions(object):230        def __init__(self, client):231            self._client = client232233        def login(self, username='test', password='test'):234            return self._client.post(235                '/auth/login',236                data={'username': username, 'password': password}237            )238239        def logout(self):240            return self._client.get('/auth/logout')241242243    @pytest.fixture244    def auth(client):245        return AuthActions(client)246247With the ``auth`` fixture, you can call ``auth.login()`` in a test to248log in as the ``test`` user, which was inserted as part of the test249data in the ``app`` fixture.250251The ``register`` view should render successfully on ``GET``. On ``POST``252with valid form data, it should redirect to the login URL and the user's253data should be in the database. Invalid data should display error254messages.255256.. code-block:: python257    :caption: ``tests/test_auth.py``258259    import pytest260    from flask import g, session261    from flaskr.db import get_db262263264    def test_register(client, app):265        assert client.get('/auth/register').status_code == 200266        response = client.post(267            '/auth/register', data={'username': 'a', 'password': 'a'}268        )269        assert response.headers["Location"] == "/auth/login"270271        with app.app_context():272            assert get_db().execute(273                "SELECT * FROM user WHERE username = 'a'",274            ).fetchone() is not None275276277    @pytest.mark.parametrize(('username', 'password', 'message'), (278        ('', '', b'Username is required.'),279        ('a', '', b'Password is required.'),280        ('test', 'test', b'already registered'),281    ))282    def test_register_validate_input(client, username, password, message):283        response = client.post(284            '/auth/register',285            data={'username': username, 'password': password}286        )287        assert message in response.data288289:meth:`client.get() <werkzeug.test.Client.get>` makes a ``GET`` request290and returns the :class:`Response` object returned by Flask. Similarly,291:meth:`client.post() <werkzeug.test.Client.post>` makes a ``POST``292request, converting the ``data`` dict into form data.293294To test that the page renders successfully, a simple request is made and295checked for a ``200 OK`` :attr:`~Response.status_code`. If296rendering failed, Flask would return a ``500 Internal Server Error``297code.298299:attr:`~Response.headers` will have a ``Location`` header with the login300URL when the register view redirects to the login view.301302:attr:`~Response.data` contains the body of the response as bytes. If303you expect a certain value to render on the page, check that it's in304``data``. Bytes must be compared to bytes. If you want to compare text,305use :meth:`get_data(as_text=True) <werkzeug.wrappers.Response.get_data>`306instead.307308``pytest.mark.parametrize`` tells Pytest to run the same test function309with different arguments. You use it here to test different invalid310input and error messages without writing the same code three times.311312The tests for the ``login`` view are very similar to those for313``register``. Rather than testing the data in the database,314:data:`session` should have ``user_id`` set after logging in.315316.. code-block:: python317    :caption: ``tests/test_auth.py``318319    def test_login(client, auth):320        assert client.get('/auth/login').status_code == 200321        response = auth.login()322        assert response.headers["Location"] == "/"323324        with client:325            client.get('/')326            assert session['user_id'] == 1327            assert g.user['username'] == 'test'328329330    @pytest.mark.parametrize(('username', 'password', 'message'), (331        ('a', 'test', b'Incorrect username.'),332        ('test', 'a', b'Incorrect password.'),333    ))334    def test_login_validate_input(auth, username, password, message):335        response = auth.login(username, password)336        assert message in response.data337338Using ``client`` in a ``with`` block allows accessing context variables339such as :data:`session` after the response is returned. Normally,340accessing ``session`` outside of a request would raise an error.341342Testing ``logout`` is the opposite of ``login``. :data:`session` should343not contain ``user_id`` after logging out.344345.. code-block:: python346    :caption: ``tests/test_auth.py``347348    def test_logout(client, auth):349        auth.login()350351        with client:352            auth.logout()353            assert 'user_id' not in session354355356Blog357----358359All the blog views use the ``auth`` fixture you wrote earlier. Call360``auth.login()`` and subsequent requests from the client will be logged361in as the ``test`` user.362363The ``index`` view should display information about the post that was364added with the test data. When logged in as the author, there should be365a link to edit the post.366367You can also test some more authentication behavior while testing the368``index`` view. When not logged in, each page shows links to log in or369register. When logged in, there's a link to log out.370371.. code-block:: python372    :caption: ``tests/test_blog.py``373374    import pytest375    from flaskr.db import get_db376377378    def test_index(client, auth):379        response = client.get('/')380        assert b"Log In" in response.data381        assert b"Register" in response.data382383        auth.login()384        response = client.get('/')385        assert b'Log Out' in response.data386        assert b'test title' in response.data387        assert b'by test on 2018-01-01' in response.data388        assert b'test\nbody' in response.data389        assert b'href="/1/update"' in response.data390391A user must be logged in to access the ``create``, ``update``, and392``delete`` views. The logged in user must be the author of the post to393access ``update`` and ``delete``, otherwise a ``403 Forbidden`` status394is returned. If a ``post`` with the given ``id`` doesn't exist,395``update`` and ``delete`` should return ``404 Not Found``.396397.. code-block:: python398    :caption: ``tests/test_blog.py``399400    @pytest.mark.parametrize('path', (401        '/create',402        '/1/update',403        '/1/delete',404    ))405    def test_login_required(client, path):406        response = client.post(path)407        assert response.headers["Location"] == "/auth/login"408409410    def test_author_required(app, client, auth):411        # change the post author to another user412        with app.app_context():413            db = get_db()414            db.execute('UPDATE post SET author_id = 2 WHERE id = 1')415            db.commit()416417        auth.login()418        # current user can't modify other user's post419        assert client.post('/1/update').status_code == 403420        assert client.post('/1/delete').status_code == 403421        # current user doesn't see edit link422        assert b'href="/1/update"' not in client.get('/').data423424425    @pytest.mark.parametrize('path', (426        '/2/update',427        '/2/delete',428    ))429    def test_exists_required(client, auth, path):430        auth.login()431        assert client.post(path).status_code == 404432433The ``create`` and ``update`` views should render and return a434``200 OK`` status for a ``GET`` request. When valid data is sent in a435``POST`` request, ``create`` should insert the new post data into the436database, and ``update`` should modify the existing data. Both pages437should show an error message on invalid data.438439.. code-block:: python440    :caption: ``tests/test_blog.py``441442    def test_create(client, auth, app):443        auth.login()444        assert client.get('/create').status_code == 200445        client.post('/create', data={'title': 'created', 'body': ''})446447        with app.app_context():448            db = get_db()449            count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]450            assert count == 2451452453    def test_update(client, auth, app):454        auth.login()455        assert client.get('/1/update').status_code == 200456        client.post('/1/update', data={'title': 'updated', 'body': ''})457458        with app.app_context():459            db = get_db()460            post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()461            assert post['title'] == 'updated'462463464    @pytest.mark.parametrize('path', (465        '/create',466        '/1/update',467    ))468    def test_create_update_validate(client, auth, path):469        auth.login()470        response = client.post(path, data={'title': '', 'body': ''})471        assert b'Title is required.' in response.data472473The ``delete`` view should redirect to the index URL and the post should474no longer exist in the database.475476.. code-block:: python477    :caption: ``tests/test_blog.py``478479    def test_delete(client, auth, app):480        auth.login()481        response = client.post('/1/delete')482        assert response.headers["Location"] == "/"483484        with app.app_context():485            db = get_db()486            post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()487            assert post is None488489490Running the Tests491-----------------492493Some extra configuration, which is not required but makes running tests with coverage494less verbose, can be added to the project's ``pyproject.toml`` file.495496.. code-block:: toml497    :caption: ``pyproject.toml``498499    [tool.pytest.ini_options]500    testpaths = ["tests"]501502    [tool.coverage.run]503    branch = true504    source = ["flaskr"]505506To run the tests, use the ``pytest`` command. It will find and run all507the test functions you've written.508509.. code-block:: none510511    $ pytest512513    ========================= test session starts ==========================514    platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0515    rootdir: /home/user/Projects/flask-tutorial516    collected 23 items517518    tests/test_auth.py ........                                      [ 34%]519    tests/test_blog.py ............                                  [ 86%]520    tests/test_db.py ..                                              [ 95%]521    tests/test_factory.py ..                                         [100%]522523    ====================== 24 passed in 0.64 seconds =======================524525If any tests fail, pytest will show the error that was raised. You can526run ``pytest -v`` to get a list of each test function rather than dots.527528To measure the code coverage of your tests, use the ``coverage`` command529to run pytest instead of running it directly.530531.. code-block:: none532533    $ coverage run -m pytest534535You can either view a simple coverage report in the terminal:536537.. code-block:: none538539    $ coverage report540541    Name                 Stmts   Miss Branch BrPart  Cover542    ------------------------------------------------------543    flaskr/__init__.py      21      0      2      0   100%544    flaskr/auth.py          54      0     22      0   100%545    flaskr/blog.py          54      0     16      0   100%546    flaskr/db.py            24      0      4      0   100%547    ------------------------------------------------------548    TOTAL                  153      0     44      0   100%549550An HTML report allows you to see which lines were covered in each file:551552.. code-block:: none553554    $ coverage html555556This generates files in the ``htmlcov`` directory. Open557``htmlcov/index.html`` in your browser to see the report.558559Continue to :doc:`deploy`.