Coverage for testrail_api_reporter/utils/csv_parser.py: 100%

1# -*- coding: utf-8 -*-

2""" CSV parser for TestRail API Reporter """

3

4 import csv

5 from datetime import datetime

6 from os.path import exists

7 from typing import List

8

9 from .logger_config import setup_logger, DEFAULT_LOGGING_LEVEL

10

11

12 class CSVParser:

13 """Parser for CSV files"""

14

15 def __init__(self, filename=None, logger=None, log_level=DEFAULT_LOGGING_LEVEL):

16 """

17 Default init

18

19 :param filename: filename for csv file

20 :param logger: logger object, optional

21 :param log_level: logging level, optional, by default is logging.DEBUG

22 """

23 if not logger:

24 self.___logger = setup_logger(name="CSVParser", log_file="CSVParser.log", level=log_level)

25 else:

26 self.___logger = logger

27 self.___logger.debug("Initializing CSV Parser")

28 self.__filename = filename

29

30 def save_history_data(self, filename=None, report=None):

31 """

32 Save history data to CSV

33

34 :param filename: file name of output file, required

35 :param report: report with distribution in CaseStat format

36 :return:

37 """

38 filename = filename if filename else self.__filename

39 if not filename:

40 raise ValueError("Filename for save report data is not provided, save history data aborted!")

41 if not report:

42 raise ValueError("Report couldn't be found, save history data aborted!")

43 date = datetime.today().strftime("%Y-%m-%d")

44 last_date = ""

45 mode = "r" if exists(filename) else "w"

46 with open(filename, mode, encoding="utf-8") as csvfile:

47 if mode == "r":

48 for row in reversed(list(csv.reader(csvfile))):

49 last_date = f"{row[0]}-{row[1]}-{row[2]}"

50 break

51 if last_date != date:

52 self.___logger.debug("Last date in file: %s for %s", filename, last_date)

53 with open(filename, "a+", newline="", encoding="utf-8") as csvfile:

54 writer = csv.writer(csvfile, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL)

55

56 writer.writerow(

57 [

58 datetime.today().strftime("%Y"),

59 datetime.today().strftime("%m"),

60 datetime.today().strftime("%d"),

61 report.get_total(),

62 report.get_automated(),

63 report.get_not_automated(),

64 report.get_not_applicable(),

65 ]

66 )

67 else:

68 self.___logger.debug("Data already stored for today, skipping save")

69

70 def load_history_data(self, filename=None) -> List:

71 """

72 Load history data to CSV

73

74 :param filename: file name of output file, required

75 :return: list with results

76 """

77 filename = filename if filename else self.__filename

78 if not filename:

79 raise ValueError("Filename for load report data is not provided, save history data aborted!")

80 timestamps = []

81 totals = []

82 automated = []

83 not_automated = []

84 nas = []

85 self.___logger.debug("Loading history data from %s", filename)

86 try:

87 with open(filename, "r", encoding="utf-8") as csvfile:

88 for row in csv.reader(csvfile):

89 timestamps.append(datetime(year=int(row[0]), month=int(row[1]), day=int(row[2])))

90 totals.append(row[3])

91 automated.append(row[4])

92 not_automated.append(row[5])

93 nas.append(row[6])

94 except FileNotFoundError:

95 raise ValueError(f"Can't open report file '{filename}', load history data aborted!") from FileNotFoundError

96 return [timestamps, totals, automated, not_automated, nas]