ansible/test/lib/ansible_test/_data/pytest/plugins/ansible_pytest_coverage.py
Matt Clay aaa6d2ecb0
Fix ansible-test pytest plugin loading. (#62119)
* Avoid assertion rewriting in pytest plugins.

Adding PYTEST_DONT_REWRITE to the ansible-test pytest plugin docstrings disables assertion rewriting in pytest for those plugins.

This avoids warnings during test execution if the plugins are loaded multiple times (such as being imported within tests).

* Run ansible-test pytest plugins early.

The ansible-test pytest plugins need to load and run earlier than conftest modules.

To facilitate this, the pytest_configure function is run during loading, which works since they are loaded (but not always run) before conftest modules are loaded.

A check has also been added to the pytest_configure functions to prevent them from running multiple times in the same process.

* Load pytest plugins using an env var.

The -p command line option loads plugins before conftest, but only during collection.
The PYTEST_PLUGINS environment variable loads plugins before confest, both during collection and test execution.
2019-09-10 23:27:05 -07:00

69 lines
1.6 KiB
Python

"""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()