Coverage for tests / integration / utils / stats.py: 50%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-03-20 10:09 -0400

1"""This module contains utility functions for stats files.""" 

2 

3import json 

4import os 

5 

6 

7def get_vulnerabilities_from_stats(stats_dir: str) -> dict: 

8 """Reads the vulnerabilities dict from the JSON stats report. 

9 

10 Args: 

11 stats_dir (str): Directory where stats files are saved. 

12 

13 Returns: 

14 dict: vulnerabilities mapping as written by Stats.save_json(), or {} if not found. 

15 """ 

16 json_path = os.path.join(stats_dir, "stats.json") 

17 if not os.path.exists(json_path): 

18 return {} 

19 with open(json_path, "r") as f: 

20 data = json.load(f) 

21 return data.get("vulnerabilities", {}) 

22 

23 

24def is_detection_flagged(vulnerabilities: dict, detection_name: str, confirmed: bool = False) -> bool: 

25 """Returns True if any node was flagged for the given detection. 

26 

27 Args: 

28 vulnerabilities (dict): The vulnerabilities dict from get_vulnerabilities_from_stats(). 

29 detection_name (str): The DETECTION_NAME string used by the detector. 

30 confirmed (bool): If True, only count confirmed vulnerabilities; otherwise include potential. 

31 

32 Returns: 

33 bool: True if at least one node was flagged. 

34 """ 

35 if detection_name not in vulnerabilities: 

36 return False 

37 for _node_name, vuln in vulnerabilities[detection_name].items(): 

38 if confirmed and vuln.get("is_vulnerable"): 

39 return True 

40 if not confirmed and (vuln.get("is_vulnerable") or vuln.get("potentially_vulnerable")): 

41 return True 

42 return False 

43 

44 

45def get_percent_query_mutation_success(stats_file_path: str) -> float: 

46 """Gets the percentage of successful queries and mutations from the stats file. 

47 

48 Args: 

49 stats_file_path (str): The path to the stats file. 

50 

51 Returns: 

52 float: The percentage of successful queries and mutations up to 2 decimal points 

53 """ 

54 with open(stats_file_path, "r") as stats_file: 

55 lines = stats_file.readlines() 

56 

57 for line in lines: 

58 if "Number of unique query/mutation successes" in line: 

59 line = line.strip().split(":") 

60 fraction_str_split = line[1].strip().split("/") 

61 numerator = int(fraction_str_split[0]) 

62 denominator = int(fraction_str_split[1]) 

63 return round(float(numerator / denominator) * 100, 2)