Test Failed
Pull Request — master (#173)
by Jan
02:52
created

oval_graph.command_line_client.client   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 198
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 32
eloc 141
dl 0
loc 198
ccs 0
cts 88
cp 0
rs 9.84
c 0
b 0
f 0

18 Methods

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