Test Failed
Pull Request — master (#156)
by Jan
04:14 queued 01:43
created

Client.get_questions()   A

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 10
nop 1
dl 0
loc 13
ccs 5
cts 5
cp 1
crap 1
rs 9.9
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
        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
        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
        raise NotImplementedError
68
69 1
    def run_gui_and_return_answers(self):
70 1
        if self.isatty:
71 1
            if self.all_rules:
72
                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
            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
            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_parser(self):
170 1
        self.parser = argparse.ArgumentParser(
171
            prog='oval-graph',
172
            description=self.MESSAGES.get('description'))
173 1
        self.parser.add_argument(
174
            '--version',
175
            action='version',
176
            version='%(prog)s ' + __version__)
177 1
        self.parser.add_argument(
178
            '-a',
179
            '--all',
180
            action="store_true",
181
            default=False,
182
            help="Process all matched rules.")
183 1
        self.parser.add_argument(
184
            '--hide-passing-tests',
185
            action="store_true",
186
            default=False,
187
            help=(
188
                "Do not display passing tests for better orientation in"
189
                " graphs that contain a large amount of nodes."))
190 1
        self.parser.add_argument(
191
            '-v',
192
            '--verbose',
193
            action="store_true",
194
            default=False,
195
            help="Displays details about the results of the running command.")
196 1
        self.parser.add_argument(
197
            '-o',
198
            '--output',
199
            action="store",
200
            default=None,
201
            help='The file where to save output.')
202 1
        self.parser.add_argument(
203
            "source_filename",
204
            help=self.MESSAGES.get('source_filename'))
205 1
        self.parser.add_argument(
206
            "rule_id", help=(
207
                "Rule ID to be visualized. A part from the full rule ID"
208
                " a part of the ID or a regular expression can be used."
209
                " If brackets are used in the regular expression "
210
                "the regular expression must be quoted."))
211