Skip to content

Commit

Permalink
Chapter 15: Coverage metrics (15a)
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Mar 4, 2020
1 parent f5cecbd commit ca278c2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
27 changes: 26 additions & 1 deletion flasky.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import os

COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()

import sys
import click
from flask_migrate import Migrate
from app import create_app, db
Expand All @@ -15,12 +23,29 @@ def make_shell_context():


@app.cli.command()
@click.option('--coverage/--no-coverage', default=False,
help='Run tests under code coverage.')
@click.argument('test_names', nargs=-1)
def test(test_names):
def test(coverage, test_names):
"""Run the unit tests."""
if coverage and not os.environ.get('FLASK_COVERAGE'):
import subprocess
os.environ['FLASK_COVERAGE'] = '1'
sys.exit(subprocess.call(sys.argv))

import unittest
if test_names:
tests = unittest.TestLoader().loadTestsFromNames(test_names)

This comment has been minimized.

Copy link
@ezebunandu

ezebunandu Oct 27, 2020

Hi Miguel,

With loadTestsFromNames, would the correct usage to run only a subset of tests, for example, test_home_page be flask test test_home_page? I get a ModuleNotFoundError when I use it like this, and I am not sure what I'm missing.

Any pointers will be welcome. Thanks

This comment has been minimized.

Copy link
@miguelgrinberg

miguelgrinberg Oct 27, 2020

Author Owner

You have to provide the full path to the test, not just the test name. Example:

(venv) $ flask test tests.test_user_model.UserModelTestCase.test_valid_reset_token
test_valid_reset_token (tests.test_user_model.UserModelTestCase) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.250s

OK

This comment has been minimized.

Copy link
@ezebunandu

ezebunandu Nov 1, 2020

Thanks. I switched to the test runner in VSCode, as that allows me to select individual tests.

else:
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if COV:
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
basedir = os.path.abspath(os.path.dirname(__file__))
covdir = os.path.join(basedir, 'tmp/coverage')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
COV.erase()
1 change: 1 addition & 0 deletions requirements/dev.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
-r common.txt
certifi==2017.7.27.1
chardet==3.0.4
coverage==4.4.1
faker==0.7.18
httpie==0.9.9
idna==2.5
Expand Down

0 comments on commit ca278c2

Please sign in to comment.