def test_py_element_string_serialization(self): elem = PyElementTree.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', 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 = PyElementTree.XML('<root>\n' ' text1\n' ' <elem>text2</elem>\n' '</root>') self.assertEqual(etree_tostring(root, method='text'), '\n text1\n text2')
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))
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))
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))