summaryrefslogtreecommitdiffstats
path: root/test/lib/ansible_test/_util/target/pytest/plugins/ansible_pytest_coverage.py
blob: b05298ab0b3d8824e327ee252e068ff1d517c9a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Monkey patch os._exit when running under coverage so we don't lose coverage data in forks, such as with `pytest --boxed`. PYTEST_DONT_REWRITE"""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type


def pytest_configure():
    """Configure this pytest plugin."""
    try:
        if pytest_configure.executed:
            return
    except AttributeError:
        pytest_configure.executed = True

    try:
        import coverage
    except ImportError:
        coverage = None

    try:
        coverage.Coverage
    except AttributeError:
        coverage = None

    if not coverage:
        return

    import gc
    import os

    coverage_instances = []

    for obj in gc.get_objects():
        if isinstance(obj, coverage.Coverage):
            coverage_instances.append(obj)

    if not coverage_instances:
        coverage_config = os.environ.get('COVERAGE_CONF')

        if not coverage_config:
            return

        coverage_output = os.environ.get('COVERAGE_FILE')

        if not coverage_output:
            return

        cov = coverage.Coverage(config_file=coverage_config)
        coverage_instances.append(cov)
    else:
        cov = None

    # noinspection PyProtectedMember
    os_exit = os._exit  # pylint: disable=protected-access

    def coverage_exit(*args, **kwargs):
        for instance in coverage_instances:
            instance.stop()
            instance.save()

        os_exit(*args, **kwargs)

    os._exit = coverage_exit  # pylint: disable=protected-access

    if cov:
        cov.start()


pytest_configure()