Test Failed
Pull Request — master (#203)
by Jan
06:26 queued 02:49
created

Client.search_rules_id()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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