Skip to content

Commit 19cfdeb

Browse files
authored
update logging preferences, handle NoDataError so that packages that properly generate no coverage don't crash (Azure#39694)
1 parent 74f5930 commit 19cfdeb

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

eng/tox/run_coverage.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,27 @@
33
import os
44
import json
55
import datetime
6+
import logging
7+
8+
from typing import Optional
69

710
from ci_tools.parsing import ParsedSetup
811
from ci_tools.variables import in_ci
912
from ci_tools.environment_exclusions import is_check_enabled
13+
from coverage.exceptions import NoDataError
1014

11-
def get_total_coverage(coverage_file: str) -> float:
15+
def get_total_coverage(coverage_file: str) -> Optional[float]:
1216
cov = coverage.Coverage(data_file=coverage_file)
1317
cov.load()
14-
report = cov.report()
15-
16-
return report
17-
18+
try:
19+
report = cov.report()
20+
return report
21+
except NoDataError as e:
22+
logging.warning(f"This package did not generate any coverage output: {e}")
23+
return None
24+
except Exception as e:
25+
logging.error(f"An error occurred while generating the coverage report: {e}")
26+
return None
1827

1928
if __name__ == "__main__":
2029
parser = argparse.ArgumentParser(
@@ -36,16 +45,20 @@ def get_total_coverage(coverage_file: str) -> float:
3645

3746
if os.path.exists(possible_coverage_file):
3847
total_coverage = get_total_coverage(possible_coverage_file)
39-
print(f"Total coverage for {pkg_details.name} is {total_coverage:.2f}%")
48+
if total_coverage is not None:
49+
logging.info(f"Total coverage for {pkg_details.name} is {total_coverage:.2f}%")
4050

41-
if in_ci():
42-
metric_obj = {}
43-
metric_obj["value"] = total_coverage / 100
44-
metric_obj["name"] = "test_coverage_ratio"
45-
metric_obj["labels"] = { "package": pkg_details.name }
46-
metric_obj["timestamp"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
47-
print(f'logmetric: {json.dumps(metric_obj)}')
51+
if in_ci():
52+
metric_obj = {}
53+
metric_obj["value"] = total_coverage / 100
54+
metric_obj["name"] = "test_coverage_ratio"
55+
metric_obj["labels"] = { "package": pkg_details.name }
56+
metric_obj["timestamp"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
57+
# normally we logging.info anywhere we need to output, but these logmetric statements
58+
# need to be the sole value on the line, as the logmetric log parsing doesn't allow prefixes
59+
# before the 'logmetric' start string.
60+
print(f'logmetric: {json.dumps(metric_obj)}')
4861

4962
if is_check_enabled(args.target_package, "cov_enforcement", False):
50-
print("Coverage enforcement is enabled for this package.")
63+
logging.info("Coverage enforcement is enabled for this package.")
5164

0 commit comments

Comments
 (0)