示例#1
0
    def test_prune_etree_function(self):
        root = ElementTree.XML('<A id="0"><B/><C/><D/></A>')
        self.assertFalse(prune_etree(root, lambda x: x.tag == 'C'))
        self.assertListEqual([e.tag for e in root.iter()], ['A', 'B', 'D'])
        self.assertEqual(root.attrib, {'id': '0'})

        root = ElementTree.XML('<A id="1"><B/><C/><D/></A>')
        self.assertTrue(prune_etree(root, lambda x: x.tag != 'C'))
        self.assertListEqual([e.tag for e in root.iter()], ['A'])
        self.assertEqual(root.attrib, {'id': '1'})

        class SelectorClass:
            tag = 'C'

            @classmethod
            def class_method(cls, elem):
                return elem.tag == cls.tag

            def method(self, elem):
                return elem.tag != self.tag

        selector = SelectorClass()

        root = ElementTree.XML('<A id="0"><B/><C/><D/></A>')
        self.assertFalse(prune_etree(root, selector.class_method))
        self.assertListEqual([e.tag for e in root.iter()], ['A', 'B', 'D'])
        self.assertEqual(root.attrib, {'id': '0'})

        root = ElementTree.XML('<A id="1"><B/><C/><D/></A>')
        self.assertTrue(prune_etree(root, selector.method))
        self.assertListEqual([e.tag for e in root.iter()], ['A'])
        self.assertEqual(root.attrib, {'id': '1'})
示例#2
0
    def test_to_dict_from_etree(self):
        vh_xml_tree = ElementTree.parse(self.vh_xml_file)
        col_xml_tree = ElementTree.parse(self.col_xml_file)

        xml_dict = self.vh_schema.to_dict(vh_xml_tree)
        self.assertNotEqual(xml_dict, VEHICLES_DICT)

        xml_dict = self.vh_schema.to_dict(vh_xml_tree,
                                          namespaces=self.vh_namespaces)
        self.assertEqual(xml_dict, VEHICLES_DICT)

        xml_dict = xmlschema.to_dict(vh_xml_tree,
                                     self.vh_schema.url,
                                     namespaces=self.vh_namespaces)
        self.assertEqual(xml_dict, VEHICLES_DICT)

        xml_dict = self.col_schema.to_dict(col_xml_tree)
        self.assertNotEqual(xml_dict, COLLECTION_DICT)

        xml_dict = self.col_schema.to_dict(col_xml_tree,
                                           namespaces=self.col_namespaces)
        self.assertEqual(xml_dict, COLLECTION_DICT)

        xml_dict = xmlschema.to_dict(col_xml_tree,
                                     self.col_schema.url,
                                     namespaces=self.col_namespaces)
        self.assertEqual(xml_dict, COLLECTION_DICT)
示例#3
0
    def test_element_string_serialization(self):
        self.assertRaises(TypeError, etree_tostring, '<element/>')

        elem = ElementTree.Element('element')
        self.assertEqual(etree_tostring(elem), '<element />')
        self.assertEqual(etree_tostring(elem, xml_declaration=True), '<element />')

        self.assertEqual(etree_tostring(elem, encoding='us-ascii'), b'<element />')
        self.assertEqual(etree_tostring(elem, encoding='us-ascii', indent='    '),
                         b'    <element />')
        self.assertEqual(etree_tostring(elem, encoding='us-ascii', xml_declaration=True),
                         b'<?xml version="1.0" encoding="us-ascii"?>\n<element />')

        self.assertEqual(etree_tostring(elem, encoding='ascii'),
                         b"<?xml version='1.0' encoding='ascii'?>\n<element />")
        self.assertEqual(etree_tostring(elem, encoding='ascii', xml_declaration=False),
                         b'<element />')
        self.assertEqual(etree_tostring(elem, encoding='utf-8'), b'<element />')
        self.assertEqual(etree_tostring(elem, encoding='utf-8', xml_declaration=True),
                         b'<?xml version="1.0" encoding="utf-8"?>\n<element />')

        self.assertEqual(etree_tostring(elem, encoding='iso-8859-1'),
                         b"<?xml version='1.0' encoding='iso-8859-1'?>\n<element />")
        self.assertEqual(etree_tostring(elem, encoding='iso-8859-1', xml_declaration=False),
                         b"<element />")

        self.assertEqual(etree_tostring(elem, method='html'), '<element></element>')
        self.assertEqual(etree_tostring(elem, method='text'), '')

        root = ElementTree.XML('<root>\n'
                               '  text1\n'
                               '  <elem>text2</elem>\n'
                               '</root>')
        self.assertEqual(etree_tostring(root, method='text'), '\n  text1\n  text2')
示例#4
0
    def test_parse_boolean_attribute(self):
        name = '{%s}motorbikes' % self.schema.target_namespace
        elem = ElementTree.Element(XSD_ELEMENT, name=name, flag='true')
        xsd_element = self.FakeElement(elem=elem,
                                       name=name,
                                       schema=self.schema,
                                       parent=None)

        self.assertIsNone(xsd_element._parse_boolean_attribute('cond'))
        self.assertTrue(xsd_element._parse_boolean_attribute('flag'))
        xsd_element.elem = ElementTree.Element(XSD_ELEMENT,
                                               name=name,
                                               flag='1')
        self.assertTrue(xsd_element._parse_boolean_attribute('flag'))
        xsd_element.elem = ElementTree.Element(XSD_ELEMENT,
                                               name=name,
                                               flag='false')
        self.assertFalse(xsd_element._parse_boolean_attribute('flag'))
        xsd_element.elem = ElementTree.Element(XSD_ELEMENT,
                                               name=name,
                                               flag='0')
        self.assertFalse(xsd_element._parse_boolean_attribute('flag'))

        xsd_element.elem = ElementTree.Element(XSD_ELEMENT,
                                               name=name,
                                               flag='False')
        with self.assertRaises(XMLSchemaParseError):
            xsd_element._parse_boolean_attribute('flag')
示例#5
0
    def test_wsdl_component(self):
        wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE)

        elem = ElementTree.Element('foo', bar='abc')
        wsdl_component = WsdlComponent(elem, wsdl_document)
        self.assertIsNone(wsdl_component.prefixed_name)
        self.assertIs(wsdl_component.attrib, elem.attrib)
        self.assertEqual(wsdl_component.get('bar'), 'abc')

        elem = ElementTree.Element('foo', name='bar')
        wsdl_component = WsdlComponent(elem, wsdl_document)
        self.assertEqual(wsdl_component.prefixed_name, 'tns:bar')

        self.assertEqual(
            wsdl_component.map_qname(
                '{http://example.com/stockquote.wsdl}bar'), 'tns:bar')
        self.assertEqual(wsdl_component.unmap_qname('tns:bar'),
                         '{http://example.com/stockquote.wsdl}bar')

        elem = ElementTree.Element('foo', a1='tns:bar', a2='unknown:bar')
        self.assertEqual(wsdl_component._parse_reference(elem, 'a1'),
                         '{http://example.com/stockquote.wsdl}bar')
        self.assertEqual(wsdl_component._parse_reference(elem, 'a2'),
                         'unknown:bar')
        self.assertIsNone(wsdl_component._parse_reference(elem, 'a3'))
示例#6
0
 def test_any_type(self):
     any_type = xmlschema.XMLSchema.meta_schema.types['anyType']
     xml_data_1 = ElementTree.Element('dummy')
     self.assertIsNone(any_type.decode(xml_data_1))
     xml_data_2 = ElementTree.fromstring(
         '<root>\n    <child_1/>\n    <child_2/>\n</root>')
     self.assertIsNone(
         any_type.decode(xml_data_2))  # Currently no decoding yet
示例#7
0
    def test_prune_etree(self):
        root = ElementTree.XML('<a><b1><c1/><c2/></b1><b2/><b3><c3/></b3></a>')
        prune_etree(root, selector=lambda x: x.tag == 'b1')
        self.assertListEqual([e.tag for e in root.iter()], ['a', 'b2', 'b3', 'c3'])

        root = ElementTree.XML('<a><b1><c1/><c2/></b1><b2/><b3><c3/></b3></a>')
        prune_etree(root, selector=lambda x: x.tag.startswith('c'))
        self.assertListEqual([e.tag for e in root.iter()], ['a', 'b1', 'b2', 'b3'])
示例#8
0
    def test_defuse_xml_unparsed_entities(self):
        xml_file = casepath('resources/unparsed_entity.xml')

        parser = SafeXMLParser(target=PyElementTree.TreeBuilder())
        with self.assertRaises(PyElementTree.ParseError) as ctx:
            ElementTree.parse(xml_file, parser=parser)
        self.assertEqual("Unparsed entities are forbidden (entity_name='logo_file')",
                         str(ctx.exception))
示例#9
0
    def test_validate(self):
        xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xml')
        root = ElementTree.parse(xml_file).getroot()
        self.assertIsNone(self.schema.elements['vehicles'].validate(root))

        xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles-1_error.xml')
        root = ElementTree.parse(xml_file).getroot()
        with self.assertRaises(XMLSchemaValidationError):
            self.schema.elements['vehicles'].validate(root)
示例#10
0
    def test_wsdl_message(self):
        wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE)

        with self.assertRaises(WsdlParseError) as ctx:
            wsdl_document._parse_messages()
        self.assertIn("duplicated message 'tns:GetLastTradePriceInput'",
                      str(ctx.exception))

        elem = ElementTree.XML(
            '<message xmlns="http://schemas.xmlsoap.org/wsdl/"\n'
            '         name="GetLastTradePriceInput">\n'
            '  <part name="body" element="xsd1:unknown"/>\n'
            '</message>')

        with self.assertRaises(WsdlParseError) as ctx:
            WsdlMessage(elem, wsdl_document)
        self.assertIn('missing schema element', str(ctx.exception))

        elem[0].attrib['element'] = 'xsd1:TradePriceRequest'
        wsdl_message = WsdlMessage(elem, wsdl_document)
        self.assertEqual(list(wsdl_message.parts), ['body'])

        elem.append(elem[0])
        with self.assertRaises(WsdlParseError) as ctx:
            WsdlMessage(elem, wsdl_document)
        self.assertIn("duplicated part 'body'", str(ctx.exception))

        elem[0].attrib['type'] = 'xsd1:TradePriceRequest'
        with self.assertRaises(WsdlParseError) as ctx:
            WsdlMessage(elem, wsdl_document)
        self.assertIn("ambiguous binding", str(ctx.exception))

        del elem[0].attrib['name']
        wsdl_message = WsdlMessage(elem, wsdl_document)
        self.assertEqual(wsdl_message.parts, {})

        elem = ElementTree.XML(
            '<message xmlns="http://schemas.xmlsoap.org/wsdl/"\n'
            '         xmlns:xs="http://www.w3.org/2001/XMLSchema"\n'
            '         name="GetLastTradePriceInput">\n'
            '  <part name="body" type="xs:string"/>\n'
            '</message>')

        with self.assertRaises(WsdlParseError) as ctx:
            WsdlMessage(elem, wsdl_document)
        self.assertIn('missing schema type', str(ctx.exception))

        wsdl_document.namespaces['xs'] = "http://www.w3.org/2001/XMLSchema"
        wsdl_message = WsdlMessage(elem, wsdl_document)
        self.assertEqual(list(wsdl_message.parts), ['body'])

        del elem[0].attrib['type']
        with self.assertRaises(WsdlParseError) as ctx:
            WsdlMessage(elem, wsdl_document)
        self.assertEqual("missing both 'type' and 'element' attributes",
                         str(ctx.exception))
示例#11
0
    def test_defuse_xml_unused_external_entities(self):
        xml_file = casepath('resources/unused_external_entity.xml')

        elem = ElementTree.parse(xml_file).getroot()
        self.assertEqual(elem.text, 'abc')

        parser = SafeXMLParser(target=PyElementTree.TreeBuilder())
        with self.assertRaises(PyElementTree.ParseError) as ctx:
            ElementTree.parse(xml_file, parser=parser)
        self.assertEqual("Entities are forbidden (entity_name='ee')", str(ctx.exception))
示例#12
0
    def test_defuse_xml_external_entities(self):
        xml_file = casepath('resources/external_entity.xml')

        with self.assertRaises(ParseError) as ctx:
            ElementTree.parse(xml_file)
        self.assertIn("undefined entity &ee", str(ctx.exception))

        parser = SafeXMLParser(target=PyElementTree.TreeBuilder())
        with self.assertRaises(PyElementTree.ParseError) as ctx:
            ElementTree.parse(xml_file, parser=parser)
        self.assertEqual("Entities are forbidden (entity_name='ee')", str(ctx.exception))
示例#13
0
def parse_cp_raw_output(stdout,
                        output_xml=None,
                        xml_counter_file=None,
                        print_counter_xml=True):

    parser_warnings = []

    # analyze the xml
    if output_xml is not None:
        xml_parsed = ElementTree.ElementTree(
            element=ElementTree.fromstring(output_xml))
        xml_file_version = get_xml_file_version(xml_parsed)
        if xml_file_version == QeXmlVersion.POST_6_2:
            xml_data, logs = parse_xml_post_6_2(xml_parsed)
        elif xml_file_version == QeXmlVersion.PRE_6_2:
            xml_data = parse_cp_xml_output(output_xml)
    else:
        parser_warnings.append('Skipping the parsing of the xml file.')
        xml_data = {}

    # analyze the counter file, which keeps info on the steps
    if xml_counter_file is not None:
        if print_counter_xml:
            xml_counter_data = parse_cp_xml_counter_output(xml_counter_file)
        else:
            xml_counter_data = parse_cp_counter_output(xml_counter_file)
    else:
        xml_counter_data = {}
    stdout = stdout.split('\n')
    # understand if the job ended smoothly
    job_successful = any('JOB DONE' in line for line in reversed(stdout))

    out_data = parse_cp_text_output(stdout, xml_data)

    for key in out_data.keys():
        if key in list(xml_data.keys()):
            raise AssertionError(f'{key} found in both dictionaries')
        if key in list(xml_counter_data.keys()):
            raise AssertionError(f'{key} found in both dictionaries')
        # out_data keys take precedence and overwrite xml_data keys,
        # if the same key name is shared by both (but this should not happen!)

    final_data = {
        **xml_data,
        **out_data,
        **xml_counter_data,
    }

    if parser_warnings:
        final_data['parser_warnings'] = parser_warnings

    # TODO: parse the trajectory and save them in a reasonable format

    return final_data, job_successful
示例#14
0
 def test_iter_location_hints(self):
     elem = ElementTree.XML(
         """<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://example.com/xmlschema/ns-A import-case4a.xsd"/>"""
     )
     self.assertListEqual(
         list(etree_iter_location_hints(elem)),
         [('http://example.com/xmlschema/ns-A', 'import-case4a.xsd')])
     elem = ElementTree.XML(
         """<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:noNamespaceSchemaLocation="schema.xsd"/>""")
     self.assertListEqual(list(etree_iter_location_hints(elem)),
                          [('', 'schema.xsd')])
    def test_complex_elements(self):
        schema = self.get_schema("""
        <xs:element name="A" type="A_type" />
        <xs:complexType name="A_type" mixed="true">
            <xs:simpleContent>
                <xs:extension base="xs:string">
                    <xs:attribute name="a1" type="xs:short" use="required"/>
                    <xs:attribute name="a2" type="xs:negativeInteger"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
        """)
        self.check_encode(
            schema.elements['A'], data={'@a1': 10, '@a2': -1, '$': 'simple '},
            expected='<A a1="10" a2="-1">simple </A>',
        )
        self.check_encode(
            schema.elements['A'], {'@a1': 10, '@a2': -1, '$': 'simple '},
            ElementTree.fromstring('<A a1="10" a2="-1">simple </A>'),
        )
        self.check_encode(
            schema.elements['A'], {'@a1': 10, '@a2': -1},
            ElementTree.fromstring('<A a1="10" a2="-1"/>')
        )
        self.check_encode(
            schema.elements['A'], {'@a1': 10, '$': 'simple '},
            ElementTree.fromstring('<A a1="10">simple </A>')
        )
        self.check_encode(schema.elements['A'], {'@a2': -1, '$': 'simple '},
                          XMLSchemaValidationError)

        schema = self.get_schema("""
        <xs:element name="A" type="A_type" />
        <xs:complexType name="A_type">
            <xs:sequence>
                <xs:element name="B1" type="xs:string"/>
                <xs:element name="B2" type="xs:integer"/>
                <xs:element name="B3" type="xs:boolean"/>
            </xs:sequence>
        </xs:complexType>
        """)
        self.check_encode(
            xsd_component=schema.elements['A'],
            data=dict([('B1', 'abc'), ('B2', 10), ('B3', False)]),
            expected=u'<A>\n<B1>abc</B1>\n<B2>10</B2>\n<B3>false</B3>\n</A>',
            indent=0,
        )
        self.check_encode(schema.elements['A'], {'B1': 'abc', 'B2': 10, 'B4': False},
                          XMLSchemaValidationError)
示例#16
0
    def test_wsdl_soap_header_bindings(self):
        wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE)

        elem = ElementTree.XML(
            '<header xmlns="http://schemas.xmlsoap.org/wsdl/soap/"\n'
            '        xmlns:tns="http://example.com/stockquote.wsdl"\n'
            '        message="tns:SubscribeToQuotes"\n'
            '        part="subscribeheader" use="literal"/>')

        with self.assertRaises(WsdlParseError) as ctx:
            SoapHeader(elem, wsdl_document)
        self.assertIn('unknown message', str(ctx.exception))

        elem.attrib['message'] = 'tns:GetLastTradePriceInput'
        with self.assertRaises(WsdlParseError) as ctx:
            SoapHeader(elem, wsdl_document)
        self.assertIn("missing message part 'subscribeheader'",
                      str(ctx.exception))

        elem.attrib['part'] = 'body'
        soap_header = SoapHeader(elem, wsdl_document)
        message_name = '{http://example.com/stockquote.wsdl}GetLastTradePriceInput'
        self.assertIs(wsdl_document.messages[message_name],
                      soap_header.message)
        self.assertIs(wsdl_document.messages[message_name].parts['body'],
                      soap_header.part)

        del elem.attrib['part']
        soap_header = SoapHeader(elem, wsdl_document)
        self.assertIs(wsdl_document.messages[message_name],
                      soap_header.message)
        self.assertIsNone(soap_header.part)

        elem = ElementTree.XML(
            '<header xmlns="http://schemas.xmlsoap.org/wsdl/soap/"\n'
            '        xmlns:tns="http://example.com/stockquote.wsdl"\n'
            '        message="tns:GetLastTradePriceInput"\n'
            '        part="body" use="literal">\n'
            '   <headerfault message="tns:GetLastTradePriceInput"\n'
            '          part="body" use="literal"/>\n'
            '</header>')

        soap_header = SoapHeader(elem, wsdl_document)
        message = wsdl_document.messages[message_name]
        self.assertIs(message, soap_header.message)
        self.assertIs(message.parts['body'], soap_header.part)
        self.assertEqual(len(soap_header.faults), 1)
        self.assertIs(message, soap_header.faults[0].message)
        self.assertIs(message.parts['body'], soap_header.faults[0].part)
示例#17
0
    def test_parse_child_component(self):
        name = '{%s}motorbikes' % self.schema.target_namespace
        elem = ElementTree.Element(XSD_ELEMENT, name=name)
        elem.append(ElementTree.Element(XSD_ANNOTATION))
        elem.append(ElementTree.Element('child1'))
        elem.append(ElementTree.Element('child2'))
        xsd_element = self.FakeElement(elem=elem,
                                       name=name,
                                       schema=self.schema,
                                       parent=None)

        self.assertEqual(
            xsd_element._parse_child_component(elem, strict=False), elem[1])
        with self.assertRaises(XMLSchemaParseError):
            xsd_element._parse_child_component(elem)
示例#18
0
    def test_document_validate_api(self):
        self.assertIsNone(xmlschema.validate(self.vh_xml_file))
        self.assertIsNone(
            xmlschema.validate(self.vh_xml_file, use_defaults=False))

        vh_2_file = self.casepath('examples/vehicles/vehicles-2_errors.xml')
        self.assertRaises(XMLSchemaValidationError, xmlschema.validate,
                          vh_2_file)

        try:
            xmlschema.validate(
                vh_2_file, namespaces={'vhx': "http://example.com/vehicles"})
        except XMLSchemaValidationError as err:
            path_line = str(err).splitlines()[-1]
        else:
            path_line = ''

        if sys.version_info >= (3, 6):
            self.assertEqual('Path: /vhx:vehicles/vhx:cars', path_line)
        else:
            self.assertTrue('Path: /vh:vehicles/vh:cars' == path_line
                            or 'Path: /vhx:vehicles/vhx:cars',
                            path_line)  # Due to unordered dicts

        # Issue #80
        vh_2_xt = ElementTree.parse(vh_2_file)
        self.assertRaises(XMLSchemaValidationError, xmlschema.validate,
                          vh_2_xt, self.vh_xsd_file)

        # Issue #145
        with open(self.vh_xml_file) as f:
            self.assertIsNone(xmlschema.validate(f, schema=self.vh_xsd_file))
示例#19
0
 def test_nillable(self):
     # Issue #76
     xsd_string = """<?xml version="1.0" encoding="UTF-8"?>
     <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
         <xs:element name="foo" type="Foo" />
         <xs:complexType name="Foo">
             <xs:sequence minOccurs="1" maxOccurs="1">
                 <xs:element name="bar" type="xs:integer" nillable="true" />
             </xs:sequence>
         </xs:complexType>
     </xs:schema>
     """
     xsd_schema = xmlschema.XMLSchema(xsd_string)
     xml_string_1 = "<foo><bar>0</bar></foo>"
     xml_string_2 = """<?xml version="1.0" encoding="UTF-8"?>
     <foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <bar xsi:nil="true"></bar>
     </foo>
     """
     self.assertTrue(
         xsd_schema.is_valid(source=xml_string_1, use_defaults=False))
     self.assertTrue(
         xsd_schema.is_valid(source=xml_string_2, use_defaults=False))
     obj = xsd_schema.decode(xml_string_2, use_defaults=False)
     self.check_etree_elements(ElementTree.fromstring(xml_string_2),
                               xsd_schema.encode(obj))
示例#20
0
    def test_iter_components(self):
        name = '{%s}motorbikes' % self.schema.target_namespace
        elem = ElementTree.Element(XSD_ELEMENT, name=name)
        xsd_element = self.FakeElement(elem, self.schema, parent=None, name=name)

        self.assertListEqual(list(xsd_element.iter_components()), [xsd_element])
        self.assertListEqual(list(xsd_element.iter_components(str)), [])
示例#21
0
        def check_encoding_with_element_tree(self):
            root = ElementTree.parse(xml_file).getroot()
            namespaces = fetch_namespaces(xml_file)
            options = {
                'namespaces': namespaces,
                'dict_class': ordered_dict_class
            }

            self.check_etree_encode(root, cdata_prefix='#',
                                    **options)  # Default converter
            self.check_etree_encode(root,
                                    ParkerConverter,
                                    validation='lax',
                                    **options)
            self.check_etree_encode(root,
                                    ParkerConverter,
                                    validation='skip',
                                    **options)
            self.check_etree_encode(root, BadgerFishConverter, **options)
            self.check_etree_encode(root, AbderaConverter, **options)
            self.check_etree_encode(root, JsonMLConverter, **options)

            options.pop('dict_class')
            self.check_json_serialization(root, cdata_prefix='#', **options)
            self.check_json_serialization(root,
                                          ParkerConverter,
                                          validation='lax',
                                          **options)
            self.check_json_serialization(root,
                                          ParkerConverter,
                                          validation='skip',
                                          **options)
            self.check_json_serialization(root, BadgerFishConverter, **options)
            self.check_json_serialization(root, AbderaConverter, **options)
            self.check_json_serialization(root, JsonMLConverter, **options)
示例#22
0
    def test_wsdl_and_soap_faults(self):
        example5_file_with_fault = casepath(
            'features/wsdl/wsdl11_example5_with_fault.wsdl')
        wsdl_document = Wsdl11Document(example5_file_with_fault)

        port_type_name = '{http://example.com/stockquote.wsdl}StockQuotePortType'
        self.assertListEqual(list(wsdl_document.port_types), [port_type_name])
        port_type = wsdl_document.port_types[port_type_name]
        operation = port_type.operations[('GetTradePrices', None, None)]

        message_name = '{http://example.com/stockquote.wsdl}FaultMessage'
        message = wsdl_document.messages[message_name]
        self.assertIs(operation.faults['fault'].message, message)

        elem = ElementTree.XML(
            '<binding xmlns="http://schemas.xmlsoap.org/wsdl/"\n'
            '     xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"\n'
            '     name="StockQuoteBinding" type="tns:StockQuotePortType"\n>'
            '  <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>\n'
            '  <operation name="GetTradePrices">'
            '    <input/>'
            '    <output/>'
            '    <fault><soap:fault name="exception"/></fault>'
            '  </operation>'
            '</binding>')

        with self.assertRaises(WsdlParseError) as ctx:
            WsdlBinding(elem, wsdl_document)
        self.assertIn("missing fault 'exception'", str(ctx.exception))
示例#23
0
    def test_wsdl_port_type(self):
        wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE)

        with self.assertRaises(WsdlParseError) as ctx:
            wsdl_document._parse_port_types()
        self.assertIn("duplicated port type 'tns:StockQuotePortType'",
                      str(ctx.exception))

        elem = ElementTree.XML(
            '<portType xmlns="http://schemas.xmlsoap.org/wsdl/"\n'
            '          name="StockQuotePortType">\n'
            '  <operation name="GetLastTradePrice">\n'
            '    <input message="tns:GetLastTradePriceInput"/>\n'
            '    <output message="tns:GetLastTradePriceOutput"/>\n'
            '  </operation>\n'
            '</portType>')

        wsdl_port_type = WsdlPortType(elem, wsdl_document)
        self.assertEqual(list(wsdl_port_type.operations),
                         [('GetLastTradePrice', None, None)])

        elem.append(elem[0])  # Duplicate operation ...
        with self.assertRaises(WsdlParseError) as ctx:
            WsdlPortType(elem, wsdl_document)
        self.assertIn('duplicated operation', str(ctx.exception))

        del elem[0].attrib['name']
        wsdl_port_type = WsdlPortType(elem, wsdl_document)
        self.assertEqual(list(wsdl_port_type.operations), [])
示例#24
0
 def test_validation_strict(self):
     self.assertRaises(
         xmlschema.XMLSchemaValidationError,
         self.vh_schema.to_dict,
         ElementTree.parse(
             self.casepath('examples/vehicles/vehicles-2_errors.xml')),
         validation='strict',
         namespaces=self.vh_namespaces)
示例#25
0
    def test_decode(self):
        xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xml')
        root = ElementTree.parse(xml_file).getroot()

        obj = self.schema.elements['vehicles'].decode(root)
        self.assertIsInstance(obj, dict)
        self.assertIn(self.schema.elements['cars'].name, obj)
        self.assertIn(self.schema.elements['bikes'].name, obj)

        xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles-2_errors.xml')
        root = ElementTree.parse(xml_file).getroot()

        obj, errors = self.schema.elements['vehicles'].decode(root, validation='lax')
        self.assertIsInstance(obj, dict)
        self.assertIn(self.schema.elements['cars'].name, obj)
        self.assertIn(self.schema.elements['bikes'].name, obj)
        self.assertEqual(len(errors), 2)
示例#26
0
    def test_wsdl_missing_message_reference(self):
        wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE)

        elem = ElementTree.XML(
            '<input xmlns="http://schemas.xmlsoap.org/wsdl/"\n'
            '       xmlns:tns="http://example.com/stockquote.wsdl"\n'
            '       message="tns:unknown"/>')

        with self.assertRaises(WsdlParseError) as ctx:
            WsdlInput(elem, wsdl_document)
        self.assertIn('unknown message', str(ctx.exception))

        elem = ElementTree.XML(
            '<input xmlns="http://schemas.xmlsoap.org/wsdl/"/>')

        input_op = WsdlInput(elem, wsdl_document)
        self.assertIsNone(input_op.message)
示例#27
0
 def test_id_property(self):
     name = '{%s}motorbikes' % self.schema.target_namespace
     elem = ElementTree.Element(XSD_ELEMENT, name=name, id='1999')
     xsd_element = self.FakeElement(elem=elem,
                                    name=name,
                                    schema=self.schema,
                                    parent=None)
     self.assertEqual(xsd_element.id, '1999')
示例#28
0
 def test_path(self):
     xt = ElementTree.parse(self.vh_xml_file)
     xd = self.vh_schema.to_dict(xt,
                                 '/vh:vehicles/vh:cars',
                                 namespaces=self.vh_namespaces)
     self.assertEqual(xd['vh:car'], VEHICLES_DICT['vh:cars']['vh:car'])
     xd = self.vh_schema.to_dict(xt,
                                 '/vh:vehicles/vh:bikes',
                                 namespaces=self.vh_namespaces)
     self.assertEqual(xd['vh:bike'], VEHICLES_DICT['vh:bikes']['vh:bike'])
示例#29
0
    def test_json_dump_and_load(self):
        vh_xml_tree = ElementTree.parse(self.vh_xml_file)
        col_xml_tree = ElementTree.parse(self.col_xml_file)
        with open(self.vh_json_file, 'w') as f:
            xmlschema.to_json(self.vh_xml_file, f)

        with open(self.vh_json_file) as f:
            root = xmlschema.from_json(f, self.vh_schema)

        os.remove(self.vh_json_file)
        self.check_etree_elements(vh_xml_tree.getroot(), root)

        with open(self.col_json_file, 'w') as f:
            xmlschema.to_json(self.col_xml_file, f)

        with open(self.col_json_file) as f:
            root = xmlschema.from_json(f, self.col_schema)

        os.remove(self.col_json_file)
        self.check_etree_elements(col_xml_tree.getroot(), root)
示例#30
0
    def test_initialization(self):
        schema_proxy = XMLSchemaProxy()
        self.assertIs(schema_proxy._schema, self.schema_class.meta_schema)

        schema_proxy = XMLSchemaProxy(self.xs1, base_element=self.xs1.elements['vehicles'])
        self.assertIs(schema_proxy._schema, self.xs1)

        with self.assertRaises(ValueError):
            XMLSchemaProxy(self.xs1, base_element=self.xs2.elements['collection'])

        with self.assertRaises(TypeError):
            XMLSchemaProxy(self.xs1, base_element=ElementTree.Element('vehicles'))
示例#31
0
    def test_xml_resource_from_element_tree(self):
        vh_etree = ElementTree.parse(self.vh_xml_file)
        vh_root = vh_etree.getroot()

        resource = XMLResource(vh_etree)
        self.assertEqual(resource.source, vh_etree)
        self.assertEqual(resource.document, vh_etree)
        self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
        self.assertIsNone(resource.url)
        self.assertIsNone(resource.text)
        resource.load()
        self.assertIsNone(resource.text)

        resource = XMLResource(vh_root)
        self.assertEqual(resource.source, vh_root)
        self.assertIsNone(resource.document)
        self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
        self.assertIsNone(resource.url)
        self.assertIsNone(resource.text)
        resource.load()
        self.assertIsNone(resource.text)