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

Converter._get_negation_character()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
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
"""
2
    This file contains a class for converting OVAL tree to according JSON used in HTML
3
"""
4
5
import re
6
7
from .oval_node import OvalNode
8
9
VALUE_TO_BOOTSTRAP_COLOR = {
10
    "true": "text-success",
11
    "false": "text-danger",
12
    "error": "text-dark",
13
    "unknown": "text-dark",
14
    "noteval": "text-dark",
15
    "notappl": "text-dark"
16
}
17
18
BOOTSTRAP_COLOR_TO_LABEL_COLOR = {
19
    "text-success": "label-success",
20
    "text-danger": "label-danger",
21
    "text-dark": "label-default"
22
}
23
24
VALUE_TO_ICON = {
25
    "true": "glyphicon glyphicon-ok text-success",
26
    "false": "glyphicon glyphicon-remove text-danger",
27
    "error": "glyphicon glyphicon-question-sign text-dark",
28
    "unknown": "glyphicon glyphicon-question-sign text-dark",
29
    "noteval": "glyphicon glyphicon-question-sign text-dark",
30
    "notappl": "glyphicon glyphicon-question-sign text-dark"
31
}
32
33
34
class Converter():
35
    """The Converter object converts OVAL tree to dict according JSON
36
       for graphic representation with JsTree.
37
38
    Attributes:
39
        tree (OvalNode): OVAL tree
40
        result (str): result of node
41
    """
42
43
    def __init__(self, tree):
44
        """This metode construct Converter.
45
46
        Args:
47
            tree (OvalNode): OVAL tree
48
49
        Raises:
50
            ValueError
51
        """
52
        if isinstance(tree, OvalNode):
53
            self.tree = tree
54
            self.result = self.tree.evaluate_tree()
55
            if self.tree.node_type == 'value':
56
                self.result = self.tree.value
57
        else:
58
            raise ValueError(
59
                'This converter can process only trees created from OvalNodes.')
60
61
    def _get_node_icon(self):
62
        values = self._get_node_style()
63
        return dict(
64
            color=VALUE_TO_BOOTSTRAP_COLOR[values['test_value']],
65
            icon=VALUE_TO_ICON[values['negation_color']],
66
        )
67
68
    def _get_comment(self):
69
        if self.tree.comment is not None:
70
            return str(self.tree.comment)
71
        return ""
72
73
    def _get_tag(self):
74
        if self.tree.tag is not None:
75
            return str(self.tree.tag)
76
        return ""
77
78
    def _get_not_negate_result(self):
79
        if self.tree.negation and self.tree.node_type == 'operator' and self._is_bool(
80
                self.result):
81
            return self._negate_bool(self.result)
82
        return self.result
83
84
    def _show_node(self, hide_passing_tests):
85
        return not(self.result == 'true' and hide_passing_tests)
86
87
    def _get_node_style(self):
88
        value = self._get_not_negate_result()
89
        out_color = None
90
        if self.tree.negation and self._is_bool(value):
91
            out_color = self._negate_bool(value)
92
        else:
93
            out_color = value
94
        return dict(
95
            negation_color=out_color,
96
            test_value=value,
97
        )
98
99
    @staticmethod
100
    def _get_negation_character(value):
101
        return ('<strong><span class="'
102
                + VALUE_TO_BOOTSTRAP_COLOR[value]
103
                + '">NOT</strong></span>')
104
105
    def _get_label(self):
106
        out = dict(negation=None, str="")
107
        if self.tree.node_type == 'value':
108
            out['negation'] = self._get_negation_label()
109
            out['str'] = re.sub(
110
                '(oval:ssg-test_|oval:ssg-)|(:def:1|:tst:1)', '', str(self.tree.node_id))
111
        else:
112
            if str(self.tree.node_id).startswith('xccdf_org'):
113
                out['str'] = re.sub(
114
                    '(xccdf_org.ssgproject.content_)', '', str(
115
                        self.tree.node_id))
116
            else:
117
                out['negation'] = self._get_negation_label()
118
                out['str'] = (self.tree.value).upper()
119
        return out
120
121
    def _get_negation_label(self):
122
        if self.tree.negation and self._is_bool(self.tree.value):
123
            return self._get_negation_character(self._negate_bool(self.tree.value))
124
        if self.tree.negation and self._is_bool(self.result):
125
            return self._get_negation_character(self.result)
126
        return None
127
128
    @staticmethod
129
    def _negate_bool(value):
130
        values = {
131
            "true": "false",
132
            "false": "true",
133
        }
134
        return values[str(value)]
135
136
    @staticmethod
137
    def _is_bool(value):
138
        return value in ("true", "false")
139
140
    def as_js_tree_dict(self, hide_passing_tests=False):
141
        """Converts the entire OVAL tree to dict according JSON
142
           for graphic representation with JsTree.
143
144
        Args:
145
            hide_passing_tests (bool): bool switch witch enable hiding passing tests
146
147
        Returns:
148
            dict. Dictionary representing OVAL tree
149
        """
150
        icons = self._get_node_icon()
151
        label = self._get_label()
152
        if self.tree.test_result_details:
153
            self.tree.test_result_details['result'] = (
154
                ' <span class="label {color_tag}">{result}</span>'
155
                .format(
156
                    color_tag=BOOTSTRAP_COLOR_TO_LABEL_COLOR[icons['color']],
157
                    result=self.result,
158
                ))
159
        out = {'text':
160
               '{negation} <strong><span class="{icon}">{label}</span></strong>'
161
               ' <span class="label {color_tag}">{tag}</span>'
162
               ' <span class="label {color_tag}">{result}</span>'
163
               ' <i>{comment}</i>'
164
               .format(
165
                   negation=str(label['negation'] if label['negation'] else ""),
166
                   icon=icons['color'],
167
                   label=label['str'],
168
                   color_tag=BOOTSTRAP_COLOR_TO_LABEL_COLOR[icons['color']],
169
                   tag=self._get_tag(),
170
                   result=self._get_not_negate_result(),
171
                   comment=self._get_comment()),
172
               "icon": icons['icon'],
173
               "state": {"opened": self._show_node(hide_passing_tests)},
174
               "info": self.tree.test_result_details,
175
               }
176
        if self.tree.children:
177
            out['children'] = [Converter(child).as_js_tree_dict(
178
                hide_passing_tests) for child in self.tree.children]
179
        return out
180
181
    def as_dict(self):
182
        """Converts the entire OVAL tree to dict.
183
184
        Returns:
185
            dict. Dictionary representing OVAL tree
186
        """
187
        node = self.tree
188
        if not node.children:
189
            return {
190
                'node_id': node.node_id,
191
                'type': node.node_type,
192
                'value': node.value,
193
                'negation': node.negation,
194
                'comment': node.comment,
195
                'tag': node.tag,
196
                'test_result_details': node.test_result_details,
197
                'child': None
198
            }
199
        return {
200
            'node_id': node.node_id,
201
            'type': node.node_type,
202
            'value': node.value,
203
            'negation': node.negation,
204
            'comment': node.comment,
205
            'tag': node.tag,
206
            'test_result_details': node.test_result_details,
207
            'child': [Converter(child).as_dict() for child in node.children]
208
        }
209