def test_namespace_support(self): obj = OrderedDict((('http://defaultns.com/:root', OrderedDict(( ('@xmlns', OrderedDict(( ('', 'http://defaultns.com/'), ('a', 'http://a.com/'), ('b', 'http://b.com/'), ))), ('http://defaultns.com/:x', OrderedDict(( ('@http://a.com/:attr', 'val'), ('#text', '1'), ))), ('http://a.com/:y', '2'), ('http://b.com/:z', '3'), ))), )) ns = { 'http://defaultns.com/': '', 'http://a.com/': 'a', 'http://b.com/': 'b', } expected_xml = '''<?xml version="1.0" encoding="utf-8"?> <root xmlns="http://defaultns.com/" xmlns:a="http://a.com/" \ xmlns:b="http://b.com/"><x a:attr="val">1</x><a:y>2</a:y><b:z>3</b:z></root>''' xml = unparse(obj, namespaces=ns) self.assertEqual(xml, expected_xml)
def parseDimension(dimension: xmltodict.OrderedDict) -> dict: """Parse the dimension/extent defintions (WMS Version 1.1.1/1.3.0) :param dimension: the WMS GetCapabilities 'Dimension' :type dimension: xmltodict.OrderedDict :raises ValueError: If dimension could not be parsed :return: a dictionary {"name": X, "values": Y, "default": Z}, could contain 'None' values :rtype: dict """ try: #use defined values defined or try to fallback to @default name = dimension["@name"] if "@name" in dimension.keys() else None default = dimension["@default"] if "@default" in dimension.keys( ) else None values = dimension["#text"] if "#text" in dimension.keys() else default dim = { "name": name, "values": values, #possible values "default": default #optional default value } except: # some required attribute was missing raise ValueError(f"Could not parse dimension '{dimension}'.") if dim["name"] == "time": times = enumerateAvailableTimes(dim["values"]) dim["values"] = times return dim
def test_multiple_roots_nofulldoc(self): obj = OrderedDict((('a', 1), ('b', 2))) xml = unparse(obj, full_document=False) self.assertEqual(xml, '<a>1</a><b>2</b>') obj = {'a': [1, 2]} xml = unparse(obj, full_document=False) self.assertEqual(xml, '<a>1</a><a>2</a>')
def test_preprocessor(self): obj = {'a': OrderedDict((('b:int', [1, 2]), ('b', 'c')))} def p(key, value): try: key, _ = key.split(':') except ValueError: pass return key, value self.assertEqual(_strip(unparse(obj, preprocessor=p)), '<a><b>1</b><b>2</b><b>c</b></a>')
def _emit(key, value, content_handler, attr_prefix='@', cdata_key='#text', depth=0, preprocessor=None, pretty=False, newl='\n', indent='\t'): if preprocessor is not None: result = preprocessor(key, value) if result is None: return key, value = result if not isinstance(value, (list, tuple)): value = [value] if depth == 0 and len(value) > 1: raise ValueError('document with multiple roots') for v in value: if v is None: v = OrderedDict() elif not isinstance(v, dict): v = _unicode(v) if isinstance(v, _basestring): v = OrderedDict(((cdata_key, v), )) cdata = None attrs = OrderedDict() children = [] for ik, iv in v.items(): if ik == cdata_key: cdata = iv continue if ik.startswith(attr_prefix): attrs[ik[len(attr_prefix):]] = iv continue children.append((ik, iv)) if pretty: content_handler.ignorableWhitespace(depth * indent) content_handler.startElement(key, AttributesImpl(attrs)) if pretty and children: content_handler.ignorableWhitespace(newl) for child_key, child_value in children: _emit(child_key, child_value, content_handler, attr_prefix, cdata_key, depth + 1, preprocessor, pretty, newl, indent) if cdata is not None: content_handler.characters(cdata) if pretty and children: content_handler.ignorableWhitespace(depth * indent) content_handler.endElement(key) if pretty and depth: content_handler.ignorableWhitespace(newl)
def test_pretty_print(self): obj = {'a': OrderedDict(( ('b', [{'c': [1, 2]}, 3]), ('x', 'y'), ))} newl = '\n' indent = '....' xml = dedent('''\ <?xml version="1.0" encoding="utf-8"?> <a> ....<b> ........<c>1</c> ........<c>2</c> ....</b> ....<b>3</b> ....<x>y</x> </a>''') self.assertEqual(xml, unparse(obj, pretty=True, newl=newl, indent=indent))
def test_get_physical_entities_no_classification(pes_object): pes_object._rpc_reply = MockRPCReply(test_xml) assert pes_object.get_physical_entities() == OrderedDict([('a-string', 'something')])
def test_physical_entities(pes_object): pes_object._rpc_reply = MockRPCReply(test_xml) assert pes_object.physical_entities == OrderedDict([('a-string', 'something')])
from voltha.adapters.adtran_olt.codec.physical_entities_state import PhysicalEntitiesState class MockRPCReply(object): def __init__(self, data_xml): self.data_xml = data_xml expected_ordered_dict_output = [ OrderedDict( [(u'name', u'temperature 0/1'), (u'availability', OrderedDict( [(u'@xmlns', u'http://www.adtran.com/ns/yang/adtran-physical-entity-availability'), (u'availability-status', None)] )), (u'classification', OrderedDict( [(u'@xmlns:adtn-phys-sens', u'http://www.adtran.com/ns/yang/adtran-physical-sensors'), ('#text', u'adtn-phys-sens:temperature-sensor-celsius')])), (u'is-field-replaceable', u'false') ] ) ] @pytest.fixture() def mock_session(): return mock.MagicMock() @pytest.fixture() def pes_object(mock_session):
def _emit( key, value, content_handler, attr_prefix="@", cdata_key="#text", depth=0, preprocessor=None, pretty=False, newl="\n", indent="\t", ): if preprocessor is not None: result = preprocessor(key, value) if result is None: return key, value = result if not isinstance(value, (list, tuple)): value = [value] if depth == 0 and len(value) > 1: raise ValueError("document with multiple roots") for v in value: if v is None: v = OrderedDict() elif not isinstance(v, dict): v = _unicode(v) if isinstance(v, _basestring): v = OrderedDict(((cdata_key, v),)) cdata = None attrs = OrderedDict() children = [] for ik, iv in v.items(): if ik == cdata_key: cdata = iv continue if ik.startswith(attr_prefix): attrs[ik[len(attr_prefix) :]] = iv continue children.append((ik, iv)) if pretty: content_handler.ignorableWhitespace(depth * indent) content_handler.startElement(key, AttributesImpl(attrs)) if pretty and children: content_handler.ignorableWhitespace(newl) for child_key, child_value in children: _emit( child_key, child_value, content_handler, attr_prefix, cdata_key, depth + 1, preprocessor, pretty, newl, indent, ) if cdata is not None: content_handler.characters(cdata) if pretty and children: content_handler.ignorableWhitespace(depth * indent) content_handler.endElement(key) if pretty and depth: content_handler.ignorableWhitespace(newl)
#!/bin/env python3 from xmltodict import OrderedDict # WMS 1.3.0 GetCapabilities #with open("GetCapabilities_1.3.0.xml", "r",1024, "utf-8") as stream: # capabilities = xmltodict.parse(stream.read()) # layers = capabilities["WMS_Capabilities"]["Capability"]["Layer"]["Layer"] layers = [ OrderedDict([('@queryable', ''), ('Name', 'background'), ('Title', 'Background'), ('KeywordList', None)]), OrderedDict([ ('@queryable', ''), ('Name', 'CLCH_0'), ('Title', 'Cloud Cover (0 - 400 hPa) at 0'), ('KeywordList', None), ('Dimension', OrderedDict([('@name', 'time'), ('@units', 'ISO8601')])), ('Extent', OrderedDict([ ('@name', 'time'), ('@default', '2019-11-07T09:00:00Z'), ('@multipleValues', '0'), ('@nearestValue', '0'), ('#text', '2019-11-07T09:00:00Z,2019-11-09T21:00:00Z/2019-11-22T09:00:00Z/PT60H' ) ])), ('Style', OrderedDict([ ('Name', 'default'), ('Title', 'title to come'), ('Abstract', 'description to come'), ('LegendURL', OrderedDict([ ('@width', ''), ('@height', ''), ('Format', 'image/png'), ('OnlineResource', OrderedDict([