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