123filename=os.path.join(124os.path.join('hopefullynonexistingpathname'),125'invalid_file.xml')126try:127self.tree.write(filename)128exceptIOError:129pass130else:131self.assertTrue(132False,"writing to an invalid file path should fail")
166handle,filename=tempfile.mkstemp(suffix=".xml")167write_to_file(filename,self.root_str,'wb')168try:169tree=self.etree.ElementTree()170root=tree.parse(filename)171# and now do it again; previous content should still be there172root2=tree.parse(filename)173self.assertEqual('a',root.tag)174self.assertEqual('a',root2.tag)175# now remove all references to root2, and parse again176delroot2177root3=tree.parse(filename)178self.assertEqual('a',root.tag)179self.assertEqual('a',root3.tag)180# root2's memory should've been freed here181# XXX how to check?182finally:183os.close(handle)184os.remove(filename)
187# (c)ElementTree class ElementTree has a 'parse' method that returns188# the root of the tree189190# parse from file object191192handle,filename=tempfile.mkstemp(suffix=".xml")193try:194os.write(handle,self.root_str)195f=open(filename,'rb')196tree=self.etree.ElementTree()197root=tree.parse(f)198f.close()199self.assertEqual(self.etree.tostring(root),self.root_str)200finally:201os.close(handle)202os.remove(filename)
205# (c)ElementTree class ElementTree has a 'parse' method that returns206# the root of the tree207208# parse from unamed file object 209f=SillyFileLike()210root=self.etree.ElementTree().parse(f)211self.assertTrue(root.tag.endswith('foo'))
267# this is a directory name that contains characters beyond latin-1268dirnameEN=_str('Directory')269dirnameRU=_str('Каталог')270filename=_str('nosuchfile.xml')271dn=tempfile.mkdtemp(prefix=dirnameEN)272try:273self.assertRaises(IOError,self.etree.parse,os.path.join(dn,filename))274finally:275os.rmdir(dn)276dn=tempfile.mkdtemp(prefix=dirnameRU)277try:278self.assertRaises(IOError,self.etree.parse,os.path.join(dn,filename))279finally:280os.rmdir(dn)
283utext=_str('Søk på nettet')284uxml='<?xml version="1.0" encoding="UTF-8"?><p>%s</p>'%utext285bom=_bytes('\\xEF\\xBB\\xBF').decode(286"unicode_escape").encode("latin1")287self.assertEqual(3,len(bom))288f=NamedTemporaryFile(delete=False)289try:290try:291f.write(bom)292f.write(uxml.encode("utf-8"))293finally:294f.close()295tree=self.etree.parse(f.name)296finally:297os.unlink(f.name)298self.assertEqual(utext,tree.getroot().text)
301utext=_str('Søk på nettet')302uxml='<?xml version="1.0" encoding="UTF-8"?><p>%s</p>'%utext303bom=_bytes('\\xEF\\xBB\\xBF').decode(304"unicode_escape").encode("latin1")305self.assertEqual(3,len(bom))306f=NamedTemporaryFile(delete=False)307try:308try:309f.write(bom)310f.write(uxml.encode("utf-8"))311finally:312f.close()313elements=[elfor_,elinself.etree.iterparse(f.name)]314self.assertEqual(1,len(elements))315root=elements[0]316finally:317os.unlink(f.name)318self.assertEqual(utext,root.text)