oval_graph.command_line_client.client_html_output   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Test Coverage

Coverage 82.47%

Importance

Changes 0
Metric Value
wmc 32
eloc 112
dl 0
loc 136
ccs 80
cts 97
cp 0.8247
rs 9.84
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A ClientHtmlOutput.open_results_in_web_browser() 0 13 5
A ClientHtmlOutput.__init__() 0 9 3
A ClientHtmlOutput._is_firefox_installed() 0 10 3
A ClientHtmlOutput.prepare_args_when_output_is_html() 0 14 1
A ClientHtmlOutput.kill_web_browsers() 0 3 2
A ClientHtmlOutput._put_to_dict_oval_trees() 0 6 1
A ClientHtmlOutput.get_file_name() 0 3 1
A ClientHtmlOutput._get_src_for_one_graph() 0 2 1
A ClientHtmlOutput.prepare_data() 0 4 1
B ClientHtmlOutput._prepare_data() 0 23 6
B ClientHtmlOutput.get_save_src() 0 8 6
A ClientHtmlOutput._open_web_browser() 0 15 2
1 1
import tempfile
2 1
import time
3 1
import webbrowser
4 1
from pathlib import Path
5 1
from subprocess import PIPE, Popen, check_call
6
7 1
from ..exceptions import NotTestedRule
8 1
from ..html_builder.graph import Graph
9 1
from .client import Client
10
11 1
START_OF_FILE_NAME = 'graph-of-'
12
13
14 1
class ClientHtmlOutput(Client):
15 1
    def __init__(self, args):
16 1
        super().__init__(args)
17 1
        self.out = self.arg.output
18 1
        self.all_in_one = self.arg.all_in_one
19 1
        self.all_rules = True if self.all_in_one else self.arg.all
20 1
        self.display_html = True if self.out is None else self.arg.display
21 1
        self.html_builder = Graph(self.arg.verbose, self.all_in_one)
22 1
        self.web_browsers = []
23 1
        self.selected_only_one_rule = False
24
25 1
    def prepare_data(self, rules):
26 1
        paths_to_generated_rules = self._prepare_data(rules)
27 1
        self.open_results_in_web_browser(paths_to_generated_rules)
28 1
        return paths_to_generated_rules
29
30 1
    def _put_to_dict_oval_trees(self, dict_oval_trees, rule):
31
        """
32
        The function inserts into dict_oval_trees a dictionary from
33
        the rule with the key as the rule id.
34
        """
35
        raise NotImplementedError
36
37 1
    def _prepare_data(self, rules):
38 1
        dict_oval_trees = {}
39 1
        paths_to_generated_rules = []
40 1
        if len(rules['rules']) == 1:
41 1
            self.selected_only_one_rule = True
42 1
        for rule in rules['rules']:
43 1
            try:
44 1
                self._put_to_dict_oval_trees(dict_oval_trees, rule)
45 1
                if not self.all_in_one:
46 1
                    path = self._get_src_for_one_graph(rule)
47 1
                    self.html_builder.save_html(dict_oval_trees, path)
48 1
                    paths_to_generated_rules.append(str(path))
49 1
                    dict_oval_trees = {}
50 1
            except NotTestedRule as error:
51 1
                start_red_color = '\033[91m'
52 1
                end_red_color = '\033[0m'
53 1
                message = f'{start_red_color}{str(error)}{end_red_color}'
54 1
                raise NotTestedRule(message) from error
55 1
        if self.all_in_one:
56
            path = self.get_save_src('rules' + self._get_date())
57
            self.html_builder.save_html(dict_oval_trees, path)
58
            paths_to_generated_rules.append(str(path))
59 1
        return paths_to_generated_rules
60
61 1
    def _get_src_for_one_graph(self, rule):
62 1
        return self.get_save_src(rule + self._get_date())
63
64 1
    @staticmethod
65
    def get_file_name(rule):
66 1
        return f"{START_OF_FILE_NAME}{rule}.html"
67
68 1
    def get_save_src(self, rule):
69 1
        if self.out is not None:
70 1
            output_path = Path(self.out)
71 1
            if not output_path.is_dir():
72 1
                if (self.all_in_one and self.all_rules) or self.selected_only_one_rule:
73 1
                    return output_path
74 1
            return output_path / self.get_file_name(rule)
75 1
        return Path(tempfile.gettempdir()) / self.get_file_name(rule)
76
77 1
    def open_results_in_web_browser(self, paths_to_results):
78 1
        if self.display_html:
79 1
            try:
80 1
                for path_to_result in paths_to_results:
81 1
                    self._open_web_browser(path_to_result)
82
            except OSError as os_error:
83
                if os_error.errno != 24:
84
                    raise OSError from os_error
85
                error_msg = (
86
                    'Opening too many reports. Increase '
87
                    'the open file limit or try to use '
88
                    'the --all-in-one parameter')
89
                raise ResourceWarning(error_msg) from os_error
90
91 1
    @staticmethod
92
    def _is_firefox_installed():
93 1
        firefox_is_installed = True
94 1
        try:
95 1
            command = ['firefox', '--version']
96 1
            if check_call(command, stdout=PIPE, stderr=PIPE):
97
                firefox_is_installed = False
98
        except FileNotFoundError:
99
            firefox_is_installed = False
100 1
        return firefox_is_installed
101
102 1
    def _open_web_browser(self, path_to_result):
103 1
        is_firefox_installed = self._is_firefox_installed()
104 1
        if is_firefox_installed:
105 1
            command = ["firefox", path_to_result]
106
            # pylint: disable=bad-option-value,R1732
107 1
            browser = Popen(command, stdout=PIPE, stderr=PIPE)
108 1
            self.web_browsers.append(browser)
109 1
            time.sleep(0.2)
110
        else:
111
            default_web_browser_name = webbrowser.get().name
112
            command = [default_web_browser_name, path_to_result]
113
            # pylint: disable=bad-option-value,R1732
114
            browser = Popen(command, stdout=PIPE, stderr=PIPE)
115
            self.web_browsers.append(browser)
116
            time.sleep(0.2)
117
118 1
    def kill_web_browsers(self):
119 1
        for web_browser in self.web_browsers:
120 1
            web_browser.kill()
121
122 1
    @staticmethod
123
    def prepare_args_when_output_is_html(parser):
124 1
        parser.add_argument(
125
            '-i',
126
            '--all-in-one',
127
            action="store_true",
128
            default=False,
129
            help="Processes all rules into one file.")
130 1
        parser.add_argument(
131
            '-d',
132
            '--display',
133
            action="store_true",
134
            default=False,
135
            help="Enables opening a web browser with a graph, when is used --output.")
136