Debian Codegraph @

t/26schema.t

raw
1 # $Id$
2
3 ##
4 # Testcases for the XML Schema interface
5 #
6
7 use strict;
8 use warnings;
9
10 use lib './t/lib';
11 use TestHelpers qw(slurp);
12
13 use Test::More;
14
15 use XML::LibXML;
16
17 if ( XML::LibXML::LIBXML_VERSION >= 20510 ) {
18 plan tests => 8;
19 }
20 else {
21 plan skip_all => 'No Schema Support compiled.';
22 }
23
24 my $xmlparser = XML::LibXML->new();
25
26 my $file = "test/schema/schema.xsd";
27 my $badfile = "test/schema/badschema.xsd";
28 my $validfile = "test/schema/demo.xml";
29 my $invalidfile = "test/schema/invaliddemo.xml";
30
31
32 # 1 parse schema from a file
33 {
34 my $rngschema = XML::LibXML::Schema->new( location => $file );
35 # TEST
36 ok ( $rngschema, 'Good XML::LibXML::Schema was initialised' );
37
38 eval { $rngschema = XML::LibXML::Schema->new( location => $badfile ); };
39 # TEST
40 ok( $@, 'Bad XML::LibXML::Schema throws an exception.' );
41 }
42
43 # 2 parse schema from a string
44 {
45 my $string = slurp($file);
46
47 my $rngschema = XML::LibXML::Schema->new( string => $string );
48 # TEST
49 ok ( $rngschema, 'RNG Schema initialized from string.' );
50
51 $string = slurp($badfile);
52 eval { $rngschema = XML::LibXML::Schema->new( string => $string ); };
53 # TEST
54 ok( $@, 'Bad string schema throws an excpetion.' );
55 }
56
57 # 3 validate a document
58 {
59 my $doc = $xmlparser->parse_file( $validfile );
60 my $rngschema = XML::LibXML::Schema->new( location => $file );
61
62 my $valid = 0;
63 eval { $valid = $rngschema->validate( $doc ); };
64 # TEST
65 is( $valid, 0, 'validate() returns 0 to indicate validity of valid file.' );
66
67 $doc = $xmlparser->parse_file( $invalidfile );
68 $valid = 0;
69 eval { $valid = $rngschema->validate( $doc ); };
70 # TEST
71 ok ( $@, 'Invalid file throws an excpetion.');
72 }
73
74 # 4 validate a node
75 {
76 my $doc = $xmlparser->load_xml(string => <<'EOF');
77 <shiporder orderid="889923">
78 <orderperson>John Smith</orderperson>
79 <shipto>
80 <name>Ola Nordmann</name>
81 </shipto>
82 </shiporder>
83 EOF
84
85 my $schema = XML::LibXML::Schema->new(string => <<'EOF');
86 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
87 <xs:element name="shiporder">
88 <xs:complexType>
89 <xs:sequence>
90 <xs:element name="orderperson" type="xs:string"/>
91 <xs:element ref="shipto"/>
92 </xs:sequence>
93 <xs:attribute name="orderid" type="xs:string" use="required"/>
94 </xs:complexType>
95 </xs:element>
96 <xs:element name="shipto">
97 <xs:complexType>
98 <xs:sequence>
99 <xs:element name="name" type="xs:string"/>
100 </xs:sequence>
101 </xs:complexType>
102 </xs:element>
103 </xs:schema>
104 EOF
105
106 my $nodelist = $doc->findnodes('/shiporder/shipto');
107 my $result = 1;
108 eval { $result = $schema->validate($nodelist->get_node(1)); };
109 # TEST
110 is( $@, '', 'validate() with element doesn\'t throw' );
111 # TEST
112 is( $result, 0, 'validate() with element returns 0' );
113 }
114