Skip to content

Commit

Permalink
add tests for coverage.
Browse files Browse the repository at this point in the history
  • Loading branch information
schettino72 committed Mar 13, 2014
1 parent bad757d commit c28d34b
Show file tree
Hide file tree
Showing 2 changed files with 136 additions and 33 deletions.
82 changes: 59 additions & 23 deletions doitpy/coverage.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,66 @@
"""
'''
create tasks for coverage.py
* test files must be named in format 'test_xxx.py'
* packages does not contain sub-packages
"""
Usage
------
Add coverage related tasks to ``dodo.py``::
from doitpy.coverage import Coverage, PythonPackage
def task_coverage():
"""show coverage for all modules including tests"""
cov = Coverage([PythonPackage('my_pkg_name', 'tests')],
config=Config(branch=False, parallel=True,
omit=['tests/no_cover.py'],)
)
yield cov.all() # create task `coverage`
yield cov.src() # create task `coverage_src`
yield cov.by_module() # create tasks `coverage_module:<path/to/test>`
From command line, list and execute tasks::
$ doit list
$ doit coverage
'''

import glob

from .config import Config


def sep(*args, separator=' '):
"""join strings or list of strings ignoring None values"""
return separator.join(a for a in args if a)


class PythonPackage(object):
"""Contain list of modules of the package (does not handle sub-packages)
"""

# TODO should track sub-packages
config = Config(
test_prefix = 'test_',
pkg_test_dir = 'tests',
)

def __init__(self, path, test_path=None, config=None):
"""if test_path is not given assume it is 'tests' inside source package"""
"""
:param (str / pathlib.Path) path: dir path to package.
:param (str / pathlib.Path) test_path: if test_path is not given assume
it is on config.pkg_test_dir inside source package.
"""
self.config = self.config.make(config)
self.test_prefix = self.config['test_prefix']

self.src_base = path if path else ''
self.src_base = str(path) if path else ''
if test_path is None:
self.test_base = '{}/{}'.format(self.src_base,
self.config['pkg_test_dir'])
else:
self.test_base = test_path
self.test_base = str(test_path)
self.src = glob.glob("{}/*.py".format(self.src_base))
self.test = glob.glob("{}/*.py".format(self.test_base))
self.test_files = glob.glob("{}/{}*.py".format(
Expand Down Expand Up @@ -55,27 +89,29 @@ def __init__(self, pkgs, config=None):
self.pkgs.append(PythonPackage(pkg))


def _action_list(self, modules, test=''):
run_options = ''
def _action_list(self, modules, test=None):
"""return list of actions to be used in a doit task"""
run_options = []
if self.config['branch']:
run_options += '--branch '
run_options.append('--branch')
if self.config['parallel']:
run_options += '--parallel-mode '
run_options.append('--parallel-mode')

report_options = ''
report_options = []
if self.config['omit']:
report_options += '--omit {}'.format(','.join(self.config['omit']))
omit_list = ','.join(self.config['omit'])
report_options.append('--omit {}'.format(omit_list))

actions = ["coverage run {} {} {}".format(
run_options, self.config['cmd_run_test'], test)]
actions = [sep("coverage run", sep(*run_options),
self.config['cmd_run_test'], test)]
if self.config['parallel']:
actions.append('coverage combine')
actions.append("coverage report --show-missing {} {}".format(
report_options, " ".join(modules)))
actions.append(sep("coverage report --show-missing",
sep(*report_options), sep(*modules)))
return actions


def all(self):
def all(self, basename='coverage'):
"""show coverage for all modules including tests"""
all_modules = []

Expand All @@ -84,13 +120,13 @@ def all(self):
all_modules.append(module)

yield {
'basename': 'coverage',
'basename': basename,
'actions': self._action_list(all_modules),
'verbosity': 2,
}


def src(self):
def src(self, basename='coverage_src'):
"""show coverage for all modules (exclude tests)"""
all_modules = []

Expand All @@ -99,13 +135,13 @@ def src(self):
all_modules.append(module)

yield {
'basename': 'coverage_src',
'basename': basename,
'actions': self._action_list(all_modules),
'verbosity': 2,
}


def by_module(self):
def by_module(self, basename='coverage_module'):
"""show coverage for individual modules"""
for pkg in self.pkgs:
to_strip = len('{}/{}'.format(pkg.test_base, pkg.test_prefix))
Expand All @@ -114,7 +150,7 @@ def by_module(self):
for test in tests:
source = pkg.src_base + '/' + test[to_strip:]
yield {
'basename': 'coverage_module',
'basename': basename,
'name': test,
'actions': self._action_list([source, test], test),
'verbosity': 2,
Expand Down
87 changes: 77 additions & 10 deletions tests/test_coverage.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,95 @@
from pathlib import Path

from doitpy.coverage import PythonPackage
from doitpy.config import Config
from doitpy.coverage import PythonPackage, Coverage

TEST_PATH = Path(__file__).parent

SAMPLE = TEST_PATH / 'sample' # path to sample project

class TestPythonPackage(object):
def test_init_tests_in_package(self):
pkg = PythonPackage(TEST_PATH / 'sample')
assert pkg.test_base == str(TEST_PATH / 'sample/tests')
pkg = PythonPackage(SAMPLE)
assert pkg.test_base == str(SAMPLE / 'tests')
assert len(pkg.src) == 2
assert str(TEST_PATH / 'sample/flake_ok.py') in pkg.src
assert str(TEST_PATH / 'sample/flake_fail.py') in pkg.src
assert str(SAMPLE / 'flake_ok.py') in pkg.src
assert str(SAMPLE / 'flake_fail.py') in pkg.src
assert len(pkg.test) == 1
assert str(TEST_PATH / 'sample/tests/test_flake_ok.py') in pkg.test
assert str(SAMPLE / 'tests/test_flake_ok.py') in pkg.test
assert pkg.test == pkg.test_files

def test_init_test_path(self):
pkg = PythonPackage(TEST_PATH / 'sample',
pkg = PythonPackage(SAMPLE,
test_path=str(TEST_PATH/'test2'))
assert pkg.test_base == str(TEST_PATH / 'test2')

def test_all_modules(self):
pkg = PythonPackage(TEST_PATH / 'sample')
pkg = PythonPackage(SAMPLE)
all_modules = list(pkg.all_modules())
assert len(all_modules) == 3
assert str(TEST_PATH / 'sample/flake_fail.py') in all_modules
assert str(SAMPLE / 'flake_fail.py') in all_modules



class TestCoverage(object):
def test_init_pkg_as_string(self):
cov = Coverage([SAMPLE])
assert len(cov.pkgs) == 1
assert cov.pkgs[0].src_base == str(SAMPLE)

def test_init_pkg_instance(self):
cov = Coverage([PythonPackage(SAMPLE)])
assert len(cov.pkgs) == 1
assert cov.pkgs[0].src_base == str(SAMPLE)

def test_cover_all(self):
pkg = PythonPackage(SAMPLE)
cov = Coverage([pkg])
task = list(cov.all('my_cov'))[0]
assert task['verbosity'] == 2
assert task['basename'] == 'my_cov'
assert task['actions'] == [
'coverage run --branch `which py.test`',
'coverage report --show-missing {}'.format(' '.join(pkg.all_modules()))
]

def test_cover_all_parallel(self):
pkg = PythonPackage(SAMPLE)
cov = Coverage([pkg], config=Config(parallel=True, branch=False,
omit=['abc']))
task = list(cov.all('my_cov'))[0]
assert task['verbosity'] == 2
assert task['basename'] == 'my_cov'
assert task['actions'] == [
'coverage run --parallel-mode `which py.test`',
'coverage combine',
'coverage report --show-missing --omit abc {}'.format(
' '.join(pkg.all_modules()))
]


def test_cover_src(self):
pkg = PythonPackage(SAMPLE)
cov = Coverage([pkg])
task = list(cov.src('my_cov'))[0]
assert task['verbosity'] == 2
assert task['basename'] == 'my_cov'
assert task['actions'] == [
'coverage run --branch `which py.test`',
'coverage report --show-missing {}'.format(' '.join(pkg.src))
]


def test_cover_module(self):
pkg = PythonPackage(SAMPLE)
cov = Coverage([pkg])
tasks = list(cov.by_module('my_cov'))
assert len(tasks) == 1
task = tasks[0]
assert task['verbosity'] == 2
assert task['basename'] == 'my_cov'
src = pkg.src_base + '/flake_ok.py'
test = pkg.src_base + '/tests/test_flake_ok.py'
assert task['actions'] == [
'coverage run --branch `which py.test` {}'.format(test),
'coverage report --show-missing {}'.format(' '.join([src, test]))
]

0 comments on commit c28d34b

Please sign in to comment.