How to instruct coverage.py to omit top-level definitions and count only method's bodies?

半城伤御伤魂 提交于 2019-12-07 18:14:26

问题


I want to test the coverage of a single package within a large body of software (specifically an Odoo addon). I have no control over the overall setup of the test. Hacking Odoo to start the coverage collection before loading the modules is not worth it -- running all Odoo tests takes about 20 minutes on regular hardware; so I want to selectively test the coverage of some custom modules.

I'm using setUpModule and tearDownModule like this:

_coverage = Coverage(
    source=[
        'odoo.addons.xhg_autrement_prices.models',
    ],
    config_file=_join('.coveragerc'),
    auto_data=True,
    data_file=_join('.coverage'),
)


def setUpModule():
    _coverage.start()


def tearDownModule():
    from test.support import captured_stderr
    _coverage.stop()
    _coverage.save()
    with captured_stderr() as stderr:
        total = _coverage.report(skip_covered=True, file=sys.stderr)
    report = stderr.getvalue()
    fail_under = _coverage.get_option('report:fail_under')
    assert not fail_under or total >= fail_under, \
        f"Coverage not reached. total: {total}; expected: {fail_under}\n{report}"

However, when the test machinery calls the setUpModule the models module under test have already been loaded by Odoo.

So, coverage.py reports the lines defining some functions (or classes) as misses. For instance, in the following class:

class SumAggregator(SimpleAggregator):
    '''Aggregate by sum.'''
    def __init__(self, start: Result = 0) -> None:
        self.start = start

    def __call__(self, results: Iterable[Result], env: Environment) -> Result:
        return sum(results, self.start)

The line that defines the __call__ method is reported not covered, but its body is a hit. The first 3 lines (the class definition, its docstring and the init definition) are reported missed. Noticeable all docstrings (which comprise about about 10% of the source code) are reported missed.

How can instruct coverage to omit top-level definitions and count only the bodies of classes or functions (methods)?

来源:https://stackoverflow.com/questions/54811638/how-to-instruct-coverage-py-to-omit-top-level-definitions-and-count-only-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!