コード例 #1
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml_parse_string_error():
    try:
        xml_parse_string("malformed", "mal", start_line=4)
        assert False
    except ExpatError as e:
        assert e.path == "mal"
        assert e.lineno == 5
コード例 #2
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml2dict_object():
    schema = {
        "type": "dict",
        "name": "foo",
        "dict_type": (
            [
                {
                    "type": "list",
                    "name": "bars",
                    "list_type": {
                        "type": "dict",
                        "name": "bar",
                        "dict_type": ([{"name": "name", "type": "string"}], []),
                    },
                },
                {
                    "type": "list",
                    "name": "bazs",
                    "list_type": {
                        "type": "dict",
                        "name": "baz",
                        "dict_type": (
                            [
                                {"name": "name", "type": "string"},
                                {"name": "bar", "type": "object", "object_group": "bars"},
                            ],
                            [],
                        ),
                    },
                },
            ],
            [],
        ),
    }
    test_xml = """<foo>
<bars>
 <bar><name>A</name></bar>
 <bar><name>B</name></bar>
</bars>
<bazs>
 <baz><name>X</name><bar>A</bar></baz>
</bazs>
</foo>
"""
    parsed = xml2dict(xml_parse_string(test_xml), schema)
    assert parsed["bazs"][0]["bar"]["name"] == "A"

    bad_xml = """<foo>
<bars>
 <bar><name>A</name></bar>
 <bar><name>B</name></bar>
</bars>
<bazs>
 <baz><name>X</name><bar>AA</bar></baz>
</bazs>
</foo>
"""
    with assert_raises(SystemParseError) as e:
        parsed = xml2dict(xml_parse_string(bad_xml), schema)
コード例 #3
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml2dict_optional():
    schema = {"type": "dict", "name": "x", "dict_type": ([{"type": "bool", "name": "b"}], [])}

    test_xml = "<x><b>true</b></x>"
    x = xml2dict(xml_parse_string(test_xml), schema)
    assert x["b"]

    test_xml = "<x></x>"
    with assert_raises(SystemParseError):
        x = xml2dict(xml_parse_string(test_xml), schema)

    # Make the child element optional instead.
    schema["dict_type"][0][0]["optional"] = True
    x = xml2dict(xml_parse_string(test_xml), schema)
    assert x["b"] is None
コード例 #4
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml2dict_bool():
    schema = {"type": "bool", "name": "b"}

    test_xml = "<b>true</b>"
    assert xml2dict(xml_parse_string(test_xml), schema)

    test_xml = "<b>false</b>"
    assert not xml2dict(xml_parse_string(test_xml), schema)

    test_xml = "<b>TrUe</b>"
    assert xml2dict(xml_parse_string(test_xml), schema)

    with assert_raises(SystemParseError):
        test_xml = "<b>bad</b>"
        assert xml2dict(xml_parse_string(test_xml), schema)
コード例 #5
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml2dict_ident_error():
    """Ensure that exceptions raised while parsing bad idents include location information."""
    test_xml = "<foo>_bad</foo>"
    schema = {"type": "ident", "name": "foo"}
    with assert_raises(SystemParseError) as e:
        x = xml2dict(xml_parse_string(test_xml), schema)
    assert "<string>:1.0" in str(e.exception)
コード例 #6
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml_parse_file_with_includes():
    included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root> <newelement1 />   <newelement2> <newelement3/> </newelement2></include_root>"""
    prx_template = """<?xml version="1.0" encoding="UTF-8" ?>
<system>{}
  <modules>
    <module name="foo">
      <bar>baz</bar>
    </module>
  </modules>
</system>"""
    prx_with_include_xml = prx_template.format('<include file="{}" />')
    prx_without_include_xml = prx_template.format("")

    result = check_xml_parse_file_with_includes_with_xml(prx_with_include_xml, included_xml)

    result_dom = xml_parse_string(result.toprettyxml())
    new_el1s = result_dom.getElementsByTagName("newelement1")
    assert len(new_el1s) == 1
    new_el1 = new_el1s[0]
    assert new_el1.parentNode == result_dom

    new_el2s = result_dom.getElementsByTagName("newelement2")
    assert len(new_el2s) == 1
    new_el2 = new_el2s[0]
    assert new_el2.parentNode == result_dom

    new_el3s = result_dom.getElementsByTagName("newelement3")
    assert len(new_el3s) == 1
    new_el3 = new_el3s[0]
    assert new_el3.parentNode == new_el2
コード例 #7
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml_parse_file_with_includes__nested():
    nested_included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root><nested_element /></include_root>"""
    included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root><included_element_1 /> <include file="{}" /> <included_element_2/></include_root>"""
    system_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <include file="{}" />
  <modules>
    <module name="foo">
      <bar>baz</bar>
    </module>
  </modules>
</system>"""
    expected_xml = """<system>
  <included_element_1 /> <nested_element /> <included_element_2/>
  <modules>
    <module name="foo">
      <bar>baz</bar>
    </module>
  </modules>
</system>"""

    result_dom = check_xml_parse_file_with_includes_with_xml(system_xml, included_xml, nested_included_xml)
    expected_dom = xml_parse_string(expected_xml)

    assert result_dom.toxml() == expected_dom.toxml()
コード例 #8
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml2dict_autoindex():
    test_xml = "<list><x><name>foo</name></x><x><name>bar</name></x><x><name>x</name></x></list>"
    schema = {
        "type": "list",
        "name": "list",
        "auto_index_field": "idx",
        "list_type": {"type": "dict", "name": "x", "dict_type": ([{"name": "name", "type": "string"}], [])},
    }
    x = xml2dict(xml_parse_string(test_xml), schema)
コード例 #9
0
ファイル: prj.py プロジェクト: GaloisInc/echronos
    def __init__(self, name, filename):
        """Create a new `Module` with a given `name`.

        The `filename` currently must point to a .c file, but this will be expanded in time.
        `project` is a pointer back to the project in which it exists.

        """
        super().__init__(name)
        self.filename = filename
        self.code_gen = None
        self.headers = []
        self.schema = None  # schema defaults to none

        # Determine what type of Module this is.
        extensions = ['.c', '.s']
        if any([filename.endswith(ext) for ext in extensions]):
            # This is a very non-perfect comment extractor
            state = "find_open"
            content = []
            start_lineno = 0
            for lineno, line in enumerate(open(filename).readlines()):
                if state == "find_open" and line.strip() == '/*<module>':
                    start_lineno = lineno
                    content.append('<module>\n')
                    state = "find_close"
                elif state == "find_close":
                    if line.strip() == "</module>*/":
                        content.append('</module>')
                        break
                    else:
                        content.append(line)
            else:
                if state == "find_close":
                    raise SystemParseError("Didn't find closing module tag")

            if content:
                self._configure_from_xml(xml_parse_string(''.join(content), filename, start_lineno))
            else:
                self.module_type = 'default'
                # If the module doesn't have something specified explicitly then if there is
                # <module>.h, then use that.
                possible_header = filename[:-1] + 'h'
                if os.path.exists(possible_header):
                    self.headers.append(Header(possible_header, None, None))

        elif filename.endswith('.s') or filename.endswith('.asm'):
            self.module_type = 'default'
        else:
            raise SystemParseError("Module %s[%s] has invalid filename" % (name, filename))
コード例 #10
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def check_xml_parse_file_with_includes__absolute_relative(absolute):
    try:
        included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root><included_element /></include_root>"""
        main_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <include file="{}" />
</system>"""
        expected_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <included_element />
</system>"""

        included_dir = tempfile.TemporaryDirectory()
        main_dir = tempfile.TemporaryDirectory()

        included_file = tempfile.NamedTemporaryFile(mode="w", delete=False, dir=included_dir.name)
        included_file.write(included_xml)
        included_file.close()

        with open(os.path.join(main_dir.name, os.path.basename(included_file.name)), "w") as empty_file:
            empty_file.write("""<?xml version="1.0" encoding="UTF-8" ?><include_root></include_root>""")

        if absolute:
            included_path = os.path.abspath(included_file.name)
        else:
            included_path = os.path.join(
                "..", os.path.basename(included_dir.name), os.path.basename(included_file.name)
            )
        main_xml = main_xml.format(included_path)
        main_file = tempfile.NamedTemporaryFile(mode="w", delete=False, dir=main_dir.name)
        main_file.write(main_xml)
        main_file.close()

        result_dom = xml_parse_file_with_includes(main_file.name)
        expected_dom = xml_parse_string(expected_xml)

        assert result_dom.toxml() == expected_dom.toxml()

    finally:
        for dir in [included_dir, main_dir]:
            dir.cleanup()
コード例 #11
0
def check_xml_parse_file_with_includes__absolute_relative(absolute):
    try:
        included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root><included_element /></include_root>"""
        main_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <include file="{}" />
</system>"""
        expected_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <included_element />
</system>"""

        included_dir = tempfile.TemporaryDirectory()
        main_dir = tempfile.TemporaryDirectory()

        included_file = tempfile.NamedTemporaryFile(mode='w', delete=False, dir=included_dir.name)
        included_file.write(included_xml)
        included_file.close()

        with open(os.path.join(main_dir.name, os.path.basename(included_file.name)), 'w') as empty_file:
            empty_file.write("""<?xml version="1.0" encoding="UTF-8" ?><include_root></include_root>""")

        if absolute:
            included_path = os.path.abspath(included_file.name)
        else:
            included_path = os.path.join('..', os.path.basename(included_dir.name),
                                         os.path.basename(included_file.name))
        main_xml = main_xml.format(included_path)
        main_file = tempfile.NamedTemporaryFile(mode='w', delete=False, dir=main_dir.name)
        main_file.write(main_xml)
        main_file.close()

        result_dom = xml_parse_file_with_includes(main_file.name)
        expected_dom = xml_parse_string(expected_xml)

        assert result_dom.toxml() == expected_dom.toxml()

    finally:
        for include_dir in [included_dir, main_dir]:
            include_dir.cleanup()
コード例 #12
0
ファイル: prj.py プロジェクト: GaloisInc/echronos
    def __init__(self):
        """Initialise the module.

        Module initialisation will ensures the class is correctly constructed.
        If the xml_schema is set, initialisation will set the schema based on the xml_schema.

        """
        if len(set([self.schema, self.xml_schema, self.xml_schema_path])) > 2:
            raise Exception("Class '{}' in {} has multiple schema sources set.".format(self.__class__.__name__,
                            os.path.abspath(inspect.getfile(self.__class__))))

        if self.schema is NOTHING:
            if self.xml_schema_path is not NOTHING:
                xml_schema_document = xml_parse_file(self.xml_schema_path)
            elif self.xml_schema is not NOTHING:
                filename = sys.modules[self.__class__.__module__].__file__
                xml_schema_document = xml_parse_string(self.xml_schema, '{}!xml_schema'.format(filename))
            else:
                raise Exception("Class '{}' in {} has none of the possible schema sources (schema, xml_schema, \
xml_schema_path) set as a class member.".format(self.__class__.__name__,
                                                os.path.abspath(inspect.getfile(self.__class__))))
            self.schema = xml2schema(xml_schema_document)
コード例 #13
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml_parse_file_with_includes__include_paths():
    try:
        included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root><included_element /></include_root>"""
        main_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <include file="{}" />
</system>"""
        expected_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <included_element />
</system>"""

        include_dirs = [tempfile.TemporaryDirectory() for _ in range(3)]
        included_dir = include_dirs[1]
        main_dir = tempfile.TemporaryDirectory()

        included_file = tempfile.NamedTemporaryFile(mode="w", delete=False, dir=included_dir.name)
        included_file.write(included_xml)
        included_file.close()

        with open(os.path.join(include_dirs[2].name, os.path.basename(included_file.name)), "w") as empty_file:
            empty_file.write("""<?xml version="1.0" encoding="UTF-8" ?><include_root></include_root>""")

        main_xml = main_xml.format(os.path.basename(included_file.name))
        main_file = tempfile.NamedTemporaryFile(mode="w", delete=False, dir=main_dir.name)
        main_file.write(main_xml)
        main_file.close()

        result_dom = xml_parse_file_with_includes(main_file.name, [d.name for d in include_dirs])
        expected_dom = xml_parse_string(expected_xml)

        assert result_dom.toxml() == expected_dom.toxml()

    finally:
        for dir in include_dirs:
            dir.cleanup()
コード例 #14
0
    def test_xml_parse_file_with_includes__include_paths(self):
        try:
            included_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<include_root><included_element /></include_root>"""
            main_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <include file="{}" />
</system>"""
            expected_xml = """<?xml version="1.0" encoding="UTF-8" ?>
<system>
  <included_element />
</system>"""

            include_dirs = [tempfile.TemporaryDirectory() for _ in range(3)]
            included_dir = include_dirs[1]
            main_dir = tempfile.TemporaryDirectory()

            included_file = tempfile.NamedTemporaryFile(mode='w', delete=False, dir=included_dir.name)
            included_file.write(included_xml)
            included_file.close()

            with open(os.path.join(include_dirs[2].name, os.path.basename(included_file.name)), 'w') as empty_file:
                empty_file.write("""<?xml version="1.0" encoding="UTF-8" ?><include_root></include_root>""")

            main_xml = main_xml.format(os.path.basename(included_file.name))
            main_file = tempfile.NamedTemporaryFile(mode='w', delete=False, dir=main_dir.name)
            main_file.write(main_xml)
            main_file.close()

            result_dom = xml_parse_file_with_includes(main_file.name, [dir_path.name for dir_path in include_dirs])
            expected_dom = xml_parse_string(expected_xml)

            self.assertEqual(result_dom.toxml(), expected_dom.toxml())

        finally:
            for include_dir in include_dirs:
                include_dir.cleanup()
コード例 #15
0
    def __init__(self):
        """Initialise the module.

        Module initialisation will ensures the class is correctly constructed.
        If the xml_schema is set, initialisation will set the schema based on the xml_schema.

        """
        self.name = None

        if len(set([self.schema, self.xml_schema, self.xml_schema_path])) > 2:
            raise Exception("Class '{}' in {} has multiple schema sources set."
                            .format(self.__class__.__name__, os.path.abspath(inspect.getfile(self.__class__))))

        if self.schema is NOTHING:
            if self.xml_schema_path is not NOTHING:
                xml_schema_document = xml_parse_file(self.xml_schema_path)
            elif self.xml_schema is not NOTHING:
                filename = sys.modules[self.__class__.__module__].__file__
                xml_schema_document = xml_parse_string(self.xml_schema, '{}!xml_schema'.format(filename))
            else:
                raise Exception("Class '{}' in {} has none of the possible schema sources (schema, xml_schema, \
xml_schema_path) set as a class member.".format(self.__class__.__name__,
                                                os.path.abspath(inspect.getfile(self.__class__))))
            self.schema = xml2schema(xml_schema_document)
コード例 #16
0
 def test_get_attribute_normal(self):
     dom = xml_parse_string('<foo x="X"/>')
     self.assertEqual(get_attribute(dom, 'x'), 'X')
     self.assertEqual(get_attribute(dom, 'x', None), 'X')
コード例 #17
0
 def test_get_attribute_error(self):
     dom = xml_parse_string('<foo/>')
     self.assertRaises(SystemParseError, get_attribute, dom, 'x')
コード例 #18
0
 def test_single_text_child_a(self):
     dom = xml_parse_string('<x></x>')
     self.assertEqual(single_text_child(dom), '')
コード例 #19
0
 def test_xml2dict_empty_node(self):
     xml = """<list></list>"""
     expected = ''
     self.assertEqual(xml2dict(xml_parse_string(xml)), expected)
コード例 #20
0
def test_xml_parse_string():
    dom = xml_parse_string('<x/>', 'mal', start_line=4)
    assert dom.tagName == 'x'
    assert dom.ownerDocument.firstChild == dom
    assert dom.ownerDocument.start_line == 4
    assert dom.ownerDocument.path == 'mal'
コード例 #21
0
def test_ensure_all_children_named_multiple_success():
    xml = "<foo><bar /><bar /><bar /><baz /></foo>"
    ensure_all_children_named(xml_parse_string(xml), 'bar', 'baz')
コード例 #22
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml2dict_length_prop():
    test_xml = "<list><li>foo</li><li>bar</li><li>baz</li></list>"
    x = xml2dict(xml_parse_string(test_xml))
    assert x.length == 3
コード例 #23
0
ファイル: prj.py プロジェクト: GaloisInc/echronos
    def __init__(self, filename, search_paths=None, prx_include_paths=None):
        """Parses the project definition file `filename` and any imported system and module definition files.

        If filename is None, then a default 'empty' project is created.

        The search path for a project is a list of paths in which modules will be searched.
        The order of the search path matters; the first path in which an entity is found is used.

        The search path consists of the 'user' search paths, and the 'built-in' search paths.
        'user' search paths are searched before 'built-in' search paths.

        The 'user' search paths consist of the 'param' search paths as passed explicitly to the class and
        the 'project' search paths, which are any search paths specified in the project file.
        'param' search paths are searched before the 'project' search paths.
        If no 'param' search paths or 'project' search paths are specified, then the 'user' search path
        defaults to the project file's directory (or the current working directory if no project file is specified.)

        """
        if filename is None:
            self.dom = xml_parse_string('<project></project>')
            self.project_dir = os.getcwd()
        else:
            self.dom = xml_parse_file(filename)
            self.project_dir = os.path.dirname(filename)

        self.entities = {}

        # Find all startup-script items.
        ss_els = self.dom.getElementsByTagName('startup-script')
        for ss in ss_els:
            command = single_text_child(ss)
            if command.split()[0].endswith('.py'):
                # prepend full path of python interpreter as .py files are not necessarily executable on Windows
                # and the command 'python3.3' is likely not in PATH
                command = '{} {}'.format(sys.executable, command)
            ret_code = os.system(command)
            if ret_code != 0:
                err = xml_error_str(ss, "Error running startup-script"
                                        ": '{}' {}".format(command, show_exit(ret_code)))
                raise ProjectStartupError(err)

        param_search_paths = search_paths if search_paths is not None else []
        project_search_paths = list(get_paths_from_dom(self.dom, 'search-path'))
        user_search_paths = param_search_paths + project_search_paths
        if len(user_search_paths) == 0:
            user_search_paths = [self.project_dir]

        built_in_search_paths = []
        if frozen:
            base_file = sys.executable if frozen else __file__
            base_file = follow_link(base_file)

            base_dir = canonical_path(os.path.dirname(base_file))

            def find_share(cur):
                cur = canonical_path(cur)
                maybe_share_path = os.path.join(cur, 'share')
                if os.path.exists(maybe_share_path):
                    return maybe_share_path
                else:
                    up = canonical_path(os.path.join(cur, os.path.pardir))
                    if up == cur:
                        return None
                    return find_share(up)
            share_dir = find_share(base_dir)
            if share_dir is None or not os.path.isdir(share_dir):
                logger.warning("Unable to find 'share' directory.")
            else:
                packages_dir = os.path.join(share_dir, 'packages')
                if not os.path.exists(packages_dir) or not os.path.isdir(packages_dir):
                    logger.warning("Can't find 'packages' directory in '{}'".format(share_dir))
                else:
                    built_in_search_paths.append(packages_dir)

        self.search_paths = user_search_paths + built_in_search_paths

        logger.debug("search_paths %s", self.search_paths)

        param_prx_include_paths = prx_include_paths if prx_include_paths is not None else []
        self._prx_include_paths = list(get_paths_from_dom(self.dom, 'prx-include-path')) + param_prx_include_paths

        output_el = maybe_single_named_child(self.dom, 'output')
        if output_el:
            path = get_attribute(output_el, 'path')
        else:
            path = 'out'
        if os.path.isabs(path):
            self.output = path
        else:
            self.output = os.path.join(self.project_dir, path)
コード例 #24
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_ensure_all_children_named_multiple_success():
    xml = "<foo><bar /><bar /><bar /><baz /></foo>"
    ensure_all_children_named(xml_parse_string(xml), "bar", "baz")
コード例 #25
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_ensure_all_children_named_error():
    xml = "<foo><bar /><baz /><bar /></foo>"
    ensure_all_children_named(xml_parse_string(xml), "bar")
コード例 #26
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_ensure_unique_tag_names_non_unique():
    non_unique = "<foo><bar /><baz /><bar /></foo>"
    ensure_unique_tag_names(element_children(xml_parse_string(non_unique)))
コード例 #27
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_xml_parse_string():
    dom = xml_parse_string("<x/>", "mal", start_line=4)
    assert dom.tagName == "x"
    assert dom.ownerDocument.firstChild == dom
    assert dom.ownerDocument.start_line == 4
    assert dom.ownerDocument.path == "mal"
コード例 #28
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_get_attribute_normal():
    dom = xml_parse_string('<foo x="X"/>')
    assert get_attribute(dom, "x") == "X"
    assert get_attribute(dom, "x", None) == "X"
コード例 #29
0
 def test_ensure_unique_tag_names_unique(self):  # pylint: disable=no-self-use
     unique = "<foo><bar /><baz /><qux /></foo>"
     ensure_unique_tag_names(element_children(xml_parse_string(unique)))
コード例 #30
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_schema_default_value():
    schema = {"type": "dict", "name": "foo", "dict_type": ([{"type": "string", "name": "bar", "default": "FOO"}], [])}
    assert xml2dict(xml_parse_string("<foo></foo>"), schema) == {"bar": "FOO"}
    assert xml2dict(xml_parse_string("<foo><bar>BAZ</bar></foo>"), schema) == {"bar": "BAZ"}
コード例 #31
0
 def test_ensure_all_children_named_multiple_success(self):  # pylint: disable=no-self-use
     xml = "<foo><bar /><bar /><bar /><baz /></foo>"
     ensure_all_children_named(xml_parse_string(xml), 'bar', 'baz')
コード例 #32
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_schema_default_none():
    test_xml = "<foo></foo>"
    schema = {"type": "dict", "name": "foo", "dict_type": ([{"type": "string", "name": "foo"}], [])}
    with assert_raises(SystemParseError):
        xml2dict(xml_parse_string(test_xml), schema)
コード例 #33
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_get_attribute_error():
    dom = xml_parse_string("<foo/>")
    get_attribute(dom, "x")
コード例 #34
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
 def check(xml, result):
     assert xml2dict(xml_parse_string(xml)) == result
コード例 #35
0
def test_ensure_unique_tag_names_non_unique():
    non_unique = "<foo><bar /><baz /><bar /></foo>"
    ensure_unique_tag_names(element_children(xml_parse_string(non_unique)))
コード例 #36
0
    def __init__(self, filename, search_paths=None, prx_include_paths=None):
        """Parses the project definition file `filename` and any imported system and module definition files.

        If filename is None, then a default 'empty' project is created.

        The search path for a project is a list of paths in which modules will be searched.
        The order of the search path matters; the first path in which an entity is found is used.

        The search path consists of the 'user' search paths, and the 'built-in' search paths.
        'user' search paths are searched before 'built-in' search paths.

        The 'user' search paths consist of the 'param' search paths as passed explicitly to the class and
        the 'project' search paths, which are any search paths specified in the project file.
        'param' search paths are searched before the 'project' search paths.
        If no 'param' search paths or 'project' search paths are specified, then the 'user' search path
        defaults to the project file's directory (or the current working directory if no project file is specified.)

        """
        if filename is None:
            self.dom = xml_parse_string('<project></project>')
            self.project_dir = os.getcwd()
        else:
            self.dom = xml_parse_file(filename)
            self.project_dir = os.path.dirname(filename)

        self.entities = {}

        # Find all startup-script items.
        ss_els = self.dom.getElementsByTagName('startup-script')
        for ss in ss_els:
            command = single_text_child(ss)
            if command.split()[0].endswith('.py'):
                # prepend full path of python interpreter as .py files are not necessarily executable on Windows
                # and the command 'python3.3' is likely not in PATH
                command = '{} {}'.format(sys.executable, command)
            ret_code = os.system(command)
            if ret_code != 0:
                err = xml_error_str(
                    ss, "Error running startup-script"
                    ": '{}' {}".format(command, show_exit(ret_code)))
                raise ProjectStartupError(err)

        param_search_paths = search_paths if search_paths is not None else []
        project_search_paths = list(get_paths_from_dom(self.dom,
                                                       'search-path'))
        user_search_paths = param_search_paths + project_search_paths
        if len(user_search_paths) == 0:
            user_search_paths = [self.project_dir]

        built_in_search_paths = []
        if frozen:
            base_file = sys.executable if frozen else __file__
            base_file = follow_link(base_file)

            base_dir = canonical_path(os.path.dirname(base_file))

            def find_share(cur):
                cur = canonical_path(cur)
                maybe_share_path = os.path.join(cur, 'share')
                if os.path.exists(maybe_share_path):
                    return maybe_share_path
                else:
                    up = canonical_path(os.path.join(cur, os.path.pardir))
                    if up == cur:
                        return None
                    return find_share(up)

            share_dir = find_share(base_dir)
            if share_dir is None or not os.path.isdir(share_dir):
                logger.warning("Unable to find 'share' directory.")
            else:
                packages_dir = os.path.join(share_dir, 'packages')
                if not os.path.exists(packages_dir) or not os.path.isdir(
                        packages_dir):
                    logger.warning(
                        "Can't find 'packages' directory in '{}'".format(
                            share_dir))
                else:
                    built_in_search_paths.append(packages_dir)

        self.search_paths = user_search_paths + built_in_search_paths

        logger.debug("search_paths %s", self.search_paths)

        param_prx_include_paths = prx_include_paths if prx_include_paths is not None else []
        self._prx_include_paths = list(
            get_paths_from_dom(self.dom,
                               'prx-include-path')) + param_prx_include_paths

        output_el = maybe_single_named_child(self.dom, 'output')
        if output_el:
            path = get_attribute(output_el, 'path')
        else:
            path = 'out'
        if os.path.isabs(path):
            self.output = path
        else:
            self.output = os.path.join(self.project_dir, path)
コード例 #37
0
def test_ensure_all_children_named_error():
    xml = "<foo><bar /><baz /><bar /></foo>"
    ensure_all_children_named(xml_parse_string(xml), 'bar')
コード例 #38
0
def test_single_text_child_a():
    dom = xml_parse_string('<x></x>')
    assert single_text_child(dom) == ''
コード例 #39
0
 def test_xml2dict_single_item_list(self):
     xml = """<list>
       <a>foo</a>
      </list>"""
     expected = ['foo']
     self.assertEqual(xml2dict(xml_parse_string(xml)), expected)
コード例 #40
0
 def check(xml, result):
     assert xml2dict(xml_parse_string(xml)) == result
コード例 #41
0
 def test_xml2dict_length_prop(self):
     test_xml = "<list><li>foo</li><li>bar</li><li>baz</li></list>"
     test_dict = xml2dict(xml_parse_string(test_xml))
     self.assertEqual(test_dict.length, 3)
コード例 #42
0
def test_xml2dict_length_prop():
    test_xml = "<list><li>foo</li><li>bar</li><li>baz</li></list>"
    x = xml2dict(xml_parse_string(test_xml))
    assert x.length == 3
コード例 #43
0
 def test_get_attribute_default(self):
     dom = xml_parse_string('<foo/>')
     self.assertIsNone(get_attribute(dom, 'x', None))
     expected_value = '5'
     self.assertIs(get_attribute(dom, 'x', expected_value), expected_value)
コード例 #44
0
def test_xml2dict_object():
    schema = {
        'type':
        'dict',
        'name':
        'foo',
        'dict_type': ([{
            'type': 'list',
            'name': 'bars',
            'list_type': {
                'type': 'dict',
                'name': 'bar',
                'dict_type': ([{
                    'name': 'name',
                    'type': 'string'
                }], [])
            }
        }, {
            'type': 'list',
            'name': 'bazs',
            'list_type': {
                'type':
                'dict',
                'name':
                'baz',
                'dict_type': ([{
                    'name': 'name',
                    'type': 'string'
                }, {
                    'name': 'bar',
                    'type': 'object',
                    'object_group': 'bars'
                }], [])
            }
        }], [])
    }
    test_xml = """<foo>
<bars>
 <bar><name>A</name></bar>
 <bar><name>B</name></bar>
</bars>
<bazs>
 <baz><name>X</name><bar>A</bar></baz>
</bazs>
</foo>
"""
    parsed = xml2dict(xml_parse_string(test_xml), schema)
    assert parsed['bazs'][0]['bar']['name'] == 'A'

    bad_xml = """<foo>
<bars>
 <bar><name>A</name></bar>
 <bar><name>B</name></bar>
</bars>
<bazs>
 <baz><name>X</name><bar>AA</bar></baz>
</bazs>
</foo>
"""
    with assert_raises(SystemParseError) as e:
        parsed = xml2dict(xml_parse_string(bad_xml), schema)
コード例 #45
0
 def test_xml_parse_string(self):
     dom = xml_parse_string('<x/>', 'mal', start_line=4)
     self.assertEqual(dom.tagName, 'x')
     self.assertEqual(dom.ownerDocument.firstChild, dom)
     self.assertEqual(dom.ownerDocument.start_line, 4)
     self.assertEqual(dom.ownerDocument.path, 'mal')
コード例 #46
0
def test_get_attribute_normal():
    dom = xml_parse_string('<foo x="X"/>')
    assert get_attribute(dom, 'x') == 'X'
    assert get_attribute(dom, 'x', None) == 'X'
コード例 #47
0
 def test_ensure_unique_tag_names_non_unique(self):
     non_unique = "<foo><bar /><baz /><bar /></foo>"
     self.assertRaises(SystemParseError, ensure_unique_tag_names, element_children(xml_parse_string(non_unique)))
コード例 #48
0
def test_get_attribute_default():
    dom = xml_parse_string('<foo/>')
    assert get_attribute(dom, 'x', None) is None
    assert get_attribute(dom, 'x', '5') is '5'
コード例 #49
0
 def test_ensure_all_children_named_error(self):
     xml = "<foo><bar /><baz /><bar /></foo>"
     self.assertRaises(SystemParseError, ensure_all_children_named, xml_parse_string(xml), 'bar')
コード例 #50
0
def test_get_attribute_error():
    dom = xml_parse_string('<foo/>')
    get_attribute(dom, 'x')
コード例 #51
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_single_text_child_a():
    dom = xml_parse_string("<x></x>")
    assert single_text_child(dom) == ""
コード例 #52
0
ファイル: prj_test.py プロジェクト: GaloisInc/echronos
def test_get_attribute_default():
    dom = xml_parse_string("<foo/>")
    assert get_attribute(dom, "x", None) is None
    assert get_attribute(dom, "x", "5") is "5"