Passed
Pull Request — master (#173)
by Jan
04:26
created

Converter._get_node_icon()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nop 1
crap 1
1
"""
2
    This file contains a class for converting OVAL tree to according JSON used in HTML
3
"""
4
5 1
import re
6
7 1
from .oval_node import OvalNode
8
9 1
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 1
BOOTSTRAP_COLOR_TO_LABEL_COLOR = {
19
    "text-success": "label-success",
20
    "text-danger": "label-danger",
21
    "text-dark": "label-default"
22
}
23
24 1
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 1
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 1
    def __init__(self, tree):
44
        """This metode construct Converter.
45
46
        Args:
47
            tree (OvalNode): OVAL tree
48
49
        Raises:
50
            ValueError
51
        """
52 1
        if isinstance(tree, OvalNode):
53 1
            self.tree = tree
54 1
            self.result = self.tree.evaluate_tree()
55 1
            if self.tree.node_type == 'value':
56 1
                self.result = self.tree.value
57
        else:
58
            raise ValueError(
59
                'This converter can process only trees created from OvalNodes.')
60
61 1
    def _get_node_icon(self):
62 1
        values = self._get_node_style()
63 1
        return dict(
64
            color=VALUE_TO_BOOTSTRAP_COLOR[values['test_value']],
65
            icon=VALUE_TO_ICON[values['negation_color']],
66
        )
67
68 1
    def _get_comment(self):
69 1
        if self.tree.comment is not None:
70 1
            return str(self.tree.comment)
71 1
        return ""
72
73 1
    def _get_tag(self):
74 1
        if self.tree.tag is not None:
75 1
            return str(self.tree.tag)
76 1
        return ""
77
78 1
    def _get_not_negate_result(self):
79 1
        if self.tree.negation and self.tree.node_type == 'operator' and self._is_bool(
80
                self.result):
81 1
            return self._negate_bool(self.result)
82 1
        return self.result
83
84 1
    def _show_node(self, hide_passing_tests):
85 1
        return not(self.result == 'true' and hide_passing_tests)
86
87 1
    def _get_node_style(self):
88 1
        value = self._get_not_negate_result()
89 1
        out_color = None
90 1
        if self.tree.negation and self._is_bool(value):
91 1
            out_color = self._negate_bool(value)
92
        else:
93 1
            out_color = value
94 1
        return dict(
95
            negation_color=out_color,
96
            test_value=value,
97
        )
98
99 1
    @staticmethod
100
    def _get_negation_character(value):
101 1
        return ('<strong><span class="'
102
                + VALUE_TO_BOOTSTRAP_COLOR[value]
103
                + '">NOT</strong></span>')
104
105 1
    def _get_label(self):
106 1
        out = dict(negation=None, str="")
107 1
        if self.tree.node_type == 'value':
108 1
            out['negation'] = self._get_negation_label()
109 1
            out['str'] = re.sub(
110
                '(oval:ssg-test_|oval:ssg-)|(:def:1|:tst:1)', '', str(self.tree.node_id))
111
        else:
112 1
            if str(self.tree.node_id).startswith('xccdf_org'):
113 1
                out['str'] = re.sub(
114
                    '(xccdf_org.ssgproject.content_)', '', str(
115
                        self.tree.node_id))
116
            else:
117 1
                out['negation'] = self._get_negation_label()
118 1
                out['str'] = (self.tree.value).upper()
119 1
        return out
120
121 1
    def _get_negation_label(self):
122 1
        if self.tree.negation and self._is_bool(self.tree.value):
123 1
            return self._get_negation_character(self._negate_bool(self.tree.value))
124 1
        if self.tree.negation and self._is_bool(self.result):
125 1
            return self._get_negation_character(self.result)
126 1
        return None
127
128 1
    @staticmethod
129
    def _negate_bool(value):
130 1
        values = {
131
            "true": "false",
132
            "false": "true",
133
        }
134 1
        return values[str(value)]
135
136 1
    @staticmethod
137
    def _is_bool(value):
138 1
        return value in ("true", "false")
139
140 1
    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 1
        icons = self._get_node_icon()
151 1
        label = self._get_label()
152 1
        if self.tree.test_result_details:
153 1
            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 1
        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 1
        if self.tree.children:
177 1
            out['children'] = [Converter(child).as_js_tree_dict(
178
                hide_passing_tests) for child in self.tree.children]
179 1
        return out
180
181 1
    def as_dict(self):
182
        """Converts the entire OVAL tree to dict.
183
184
        Returns:
185
            dict. Dictionary representing OVAL tree
186
        """
187 1
        node = self.tree
188 1
        if not node.children:
189 1
            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 1
        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