def test_xml_resource_iterparse(self): resource = XMLResource(self.vh_xml_file) self.assertEqual(resource.defuse, 'remote') for _, elem in resource.iterparse(self.col_xml_file, events=('end', )): self.assertTrue(is_etree_element(elem)) resource.defuse = 'always' for _, elem in resource.iterparse(self.col_xml_file, events=('end', )): self.assertTrue(is_etree_element(elem))
def test_load_xml_resource(self): self.assertTrue( is_etree_element( load_xml_resource(self.vh_xml_file, element_only=True))) root, text, url = load_xml_resource(self.vh_xml_file, element_only=False) self.assertTrue(is_etree_element(root)) self.assertEqual(root.tag, '{http://example.com/vehicles}vehicles') self.assertTrue(text.startswith('<?xml version')) self.check_url(url, self.vh_xml_file)
def test_xml_resource_parse(self): resource = XMLResource(self.vh_xml_file) self.assertEqual(resource.defuse, 'remote') xml_document = resource.parse(self.col_xml_file) self.assertTrue(is_etree_element(xml_document.getroot())) resource.defuse = 'always' xml_document = resource.parse(self.col_xml_file) self.assertTrue(is_etree_element(xml_document.getroot()))
def get_schema_source(self, source): """ Returns a schema source that can be used to create an XMLSchema instance. :param source: A string or an ElementTree's Element. :return: An schema source string, an ElementTree's Element or a full pathname. """ if is_etree_element(source): if source.tag in (XSD_SCHEMA, 'schema'): return source elif get_namespace(source.tag): raise XMLSchemaValueError("source %r namespace has to be empty." % source) elif source.tag not in {'element', 'attribute', 'simpleType', 'complexType', 'group', 'attributeGroup', 'notation'}: raise XMLSchemaValueError("% is not an XSD global definition/declaration." % source) root = etree_element('schema', attrib={ 'xmlns:xs': "http://www.w3.org/2001/XMLSchema", 'elementFormDefault': "qualified", 'version': self.schema_class.XSD_VERSION, }) root.append(source) return root else: source = source.strip() if not source.startswith('<'): return casepath(source) elif source.startswith('<?xml ') or source.startswith('<xs:schema '): return source else: return SCHEMA_TEMPLATE.format(self.schema_class.XSD_VERSION, source)
def test_encode_to_element_tree(self): col_data = self.col_schema.decode(self.col_xml_filename) obj = col_data.encode() self.assertTrue(is_etree_element(obj)) self.assertIsInstance(etree_tostring(obj), str) self.assertIsNone( etree_elements_assert_equal(obj, self.col_xml_root, strict=False)) with self.assertRaises(ValueError) as ec: col_data.xsd_type = col_data[0].xsd_type self.assertEqual(str(ec.exception), "the instance is already bound to another XSD type") with self.assertRaises(ValueError) as ec: col_data.xsd_element = col_data[0].xsd_element self.assertEqual( str(ec.exception), "the instance is already bound to another XSD element") any_data = DataElement('a') any_data.append(DataElement('b1', 1999)) any_data.append(DataElement('b2', 'alpha')) any_data.append(DataElement('b3', True)) with self.assertRaises(ValueError) as ec: any_data.encode() self.assertIn("has no schema bindings", str(ec.exception)) root = ElementTree.XML( '<a><b1>1999</b1><b2>alpha</b2><b3>true</b3></a>') obj = any_data.encode(validation='skip') self.assertTrue(is_etree_element(obj)) self.assertIsInstance(etree_tostring(obj), str) self.assertIsNone(etree_elements_assert_equal(obj, root, strict=False)) any_data = DataElement('root', attrib={'a1': 49}) any_data.append(DataElement('child', 18.7, attrib={'a2': False})) root = ElementTree.XML( '<root a1="49"><child a2="false">18.7</child></root>') obj = any_data.encode(validation='skip') self.assertTrue(is_etree_element(obj)) self.assertIsInstance(etree_tostring(obj), str) self.assertIsNone(etree_elements_assert_equal(obj, root, strict=False))
def check_encode(self, xsd_component, data, expected, **kwargs): if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, xsd_component.encode, data, **kwargs) elif is_etree_element(expected): elem = xsd_component.encode(data, **kwargs) self.check_etree_elements(expected, elem) else: obj = xsd_component.encode(data, **kwargs) if isinstance(obj, tuple) and len(obj) == 2 and isinstance(obj[1], list): self.assertEqual(expected, obj[0]) self.assertTrue(isinstance(obj[0], type(expected))) elif is_etree_element(obj): namespaces = kwargs.pop('namespaces', self.default_namespaces) self.assertEqual(expected, etree_tostring(obj, namespaces=namespaces).strip()) else: self.assertEqual(expected, obj) self.assertTrue(isinstance(obj, type(expected)))
def test_facet_lists(self): for builtin_types in (XSD_10_BUILTIN_TYPES, XSD_11_BUILTIN_TYPES): for item in builtin_types: if 'facets' in item: self.assertIsInstance(item['facets'], list) self.assertLessEqual( len([e for e in item['facets'] if callable(e)]), 1) for e in item['facets']: self.assertTrue(callable(e) or is_etree_element(e))
def test_max_occurs_sequence(self): # Issue #119 schema = self.get_schema(""" <xs:element name="foo"> <xs:complexType> <xs:sequence> <xs:element name="A" type="xs:integer" maxOccurs="2" /> </xs:sequence> </xs:complexType> </xs:element>""") # Check validity self.assertIsNone(schema.validate("<foo><A>1</A></foo>")) self.assertIsNone(schema.validate("<foo><A>1</A><A>2</A></foo>")) with self.assertRaises(XMLSchemaChildrenValidationError): schema.validate("<foo><A>1</A><A>2</A><A>3</A></foo>") self.assertTrue(is_etree_element(schema.to_etree({'A': 1}, path='foo'))) self.assertTrue( is_etree_element(schema.to_etree({'A': [1]}, path='foo'))) self.assertTrue( is_etree_element(schema.to_etree({'A': [1, 2]}, path='foo'))) with self.assertRaises(XMLSchemaChildrenValidationError): schema.to_etree({'A': [1, 2, 3]}, path='foo') schema = self.get_schema(""" <xs:element name="foo"> <xs:complexType> <xs:sequence> <xs:element name="A" type="xs:integer" maxOccurs="2" /> <xs:element name="B" type="xs:integer" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element>""") self.assertTrue( is_etree_element(schema.to_etree({'A': [1, 2]}, path='foo'))) with self.assertRaises(XMLSchemaChildrenValidationError): schema.to_etree({'A': [1, 2, 3]}, path='foo')
def test_xml_document_etree_interface(self): xml_document = XmlDocument(self.vh_xml_file) self.assertIs(xml_document.getroot(), xml_document._root) self.assertTrue(is_etree_element(xml_document.getroot())) self.assertTrue(is_etree_document(xml_document.get_etree_document())) xml_document = XmlDocument(self.vh_xml_file, lazy=1) with self.assertRaises(XMLResourceError) as ctx: xml_document.get_etree_document() self.assertIn('cannot create an ElementTree from a lazy resource', str(ctx.exception)) vh_tree = ElementTree.parse(self.vh_xml_file) xml_document = XmlDocument(vh_tree, base_url=self.vh_dir) self.assertIs(xml_document.source, vh_tree) self.assertIs(xml_document.get_etree_document(), vh_tree)