Skip to content

Commit 9d043e6

Browse files
committed
WIP
1 parent 4beb0c0 commit 9d043e6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/pytest_cov/plugin.py

+28
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import warnings
55

66
import pytest
7+
import coverage
78
from coverage.misc import CoverageException
89

910
from . import compat
@@ -48,6 +49,16 @@ def validate_fail_under(num_str):
4849
return float(num_str)
4950

5051

52+
def validate_contexts(arg):
53+
if coverage.version_info <= (5, 0):
54+
msg = '--cov-contexts is only supported with coverage.py >= 5.x'
55+
raise argparse.ArgumentTypeError(msg)
56+
if arg != "test":
57+
msg = '--cov-contexts=test is the only supported value'
58+
raise argparse.ArgumentTypeError(msg)
59+
return arg
60+
61+
5162
class StoreReport(argparse.Action):
5263
def __call__(self, parser, namespace, values, option_string=None):
5364
report_type, file = values
@@ -88,6 +99,9 @@ def pytest_addoption(parser):
8899
'Default: False')
89100
group.addoption('--cov-branch', action='store_true', default=None,
90101
help='Enable branch coverage.')
102+
group.addoption('--cov-contexts', action='store', metavar='CONTEXT',
103+
type=validate_contexts,
104+
help='Dynamic contexts to use. "test" for now.')
91105

92106

93107
def _prepare_cov_source(cov_source):
@@ -131,6 +145,7 @@ def __init__(self, options, pluginmanager, start=True):
131145
self.failed = False
132146
self._started = False
133147
self._disabled = False
148+
self.test_contexts = False
134149
self.options = options
135150

136151
is_dist = (getattr(options, 'numprocesses', False) or
@@ -146,6 +161,9 @@ def __init__(self, options, pluginmanager, start=True):
146161
self.options.cov_report = {}
147162
self.options.cov_source = _prepare_cov_source(self.options.cov_source)
148163

164+
if getattr(options, 'cov_contexts', None) == 'test':
165+
self.test_contexts = True
166+
149167
if is_dist and start:
150168
self.start(engine.DistMaster)
151169
elif start:
@@ -293,8 +311,12 @@ def pytest_runtest_setup(self, item):
293311
# test is run in another process than session, run
294312
# coverage manually
295313
embed.init()
314+
if self.test_contexts:
315+
self.switch_context(item, 'setup')
296316

297317
def pytest_runtest_teardown(self, item):
318+
if self.test_contexts:
319+
self.switch_context(item, 'teardown')
298320
embed.cleanup()
299321

300322
@compat.hookwrapper
@@ -305,8 +327,14 @@ def pytest_runtest_call(self, item):
305327
yield
306328
self.cov_controller.resume()
307329
else:
330+
if self.test_contexts:
331+
self.switch_context(item, 'run')
308332
yield
309333

334+
def switch_context(self, item, when):
335+
context = "{item.nodeid}|{when}".format(item=item, when=when)
336+
self.cov_controller.cov.switch_context(context)
337+
310338

311339
@pytest.fixture
312340
def no_cover():

0 commit comments

Comments
 (0)