Passed
Pull Request — master (#160)
by Jan
08:04 queued 04:21
created

Client._get_rules()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 5
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1 1
import re
2 1
import argparse
3 1
from datetime import datetime
4 1
import sys
5
6 1
from ..exceptions import NotChecked
7 1
from ..__init__ import __version__
8
9
10 1
class Client():
11 1
    def __init__(self, args):
12 1
        self.parser = None
13 1
        self.MESSAGES = self._get_message()
14 1
        self.arg = self.parse_arguments(args)
15 1
        self.hide_passing_tests = self.arg.hide_passing_tests
16 1
        self.source_filename = self.arg.source_filename
17 1
        self.rule_name = self.arg.rule_id
18 1
        self.out = self.arg.output
19 1
        self.verbose = self.arg.verbose
20
21 1
        self.date = str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
22 1
        self.isatty = sys.stdout.isatty()
23
24 1
        self.all_rules = self.arg.all
25 1
        self.show_failed_rules = False
26 1
        self.show_not_selected_rules = False
27
28 1
    def _get_message(self):
29 1
        MESSAGES = {
30
            'description': '',
31
            'source_filename': '',
32
        }
33 1
        return MESSAGES
34
35
    """
36
    Non-implemented functions can handle different types of the input file.
37
38
    Functions for input file processing and corresponding rule ID.
39
    """
40
41 1
    def prepare_data(self, rules):
42
        """
43
        Function processes HTML graphs or JSON and
44
        return array of where is saved output file if exitsts.
45
        """
46 1
        raise NotImplementedError
47
48
    # Functions for selection of rules
49
50 1
    def search_rules_id(self):
51
        """
52
        Function retunes array of all matched IDs of rules in selected file.
53
        """
54 1
        raise NotImplementedError
55
56 1
    def get_only_fail_rule(self, rules):
57
        """
58
        Function processes array of matched IDs of rules in selected file.
59
        Function retunes array of failed matched IDs of rules in selected file.
60
        """
61 1
        raise NotImplementedError
62
63 1
    def _get_lines_of_wanted_not_selected_rules(self):
64
        """
65
        Function retunes array of lines where is not selected IDs of rules in selected file.
66
        """
67 1
        raise NotImplementedError
68
69 1
    def run_gui_and_return_answers(self):
70 1
        if self.isatty:
71 1
            if self.all_rules:
72 1
                return self._get_rules()
73
            else:
74 1
                try:
75 1
                    import inquirer
76 1
                    return inquirer.prompt(self.get_questions())
77 1
                except ImportError:
78 1
                    print(self.get_selection_rules())
79 1
                    return None
80
        else:
81 1
            return self._get_rules()
82
83 1
    def _get_rules(self):
84 1
        return {
85
            'rules': self.get_only_fail_rule(
86
                self.search_rules_id())} if self.show_failed_rules else {
87
            'rules': self.search_rules_id()}
88
89 1
    def _get_list_of_matched_rules(self):
90 1
        return self.get_only_fail_rule(
91
            self.search_rules_id()) if self.show_failed_rules else self.search_rules_id()
92
93 1
    def _get_list_of_lines(self):
94 1
        lines = ['== The Rule ID regular expressions ==']
95 1
        for rule in self._get_list_of_matched_rules():
96 1
            lines.append("^" + rule + "$")
97 1
        if self.show_not_selected_rules:
98 1
            for line in self._get_lines_of_wanted_not_selected_rules():
99 1
                lines.append(line)
100 1
        lines.append(
101
            "Interactive rule selection is not available,"
102
            " because inquirer is not installed."
103
            " Copy id of the rule you want to visualize and"
104
            " paste it into a command with regular"
105
            " expression characters(^$).\n"
106
            "Alternatively, use the --all or --all-in-one arguments.")
107 1
        return lines
108
109 1
    def get_selection_rules(self):
110 1
        return "\n".join(self._get_list_of_lines())
111
112 1
    def _get_choices(self):
113 1
        if self.show_not_selected_rules:
114 1
            print("\n".join(self._get_lines_of_wanted_not_selected_rules()))
115 1
        return self._get_list_of_matched_rules()
116
117 1
    def get_questions(self):
118 1
        choices = self._get_choices()
119 1
        from inquirer.questions import Checkbox as checkbox
120 1
        questions = [
121
            checkbox(
122
                'rules',
123
                message=(
124
                    "= The Rules IDs = (move - UP and DOWN arrows,"
125
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
126
                choices=choices,
127
            ),
128
        ]
129 1
        return questions
130
131 1
    def _get_wanted_rules_from_array_of_IDs(self, rules):
132 1
        return [
133
            x for x in rules if re.search(
134
                self.rule_name, x)]
135
136 1
    def _check_rules_id(self, rules, notselected_rules):
137 1
        if len(notselected_rules) and not rules:
138 1
            raise ValueError(
139
                ('Rule(s) "{}" was not selected, '
140
                 "so there are no results. The rule is"
141
                 ' "notselected" because it'
142
                 " wasn't a part of the executed profile"
143
                 " and therefore it wasn't evaluated "
144
                 "during the scan.")
145
                .format(notselected_rules))
146 1
        elif not notselected_rules and not rules:
147 1
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
148
        else:
149 1
            return rules
150
151
    # Function for setting arguments
152
153 1
    def parse_arguments(self, args):
154 1
        self.prepare_parser()
155 1
        return self.parser.parse_args(args)
156
157 1
    def prepare_args_when_user_can_list_in_rules(self):
158 1
        self.parser.add_argument(
159
            '--show-failed-rules',
160
            action="store_true",
161
            default=False,
162
            help="Show only FAILED rules")
163 1
        self.parser.add_argument(
164
            '--show-not-selected-rules',
165
            action="store_true",
166
            default=False,
167
            help="Show notselected rules. These rules will not be visualized.")
168
169 1
    def prepare_args_options_all_hide_passing_tests(self):
170 1
        self.parser.add_argument(
171
            '-a',
172
            '--all',
173
            action="store_true",
174
            default=False,
175
            help="Process all matched rules.")
176 1
        self.parser.add_argument(
177
            '--hide-passing-tests',
178
            action="store_true",
179
            default=False,
180
            help=(
181
                "Do not display passing tests for better orientation in"
182
                " graphs that contain a large amount of nodes."))
183
184 1
    def prepare_args_source_file(self):
185 1
        self.parser.add_argument(
186
            "source_filename",
187
            help=self.MESSAGES.get('source_filename'))
188
189 1
    def prepare_args_rule_id(self):
190 1
        self.parser.add_argument(
191
            "rule_id", help=(
192
                "Rule ID to be visualized. A part from the full rule ID"
193
                " a part of the ID or a regular expression can be used."
194
                " If brackets are used in the regular expression "
195
                "the regular expression must be quoted."))
196
197 1
    def prepare_args_basic_functions(self):
198 1
        self.parser = argparse.ArgumentParser(
199
            prog='oval-graph',
200
            description=self.MESSAGES.get('description'))
201 1
        self.parser.add_argument(
202
            '--version',
203
            action='version',
204
            version='%(prog)s ' + __version__)
205 1
        self.parser.add_argument(
206
            '-v',
207
            '--verbose',
208
            action="store_true",
209
            default=False,
210
            help="Displays details about the results of the running command.")
211 1
        self.parser.add_argument(
212
            '-o',
213
            '--output',
214
            action="store",
215
            default=None,
216
            help='The file where to save output.')
217
218 1
    def prepare_parser(self):
219 1
        self.prepare_args_basic_functions()
220 1
        self.prepare_args_options_all_hide_passing_tests()
221 1
        self.prepare_args_source_file()
222
        self.prepare_args_rule_id()
223