Passed
Pull Request — master (#156)
by Jan
06:11
created

Client._check_rules_id()   A

Complexity

Conditions 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 8
nop 3
dl 0
loc 13
ccs 6
cts 6
cp 1
crap 5
rs 9.3333
c 0
b 0
f 0
1 1
import argparse
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2 1
import re
3 1
import sys
4 1
from datetime import datetime
5
6 1
from .. import __version__
7
8
9 1
class Client():
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
best-practice introduced by
Too many instance attributes (12/7)
Loading history...
10 1
    def __init__(self, args):
11 1
        self.parser = None
12 1
        self.arg = self.parse_arguments(args)
13 1
        self.hide_passing_tests = self.arg.hide_passing_tests
14 1
        self.source_filename = self.arg.source_filename
15 1
        self.rule_name = self.arg.rule_id
16 1
        self.out = self.arg.output
17 1
        self.verbose = self.arg.verbose
18
19 1
        self.date = str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
20 1
        self.isatty = sys.stdout.isatty()
21
22 1
        self.all_rules = self.arg.all
23 1
        self.show_failed_rules = False
24 1
        self.show_not_selected_rules = False
25
26 1
    @staticmethod
27
    def _get_message():
28 1
        return {
29
            'description': '',
30
            'source_filename': '',
31
        }
32
33
    # Functions for selection of rules
34
35 1
    def search_rules_id(self):
36
        """
37
        Function retunes array of all matched IDs of rules in selected file.
38
        """
39 1
        raise NotImplementedError
40
41 1
    def get_only_fail_rule(self, rules):
42
        """
43
        Function processes array of matched IDs of rules in selected file.
44
        Function retunes array of failed matched IDs of rules in selected file.
45
        """
46 1
        raise NotImplementedError
47
48 1
    def _get_rows_of_unselected_rules(self):
49
        """
50
        Function retunes array of rows where is not selected IDs of rules in selected file.
51
        """
52 1
        raise NotImplementedError
53
54 1
    def run_gui_and_return_answers(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
55 1
        if self.isatty:
56 1
            if self.all_rules:
57 1
                return self._get_rules()
58
59 1
            try:
60 1
                import inquirer
0 ignored issues
show
introduced by
Import outside toplevel (inquirer)
Loading history...
61 1
                return inquirer.prompt(self.get_questions())
62 1
            except ImportError:
63 1
                print(self.get_selection_rules())
64 1
            return None
65 1
        return self._get_rules()
66
67 1
    def _get_rules(self):
68 1
        if self.show_failed_rules:
69 1
            return {'rules': self.get_only_fail_rule(self.search_rules_id())}
70 1
        return {'rules': self.search_rules_id()}
71
72 1
    def _get_list_of_matched_rules(self):
73 1
        if self.show_failed_rules:
74 1
            return self.get_only_fail_rule(self.search_rules_id())
75 1
        return self.search_rules_id()
76
77 1
    def _get_list_of_lines(self):
78 1
        lines = ['== The Rule ID regular expressions ==']
79 1
        for rule in self._get_list_of_matched_rules():
80 1
            lines.append("^" + rule + "$")
81 1
        if self.show_not_selected_rules:
82 1
            for line in self._get_rows_of_unselected_rules():
83 1
                lines.append(line)
84 1
        lines.append(
85
            "Interactive rule selection is not available,"
86
            " because inquirer is not installed."
87
            " Copy id of the rule you want to visualize and"
88
            " paste it into a command with regular"
89
            " expression characters(^$).\n"
90
            "Alternatively, use the --all or --all-in-one arguments.")
91 1
        return lines
92
93 1
    def get_selection_rules(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
94 1
        return "\n".join(self._get_list_of_lines())
95
96 1
    def _get_choices(self):
97 1
        if self.show_not_selected_rules:
98 1
            print("\n".join(self._get_rows_of_unselected_rules()))
99 1
        return self._get_list_of_matched_rules()
100
101 1
    def get_questions(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
102 1
        from inquirer.questions import Checkbox as checkbox
0 ignored issues
show
introduced by
Import outside toplevel (inquirer.questions.Checkbox)
Loading history...
103 1
        choices = self._get_choices()
104 1
        questions = [
105
            checkbox(
106
                'rules',
107
                message=(
108
                    "= The Rules IDs = (move - UP and DOWN arrows,"
109
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
110
                choices=choices,
111
            ),
112
        ]
113 1
        return questions
114
115 1
    def _get_wanted_rules(self, rules):
116 1
        return [
117
            x for x in rules if re.search(
118
                self.rule_name, x)]
119
120 1
    def _check_rules_id(self, rules, notselected_rules):
121 1
        if notselected_rules and not rules:
122 1
            raise ValueError(
123
                ('Rule(s) "{}" was not selected, '
124
                 "so there are no results. The rule is"
125
                 ' "notselected" because it'
126
                 " wasn't a part of the executed profile"
127
                 " and therefore it wasn't evaluated "
128
                 "during the scan.")
129
                .format(notselected_rules))
130 1
        if not notselected_rules and not rules:
131 1
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
132 1
        return rules
133
134
    # Function for setting arguments
135
136 1
    def parse_arguments(self, args):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
137 1
        self.prepare_parser()
138 1
        if args is None:
139
            return self.parser.parse_args()
140 1
        return self.parser.parse_args(args)
141
142 1
    def prepare_args_when_user_can_list_in_rules(self):
0 ignored issues
show
Coding Style Naming introduced by
Method name "prepare_args_when_user_can_list_in_rules" doesn't conform to '[a-z_][a-z0-9_]2,30$' pattern ('[a-z_][a-z0-9_]2,30$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
introduced by
Missing function or method docstring
Loading history...
143 1
        self.parser.add_argument(
144
            '--show-failed-rules',
145
            action="store_true",
146
            default=False,
147
            help="Show only FAILED rules")
148 1
        self.parser.add_argument(
149
            '--show-not-selected-rules',
150
            action="store_true",
151
            default=False,
152
            help="Show notselected rules. These rules will not be visualized.")
153
154 1
    def prepare_parser(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
155 1
        self.parser = argparse.ArgumentParser(
156
            prog='oval-graph',
157
            description=self._get_message().get('description'))
158 1
        self.parser.add_argument(
159
            '--version',
160
            action='version',
161
            version='%(prog)s ' + __version__)
162 1
        self.parser.add_argument(
163
            '-a',
164
            '--all',
165
            action="store_true",
166
            default=False,
167
            help="Process all matched rules.")
168 1
        self.parser.add_argument(
169
            '--hide-passing-tests',
170
            action="store_true",
171
            default=False,
172
            help=(
173
                "Do not display passing tests for better orientation in"
174
                " graphs that contain a large amount of nodes."))
175 1
        self.parser.add_argument(
176
            '-v',
177
            '--verbose',
178
            action="store_true",
179
            default=False,
180
            help="Displays details about the results of the running command.")
181 1
        self.parser.add_argument(
182
            '-o',
183
            '--output',
184
            action="store",
185
            default=None,
186
            help='The file where to save output.')
187 1
        self.parser.add_argument(
188
            "source_filename",
189
            help=self._get_message().get('source_filename'))
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