xref: /aosp_15_r20/external/libxml2/python/tests/validRNG.py (revision 7c5688314b92172186c154356a6374bf7684c3ca)
1#!/usr/bin/env python3
2import setup_test
3import libxml2
4import sys
5
6ARG = 'test string'
7
8class ErrorHandler:
9
10    def __init__(self):
11        self.errors = []
12
13    def handler(self, msg, data):
14        if data != ARG:
15            raise Exception("Error handler did not receive correct argument")
16        self.errors.append(msg)
17
18# Memory debug specific
19libxml2.debugMemory(1)
20
21schema="""<?xml version="1.0"?>
22<element name="foo"
23         xmlns="http://relaxng.org/ns/structure/1.0"
24         xmlns:a="http://relaxng.org/ns/annotation/1.0"
25         xmlns:ex1="http://www.example.com/n1"
26         xmlns:ex2="http://www.example.com/n2">
27  <a:documentation>A foo element.</a:documentation>
28  <element name="ex1:bar1">
29    <empty/>
30  </element>
31  <element name="ex2:bar2">
32    <empty/>
33  </element>
34</element>
35"""
36
37valid="""<?xml version="1.0"?>
38<foo><pre1:bar1 xmlns:pre1="http://www.example.com/n1"/><pre2:bar2 xmlns:pre2="http://www.example.com/n2"/></foo>"""
39
40invalid="""<?xml version="1.0"?>
41<foo><pre1:bar1 xmlns:pre1="http://www.example.com/n1">bad</pre1:bar1><pre2:bar2 xmlns:pre2="http://www.example.com/n2"/></foo>"""
42
43rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema))
44rngs = rngp.relaxNGParse()
45ctxt = rngs.relaxNGNewValidCtxt()
46e = ErrorHandler()
47ctxt.setValidityErrorHandler(e.handler, e.handler, ARG)
48
49# Test valid document
50doc = libxml2.parseDoc(valid)
51ret = doc.relaxNGValidateDoc(ctxt)
52if ret != 0 or e.errors:
53    print("error doing RelaxNG validation")
54    sys.exit(1)
55doc.freeDoc()
56
57# Test invalid document
58doc = libxml2.parseDoc(invalid)
59ret = doc.relaxNGValidateDoc(ctxt)
60if ret == 0 or not e.errors:
61    print("Error: document supposed to be RelaxNG invalid")
62    sys.exit(1)
63doc.freeDoc()
64
65del rngp
66del rngs
67del ctxt
68libxml2.relaxNGCleanupTypes()
69
70# Memory debug specific
71libxml2.cleanupParser()
72if libxml2.debugMemory(1) == 0:
73    print("OK")
74else:
75    print("Memory leak %d bytes" % (libxml2.debugMemory(1)))
76
77