Debian Codegraph @

python/tests/unicode.py

raw
1 from io import BytesIO, StringIO
2 import libxml2
3 import sys
4 from xml.sax.handler import ContentHandler
5 from xml.sax.xmlreader import InputSource
6 import xml.sax
7
8
9 # Test data: an XML file with a 100,000 Unicode smileys, which expand
10 # into 400,000 bytes after UTF-8 encoding.
11 SMILEY = '\U0001f600'
12 TEXT = 100_000 * SMILEY
13 XML_STRING = '<?xml version="1.0" encoding="UTF-8" ?>\n<root>' + TEXT + '</root>'
14 XML_BYTES = XML_STRING.encode('utf-8')
15
16
17 def RunTest(test_name, source):
18 expected = TEXT
19 received = ''
20
21 class TestHandler(ContentHandler):
22 def characters(self, content):
23 nonlocal received
24 received += content
25
26 reader = xml.sax.make_parser(['drv_libxml2'])
27 reader.setContentHandler(TestHandler())
28 reader.parse(source)
29 if expected != received:
30 print(test_name, 'failed!')
31 print('Expected length:', len(expected))
32 print('Received length:', len(received))
33 print('Expected text: (prefix only)', expected[:100])
34 print('Received text: (prefix only)', received[:100])
35 sys.exit(1)
36
37
38 def TestBytesInput():
39 source = InputSource()
40 source.setByteStream(BytesIO(XML_BYTES))
41 RunTest('TestBytesInput', source)
42
43
44 def TestStringInput():
45 source = InputSource()
46 source.setCharacterStream(StringIO(XML_STRING))
47 RunTest('TestStringInput', source)
48
49
50 # Memory debug specific
51 libxml2.debugMemory(1)
52
53 TestBytesInput()
54 TestStringInput()
55
56 # Memory debug specific
57 libxml2.cleanupParser()
58 if libxml2.debugMemory(1) == 0:
59 print("OK")
60 else:
61 print("Memory leak %d bytes" % (libxml2.debugMemory(1)))