33import os
44import json
55import datetime
6+ import logging
7+
8+ from typing import Optional
69
710from ci_tools .parsing import ParsedSetup
811from ci_tools .variables import in_ci
912from 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
1928if __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