-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpytest_circleci_coverage.py
More file actions
63 lines (48 loc) · 1.75 KB
/
pytest_circleci_coverage.py
File metadata and controls
63 lines (48 loc) · 1.75 KB
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
import json
import os.path
import sys
from coverage import CoverageData
def pytest_addoption(parser):
parser.addoption("--circleci-coverage", dest="circleci-coverage")
def pytest_sessionfinish(session):
try:
output_path = session.config.getoption("circleci-coverage")
if not output_path:
# If the flag is not set, noop skip coverage reporting.
return
print("Generating CircleCI coverage JSON...")
data = CoverageData()
data.read()
files = data.measured_files()
if not files:
print(
"No coverage data found. "
+ "Ensure pytest is run with --cov and --cov-context=test flags.",
file=sys.stderr,
)
return
has_contexts = False
tests = {}
for filename in files:
contexts = data.contexts_by_lineno(filename=filename)
rev = {}
for lineno, contexts in contexts.items():
for context in contexts:
if context:
rev.setdefault(context, []).append(lineno)
has_contexts = True
if rev:
name = os.path.relpath(filename)
tests[name] = rev
if not has_contexts:
print(
"No coverage context data found. "
+ "Ensure pytest is run with --cov-context=test to enable context tracking.",
file=sys.stderr,
)
return
with open(output_path, "w") as f:
json.dump(tests, f)
print(f"Coverage data written to {output_path}")
except Exception as e:
print(f"Unexpected error generating coverage data: {e}", file=sys.stderr)