1#!/usr/bin/python -u 2# 3# this tests the entities substitutions with the XmlTextReader interface 4# 5import sys 6import StringIO 7import libxml2 8 9schema="""<element name="foo" xmlns="http://relaxng.org/ns/structure/1.0" 10 datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes"> 11 <oneOrMore> 12 <element name="label"> 13 <text/> 14 </element> 15 <optional> 16 <element name="opt"> 17 <empty/> 18 </element> 19 </optional> 20 <element name="item"> 21 <data type="byte"/> 22 </element> 23 </oneOrMore> 24</element> 25""" 26# Memory debug specific 27libxml2.debugMemory(1) 28 29# 30# Parse the Relax NG Schemas 31# 32rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) 33rngs = rngp.relaxNGParse() 34del rngp 35 36# 37# Parse and validate the correct document 38# 39docstr="""<foo> 40<label>some text</label> 41<item>100</item> 42</foo>""" 43 44f = StringIO.StringIO(docstr) 45input = libxml2.inputBuffer(f) 46reader = input.newTextReader("correct") 47reader.RelaxNGSetSchema(rngs) 48ret = reader.Read() 49while ret == 1: 50 ret = reader.Read() 51 52if ret != 0: 53 print "Error parsing the document" 54 sys.exit(1) 55 56if reader.IsValid() != 1: 57 print "Document failed to validate" 58 sys.exit(1) 59 60# 61# Parse and validate the incorrect document 62# 63docstr="""<foo> 64<label>some text</label> 65<item>1000</item> 66</foo>""" 67 68err="" 69# RNG errors are not as good as before , TODO 70#expect="""RNG validity error: file error line 3 element text 71#Type byte doesn't allow value '1000' 72#RNG validity error: file error line 3 element text 73#Error validating datatype byte 74#RNG validity error: file error line 3 element text 75#Element item failed to validate content 76#""" 77expect="""Type byte doesn't allow value '1000' 78Error validating datatype byte 79Element item failed to validate content 80""" 81 82def callback(ctx, str): 83 global err 84 err = err + "%s" % (str) 85libxml2.registerErrorHandler(callback, "") 86 87f = StringIO.StringIO(docstr) 88input = libxml2.inputBuffer(f) 89reader = input.newTextReader("error") 90reader.RelaxNGSetSchema(rngs) 91ret = reader.Read() 92while ret == 1: 93 ret = reader.Read() 94 95if ret != 0: 96 print "Error parsing the document" 97 sys.exit(1) 98 99if reader.IsValid() != 0: 100 print "Document failed to detect the validation error" 101 sys.exit(1) 102 103if err != expect: 104 print "Did not get the expected error message:" 105 print err 106 sys.exit(1) 107 108# 109# cleanup 110# 111del f 112del input 113del reader 114del rngs 115libxml2.relaxNGCleanupTypes() 116 117# Memory debug specific 118libxml2.cleanupParser() 119if libxml2.debugMemory(1) == 0: 120 print "OK" 121else: 122 print "Memory leak %d bytes" % (libxml2.debugMemory(1)) 123 libxml2.dumpMemory() 124