Test Coverage

Writing unit tests for your application lets you check that the code you wrote works the way you expect. Flask provides a test client that simulates requests to the application and returns the response data.

You should test as much of your code as possible. Code in functions only runs when the function is called, and code in branches, such as if blocks, only runs when the condition is met. You want to make sure that each function is tested with data that covers each branch.

The closer you get to 100% coverage, the more comfortable you can be that making a change won’t unexpectedly change other behavior. However, 100% coverage doesn’t guarantee that your application doesn’t have bugs. In particular, it doesn’t test how the user interacts with the application in the browser. Despite this, test coverage is an important tool to use during development.

Note

This is being introduced late in the tutorial, but in your future projects you should test as you develop.

You’ll use pytest and coverage to test and measure your code. Install them both:

  1. $ pip install pytest coverage

Setup and Fixtures

The test code is located in the tests directory. This directory is next to the flaskr package, not inside it. The tests/conftest.py file contains setup functions called fixtures that each test will use. Tests are in Python modules that start with test_, and each test function in those modules also starts with test_.

Each test will create a new temporary database file and populate some data that will be used in the tests. Write a SQL file to insert that data.

tests/data.sql

  1. INSERT INTO user (username, password)
  2. VALUES
  3. ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),
  4. ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');
  5. INSERT INTO post (title, body, author_id, created)
  6. VALUES
  7. ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');

The app fixture will call the factory and pass test_config to configure the application and database for testing instead of using your local development configuration.

tests/conftest.py

  1. import os
  2. import tempfile
  3. import pytest
  4. from flaskr import create_app
  5. from flaskr.db import get_db, init_db
  6. with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:
  7. _data_sql = f.read().decode('utf8')
  8. @pytest.fixture
  9. def app():
  10. db_fd, db_path = tempfile.mkstemp()
  11. app = create_app({
  12. 'TESTING': True,
  13. 'DATABASE': db_path,
  14. })
  15. with app.app_context():
  16. init_db()
  17. get_db().executescript(_data_sql)
  18. yield app
  19. os.close(db_fd)
  20. os.unlink(db_path)
  21. @pytest.fixture
  22. def client(app):
  23. return app.test_client()
  24. @pytest.fixture
  25. def runner(app):
  26. return app.test_cli_runner()

tempfile.mkstemp() creates and opens a temporary file, returning the file descriptor and the path to it. The DATABASE path is overridden so it points to this temporary path instead of the instance folder. After setting the path, the database tables are created and the test data is inserted. After the test is over, the temporary file is closed and removed.

TESTING tells Flask that the app is in test mode. Flask changes some internal behavior so it’s easier to test, and other extensions can also use the flag to make testing them easier.

The client fixture calls app.test_client() with the application object created by the app fixture. Tests will use the client to make requests to the application without running the server.

The runner fixture is similar to client. app.test_cli_runner() creates a runner that can call the Click commands registered with the application.

Pytest uses fixtures by matching their function names with the names of arguments in the test functions. For example, the test_hello function you’ll write next takes a client argument. Pytest matches that with the client fixture function, calls it, and passes the returned value to the test function.

Factory

There’s not much to test about the factory itself. Most of the code will be executed for each test already, so if something fails the other tests will notice.

The only behavior that can change is passing test config. If config is not passed, there should be some default configuration, otherwise the configuration should be overridden.

tests/test_factory.py

  1. from flaskr import create_app
  2. def test_config():
  3. assert not create_app().testing
  4. assert create_app({'TESTING': True}).testing
  5. def test_hello(client):
  6. response = client.get('/hello')
  7. assert response.data == b'Hello, World!'

You added the hello route as an example when writing the factory at the beginning of the tutorial. It returns “Hello, World!”, so the test checks that the response data matches.

Database

Within an application context, get_db should return the same connection each time it’s called. After the context, the connection should be closed.

tests/test_db.py

  1. import sqlite3
  2. import pytest
  3. from flaskr.db import get_db
  4. def test_get_close_db(app):
  5. with app.app_context():
  6. db = get_db()
  7. assert db is get_db()
  8. with pytest.raises(sqlite3.ProgrammingError) as e:
  9. db.execute('SELECT 1')
  10. assert 'closed' in str(e.value)

The init-db command should call the init_db function and output a message.

tests/test_db.py

  1. def test_init_db_command(runner, monkeypatch):
  2. class Recorder(object):
  3. called = False
  4. def fake_init_db():
  5. Recorder.called = True
  6. monkeypatch.setattr('flaskr.db.init_db', fake_init_db)
  7. result = runner.invoke(args=['init-db'])
  8. assert 'Initialized' in result.output
  9. assert Recorder.called

This test uses Pytest’s monkeypatch fixture to replace the init_db function with one that records that it’s been called. The runner fixture you wrote above is used to call the init-db command by name.

Authentication

For most of the views, a user needs to be logged in. The easiest way to do this in tests is to make a POST request to the login view with the client. Rather than writing that out every time, you can write a class with methods to do that, and use a fixture to pass it the client for each test.

tests/conftest.py

  1. class AuthActions(object):
  2. def __init__(self, client):
  3. self._client = client
  4. def login(self, username='test', password='test'):
  5. return self._client.post(
  6. '/auth/login',
  7. data={'username': username, 'password': password}
  8. )
  9. def logout(self):
  10. return self._client.get('/auth/logout')
  11. @pytest.fixture
  12. def auth(client):
  13. return AuthActions(client)

With the auth fixture, you can call auth.login() in a test to log in as the test user, which was inserted as part of the test data in the app fixture.

The register view should render successfully on GET. On POST with valid form data, it should redirect to the login URL and the user’s data should be in the database. Invalid data should display error messages.

tests/test_auth.py

  1. import pytest
  2. from flask import g, session
  3. from flaskr.db import get_db
  4. def test_register(client, app):
  5. assert client.get('/auth/register').status_code == 200
  6. response = client.post(
  7. '/auth/register', data={'username': 'a', 'password': 'a'}
  8. )
  9. assert 'http://localhost/auth/login' == response.headers['Location']
  10. with app.app_context():
  11. assert get_db().execute(
  12. "select * from user where username = 'a'",
  13. ).fetchone() is not None
  14. @pytest.mark.parametrize(('username', 'password', 'message'), (
  15. ('', '', b'Username is required.'),
  16. ('a', '', b'Password is required.'),
  17. ('test', 'test', b'already registered'),
  18. ))
  19. def test_register_validate_input(client, username, password, message):
  20. response = client.post(
  21. '/auth/register',
  22. data={'username': username, 'password': password}
  23. )
  24. assert message in response.data

client.get() makes a GET request and returns the Response object returned by Flask. Similarly, client.post() makes a POST request, converting the data dict into form data.

To test that the page renders successfully, a simple request is made and checked for a 200 OK status_code. If rendering failed, Flask would return a 500 Internal Server Error code.

headers will have a Location header with the login URL when the register view redirects to the login view.

data contains the body of the response as bytes. If you expect a certain value to render on the page, check that it’s in data. Bytes must be compared to bytes. If you want to compare text, use get_data(as_text=True) instead.

pytest.mark.parametrize tells Pytest to run the same test function with different arguments. You use it here to test different invalid input and error messages without writing the same code three times.

The tests for the login view are very similar to those for register. Rather than testing the data in the database, session should have user_id set after logging in.

tests/test_auth.py

  1. def test_login(client, auth):
  2. assert client.get('/auth/login').status_code == 200
  3. response = auth.login()
  4. assert response.headers['Location'] == 'http://localhost/'
  5. with client:
  6. client.get('/')
  7. assert session['user_id'] == 1
  8. assert g.user['username'] == 'test'
  9. @pytest.mark.parametrize(('username', 'password', 'message'), (
  10. ('a', 'test', b'Incorrect username.'),
  11. ('test', 'a', b'Incorrect password.'),
  12. ))
  13. def test_login_validate_input(auth, username, password, message):
  14. response = auth.login(username, password)
  15. assert message in response.data

Using client in a with block allows accessing context variables such as session after the response is returned. Normally, accessing session outside of a request would raise an error.

Testing logout is the opposite of login. session should not contain user_id after logging out.

tests/test_auth.py

  1. def test_logout(client, auth):
  2. auth.login()
  3. with client:
  4. auth.logout()
  5. assert 'user_id' not in session

Blog

All the blog views use the auth fixture you wrote earlier. Call auth.login() and subsequent requests from the client will be logged in as the test user.

The index view should display information about the post that was added with the test data. When logged in as the author, there should be a link to edit the post.

You can also test some more authentication behavior while testing the index view. When not logged in, each page shows links to log in or register. When logged in, there’s a link to log out.

tests/test_blog.py

  1. import pytest
  2. from flaskr.db import get_db
  3. def test_index(client, auth):
  4. response = client.get('/')
  5. assert b"Log In" in response.data
  6. assert b"Register" in response.data
  7. auth.login()
  8. response = client.get('/')
  9. assert b'Log Out' in response.data
  10. assert b'test title' in response.data
  11. assert b'by test on 2018-01-01' in response.data
  12. assert b'test\nbody' in response.data
  13. assert b'href="/1/update"' in response.data

A user must be logged in to access the create, update, and delete views. The logged in user must be the author of the post to access update and delete, otherwise a 403 Forbidden status is returned. If a post with the given id doesn’t exist, update and delete should return 404 Not Found.

tests/test_blog.py

  1. @pytest.mark.parametrize('path', (
  2. '/create',
  3. '/1/update',
  4. '/1/delete',
  5. ))
  6. def test_login_required(client, path):
  7. response = client.post(path)
  8. assert response.headers['Location'] == 'http://localhost/auth/login'
  9. def test_author_required(app, client, auth):
  10. # change the post author to another user
  11. with app.app_context():
  12. db = get_db()
  13. db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
  14. db.commit()
  15. auth.login()
  16. # current user can't modify other user's post
  17. assert client.post('/1/update').status_code == 403
  18. assert client.post('/1/delete').status_code == 403
  19. # current user doesn't see edit link
  20. assert b'href="/1/update"' not in client.get('/').data
  21. @pytest.mark.parametrize('path', (
  22. '/2/update',
  23. '/2/delete',
  24. ))
  25. def test_exists_required(client, auth, path):
  26. auth.login()
  27. assert client.post(path).status_code == 404

The create and update views should render and return a 200 OK status for a GET request. When valid data is sent in a POST request, create should insert the new post data into the database, and update should modify the existing data. Both pages should show an error message on invalid data.

tests/test_blog.py

  1. def test_create(client, auth, app):
  2. auth.login()
  3. assert client.get('/create').status_code == 200
  4. client.post('/create', data={'title': 'created', 'body': ''})
  5. with app.app_context():
  6. db = get_db()
  7. count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]
  8. assert count == 2
  9. def test_update(client, auth, app):
  10. auth.login()
  11. assert client.get('/1/update').status_code == 200
  12. client.post('/1/update', data={'title': 'updated', 'body': ''})
  13. with app.app_context():
  14. db = get_db()
  15. post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
  16. assert post['title'] == 'updated'
  17. @pytest.mark.parametrize('path', (
  18. '/create',
  19. '/1/update',
  20. ))
  21. def test_create_update_validate(client, auth, path):
  22. auth.login()
  23. response = client.post(path, data={'title': '', 'body': ''})
  24. assert b'Title is required.' in response.data

The delete view should redirect to the index URL and the post should no longer exist in the database.

tests/test_blog.py

  1. def test_delete(client, auth, app):
  2. auth.login()
  3. response = client.post('/1/delete')
  4. assert response.headers['Location'] == 'http://localhost/'
  5. with app.app_context():
  6. db = get_db()
  7. post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
  8. assert post is None

Running the Tests

Some extra configuration, which is not required but makes running tests with coverage less verbose, can be added to the project’s setup.cfg file.

setup.cfg

  1. [tool:pytest]
  2. testpaths = tests
  3. [coverage:run]
  4. branch = True
  5. source =
  6. flaskr

To run the tests, use the pytest command. It will find and run all the test functions you’ve written.

  1. $ pytest
  2. ========================= test session starts ==========================
  3. platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0
  4. rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg
  5. collected 23 items
  6. tests/test_auth.py ........ [ 34%]
  7. tests/test_blog.py ............ [ 86%]
  8. tests/test_db.py .. [ 95%]
  9. tests/test_factory.py .. [100%]
  10. ====================== 24 passed in 0.64 seconds =======================

If any tests fail, pytest will show the error that was raised. You can run pytest -v to get a list of each test function rather than dots.

To measure the code coverage of your tests, use the coverage command to run pytest instead of running it directly.

  1. $ coverage run -m pytest

You can either view a simple coverage report in the terminal:

  1. $ coverage report
  2. Name Stmts Miss Branch BrPart Cover
  3. ------------------------------------------------------
  4. flaskr/__init__.py 21 0 2 0 100%
  5. flaskr/auth.py 54 0 22 0 100%
  6. flaskr/blog.py 54 0 16 0 100%
  7. flaskr/db.py 24 0 4 0 100%
  8. ------------------------------------------------------
  9. TOTAL 153 0 44 0 100%

An HTML report allows you to see which lines were covered in each file:

  1. $ coverage html

This generates files in the htmlcov directory. Open htmlcov/index.html in your browser to see the report.

Continue to Deploy to Production.