Passed
Pull Request — master (#147)
by Jan
04:35
created

oval_graph.client   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 240
Duplicated Lines 0 %

Test Coverage

Coverage 95.45%

Importance

Changes 0
Metric Value
eloc 198
dl 0
loc 240
ccs 126
cts 132
cp 0.9545
rs 9.0399
c 0
b 0
f 0
wmc 42

22 Methods

Rating   Name   Duplication   Size   Complexity  
A Client._check_rules_id() 0 14 5
A Client.get_questions() 0 13 1
A Client._get_wanted_rules_from_array_of_IDs() 0 4 1
A Client._get_only_fail_rule() 0 5 2
A Client._build_and_save_html() 0 4 1
A Client.get_list_of_lines() 0 15 4
A Client.search_rules_id() 0 6 1
A Client.run_gui_and_return_answers() 0 13 4
A Client.get_list_of_matched_rules() 0 3 2
A Client.print_red_text() 0 4 1
A Client._get_rules() 0 5 2
A Client._get_message() 0 7 1
A Client.get_save_src() 0 9 2
A Client.__init__() 0 20 1
A Client.prepare_data() 0 4 1
A Client.get_choices() 0 4 2
A Client.parse_arguments() 0 3 1
A Client.get_lines_of_wanted_not_selected_rules() 0 7 2
A Client.get_src() 0 3 1
A Client.get_selection_rules() 0 2 1
A Client._prepare_data() 0 17 5
B Client.prepare_parser() 0 39 1

How to fix   Complexity   

Complexity

Complex classes like oval_graph.client often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1 1
import re
2 1
import argparse
3 1
import tempfile
4 1
import os
5 1
import webbrowser
6 1
import json
7 1
import shutil
8 1
from datetime import datetime
9 1
import sys
10
11 1
from .xml_parser import XmlParser
12 1
from .exceptions import NotChecked
13 1
from ._builder_html_graph import BuilderHtmlGraph
14 1
from .__init__ import __version__
15
16
17 1
class Client():
18 1
    def __init__(self, args):
19 1
        self.parser = None
20 1
        self.MESSAGES = self._get_message()
21 1
        self.arg = self.parse_arguments(args)
22 1
        self.hide_passing_tests = self.arg.hide_passing_tests
23 1
        self.source_filename = self.arg.source_filename
24 1
        self.rule_name = self.arg.rule_id
25 1
        self.out = self.arg.output
26 1
        self.all_rules = self.arg.all
27 1
        self.all_in_one = None
28 1
        self.display_html = None
29 1
        self.isatty = sys.stdout.isatty()
30 1
        self.show_failed_rules = False
31 1
        self.show_not_selected_rules = False
32 1
        self.xml_parser = XmlParser(
33
            self.source_filename)
34 1
        self.parts = self.get_src('parts')
35 1
        self.START_OF_FILE_NAME = 'graph-of-'
36 1
        self.date = str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
37 1
        self.verbose = self.arg.verbose
38
39 1
    def _get_message(self):
40 1
        MESSAGES = {
41
            'description': '',
42
            '--output': '',
43
            'source_filename': '',
44
        }
45 1
        return MESSAGES
46
47 1
    def print_red_text(self, text):
48
        CRED = '\033[91m'
49
        CEND = '\033[0m'
50
        print(CRED + str(text) + CEND)
51
52 1
    def run_gui_and_return_answers(self):
53 1
        if self.isatty:
54 1
            if self.all_rules:
55
                return self._get_rules()
56
            else:
57 1
                try:
58 1
                    import inquirer
59 1
                    return inquirer.prompt(self.get_questions())
60 1
                except ImportError:
61 1
                    print(self.get_selection_rules())
62 1
                    return None
63
        else:
64 1
            return self._get_rules()
65
66 1
    def _get_rules(self):
67 1
        return {
68
            'rules': self._get_only_fail_rule(
69
                self.search_rules_id())} if self.show_failed_rules else {
70
            'rules': self.search_rules_id()}
71
72 1
    def get_list_of_matched_rules(self):
73 1
        return self._get_only_fail_rule(
74
            self.search_rules_id()) if self.show_failed_rules else self.search_rules_id()
75
76 1
    def get_list_of_lines(self):
77 1
        lines = ['== The Rule ID regular expressions ==']
78 1
        for rule in self.get_list_of_matched_rules():
79 1
            lines.append("^" + rule + "$")
80 1
        if self.show_not_selected_rules:
81 1
            for line in self.get_lines_of_wanted_not_selected_rules():
82 1
                lines.append(line)
83 1
        lines.append(
84
            "Interactive rule selection is not available,"
85
            " because inquirer is not installed."
86
            " Copy id of the rule you want to visualize and"
87
            " paste it into a command with regular"
88
            " expression characters(^$).\n"
89
            "Alternatively, use the --all or --all-in-one arguments.")
90 1
        return lines
91
92 1
    def get_selection_rules(self):
93 1
        return "\n".join(self.get_list_of_lines())
94
95 1
    def get_lines_of_wanted_not_selected_rules(self):
96 1
        out = []
97 1
        out.append('== The not selected rule IDs ==')
98 1
        for rule in self._get_wanted_rules_from_array_of_IDs(
99
                self.xml_parser.notselected_rules):
100 1
            out.append(rule + '(Not selected)')
101 1
        return out
102
103 1
    def get_choices(self):
104 1
        if self.show_not_selected_rules:
105 1
            print("\n".join(self.get_lines_of_wanted_not_selected_rules()))
106 1
        return self.get_list_of_matched_rules()
107
108 1
    def get_questions(self):
109 1
        choices = self.get_choices()
110 1
        from inquirer.questions import Checkbox as checkbox
111 1
        questions = [
112
            checkbox(
113
                'rules',
114
                message=(
115
                    "= The Rules IDs = (move - UP and DOWN arrows,"
116
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
117
                choices=choices,
118
            ),
119
        ]
120 1
        return questions
121
122 1
    def _get_only_fail_rule(self, rules):
123 1
        return list(
124
            filter(
125
                lambda rule: self.xml_parser.used_rules[rule]['result'] == 'fail',
126
                rules))
127
128 1
    def _get_wanted_rules_from_array_of_IDs(self, rules):
129 1
        return [
130
            x for x in rules if re.search(
131
                self.rule_name, x)]
132
133 1
    def search_rules_id(self):
134 1
        return self._check_rules_id(
135
            self._get_wanted_rules_from_array_of_IDs(
136
                self.xml_parser.used_rules.keys()),
137
            self._get_wanted_rules_from_array_of_IDs(
138
                self.xml_parser.notselected_rules))
139
140 1
    def _check_rules_id(self, rules, notselected_rules):
141 1
        if len(notselected_rules) and not rules:
142 1
            raise ValueError(
143
                ('Rule(s) "{}" was not selected, '
144
                 "so there are no results. The rule is"
145
                 ' "notselected" because it'
146
                 " wasn't a part of the executed profile"
147
                 " and therefore it wasn't evaluated "
148
                 "during the scan.")
149
                .format(notselected_rules))
150 1
        elif not notselected_rules and not rules:
151 1
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
152
        else:
153 1
            return rules
154
155 1
    def get_save_src(self, rule):
156 1
        if self.out is not None:
157 1
            os.makedirs(self.out, exist_ok=True)
158 1
            return os.path.join(
159
                self.out,
160
                self.START_OF_FILE_NAME + rule + '.html')
161 1
        return os.path.join(
162
            tempfile.gettempdir(),
163
            self.START_OF_FILE_NAME + rule + '.html')
164
165 1
    def get_src(self, src):
166 1
        _dir = os.path.dirname(os.path.realpath(__file__))
167 1
        return str(os.path.join(_dir, src))
168
169 1
    def _build_and_save_html(self, dict_oval_trees, src, rules, out):
170 1
        builder = BuilderHtmlGraph(
171
            self.parts, self.display_html, self.verbose)
172 1
        builder.save_html_and_open_html(dict_oval_trees, src, rules, out)
173
174 1
    def _prepare_data(self, rules, dict_oval_trees, out):
175 1
        for rule in rules['rules']:
176 1
            try:
177 1
                self._put_to_dict_oval_trees(dict_oval_trees, rule)
178 1
                if not self.all_in_one:
179 1
                    self._build_and_save_html(
180
                        dict_oval_trees, self._get_src_for_one_graph(
181
                            rule), dict(
182
                            rules=[rule]), out)
183 1
                    dict_oval_trees = {}
184 1
            except NotChecked as error:
185
                self.print_red_text(error)
186 1
        if self.all_in_one:
187
            self._build_and_save_html(
188
                dict_oval_trees, self.get_save_src(
189
                    'rules' + self.date), rules, out)
190 1
        return out
191
192 1
    def prepare_data(self, rules):
193 1
        out = []
194 1
        oval_tree_dict = dict()
195 1
        return self._prepare_data(rules, oval_tree_dict, out)
196
197 1
    def parse_arguments(self, args):
198 1
        self.prepare_parser()
199 1
        return self.parser.parse_args(args)
200
201 1
    def prepare_parser(self):
202 1
        self.parser = argparse.ArgumentParser(
203
            prog='oval-graph',
204
            description=self.MESSAGES.get('description'))
205 1
        self.parser.add_argument(
206
            '--version',
207
            action='version',
208
            version='%(prog)s ' + __version__)
209 1
        self.parser.add_argument(
210
            '-a',
211
            '--all',
212
            action="store_true",
213
            default=False,
214
            help="Process all matched rules.")
215 1
        self.parser.add_argument(
216
            '--hide-passing-tests',
217
            action="store_true",
218
            default=False,
219
            help=(
220
                "Do not display passing tests for better orientation in"
221
                " graphs that contain a large amount of nodes."))
222 1
        self.parser.add_argument(
223
            '-v',
224
            '--verbose',
225
            action="store_true",
226
            default=False,
227
            help="Displays details about the results of the running command.")
228 1
        self.parser.add_argument(
229
            '-o',
230
            '--output',
231
            action="store",
232
            default=None,
233
            help=self.MESSAGES.get('--output'))
234 1
        self.parser.add_argument(
235
            "source_filename",
236
            help=self.MESSAGES.get('source_filename'))
237 1
        self.parser.add_argument(
238
            "rule_id", help=(
239
                "Rule ID to be visualized. A part from the full rule ID"
240
                " a part of the ID or a regular expression can be used."
241
                " If brackets are used in the regular expression "
242
                "the regular expression must be quoted."))
243