Passed
Pull Request — master (#3193)
by Alexander
02:07
created

ssg.xml.map_elements_to_their_ids()   A

Complexity

Conditions 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 4.5185

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 2
dl 0
loc 16
rs 10
c 0
b 0
f 0
ccs 1
cts 7
cp 0.1429
crap 4.5185
1 1
from __future__ import absolute_import
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2 1
from __future__ import print_function
3
4 1
import platform
5
6 1
from .constants import xml_version, oval_header, timestamp
7
8
9 1
try:
10 1
    from xml.etree import cElementTree as ElementTree
11
except ImportError:
12
    import cElementTree as ElementTree
13
14
15 1
def oval_generated_header(product_name, schema_version, ssg_version):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
16 1
    return xml_version + oval_header + \
17
        """
18
    <generator>
19
        <oval:product_name>%s from SCAP Security Guide</oval:product_name>
20
        <oval:product_version>ssg: %s, python: %s</oval:product_version>
21
        <oval:schema_version>%s</oval:schema_version>
22
        <oval:timestamp>%s</oval:timestamp>
23
    </generator>""" % (product_name, ssg_version, platform.python_version(),
24
                       schema_version, timestamp)
25
26
27 1
def parse_file(filename):
28
    """
29
    Given a filename, return the root of the ElementTree
30
    """
31
    return ElementTree.parse(filename).getroot()
32
33
34 1
def map_elements_to_their_ids(tree, xpath_expr):
35
    """
36
    Given an ElementTree and an XPath expression,
37
    iterate through matching elements and create 1:1 id->element mapping.
38
39
    Raises AssertionError if a matching element doesn't have the ``id``
40
    attribute.
41
42
    Returns mapping as a dictionary
43
    """
44
    aggregated = {}
45
    for element in tree.findall(xpath_expr):
46
        element_id = element.get("id")
47
        assert element_id is not None
48
        aggregated[element_id] = element
49
    return aggregated
50