diff options
author | kou <kou@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2014-05-27 13:10:55 +0000 |
---|---|---|
committer | kou <kou@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2014-05-27 13:10:55 +0000 |
commit | ba3d2f4ac20bec871fe96a393d923d0cbb0fd96a (patch) | |
tree | 897a0308607db1dad21eef1fee86b351e93ebfa5 /test | |
parent | 313fa180333a1eb4d1fa1542930e83f8d77e6b2d (diff) | |
download | ruby-ba3d2f4ac20bec871fe96a393d923d0cbb0fd96a.tar.gz |
* test/rexml/test_contrib.rb: Indent.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@46174 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'test')
35 files changed, 4966 insertions, 4966 deletions
diff --git a/test/rexml/parse/test_document_type_declaration.rb b/test/rexml/parse/test_document_type_declaration.rb index fb7cee5c3b..59fe561155 100644 --- a/test/rexml/parse/test_document_type_declaration.rb +++ b/test/rexml/parse/test_document_type_declaration.rb @@ -2,48 +2,48 @@ require "test/unit" require "rexml/document" module REXMLTests -class TestParseDocumentTypeDeclaration < Test::Unit::TestCase - private - def xml(internal_subset) - <<-XML + class TestParseDocumentTypeDeclaration < Test::Unit::TestCase + private + def xml(internal_subset) + <<-XML <!DOCTYPE r SYSTEM "urn:x-rexml:test" [ #{internal_subset} ]> <r/> - XML - end + XML + end - def parse(internal_subset) - REXML::Document.new(xml(internal_subset)).doctype - end + def parse(internal_subset) + REXML::Document.new(xml(internal_subset)).doctype + end - class TestMixed < self - def test_entity_element - doctype = parse(<<-INTERNAL_SUBSET) + class TestMixed < self + def test_entity_element + doctype = parse(<<-INTERNAL_SUBSET) <!ENTITY entity-name "entity content"> <!ELEMENT element-name EMPTY> - INTERNAL_SUBSET - assert_equal([REXML::Entity, REXML::ElementDecl], - doctype.children.collect(&:class)) - end + INTERNAL_SUBSET + assert_equal([REXML::Entity, REXML::ElementDecl], + doctype.children.collect(&:class)) + end - def test_attlist_entity - doctype = parse(<<-INTERNAL_SUBSET) + def test_attlist_entity + doctype = parse(<<-INTERNAL_SUBSET) <!ATTLIST attribute-list-name attribute-name CDATA #REQUIRED> <!ENTITY entity-name "entity content"> - INTERNAL_SUBSET - assert_equal([REXML::AttlistDecl, REXML::Entity], - doctype.children.collect(&:class)) - end + INTERNAL_SUBSET + assert_equal([REXML::AttlistDecl, REXML::Entity], + doctype.children.collect(&:class)) + end - def test_notation_attlist - doctype = parse(<<-INTERNAL_SUBSET) + def test_notation_attlist + doctype = parse(<<-INTERNAL_SUBSET) <!NOTATION notation-name SYSTEM "system-literal"> <!ATTLIST attribute-list-name attribute-name CDATA #REQUIRED> - INTERNAL_SUBSET - assert_equal([REXML::NotationDecl, REXML::AttlistDecl], - doctype.children.collect(&:class)) + INTERNAL_SUBSET + assert_equal([REXML::NotationDecl, REXML::AttlistDecl], + doctype.children.collect(&:class)) + end end end end -end diff --git a/test/rexml/parse/test_notation_declaration.rb b/test/rexml/parse/test_notation_declaration.rb index ecce44a790..0a4e737abf 100644 --- a/test/rexml/parse/test_notation_declaration.rb +++ b/test/rexml/parse/test_notation_declaration.rb @@ -2,98 +2,98 @@ require 'test/unit' require 'rexml/document' module REXMLTests -class TestParseNotationDeclaration < Test::Unit::TestCase - private - def xml(internal_subset) - <<-XML + class TestParseNotationDeclaration < Test::Unit::TestCase + private + def xml(internal_subset) + <<-XML <!DOCTYPE r SYSTEM "urn:x-henrikmartensson:test" [ #{internal_subset} ]> <r/> - XML - end - - def parse(internal_subset) - REXML::Document.new(xml(internal_subset)).doctype - end - - class TestCommon < self - def test_name - doctype = parse("<!NOTATION name PUBLIC 'urn:public-id'>") - assert_equal("name", doctype.notation("name").name) + XML end - end - class TestExternalID < self - class TestSystem < self - def test_single_quote - doctype = parse(<<-INTERNAL_SUBSET) -<!NOTATION name SYSTEM 'system-literal'> - INTERNAL_SUBSET - assert_equal("system-literal", doctype.notation("name").system) - end + def parse(internal_subset) + REXML::Document.new(xml(internal_subset)).doctype + end - def test_double_quote - doctype = parse(<<-INTERNAL_SUBSET) -<!NOTATION name SYSTEM "system-literal"> - INTERNAL_SUBSET - assert_equal("system-literal", doctype.notation("name").system) + class TestCommon < self + def test_name + doctype = parse("<!NOTATION name PUBLIC 'urn:public-id'>") + assert_equal("name", doctype.notation("name").name) end end - class TestPublic < self - class TestPublicIDLiteral < self + class TestExternalID < self + class TestSystem < self def test_single_quote doctype = parse(<<-INTERNAL_SUBSET) -<!NOTATION name PUBLIC 'public-id-literal' "system-literal"> +<!NOTATION name SYSTEM 'system-literal'> INTERNAL_SUBSET - assert_equal("public-id-literal", doctype.notation("name").public) + assert_equal("system-literal", doctype.notation("name").system) end def test_double_quote doctype = parse(<<-INTERNAL_SUBSET) -<!NOTATION name PUBLIC "public-id-literal" "system-literal"> +<!NOTATION name SYSTEM "system-literal"> INTERNAL_SUBSET - assert_equal("public-id-literal", doctype.notation("name").public) + assert_equal("system-literal", doctype.notation("name").system) end end - class TestSystemLiteral < self - def test_single_quote - doctype = parse(<<-INTERNAL_SUBSET) -<!NOTATION name PUBLIC "public-id-literal" 'system-literal'> - INTERNAL_SUBSET - assert_equal("system-literal", doctype.notation("name").system) + class TestPublic < self + class TestPublicIDLiteral < self + def test_single_quote + doctype = parse(<<-INTERNAL_SUBSET) +<!NOTATION name PUBLIC 'public-id-literal' "system-literal"> + INTERNAL_SUBSET + assert_equal("public-id-literal", doctype.notation("name").public) + end + + def test_double_quote + doctype = parse(<<-INTERNAL_SUBSET) +<!NOTATION name PUBLIC "public-id-literal" "system-literal"> + INTERNAL_SUBSET + assert_equal("public-id-literal", doctype.notation("name").public) + end end - def test_double_quote - doctype = parse(<<-INTERNAL_SUBSET) + class TestSystemLiteral < self + def test_single_quote + doctype = parse(<<-INTERNAL_SUBSET) +<!NOTATION name PUBLIC "public-id-literal" 'system-literal'> + INTERNAL_SUBSET + assert_equal("system-literal", doctype.notation("name").system) + end + + def test_double_quote + doctype = parse(<<-INTERNAL_SUBSET) <!NOTATION name PUBLIC "public-id-literal" "system-literal"> - INTERNAL_SUBSET - assert_equal("system-literal", doctype.notation("name").system) + INTERNAL_SUBSET + assert_equal("system-literal", doctype.notation("name").system) + end end end - end - class TestMixed < self - def test_system_public - doctype = parse(<<-INTERNAL_SUBSET) + class TestMixed < self + def test_system_public + doctype = parse(<<-INTERNAL_SUBSET) <!NOTATION system-name SYSTEM "system-literal"> <!NOTATION public-name PUBLIC "public-id-literal" 'system-literal'> - INTERNAL_SUBSET - assert_equal(["system-name", "public-name"], - doctype.notations.collect(&:name)) - end + INTERNAL_SUBSET + assert_equal(["system-name", "public-name"], + doctype.notations.collect(&:name)) + end - def test_public_system - doctype = parse(<<-INTERNAL_SUBSET) + def test_public_system + doctype = parse(<<-INTERNAL_SUBSET) <!NOTATION public-name PUBLIC "public-id-literal" 'system-literal'> <!NOTATION system-name SYSTEM "system-literal"> - INTERNAL_SUBSET - assert_equal(["public-name", "system-name"], - doctype.notations.collect(&:name)) + INTERNAL_SUBSET + assert_equal(["public-name", "system-name"], + doctype.notations.collect(&:name)) + end end end end end -end diff --git a/test/rexml/test_attributes.rb b/test/rexml/test_attributes.rb index fea4ee7636..aea1d8857c 100644 --- a/test/rexml/test_attributes.rb +++ b/test/rexml/test_attributes.rb @@ -2,203 +2,203 @@ require 'test/unit/testcase' require 'rexml/document' module REXMLTests -class AttributesTester < Test::Unit::TestCase - include REXML - def test_accessor - doc = Document.new("<a xmlns:foo='a' xmlns:bar='b' foo:att='1' bar:att='2' att='3'/>") - assert_equal '3', doc.root.attributes['att'] - assert_equal '2', doc.root.attributes['bar:att'] - doc.root.attributes['att'] = 5 - assert_equal '5', doc.root.attributes['att'] - end - - def test_each_attribute - doc = Document.new('<a x="1" y="2"/>') - doc.root.attributes.each_attribute {|attr| - if attr.expanded_name == 'x' - assert_equal '1', attr.value - elsif attr.expanded_name == 'y' - assert_equal '2', attr.value - else - assert_fail "No such attribute!!" - end - } - end + class AttributesTester < Test::Unit::TestCase + include REXML + def test_accessor + doc = Document.new("<a xmlns:foo='a' xmlns:bar='b' foo:att='1' bar:att='2' att='3'/>") + assert_equal '3', doc.root.attributes['att'] + assert_equal '2', doc.root.attributes['bar:att'] + doc.root.attributes['att'] = 5 + assert_equal '5', doc.root.attributes['att'] + end - def test_each - doc = Document.new('<a x="1" y="2"/>') - doc.root.attributes.each {|name, value| - if name == 'x' - assert_equal '1', value - elsif name == 'y' - assert_equal '2', value - else - assert_fail "No such attribute!!" - end - } - end + def test_each_attribute + doc = Document.new('<a x="1" y="2"/>') + doc.root.attributes.each_attribute {|attr| + if attr.expanded_name == 'x' + assert_equal '1', attr.value + elsif attr.expanded_name == 'y' + assert_equal '2', attr.value + else + assert_fail "No such attribute!!" + end + } + end - def test_get_attribute - doc = Document.new('<a xmlns:x="a" x:foo="1" foo="2" bar="3"/>') - assert_equal '2', doc.root.attributes.get_attribute("foo").value - assert_equal '1', doc.root.attributes.get_attribute("x:foo").value - end + def test_each + doc = Document.new('<a x="1" y="2"/>') + doc.root.attributes.each {|name, value| + if name == 'x' + assert_equal '1', value + elsif name == 'y' + assert_equal '2', value + else + assert_fail "No such attribute!!" + end + } + end - def test_size - doc = Document.new("<a xmlns:foo='a' x='1' y='2' foo:x='3'/>") - assert_equal 4, doc.root.attributes.length - end + def test_get_attribute + doc = Document.new('<a xmlns:x="a" x:foo="1" foo="2" bar="3"/>') + assert_equal '2', doc.root.attributes.get_attribute("foo").value + assert_equal '1', doc.root.attributes.get_attribute("x:foo").value + end - def test_setter - doc = Document.new("<a xmlns:x='a' x:foo='1' foo='3'/>") - doc.root.attributes['y:foo'] = '2' - assert_equal '2', doc.root.attributes['y:foo'] - doc.root.attributes['foo'] = '4' - assert_equal '4', doc.root.attributes['foo'] - doc.root.attributes['x:foo'] = nil - assert_equal 3, doc.root.attributes.size - end + def test_size + doc = Document.new("<a xmlns:foo='a' x='1' y='2' foo:x='3'/>") + assert_equal 4, doc.root.attributes.length + end - def test_delete - doc = Document.new("<a xmlns:y='a' xmlns:x='b' xmlns:z='c' y:foo='0' x:foo='1' foo='3' z:foo='4'/>") - doc.root.attributes.delete 'foo' - assert_equal 6, doc.root.attributes.size - assert_equal '1', doc.root.attributes['x:foo'] + def test_setter + doc = Document.new("<a xmlns:x='a' x:foo='1' foo='3'/>") + doc.root.attributes['y:foo'] = '2' + assert_equal '2', doc.root.attributes['y:foo'] + doc.root.attributes['foo'] = '4' + assert_equal '4', doc.root.attributes['foo'] + doc.root.attributes['x:foo'] = nil + assert_equal 3, doc.root.attributes.size + end - doc.root.attributes.delete 'x:foo' - assert_equal 5, doc.root.attributes.size + def test_delete + doc = Document.new("<a xmlns:y='a' xmlns:x='b' xmlns:z='c' y:foo='0' x:foo='1' foo='3' z:foo='4'/>") + doc.root.attributes.delete 'foo' + assert_equal 6, doc.root.attributes.size + assert_equal '1', doc.root.attributes['x:foo'] - attr = doc.root.attributes.get_attribute('y:foo') - doc.root.attributes.delete attr - assert_equal 4, doc.root.attributes.size + doc.root.attributes.delete 'x:foo' + assert_equal 5, doc.root.attributes.size - assert_equal '4', doc.root.attributes['z:foo'] - end + attr = doc.root.attributes.get_attribute('y:foo') + doc.root.attributes.delete attr + assert_equal 4, doc.root.attributes.size - def test_prefixes - doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' z='glorp' x:k='gru'/>") - prefixes = doc.root.attributes.prefixes - assert_equal 2, prefixes.size - assert_equal 0, (prefixes - ['x', 'y']).size - end + assert_equal '4', doc.root.attributes['z:foo'] + end - # Contributed by Mike Stok - def test_values_with_apostrophes - doc = Document.new(%q#<tag h1="1'2'" h2='1"2'/>#) - s = doc.to_s - assert(s =~ /h1='1'2''/) - assert(s =~ /h2='1"2'/) - end + def test_prefixes + doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' z='glorp' x:k='gru'/>") + prefixes = doc.root.attributes.prefixes + assert_equal 2, prefixes.size + assert_equal 0, (prefixes - ['x', 'y']).size + end - # Submitted by Kou - def test_namespace_conflict - assert_raise( ParseException, - "Declaring two attributes with the same namespace should be an error" ) do - REXML::Document.new <<-XML - <x xmlns:n1="http://www.w3.org" - xmlns:n2="http://www.w3.org" > - <bad n1:a="1" n2:a="2" /> - </x> - XML + # Contributed by Mike Stok + def test_values_with_apostrophes + doc = Document.new(%q#<tag h1="1'2'" h2='1"2'/>#) + s = doc.to_s + assert(s =~ /h1='1'2''/) + assert(s =~ /h2='1"2'/) end - REXML::Document.new("<a xmlns:a='a' xmlns:b='a'></a>") - end + # Submitted by Kou + def test_namespace_conflict + assert_raise( ParseException, + "Declaring two attributes with the same namespace should be an error" ) do + REXML::Document.new <<-XML + <x xmlns:n1="http://www.w3.org" + xmlns:n2="http://www.w3.org" > + <bad n1:a="1" n2:a="2" /> + </x> + XML + end - # Submitted by Kou - def test_attribute_deletion - e = REXML::Element.new - e.add_namespace("a", "http://a/") - e.add_namespace("b", "http://b/") - e.add_attributes({"c" => "cc", "a:c" => "cC", "b:c" => "CC"}) + REXML::Document.new("<a xmlns:a='a' xmlns:b='a'></a>") + end - e.attributes.delete("c") - assert_nil(e.attributes.get_attribute("c")) + # Submitted by Kou + def test_attribute_deletion + e = REXML::Element.new + e.add_namespace("a", "http://a/") + e.add_namespace("b", "http://b/") + e.add_attributes({"c" => "cc", "a:c" => "cC", "b:c" => "CC"}) - before_size = e.attributes.size - e.attributes.delete("c") - assert_nil(e.attributes.get_attribute("c")) - assert_equal(before_size, e.attributes.size) + e.attributes.delete("c") + assert_nil(e.attributes.get_attribute("c")) - e.attributes.delete(e.attributes.get_attribute("a:c")) - assert_nil(e.attributes.get_attribute("a:c")) + before_size = e.attributes.size + e.attributes.delete("c") + assert_nil(e.attributes.get_attribute("c")) + assert_equal(before_size, e.attributes.size) - e.attributes.delete("b:c") - assert_nil(e.attributes.get_attribute("b:c")) + e.attributes.delete(e.attributes.get_attribute("a:c")) + assert_nil(e.attributes.get_attribute("a:c")) - before_size = e.attributes.size - e.attributes.delete(e.attributes.get_attribute("b:c")) - assert_nil(e.attributes.get_attribute("b:c")) - assert_equal(before_size, e.attributes.size) + e.attributes.delete("b:c") + assert_nil(e.attributes.get_attribute("b:c")) - before_size = e.attributes.size - e.attributes.delete("c") - assert_nil(e.attributes.get_attribute("c")) - assert_equal(before_size, e.attributes.size) + before_size = e.attributes.size + e.attributes.delete(e.attributes.get_attribute("b:c")) + assert_nil(e.attributes.get_attribute("b:c")) + assert_equal(before_size, e.attributes.size) - e.add_attribute("c", "cc") + before_size = e.attributes.size + e.attributes.delete("c") + assert_nil(e.attributes.get_attribute("c")) + assert_equal(before_size, e.attributes.size) - e.attributes.delete(e.attributes.get_attribute("c")) - assert_nil(e.attributes.get_attribute("c")) - end + e.add_attribute("c", "cc") - # Submitted by Kou - def test_element_usage - attr = Attribute.new("name", "value") - elem = Element.new("elem") - a = Attribute.new(attr, elem) - assert_equal(elem, a.element) - end + e.attributes.delete(e.attributes.get_attribute("c")) + assert_nil(e.attributes.get_attribute("c")) + end - def attr_test(attr_name,attr_value) - a1 = REXML::Attribute.new(attr_name,attr_value) + # Submitted by Kou + def test_element_usage + attr = Attribute.new("name", "value") + elem = Element.new("elem") + a = Attribute.new(attr, elem) + assert_equal(elem, a.element) + end - s1 = a1.value - s2 = a1.value + def attr_test(attr_name,attr_value) + a1 = REXML::Attribute.new(attr_name,attr_value) - #p s1 - #p s2 - assert_equal(s1,s2) + s1 = a1.value + s2 = a1.value - a2 = REXML::Attribute.new(attr_name,attr_value) + #p s1 + #p s2 + assert_equal(s1,s2) - a2.to_s # NB invocation of to_s - s1 = a2.value - s2 = a2.value + a2 = REXML::Attribute.new(attr_name,attr_value) - #p s1 - #p s2 - assert_equal(s1,s2) - end + a2.to_s # NB invocation of to_s + s1 = a2.value + s2 = a2.value - def test_amp_attributes - attr_test('name','value with & ampersand only') - end + #p s1 + #p s2 + assert_equal(s1,s2) + end - def test_amp_and_lf_attributes - attr_test('name','value with LF 
 & ampersand') - end + def test_amp_attributes + attr_test('name','value with & ampersand only') + end - def test_quoting - d = Document.new(%q{<a x='1' y="2"/>}) - assert_equal( %q{<a x='1' y='2'/>}, d.to_s ) - d.root.context[:attribute_quote] = :quote - assert_equal( %q{<a x="1" y="2"/>}, d.to_s ) + def test_amp_and_lf_attributes + attr_test('name','value with LF 
 & ampersand') + end - d = Document.new(%q{<a x='1' y="2"><b z='3'/></a>}) - assert_equal( %q{<a x='1' y='2'><b z='3'/></a>}, d.to_s ) - d.root.context[:attribute_quote] = :quote - assert_equal( %q{<a x="1" y="2"><b z="3"/></a>}, d.to_s ) - end + def test_quoting + d = Document.new(%q{<a x='1' y="2"/>}) + assert_equal( %q{<a x='1' y='2'/>}, d.to_s ) + d.root.context[:attribute_quote] = :quote + assert_equal( %q{<a x="1" y="2"/>}, d.to_s ) - def test_ticket_127 - doc = Document.new - doc.add_element 'a', { 'v' => 'x & y' } - assert doc.to_s.index(';') - end + d = Document.new(%q{<a x='1' y="2"><b z='3'/></a>}) + assert_equal( %q{<a x='1' y='2'><b z='3'/></a>}, d.to_s ) + d.root.context[:attribute_quote] = :quote + assert_equal( %q{<a x="1" y="2"><b z="3"/></a>}, d.to_s ) + end + + def test_ticket_127 + doc = Document.new + doc.add_element 'a', { 'v' => 'x & y' } + assert doc.to_s.index(';') + end - def test_to_a_with_namespaces - document = Document.new(<<-XML) + def test_to_a_with_namespaces + document = Document.new(<<-XML) <root xmlns:ns1="http://example.org/ns1" xmlns:ns2="http://example.org/ns2"> @@ -209,14 +209,14 @@ class AttributesTester < Test::Unit::TestCase other-attribute="other-value"/> </root> XML - child = document.root.elements["child"] - assert_equal([ - "attribute='no-ns'", - "ns1:attribute='ns1'", - "ns2:attribute='ns2'", - "other-attribute='other-value'", - ], - child.attributes.to_a.collect(&:to_string).sort) + child = document.root.elements["child"] + assert_equal([ + "attribute='no-ns'", + "ns1:attribute='ns1'", + "ns2:attribute='ns2'", + "other-attribute='other-value'", + ], + child.attributes.to_a.collect(&:to_string).sort) + end end end -end diff --git a/test/rexml/test_attributes_mixin.rb b/test/rexml/test_attributes_mixin.rb index a92c783d1a..17cca4efc3 100644 --- a/test/rexml/test_attributes_mixin.rb +++ b/test/rexml/test_attributes_mixin.rb @@ -2,30 +2,30 @@ require 'test/unit' require 'rexml/document' module REXMLTests -class TestAttributes < Test::Unit::TestCase - def setup - @ns_a = "urn:x-test:a" - @ns_b = "urn:x-test:b" - element_string = <<-"XMLEND" - <test xmlns:a="#{@ns_a}" - xmlns:b="#{@ns_b}" - a = "1" - b = '2' - a:c = "3" - a:d = '4' - a:e = "5" - b:f = "6"/> - XMLEND - @attributes = REXML::Document.new(element_string).root.attributes - end + class TestAttributes < Test::Unit::TestCase + def setup + @ns_a = "urn:x-test:a" + @ns_b = "urn:x-test:b" + element_string = <<-"XMLEND" + <test xmlns:a="#{@ns_a}" + xmlns:b="#{@ns_b}" + a = "1" + b = '2' + a:c = "3" + a:d = '4' + a:e = "5" + b:f = "6"/> + XMLEND + @attributes = REXML::Document.new(element_string).root.attributes + end - def test_get_attribute_ns - assert_equal("1", @attributes.get_attribute_ns("", "a").value) - assert_equal("2", @attributes.get_attribute_ns("", "b").value) - assert_equal("3", @attributes.get_attribute_ns(@ns_a, "c").value) - assert_equal("4", @attributes.get_attribute_ns(@ns_a, "d").value) - assert_equal("5", @attributes.get_attribute_ns(@ns_a, "e").value) - assert_equal("6", @attributes.get_attribute_ns(@ns_b, "f").value) + def test_get_attribute_ns + assert_equal("1", @attributes.get_attribute_ns("", "a").value) + assert_equal("2", @attributes.get_attribute_ns("", "b").value) + assert_equal("3", @attributes.get_attribute_ns(@ns_a, "c").value) + assert_equal("4", @attributes.get_attribute_ns(@ns_a, "d").value) + assert_equal("5", @attributes.get_attribute_ns(@ns_a, "e").value) + assert_equal("6", @attributes.get_attribute_ns(@ns_b, "f").value) + end end end -end diff --git a/test/rexml/test_changing_encoding.rb b/test/rexml/test_changing_encoding.rb index 0e0cd6cf8b..5a085e2519 100644 --- a/test/rexml/test_changing_encoding.rb +++ b/test/rexml/test_changing_encoding.rb @@ -3,42 +3,42 @@ require 'rexml/encoding' module REXMLTests -class ChangingEncodings < Test::Unit::TestCase - def initialize a - @u = 'テスト ほげ ふが 美しい' - @e = @u.encode("EUC-JP") - @f = Foo.new - super - end + class ChangingEncodings < Test::Unit::TestCase + def initialize a + @u = 'テスト ほげ ふが 美しい' + @e = @u.encode("EUC-JP") + @f = Foo.new + super + end - class Foo - include REXML::Encoding - end + class Foo + include REXML::Encoding + end - # Note that these tests must be executed in order for the third one to - # actually test anything. - def test_0_euc - @f.encoding = 'EUC-JP' - assert_equal( @u, @f.decode(@e) ) - # This doesn't happen anymore, for some reason - #assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) { - # @f.decode(@u) == @u - #} - end + # Note that these tests must be executed in order for the third one to + # actually test anything. + def test_0_euc + @f.encoding = 'EUC-JP' + assert_equal( @u, @f.decode(@e) ) + # This doesn't happen anymore, for some reason + #assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) { + # @f.decode(@u) == @u + #} + end - def test_1_utf - @f.encoding = 'UTF-8' - assert_not_equal( @u, @f.decode( @e ) ) - assert_equal( @u, @f.decode( @u ) ) - end + def test_1_utf + @f.encoding = 'UTF-8' + assert_not_equal( @u, @f.decode( @e ) ) + assert_equal( @u, @f.decode( @u ) ) + end - def test_2_euc - @f.encoding = 'EUC-JP' - assert_equal( @u, @f.decode(@e) ) - # This doesn't happen anymore, for some reason - #assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) { - # @f.decode(@u) == @u - #} + def test_2_euc + @f.encoding = 'EUC-JP' + assert_equal( @u, @f.decode(@e) ) + # This doesn't happen anymore, for some reason + #assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) { + # @f.decode(@u) == @u + #} + end end end -end diff --git a/test/rexml/test_contrib.rb b/test/rexml/test_contrib.rb index ea357b139f..917502fca6 100644 --- a/test/rexml/test_contrib.rb +++ b/test/rexml/test_contrib.rb @@ -7,11 +7,11 @@ require "rexml/parseexception" require "rexml/formatters/default" module REXMLTests -class ContribTester < Test::Unit::TestCase - include REXMLTestUtils - include REXML + class ContribTester < Test::Unit::TestCase + include REXMLTestUtils + include REXML - XML_STRING_01 = <<DELIMITER + XML_STRING_01 = <<DELIMITER <?xml version="1.0" encoding="UTF-8"?> <biblio> <entry type="Book"> @@ -32,7 +32,7 @@ class ContribTester < Test::Unit::TestCase </biblio> DELIMITER - XML_STRING_02 = <<DELIMITER + XML_STRING_02 = <<DELIMITER <biblio> <entry type="Book"> <language>english</language> @@ -52,205 +52,205 @@ DELIMITER </biblio> DELIMITER - # Tobias Reif <tobiasreif@pinkjuice.com> - def test_bad_doctype_Tobias - source = <<-EOF - <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" - "http://www.w3.org/TR/SVG/DTD/svg10.dtd" - [ - <!-- <!ENTITY % fast-slow "0 0 .5 1">--> - <!--<!ENTITY % slow-fast ".5 0 1 1">--> - <!ENTITY hover_ani - '<animateTransform attributeName="transform" - type="scale" restart="whenNotActive" values="1;0.96" - dur="0.5s" calcMode="spline" keySplines="0 0 .5 1" - fill="freeze" begin="mouseover"/> - <animateTransform attributeName="transform" - type="scale" restart="whenNotActive" values="0.96;1" - dur="0.5s" calcMode="spline" keySplines=".5 0 1 1" - fill="freeze" begin="mouseover+0.5s"/>' + # Tobias Reif <tobiasreif@pinkjuice.com> + def test_bad_doctype_Tobias + source = <<-EOF + <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" + "http://www.w3.org/TR/SVG/DTD/svg10.dtd" + [ + <!-- <!ENTITY % fast-slow "0 0 .5 1">--> + <!--<!ENTITY % slow-fast ".5 0 1 1">--> + <!ENTITY hover_ani + '<animateTransform attributeName="transform" + type="scale" restart="whenNotActive" values="1;0.96" + dur="0.5s" calcMode="spline" keySplines="0 0 .5 1" + fill="freeze" begin="mouseover"/> + <animateTransform attributeName="transform" + type="scale" restart="whenNotActive" values="0.96;1" + dur="0.5s" calcMode="spline" keySplines=".5 0 1 1" + fill="freeze" begin="mouseover+0.5s"/>' + > + ] > - ] - > - EOF - doc = REXML::Document.new source - doc.write(out="") - assert(out[/>\'>/] != nil, "Couldn't find >'>") - assert(out[/\]>/] != nil, "Couldn't find ]>") - end + EOF + doc = REXML::Document.new source + doc.write(out="") + assert(out[/>\'>/] != nil, "Couldn't find >'>") + assert(out[/\]>/] != nil, "Couldn't find ]>") + end - # Peter Verhage - def test_namespace_Peter - source = <<-EOF - <?xml version="1.0"?> - <config:myprog-config xmlns:config="http://someurl/program/version"> - <!-- main options --> - <config:main> - <config:parameter name="name" value="value"/> - </config:main> - </config:myprog-config> - EOF - doc = REXML::Document.new source - assert_equal "myprog-config", doc.root.name - count = 0 - REXML::XPath.each(doc, "x:myprog-config/x:main/x:parameter", - {"x"=>"http://someurl/program/version"}) { |element| - assert_equal "name", element.attributes["name"] - count += 1; - } - assert_equal 1, count - assert_equal "myprog-config", doc.elements["config:myprog-config"].name - end + # Peter Verhage + def test_namespace_Peter + source = <<-EOF + <?xml version="1.0"?> + <config:myprog-config xmlns:config="http://someurl/program/version"> + <!-- main options --> + <config:main> + <config:parameter name="name" value="value"/> + </config:main> + </config:myprog-config> + EOF + doc = REXML::Document.new source + assert_equal "myprog-config", doc.root.name + count = 0 + REXML::XPath.each(doc, "x:myprog-config/x:main/x:parameter", + {"x"=>"http://someurl/program/version"}) { |element| + assert_equal "name", element.attributes["name"] + count += 1; + } + assert_equal 1, count + assert_equal "myprog-config", doc.elements["config:myprog-config"].name + end - # Tobias Reif <tobiasreif@pinkjuice.com> - def test_complex_xpath_Tobias - source = <<-EOF - <root> - <foo> - <bar style="baz"/> - <blah style="baz"/> - <blam style="baz"/> - </foo> - <wax> - <fudge> - <noodle/> - </fudge> - </wax> - </root> - EOF - # elements that have child elements - # but not grandchildren - # and not children that don't have a style attribute - # and not children that have a unique style attribute - complex_path = "*[* "+ - "and not(*/node()) "+ - "and not(*[not(@style)]) "+ - "and not(*/@style != */@style)]" - doc = REXML::Document.new source - results = REXML::XPath.match( doc.root, complex_path ) - assert(results) - assert_equal 1, results.size - assert_equal "foo", results[0].name - end + # Tobias Reif <tobiasreif@pinkjuice.com> + def test_complex_xpath_Tobias + source = <<-EOF + <root> + <foo> + <bar style="baz"/> + <blah style="baz"/> + <blam style="baz"/> + </foo> + <wax> + <fudge> + <noodle/> + </fudge> + </wax> + </root> + EOF + # elements that have child elements + # but not grandchildren + # and not children that don't have a style attribute + # and not children that have a unique style attribute + complex_path = "*[* "+ + "and not(*/node()) "+ + "and not(*[not(@style)]) "+ + "and not(*/@style != */@style)]" + doc = REXML::Document.new source + results = REXML::XPath.match( doc.root, complex_path ) + assert(results) + assert_equal 1, results.size + assert_equal "foo", results[0].name + end - # "Chris Morris" <chrismo@charter.net> - def test_extra_newline_on_read_Chris - text = 'test text' - e = REXML::Element.new('Test') - e.add_text(text) - REXML::Formatters::Default.new.write(e,out="") + # "Chris Morris" <chrismo@charter.net> + def test_extra_newline_on_read_Chris + text = 'test text' + e = REXML::Element.new('Test') + e.add_text(text) + REXML::Formatters::Default.new.write(e,out="") - doc = REXML::Document.new(out) - outtext = doc.root.text + doc = REXML::Document.new(out) + outtext = doc.root.text - assert_equal(text, outtext) - end + assert_equal(text, outtext) + end - # Tobias Reif <tobiasreif@pinkjuice.com> - def test_other_xpath_Tobias - schema = <<-DELIM - <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" - elementFormDefault="qualified"> - <xs:element name="rect"> - <xs:complexType> - <xs:attribute name="width" type="xs:byte" use="required"/> - <xs:attribute name="height" type="xs:byte" use="required"/> - </xs:complexType> - </xs:element> - <xs:element name="svg"> - <xs:complexType> - <xs:sequence> - <xs:element ref="rect"/> - </xs:sequence> - </xs:complexType> - </xs:element> - </xs:schema> - DELIM - - doc = REXML::Document.new schema - - result = REXML::XPath.first(doc.root, 'xs:element[descendant::xs:element[@ref]]') - assert result - assert_equal "svg", result.attributes['name'] - result = REXML::XPath.first(doc, 'element[descendant::element[@ref]]') - assert_nil result - end + # Tobias Reif <tobiasreif@pinkjuice.com> + def test_other_xpath_Tobias + schema = <<-DELIM + <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" + elementFormDefault="qualified"> + <xs:element name="rect"> + <xs:complexType> + <xs:attribute name="width" type="xs:byte" use="required"/> + <xs:attribute name="height" type="xs:byte" use="required"/> + </xs:complexType> + </xs:element> + <xs:element name="svg"> + <xs:complexType> + <xs:sequence> + <xs:element ref="rect"/> + </xs:sequence> + </xs:complexType> + </xs:element> + </xs:schema> + DELIM + + doc = REXML::Document.new schema + + result = REXML::XPath.first(doc.root, 'xs:element[descendant::xs:element[@ref]]') + assert result + assert_equal "svg", result.attributes['name'] + result = REXML::XPath.first(doc, 'element[descendant::element[@ref]]') + assert_nil result + end - #this first test succeeds, to check if stuff is set up correctly - def test_xpath_01_TobiasReif - doc = Document.new XML_STRING_01.dup - desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>' - xpath = '//author' - result = XPath.first(doc, xpath) - assert_equal desired_result.to_s, result.to_s - end + #this first test succeeds, to check if stuff is set up correctly + def test_xpath_01_TobiasReif + doc = Document.new XML_STRING_01.dup + desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>' + xpath = '//author' + result = XPath.first(doc, xpath) + assert_equal desired_result.to_s, result.to_s + end - def test_xpath_whitespace_TobiasReif - # same as above, with whitespace in XPath - doc = Document.new(XML_STRING_01.dup) - desired_result = Document.new('<author>Thomas, David; Hunt, Andrew</author>') - xpath = "\/\/author\n \n" - result = XPath.first(doc, xpath) - failure_message = "\n[[[TR: AFAIK, whitespace should be allowed]]]\n" - assert_equal(desired_result.to_s, result.to_s, failure_message) - end + def test_xpath_whitespace_TobiasReif + # same as above, with whitespace in XPath + doc = Document.new(XML_STRING_01.dup) + desired_result = Document.new('<author>Thomas, David; Hunt, Andrew</author>') + xpath = "\/\/author\n \n" + result = XPath.first(doc, xpath) + failure_message = "\n[[[TR: AFAIK, whitespace should be allowed]]]\n" + assert_equal(desired_result.to_s, result.to_s, failure_message) + end - def test_xpath_02_TobiasReif - doc = Document.new XML_STRING_01.dup - desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>' - # Could that quirky - # Programmer',"'",'s - # be handled automatically, somehow? - # Or is there a simpler way? (the below XPath should match the author element above, - # AFAIK; I tested it inside an XSLT) - xpath = %q{/biblio/entry[ - title/text()=concat('Programming Ruby. The Pragmatic Programmer',"'",'s Guide') - and - year='2000' - ]/author} - result = XPath.first(doc, xpath) - failure_message = "\nHow to handle the apos inside the string inside the XPath?\nXPath = #{xpath}\n" - assert_equal desired_result.to_s, result.to_s, failure_message - end + def test_xpath_02_TobiasReif + doc = Document.new XML_STRING_01.dup + desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>' + # Could that quirky + # Programmer',"'",'s + # be handled automatically, somehow? + # Or is there a simpler way? (the below XPath should match the author element above, + # AFAIK; I tested it inside an XSLT) + xpath = %q{/biblio/entry[ + title/text()=concat('Programming Ruby. The Pragmatic Programmer',"'",'s Guide') + and + year='2000' + ]/author} + result = XPath.first(doc, xpath) + failure_message = "\nHow to handle the apos inside the string inside the XPath?\nXPath = #{xpath}\n" + assert_equal desired_result.to_s, result.to_s, failure_message + end - def test_xpath_03_TobiasReif - doc = Document.new XML_STRING_02.dup - desired_result_string = "<entry type='Book'> + def test_xpath_03_TobiasReif + doc = Document.new XML_STRING_02.dup + desired_result_string = "<entry type='Book'> <language>english</language> <publisher>Addison-Wesley</publisher> <title>Programming Ruby. The Pragmatic Programmer's Guide</title> <type>Book</type> <year>2000</year> </entry>" - Document.new desired_result_string - xpath = "/biblio/entry[not(author)]" - result = XPath.first(doc, xpath) - assert_equal desired_result_string, result.to_s - end - - def test_umlaut - koln_iso = "K\xf6ln" - koln_utf = "K\xc3\xb6ln" - source_iso = "<?xml version='1.0' encoding='ISO-8859-1'?><test>#{koln_iso}</test>" - source_utf = "<?xml version='1.0' encoding='UTF-8'?><test>#{koln_utf}</test>" - - if String.method_defined? :encode - koln_iso.force_encoding('iso-8859-1') - koln_utf.force_encoding('utf-8') - source_iso.force_encoding('iso-8859-1') - source_utf.force_encoding('utf-8') + Document.new desired_result_string + xpath = "/biblio/entry[not(author)]" + result = XPath.first(doc, xpath) + assert_equal desired_result_string, result.to_s end - doc = REXML::Document.new(source_iso) - assert_equal('ISO-8859-1', doc.xml_decl.encoding) - assert_equal(koln_utf, doc.root.text) - doc.write(out="") - assert_equal(source_iso, out ) - doc.xml_decl.encoding = 'UTF-8' - doc.write(out="") - assert_equal(source_utf, out) + def test_umlaut + koln_iso = "K\xf6ln" + koln_utf = "K\xc3\xb6ln" + source_iso = "<?xml version='1.0' encoding='ISO-8859-1'?><test>#{koln_iso}</test>" + source_utf = "<?xml version='1.0' encoding='UTF-8'?><test>#{koln_utf}</test>" + + if String.method_defined? :encode + koln_iso.force_encoding('iso-8859-1') + koln_utf.force_encoding('utf-8') + source_iso.force_encoding('iso-8859-1') + source_utf.force_encoding('utf-8') + end + + doc = REXML::Document.new(source_iso) + assert_equal('ISO-8859-1', doc.xml_decl.encoding) + assert_equal(koln_utf, doc.root.text) + doc.write(out="") + assert_equal(source_iso, out ) + doc.xml_decl.encoding = 'UTF-8' + doc.write(out="") + assert_equal(source_utf, out) - doc = Document.new <<-EOF + doc = Document.new <<-EOF <?xml version="1.0" encoding="ISO-8859-1"?> <intranet> <position><aktuell datum="01-10-11">Technik</aktuell></position> @@ -266,254 +266,254 @@ Die Technik ist das R\xFCckgrat der meisten Gesch\xFCftsprozesse bei Home of the </nebenspalte> </intranet> EOF - tn = XPath.first(doc, "//nebenspalte/text()[2]") - expected_iso = "N\xFCtzliches von Flashern f\xFCr Flasher." - expected_utf = expected_iso.unpack('C*').pack('U*') - expected_iso.force_encoding(::Encoding::ISO_8859_1) - expected_utf.force_encoding(::Encoding::UTF_8) - assert_equal(expected_utf, tn.to_s.strip) - f = REXML::Formatters::Default.new - f.write( tn, Output.new(o = "", "ISO-8859-1") ) - assert_equal(expected_iso, o.strip) - - doc = Document.new File.new(fixture_path('xmlfile-bug.xml')) - tn = XPath.first(doc, "//nebenspalte/text()[2]") - assert_equal(expected_utf, tn.to_s.strip) - f.write( tn, Output.new(o = "", "ISO-8859-1") ) - assert_equal(expected_iso, o.strip) - end - - def test_element_cloning_namespace_Chris - aDoc = REXML::Document.new '<h1 tpl:content="title" xmlns:tpl="1">Dummy title</h1>' + tn = XPath.first(doc, "//nebenspalte/text()[2]") + expected_iso = "N\xFCtzliches von Flashern f\xFCr Flasher." + expected_utf = expected_iso.unpack('C*').pack('U*') + expected_iso.force_encoding(::Encoding::ISO_8859_1) + expected_utf.force_encoding(::Encoding::UTF_8) + assert_equal(expected_utf, tn.to_s.strip) + f = REXML::Formatters::Default.new + f.write( tn, Output.new(o = "", "ISO-8859-1") ) + assert_equal(expected_iso, o.strip) + + doc = Document.new File.new(fixture_path('xmlfile-bug.xml')) + tn = XPath.first(doc, "//nebenspalte/text()[2]") + assert_equal(expected_utf, tn.to_s.strip) + f.write( tn, Output.new(o = "", "ISO-8859-1") ) + assert_equal(expected_iso, o.strip) + end - anElement = anElement = aDoc.elements[1] - elementAttrPrefix = anElement.attributes.get_attribute('content').prefix + def test_element_cloning_namespace_Chris + aDoc = REXML::Document.new '<h1 tpl:content="title" xmlns:tpl="1">Dummy title</h1>' - aClone = anElement.clone - cloneAttrPrefix = aClone.attributes.get_attribute('content').prefix + anElement = anElement = aDoc.elements[1] + elementAttrPrefix = anElement.attributes.get_attribute('content').prefix - assert_equal( elementAttrPrefix , cloneAttrPrefix ) - end + aClone = anElement.clone + cloneAttrPrefix = aClone.attributes.get_attribute('content').prefix - def test_namespaces_in_attlist_tobias - in_string = File.open(fixture_path('foo.xml'), 'r') do |file| - file.read + assert_equal( elementAttrPrefix , cloneAttrPrefix ) end - doc = Document.new in_string + def test_namespaces_in_attlist_tobias + in_string = File.open(fixture_path('foo.xml'), 'r') do |file| + file.read + end - assert_nil XPath.first(doc,'//leg') - assert_equal 'http://www.foo.com/human', doc.root.elements[1].namespace - assert_equal 'human leg', - XPath.first(doc, '//x:leg/text()', {'x'=>'http://www.foo.com/human'}).to_s - end + doc = Document.new in_string - # Alun ap Rhisiart - def test_less_than_in_element_content - source = File.new(fixture_path('ProductionSupport.xml')) - h = Hash.new - doc = REXML::Document.new source - doc.elements.each("//CommonError") { |el| - h[el.elements['Key'].text] = 'okay' - } - assert(h.include?('MotorInsuranceContract(Object)>>#error:')) - end + assert_nil XPath.first(doc,'//leg') + assert_equal 'http://www.foo.com/human', doc.root.elements[1].namespace + assert_equal 'human leg', + XPath.first(doc, '//x:leg/text()', {'x'=>'http://www.foo.com/human'}).to_s + end - # XPaths provided by Thomas Sawyer - def test_various_xpath - #@doc = REXML::Document.new('<r a="1"><p><c b="2"/></p></r>') - doc = REXML::Document.new('<r a="1"><p><c b="2">3</c></p></r>') - - [['/r', REXML::Element], - ['/r/p/c', REXML::Element], - ['/r/attribute::a', Attribute], - ['/r/@a', Attribute], - ['/r/attribute::*', Attribute], - ['/r/@*', Attribute], - ['/r/p/c/attribute::b', Attribute], - ['/r/p/c/@b', Attribute], - ['/r/p/c/attribute::*', Attribute], - ['/r/p/c/@*', Attribute], - ['//c/attribute::b', Attribute], - ['//c/@b', Attribute], - ['//c/attribute::*', Attribute], - ['//c/@*', Attribute], - ['.//node()', REXML::Node ], - ['.//node()[@a]', REXML::Element ], - ['.//node()[@a="1"]', REXML::Element ], - ['.//node()[@b]', REXML::Element ], # no show, why? - ['.//node()[@b="2"]', REXML::Element ] - ].each do |xpath,kind| - begin - REXML::XPath.each( doc, xpath ) do |what| - assert_kind_of( kind, what, "\n\nWrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n\n" ) + # Alun ap Rhisiart + def test_less_than_in_element_content + source = File.new(fixture_path('ProductionSupport.xml')) + h = Hash.new + doc = REXML::Document.new source + doc.elements.each("//CommonError") { |el| + h[el.elements['Key'].text] = 'okay' + } + assert(h.include?('MotorInsuranceContract(Object)>>#error:')) + end + + # XPaths provided by Thomas Sawyer + def test_various_xpath + #@doc = REXML::Document.new('<r a="1"><p><c b="2"/></p></r>') + doc = REXML::Document.new('<r a="1"><p><c b="2">3</c></p></r>') + + [['/r', REXML::Element], + ['/r/p/c', REXML::Element], + ['/r/attribute::a', Attribute], + ['/r/@a', Attribute], + ['/r/attribute::*', Attribute], + ['/r/@*', Attribute], + ['/r/p/c/attribute::b', Attribute], + ['/r/p/c/@b', Attribute], + ['/r/p/c/attribute::*', Attribute], + ['/r/p/c/@*', Attribute], + ['//c/attribute::b', Attribute], + ['//c/@b', Attribute], + ['//c/attribute::*', Attribute], + ['//c/@*', Attribute], + ['.//node()', REXML::Node ], + ['.//node()[@a]', REXML::Element ], + ['.//node()[@a="1"]', REXML::Element ], + ['.//node()[@b]', REXML::Element ], # no show, why? + ['.//node()[@b="2"]', REXML::Element ] + ].each do |xpath,kind| + begin + REXML::XPath.each( doc, xpath ) do |what| + assert_kind_of( kind, what, "\n\nWrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n\n" ) + end + rescue Exception + puts "PATH WAS: #{xpath}" + raise end - rescue Exception - puts "PATH WAS: #{xpath}" - raise end - end - [ - ['/r', 'attribute::a', Attribute ], - ['/r', '@a', Attribute ], - ['/r', 'attribute::*', Attribute ], - ['/r', '@*', Attribute ], - ['/r/p/c', 'attribute::b', Attribute ], - ['/r/p/c', '@b', Attribute ], - ['/r/p/c', 'attribute::*', Attribute ], - ['/r/p/c', '@*', Attribute ] - ].each do |nodepath, xpath, kind| - begin - context = REXML::XPath.first(doc, nodepath) - REXML::XPath.each( context, xpath ) do |what| - assert_kind_of kind, what, "Wrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n" + [ + ['/r', 'attribute::a', Attribute ], + ['/r', '@a', Attribute ], + ['/r', 'attribute::*', Attribute ], + ['/r', '@*', Attribute ], + ['/r/p/c', 'attribute::b', Attribute ], + ['/r/p/c', '@b', Attribute ], + ['/r/p/c', 'attribute::*', Attribute ], + ['/r/p/c', '@*', Attribute ] + ].each do |nodepath, xpath, kind| + begin + context = REXML::XPath.first(doc, nodepath) + REXML::XPath.each( context, xpath ) do |what| + assert_kind_of kind, what, "Wrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n" + end + rescue Exception + puts "PATH WAS: #{xpath}" + raise end - rescue Exception - puts "PATH WAS: #{xpath}" - raise end end - end - def test_entities_Holden_Glova - document = <<-EOL - <?xml version="1.0" encoding="UTF-8"?> - <!DOCTYPE rubynet [ - <!ENTITY rbconfig.MAJOR "1"> - <!ENTITY rbconfig.MINOR "7"> - <!ENTITY rbconfig.TEENY "2"> - <!ENTITY rbconfig.ruby_version "&rbconfig.MAJOR;.&rbconfig.MINOR;"> - <!ENTITY rbconfig.arch "i386-freebsd5"> - <!ENTITY rbconfig.prefix "/usr/local"> - <!ENTITY rbconfig.libdir "&rbconfig.prefix;/lib"> - <!ENTITY rbconfig.includedir "&rbconfig.prefix;/include"> - <!ENTITY rbconfig.sitedir "&rbconfig.prefix;/lib/ruby/site_ruby"> - <!ENTITY rbconfig.sitelibdir "&rbconfig.sitedir;/&rbconfig.ruby_version;"> - <!ENTITY rbconfig.sitearchdir "&rbconfig.sitelibdir;/&rbconfig.arch;"> - ]> - <rubynet> - <pkg version="version1.0"> - <files> - <file> - <filename>uga.rb</filename> - <mode>0444</mode> - <path>&rbconfig.libdir;/rexml</path> - <content encoding="xml">... the file here</content> - </file> - <file> - <filename>booga.h</filename> - <mode>0444</mode> - <path>&rbconfig.includedir;</path> - <content encoding="xml">... the file here</content> - </file> - <file> - <filename>foo.so</filename> - <mode>0555</mode> - <path>&rbconfig.sitearchdir;/rexml</path> - <content encoding="mime64">Li4uIHRoZSBmaWxlIGhlcmU=\n</content> - </file> - </files> - </pkg> - </rubynet> - EOL - - file_xpath = '/rubynet/pkg/files/file' - - root = REXML::Document.new(document) - - root.elements.each(file_xpath) do |metadata| - text = metadata.elements['path'].get_text.value - assert text !~ /&rbconfig/, "'#{text}' failed" - end + def test_entities_Holden_Glova + document = <<-EOL + <?xml version="1.0" encoding="UTF-8"?> + <!DOCTYPE rubynet [ + <!ENTITY rbconfig.MAJOR "1"> + <!ENTITY rbconfig.MINOR "7"> + <!ENTITY rbconfig.TEENY "2"> + <!ENTITY rbconfig.ruby_version "&rbconfig.MAJOR;.&rbconfig.MINOR;"> + <!ENTITY rbconfig.arch "i386-freebsd5"> + <!ENTITY rbconfig.prefix "/usr/local"> + <!ENTITY rbconfig.libdir "&rbconfig.prefix;/lib"> + <!ENTITY rbconfig.includedir "&rbconfig.prefix;/include"> + <!ENTITY rbconfig.sitedir "&rbconfig.prefix;/lib/ruby/site_ruby"> + <!ENTITY rbconfig.sitelibdir "&rbconfig.sitedir;/&rbconfig.ruby_version;"> + <!ENTITY rbconfig.sitearchdir "&rbconfig.sitelibdir;/&rbconfig.arch;"> + ]> + <rubynet> + <pkg version="version1.0"> + <files> + <file> + <filename>uga.rb</filename> + <mode>0444</mode> + <path>&rbconfig.libdir;/rexml</path> + <content encoding="xml">... the file here</content> + </file> + <file> + <filename>booga.h</filename> + <mode>0444</mode> + <path>&rbconfig.includedir;</path> + <content encoding="xml">... the file here</content> + </file> + <file> + <filename>foo.so</filename> + <mode>0555</mode> + <path>&rbconfig.sitearchdir;/rexml</path> + <content encoding="mime64">Li4uIHRoZSBmaWxlIGhlcmU=\n</content> + </file> + </files> + </pkg> + </rubynet> + EOL + + file_xpath = '/rubynet/pkg/files/file' + + root = REXML::Document.new(document) + + root.elements.each(file_xpath) do |metadata| + text = metadata.elements['path'].get_text.value + assert text !~ /&rbconfig/, "'#{text}' failed" + end - #Error occurred in test_package_file_opens(TC_PackageInstall): - # ArgumentError: - #illegal access mode &rbconfig.prefix;/lib/rexml - # - #[synack@Evergreen] src $ ruby --version - #ruby 1.6.7 (2002-03-01) [i686-linux-gnu] - # - #It looks like it expanded the first entity, but didn't reparse it for more - #entities. possible bug - or have I mucked this up? - end + #Error occurred in test_package_file_opens(TC_PackageInstall): + # ArgumentError: + #illegal access mode &rbconfig.prefix;/lib/rexml + # + #[synack@Evergreen] src $ ruby --version + #ruby 1.6.7 (2002-03-01) [i686-linux-gnu] + # + #It looks like it expanded the first entity, but didn't reparse it for more + #entities. possible bug - or have I mucked this up? + end - def test_whitespace_after_xml_decl - Document.new <<EOL + def test_whitespace_after_xml_decl + Document.new <<EOL <?xml version='1.0'?> <blo> <wak> </wak> </blo> EOL - end + end - def test_external_entity - xp = '//channel/title' + def test_external_entity + xp = '//channel/title' - %w{working.rss broken.rss}.each do |path| - File.open(File.join(fixture_path(path))) do |file| - doc = REXML::Document.new file.readlines.join('') + %w{working.rss broken.rss}.each do |path| + File.open(File.join(fixture_path(path))) do |file| + doc = REXML::Document.new file.readlines.join('') - # check to make sure everything is kosher - assert_equal( doc.root.class, REXML::Element ) - assert_equal( doc.root.elements.class, REXML::Elements ) + # check to make sure everything is kosher + assert_equal( doc.root.class, REXML::Element ) + assert_equal( doc.root.elements.class, REXML::Elements ) - # get the title of the feed - assert( doc.root.elements[xp].kind_of?( REXML::Element ) ) + # get the title of the feed + assert( doc.root.elements[xp].kind_of?( REXML::Element ) ) + end end end - end - def test_maintain_dtd - src = %q{<?xml version="1.0" encoding="UTF-8"?> + def test_maintain_dtd + src = %q{<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ivattacks SYSTEM "../../ivacm.dtd" [ <!ENTITY % extern-packages SYSTEM "../../ivpackages.dtd"> <!ENTITY % extern-packages SYSTEM "../../common-declarations.dtd"> %extern-packages; %extern-common; ]>} - doc = Document.new( src ) - doc.write( out="" ) - src = src.tr('"', "'") - out = out.tr('"', "'") - assert_equal( src, out ) - end + doc = Document.new( src ) + doc.write( out="" ) + src = src.tr('"', "'") + out = out.tr('"', "'") + assert_equal( src, out ) + end - def test_text_nodes_nomatch - source = "<root><child>test</child></root>" - d = REXML::Document.new( source ) - r = REXML::XPath.match( d, %q{/root/child[text()="no-test"]} ) - assert_equal( 0, r.size ) - end + def test_text_nodes_nomatch + source = "<root><child>test</child></root>" + d = REXML::Document.new( source ) + r = REXML::XPath.match( d, %q{/root/child[text()="no-test"]} ) + assert_equal( 0, r.size ) + end - def test_raw_Terje_Elde - f = REXML::Formatters::Default.new - txt = 'abcødef' - a = Text.new( txt,false,nil,true ) - f.write(a,out="") - assert_equal( txt, out ) - - txt = '<sean><russell>abcødef</russell></sean>' - a = Document.new( txt, { :raw => ["russell"] } ) - f.write(a,out="") - assert_equal( txt, out ) - end + def test_raw_Terje_Elde + f = REXML::Formatters::Default.new + txt = 'abcødef' + a = Text.new( txt,false,nil,true ) + f.write(a,out="") + assert_equal( txt, out ) + + txt = '<sean><russell>abcødef</russell></sean>' + a = Document.new( txt, { :raw => ["russell"] } ) + f.write(a,out="") + assert_equal( txt, out ) + end - def test_indenting_error - a=Element.new("test1") - b=Element.new("test2") - c=Element.new("test3") - b << c - a << b + def test_indenting_error + a=Element.new("test1") + b=Element.new("test2") + c=Element.new("test3") + b << c + a << b - REXML::Formatters::Pretty.new.write(a,"") - end + REXML::Formatters::Pretty.new.write(a,"") + end - def test_pos - require 'tempfile' - Tempfile.create("tidal") {|testfile| - testdata = %Q{<calibration> + def test_pos + require 'tempfile' + Tempfile.create("tidal") {|testfile| + testdata = %Q{<calibration> <section name="parameters"> <param name="barpress">760</param> <param name="hertz">50</param> @@ -521,63 +521,63 @@ EOL </calibration> } - testfile.puts testdata - testfile.rewind - assert_nothing_raised do - REXML::Document.new(testfile) - end - } - end + testfile.puts testdata + testfile.rewind + assert_nothing_raised do + REXML::Document.new(testfile) + end + } + end - def test_deep_clone - a = Document.new( '<?xml version="1.0"?><!DOCTYPE html PUBLIC - "-//W3C//DTD - XHTML 1.0 Transitional//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html - xmlns="http:///www.w3.org/1999/xhtml"></html>' ) - b = a.deep_clone - assert_equal a.to_s, b.to_s - end + def test_deep_clone + a = Document.new( '<?xml version="1.0"?><!DOCTYPE html PUBLIC + "-//W3C//DTD + XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html + xmlns="http:///www.w3.org/1999/xhtml"></html>' ) + b = a.deep_clone + assert_equal a.to_s, b.to_s + end - def test_double_escaping - data = '<title>AT&T</title>' - xml = "<description><![CDATA[#{data}]]></description>" + def test_double_escaping + data = '<title>AT&T</title>' + xml = "<description><![CDATA[#{data}]]></description>" - doc = REXML::Document.new(xml) - description = doc.find {|e| e.name=="description"} - assert_equal data, description.text - end + doc = REXML::Document.new(xml) + description = doc.find {|e| e.name=="description"} + assert_equal data, description.text + end - def test_ticket_12 - cfg = "<element><anotherelement><child1>a</child1><child2>b</child2></anotherelement></element>" + def test_ticket_12 + cfg = "<element><anotherelement><child1>a</child1><child2>b</child2></anotherelement></element>" - config = REXML::Document.new( cfg ) + config = REXML::Document.new( cfg ) - assert_equal( "a", config.elements[ "//child1" ].text ) - end + assert_equal( "a", config.elements[ "//child1" ].text ) + end =begin - # This is a silly test, and is low priority - def test_namespace_serialization_tobi_reif - doc = Document.new '<doc xmlns:b="http://www.foo.foo"> - <b:p/> -</doc>' - ns = 'http://www.foo.foo' - ns_declaration={'f'=>ns} - returned = XPath.match(doc,'//f:p',ns_declaration) - # passes: - assert( (returned[0].namespace==ns), 'namespace should be '+ns) - serialized = returned.to_s - serialized_and_parsed = Document.new(serialized) - puts 'serialized: '+serialized - # ... currently brings <b:p/> - # prefix b is undeclared (!) - assert( (serialized_and_parsed.namespace==ns), - 'namespace should still be '+ns.inspect+ - ' and not '+serialized_and_parsed.namespace.inspect) - # ... currently results in a failure: - # 'namespace should still be "http://www.foo.foo" and not ""' - end + # This is a silly test, and is low priority + def test_namespace_serialization_tobi_reif + doc = Document.new '<doc xmlns:b="http://www.foo.foo"> + <b:p/> + </doc>' + ns = 'http://www.foo.foo' + ns_declaration={'f'=>ns} + returned = XPath.match(doc,'//f:p',ns_declaration) + # passes: + assert( (returned[0].namespace==ns), 'namespace should be '+ns) + serialized = returned.to_s + serialized_and_parsed = Document.new(serialized) + puts 'serialized: '+serialized + # ... currently brings <b:p/> + # prefix b is undeclared (!) + assert( (serialized_and_parsed.namespace==ns), + 'namespace should still be '+ns.inspect+ + ' and not '+serialized_and_parsed.namespace.inspect) + # ... currently results in a failure: + # 'namespace should still be "http://www.foo.foo" and not ""' + end =end -end + end end diff --git a/test/rexml/test_core.rb b/test/rexml/test_core.rb index 8bba293cbf..f628cb9519 100644 --- a/test/rexml/test_core.rb +++ b/test/rexml/test_core.rb @@ -12,1165 +12,1165 @@ require "rexml/undefinednamespaceexception" require_relative "listener" module REXMLTests -class Tester < Test::Unit::TestCase - include REXMLTestUtils - include REXML - def setup - @xsa_source = <<-EOL - <?xml version="1.0"?> - <?xsl stylesheet="blah.xsl"?> - <!-- The first line tests the XMLDecl, the second tests PI. - The next line tests DocType. This line tests comments. --> - <!DOCTYPE xsa PUBLIC - "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" - "http://www.garshol.priv.no/download/xsa/xsa.dtd"> - - <xsa> - <vendor id="blah"> - <name>Lars Marius Garshol</name> - <email>larsga@garshol.priv.no</email> - <url>http://www.stud.ifi.uio.no/~lmariusg/</url> - </vendor> - </xsa> - EOL - end + class Tester < Test::Unit::TestCase + include REXMLTestUtils + include REXML + def setup + @xsa_source = <<-EOL + <?xml version="1.0"?> + <?xsl stylesheet="blah.xsl"?> + <!-- The first line tests the XMLDecl, the second tests PI. + The next line tests DocType. This line tests comments. --> + <!DOCTYPE xsa PUBLIC + "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" + "http://www.garshol.priv.no/download/xsa/xsa.dtd"> + + <xsa> + <vendor id="blah"> + <name>Lars Marius Garshol</name> + <email>larsga@garshol.priv.no</email> + <url>http://www.stud.ifi.uio.no/~lmariusg/</url> + </vendor> + </xsa> + EOL + end - def test_bad_markup - [ - "<pkg='version'> foo </pkg>", - '<0/>', - '<a>&</a>', - '<a>&a</a>', -# '<a>&a;</a>', # FIXME - '<a a="<"/>', - '<a 3="<"/>', - '<a a="1" a="2"/>', - '<a><!-- -- --></a>', - '<a><!-- ---></a>', - '<a>�</a>', - '<a>�</a>', - "<a a='�' />", - "<a>\f</a>", - "<a a='\f' />", - "<a>\000</a>", + def test_bad_markup + [ + "<pkg='version'> foo </pkg>", + '<0/>', + '<a>&</a>', + '<a>&a</a>', +# '<a>&a;</a>', # FIXME + '<a a="<"/>', + '<a 3="<"/>', + '<a a="1" a="2"/>', + '<a><!-- -- --></a>', + '<a><!-- ---></a>', + '<a>�</a>', + '<a>�</a>', + "<a a='�' />", + "<a>\f</a>", + "<a a='\f' />", + "<a>\000</a>", # FIXME '<a' + [65535].pack('U') + ' />', - '<a></a>', - '<a></a>', + '<a></a>', + '<a></a>', # FIXME '<a' + [0x0371].pack('U') + ' />', # FIXME '<a a' + [0x0371].pack('U') + '="" />', - ].each do |src| - assert_raise( ParseException, %Q{Parse #{src.inspect} should have failed!} ) do - Document.new(src) + ].each do |src| + assert_raise( ParseException, %Q{Parse #{src.inspect} should have failed!} ) do + Document.new(src) + end end end - end - def test_attribute - # Testing constructors - #a = Attribute.new "hello", "dolly" - #b = Attribute.new a - #d = Document.new( "<a hello='dolly' href='blah'/>" ) - #c = d[0].attributes.get_attribute( "hello" ) - - #assert_equal a, b - #for attr in [ a, b, c] - # assert_equal "hello", attr.name - # assert_equal "dolly", attr.value - #end - - # This because of a reported bug in attribute handling in 1.0a8 - source = '<a att="A">blah</a>' - doc = Document.new source - doc.elements.each do |a| - a.attributes['att'] << 'B' - assert_equal "AB", a.attributes['att'] - a.attributes['att'] = 'C' - assert_equal "C", a.attributes['att'] - end - - # Bryan Murphy <murphybryanp@yahoo.com> - text = "this is a {target[@name='test']/@value} test" - source = <<-EOL - <?xml version="1.0"?> - <doc search="#{text}"/> - EOL - - xml = Document.new source - value = xml.root.attributes["search"] - assert_equal text, value.to_s - - e = Element.new "test" - e.add_attributes({ "name1" => "test1", "name4" => "test4" }) - e.add_attributes([["name3","test3"], ["name2","test2"]]) - assert_equal "test1", e.attributes["name1"] - assert_equal "test2", e.attributes["name2"] - assert_equal "test3", e.attributes["name3"] - assert_equal "test4", e.attributes["name4"] - - # ensure that the attributes come out in sorted order - assert_equal %w(<test - name1='test1' - name2='test2' - name3='test3' - name4='test4'/>).join(' '), e.to_s - end + def test_attribute + # Testing constructors + #a = Attribute.new "hello", "dolly" + #b = Attribute.new a + #d = Document.new( "<a hello='dolly' href='blah'/>" ) + #c = d[0].attributes.get_attribute( "hello" ) + + #assert_equal a, b + #for attr in [ a, b, c] + # assert_equal "hello", attr.name + # assert_equal "dolly", attr.value + #end + + # This because of a reported bug in attribute handling in 1.0a8 + source = '<a att="A">blah</a>' + doc = Document.new source + doc.elements.each do |a| + a.attributes['att'] << 'B' + assert_equal "AB", a.attributes['att'] + a.attributes['att'] = 'C' + assert_equal "C", a.attributes['att'] + end - def test_cdata - test = "The quick brown fox jumped - & < & < \" ' - over the lazy dog." + # Bryan Murphy <murphybryanp@yahoo.com> + text = "this is a {target[@name='test']/@value} test" + source = <<-EOL + <?xml version="1.0"?> + <doc search="#{text}"/> + EOL + + xml = Document.new source + value = xml.root.attributes["search"] + assert_equal text, value.to_s + + e = Element.new "test" + e.add_attributes({ "name1" => "test1", "name4" => "test4" }) + e.add_attributes([["name3","test3"], ["name2","test2"]]) + assert_equal "test1", e.attributes["name1"] + assert_equal "test2", e.attributes["name2"] + assert_equal "test3", e.attributes["name3"] + assert_equal "test4", e.attributes["name4"] + + # ensure that the attributes come out in sorted order + assert_equal %w(<test + name1='test1' + name2='test2' + name3='test3' + name4='test4'/>).join(' '), e.to_s + end - source = "<a><![CDATA[#{test}]]></a>" - d = REXML::Document.new( source ) + def test_cdata + test = "The quick brown fox jumped + & < & < \" ' + over the lazy dog." - # Test constructors - cdata = d[0][0] - assert_equal test, cdata.value - end + source = "<a><![CDATA[#{test}]]></a>" + d = REXML::Document.new( source ) - def test_comment - string = "This is a new comment!" - source = "<!--#{string}-->" - comment = Comment.new string - REXML::Formatters::Default.new.write( comment, out = "" ) - assert_equal(source, out) - - comment2 = Comment.new comment - assert_equal(comment, comment2) - - assert_raise(ParseException) { - REXML::Document.new("<d><!- foo --></d>") - } - assert_raise(ParseException) { - REXML::Document.new("<d><!-- foo -></d>") - } - end + # Test constructors + cdata = d[0][0] + assert_equal test, cdata.value + end - def test_whitespace - doc = Document.new "<root-element><first-element/></root-element>" - assert_equal 1, doc.root.size - assert_equal 1, doc.root.elements.size - doc = Document.new "<root-element> - <first-element/> - </root-element>" - assert_equal 3, doc.root.size - assert_equal 1, doc.root.elements.size - - text = " This is text - with a lot of whitespace " - source = "<a>#{text}<b>#{text}</b><c>#{text}</c>#{text}</a>" - - doc = Document.new( source, { - :respect_whitespace => %w{ a c } - } ) - assert_equal text, doc.elements["//c"].text - string = "" - doc.root.each { |n| string << n.to_s if n.kind_of? Text } - assert_equal text+text, string - - string =" lots of blank - space" - doc.root.add_element("d").add_element("c").text = string - doc.root.add_element("e").text = string - assert_equal string, doc.elements["/a/d/c"].text - assert string != doc.elements["/a/e"].text, "Text wasn't properly compressed" - - doc = Document.new source, { :respect_whitespace => :all } - doc.root.add_element("d").text = string - assert_equal text, doc.root.text - nxt = "" - doc.root.each { |n| nxt << n.to_s if n.kind_of? Text } - assert_equal text+text, nxt - assert_equal text, doc.root.elements["b"].text - assert_equal text, doc.root.elements["c"].text - assert_equal string, doc.root.elements["d"].text - end + def test_comment + string = "This is a new comment!" + source = "<!--#{string}-->" + comment = Comment.new string + REXML::Formatters::Default.new.write( comment, out = "" ) + assert_equal(source, out) + + comment2 = Comment.new comment + assert_equal(comment, comment2) + + assert_raise(ParseException) { + REXML::Document.new("<d><!- foo --></d>") + } + assert_raise(ParseException) { + REXML::Document.new("<d><!-- foo -></d>") + } + end - # This isn't complete. We need to check declarations and comments - def test_doctype - string = "something" - correct = "<!DOCTYPE something>" - doc = DocType.new(string) - assert_equal(string, doc.name) - doc.write(out="") - assert_equal(correct, out) - - doc2 = DocType.new(doc) - assert_equal(doc.name, doc2.name) - assert_equal(doc.external_id, doc2.external_id) - - correct = '<!DOCTYPE xsa PUBLIC "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" "http://www.garshol.priv.no/download/xsa/xsa.dtd">' - - one_line_source = '<!DOCTYPE xsa PUBLIC "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" "http://www.garshol.priv.no/download/xsa/xsa.dtd"><a/>' - doc = Document.new( one_line_source ) - doc = doc[0] - assert(doc) - doc.write(test="") - assert_equal(correct, test) - - multi_line_source = '<!DOCTYPE xsa PUBLIC - "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" - "http://www.garshol.priv.no/download/xsa/xsa.dtd"> - <a/>' - d = Document.new( multi_line_source ) - doc = d[0] - assert(doc) - doc.write(test="") - assert_equal(correct, test) - - odd_space_source = ' <!DOCTYPE - xsa PUBLIC "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" - "http://www.garshol.priv.no/download/xsa/xsa.dtd"> <a/>' - d = Document.new( odd_space_source ) - dt = d.doctype - dt.write(test="") - assert_equal(correct, test) - - # OK, the BIG doctype test, numba wun - docin = File.new(fixture_path("doctype_test.xml")) - doc = Document.new(docin) - doc.write(test="") - assert_equal(31, doc.doctype.size) - end + def test_whitespace + doc = Document.new "<root-element><first-element/></root-element>" + assert_equal 1, doc.root.size + assert_equal 1, doc.root.elements.size + doc = Document.new "<root-element> + <first-element/> + </root-element>" + assert_equal 3, doc.root.size + assert_equal 1, doc.root.elements.size + + text = " This is text + with a lot of whitespace " + source = "<a>#{text}<b>#{text}</b><c>#{text}</c>#{text}</a>" + + doc = Document.new( source, { + :respect_whitespace => %w{ a c } + } ) + assert_equal text, doc.elements["//c"].text + string = "" + doc.root.each { |n| string << n.to_s if n.kind_of? Text } + assert_equal text+text, string + + string =" lots of blank + space" + doc.root.add_element("d").add_element("c").text = string + doc.root.add_element("e").text = string + assert_equal string, doc.elements["/a/d/c"].text + assert string != doc.elements["/a/e"].text, "Text wasn't properly compressed" + + doc = Document.new source, { :respect_whitespace => :all } + doc.root.add_element("d").text = string + assert_equal text, doc.root.text + nxt = "" + doc.root.each { |n| nxt << n.to_s if n.kind_of? Text } + assert_equal text+text, nxt + assert_equal text, doc.root.elements["b"].text + assert_equal text, doc.root.elements["c"].text + assert_equal string, doc.root.elements["d"].text + end - def test_document - # Testing cloning - source = "<element/>" - doc = Document.new source + # This isn't complete. We need to check declarations and comments + def test_doctype + string = "something" + correct = "<!DOCTYPE something>" + doc = DocType.new(string) + assert_equal(string, doc.name) + doc.write(out="") + assert_equal(correct, out) + + doc2 = DocType.new(doc) + assert_equal(doc.name, doc2.name) + assert_equal(doc.external_id, doc2.external_id) + + correct = '<!DOCTYPE xsa PUBLIC "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" "http://www.garshol.priv.no/download/xsa/xsa.dtd">' + + one_line_source = '<!DOCTYPE xsa PUBLIC "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" "http://www.garshol.priv.no/download/xsa/xsa.dtd"><a/>' + doc = Document.new( one_line_source ) + doc = doc[0] + assert(doc) + doc.write(test="") + assert_equal(correct, test) + + multi_line_source = '<!DOCTYPE xsa PUBLIC + "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" + "http://www.garshol.priv.no/download/xsa/xsa.dtd"> + <a/>' + d = Document.new( multi_line_source ) + doc = d[0] + assert(doc) + doc.write(test="") + assert_equal(correct, test) + + odd_space_source = ' <!DOCTYPE + xsa PUBLIC "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" + "http://www.garshol.priv.no/download/xsa/xsa.dtd"> <a/>' + d = Document.new( odd_space_source ) + dt = d.doctype + dt.write(test="") + assert_equal(correct, test) + + # OK, the BIG doctype test, numba wun + docin = File.new(fixture_path("doctype_test.xml")) + doc = Document.new(docin) + doc.write(test="") + assert_equal(31, doc.doctype.size) + end - # Testing Root - assert_equal doc.root.name.to_s, "element" + def test_document + # Testing cloning + source = "<element/>" + doc = Document.new source - # Testing String source - source = @xsa_source - doc = Document.new source - assert_instance_of XMLDecl, doc.xml_decl - assert_instance_of DocType, doc.doctype - assert_equal doc.version, "1.0" + # Testing Root + assert_equal doc.root.name.to_s, "element" - source = File.new(fixture_path("dash.xml")) - doc = Document.new source - assert_equal "content-2", doc.elements["//content-2"].name - end + # Testing String source + source = @xsa_source + doc = Document.new source + assert_instance_of XMLDecl, doc.xml_decl + assert_instance_of DocType, doc.doctype + assert_equal doc.version, "1.0" - def test_instruction - target = "use" - content = "ruby" - source = "<?#{target} #{content}?>" + source = File.new(fixture_path("dash.xml")) + doc = Document.new source + assert_equal "content-2", doc.elements["//content-2"].name + end - instruction = Instruction.new target, content - instruction2 = Instruction.new instruction - assert_equal(instruction, instruction2) - REXML::Formatters::Default.new.write( instruction, out = "" ) - assert_equal(source, out) + def test_instruction + target = "use" + content = "ruby" + source = "<?#{target} #{content}?>" - d = Document.new( source ) - instruction2 = d[0] - assert_equal(instruction.to_s, instruction2.to_s) + instruction = Instruction.new target, content + instruction2 = Instruction.new instruction + assert_equal(instruction, instruction2) + REXML::Formatters::Default.new.write( instruction, out = "" ) + assert_equal(source, out) - assert_raise(ParseException) { - REXML::Document.new("<d><?foo bar></d>") - } - end + d = Document.new( source ) + instruction2 = d[0] + assert_equal(instruction.to_s, instruction2.to_s) - def test_parent - parent = Parent.new - begin - parent << "Something" - rescue Exception - parent << Comment.new("Some comment") - assert parent.size == 1, "size of parent should be 1" - else - assert_fail "should have gotten an exception trying to add a "+ "String to a Parent" - end - - source = "<a><one/><three/><five/></a>" - doc = Document.new source - three = doc.root.elements["three"] - doc.root.insert_before( three, Element.new("two") ) - nxt = doc.root.elements["one"] - string = "" - while nxt - string << nxt.name - nxt = nxt.next_sibling - end - assert_equal "onetwothreefive", string - - - doc.root.insert_after( three, Element.new("four") ) - string = "" - doc.root.each { |element| string << element.name } - assert_equal "onetwothreefourfive", string - - string = "" - nxt = doc.root.elements["five"] - while nxt - string << nxt.name - nxt = nxt.previous_sibling - end - assert_equal "fivefourthreetwoone", string - - doc.insert_after "//two", Element.new("two-and-half") - string = doc.root.elements.collect {|x| x.name}.join - assert_equal "onetwotwo-and-halfthreefourfive", string - doc.elements["/a/five"].insert_before "../four", Element.new("three-and-half") - string = doc.root.elements.collect {|x| x.name}.join - assert_equal "onetwotwo-and-halfthreethree-and-halffourfive", string - - doc.elements["/a/five"].previous_sibling = Element.new("four-and-half") - string = doc.root.elements.collect {|x| x.name}.join - assert_equal "onetwotwo-and-halfthreethree-and-halffourfour-and-halffive", string - doc.elements["/a/one"].next_sibling = Element.new("one-and-half") - string = doc.root.elements.collect {|x| x.name}.join - assert_equal "oneone-and-halftwotwo-and-halfthreethree-and-halffourfour-and-halffive", string - - doc = Document.new "<a><one/><three/></a>" - doc.root[1,0] = Element.new "two" - string = "" - doc.root.each { |el| string << el.name } - assert_equal "onetwothree", string - end + assert_raise(ParseException) { + REXML::Document.new("<d><?foo bar></d>") + } + end - # The Source classes are tested extensively throughout the test suite - def test_source - # Testing string source - source = @xsa_source - doc = Document.new source - assert_equal doc.root.name.to_s, "xsa" + def test_parent + parent = Parent.new + begin + parent << "Something" + rescue Exception + parent << Comment.new("Some comment") + assert parent.size == 1, "size of parent should be 1" + else + assert_fail "should have gotten an exception trying to add a "+ "String to a Parent" + end - # Testing IO source - doc = Document.new File.new(fixture_path("project.xml")) - assert_equal doc.root.name.to_s, "Project" - end + source = "<a><one/><three/><five/></a>" + doc = Document.new source + three = doc.root.elements["three"] + doc.root.insert_before( three, Element.new("two") ) + nxt = doc.root.elements["one"] + string = "" + while nxt + string << nxt.name + nxt = nxt.next_sibling + end + assert_equal "onetwothreefive", string - def test_text - f = REXML::Formatters::Default.new - string = "Some text" - text = Text.new(string) - assert_equal(string, text.to_s) - text2 = Text.new(text) - assert_equal(text, text2) - #testing substitution - string = "0 < ( 1 & 1 )" - correct = "0 < ( 1 & 1 )" - text = Text.new(string, true) - f.write(text,out="") - assert_equal(correct, out) - - string = "Cats & dogs" - text = Text.new(string, false, nil, true) - assert_equal(string, text.to_s) - - string2 = "<a>#{string}</a>" - doc = Document.new( string2, { - :raw => %w{ a b } - } ) - f.write(doc,out="") - assert_equal(string2, out) - b = doc.root.add_element( "b" ) - b.text = string - assert_equal(string, b.get_text.to_s) - - c = doc.root.add_element("c") - c.text = string - assert_equal("Cats &amp; dogs", c.get_text.to_s) - - # test all - string = "<a>&<b><</b><c>><d>"</d></c></a>" - doc = Document.new(string, { :raw => :all }) - assert_equal( "&", doc.elements["/a"][0].to_s ) - assert_equal( "&", doc.elements["/a"].text ) - assert_equal( "<", doc.elements["/a/b"][0].to_s ) - assert_equal( "<", doc.elements["/a/b"].text ) - assert_equal( ">", doc.elements["/a/c"][0].to_s ) - assert_equal( ">", doc.elements["/a/c"].text ) - assert_equal( '"', doc.elements["//d"][0].to_s ) - assert_equal( '"', doc.elements["//d"].text ) - - # test some other stuff - doc = Document.new('<a><b/></a>') - doc.root.text = 'Sean' - assert_equal( '<a><b/>Sean</a>', doc.to_s ) - doc.root.text = 'Elliott' - assert_equal( '<a><b/>Elliott</a>', doc.to_s ) - doc.root.add_element( 'c' ) - assert_equal( '<a><b/>Elliott<c/></a>', doc.to_s ) - doc.root.text = 'Russell' - assert_equal( '<a><b/>Russell<c/></a>', doc.to_s ) - doc.root.text = nil - assert_equal( '<a><b/><c/></a>', doc.to_s ) - end - def test_text_frozen - string = "Frozen".freeze - text = Text.new(string) - assert_equal(string, text.to_s) - end + doc.root.insert_after( three, Element.new("four") ) + string = "" + doc.root.each { |element| string << element.name } + assert_equal "onetwothreefourfive", string - def test_xmldecl - source = "<?xml version='1.0'?>" - # test args - # test no args - decl2 = XMLDecl.new - assert_equal source, decl2.to_s - # test XMLDecl - decl2 = XMLDecl.new "1.0" - assert_equal source, decl2.to_s - end + string = "" + nxt = doc.root.elements["five"] + while nxt + string << nxt.name + nxt = nxt.previous_sibling + end + assert_equal "fivefourthreetwoone", string + + doc.insert_after "//two", Element.new("two-and-half") + string = doc.root.elements.collect {|x| x.name}.join + assert_equal "onetwotwo-and-halfthreefourfive", string + doc.elements["/a/five"].insert_before "../four", Element.new("three-and-half") + string = doc.root.elements.collect {|x| x.name}.join + assert_equal "onetwotwo-and-halfthreethree-and-halffourfive", string + + doc.elements["/a/five"].previous_sibling = Element.new("four-and-half") + string = doc.root.elements.collect {|x| x.name}.join + assert_equal "onetwotwo-and-halfthreethree-and-halffourfour-and-halffive", string + doc.elements["/a/one"].next_sibling = Element.new("one-and-half") + string = doc.root.elements.collect {|x| x.name}.join + assert_equal "oneone-and-halftwotwo-and-halfthreethree-and-halffourfour-and-halffive", string + + doc = Document.new "<a><one/><three/></a>" + doc.root[1,0] = Element.new "two" + string = "" + doc.root.each { |el| string << el.name } + assert_equal "onetwothree", string + end - def test_xmldecl_utf_16be_encoding_name - assert_equal("<?xml version='1.0' encoding='UTF-16'?>", - XMLDecl.new("1.0", "UTF-16").to_s) - end + # The Source classes are tested extensively throughout the test suite + def test_source + # Testing string source + source = @xsa_source + doc = Document.new source + assert_equal doc.root.name.to_s, "xsa" - def each_test( element, xpath, num_children ) - count = 0 - element.each_element( xpath ) { |child| - count += 1 - yield child if block_given? - } - assert_equal num_children, count - end + # Testing IO source + doc = Document.new File.new(fixture_path("project.xml")) + assert_equal doc.root.name.to_s, "Project" + end - # This is the biggest test, as the number of permutations of xpath are - # enormous. - def test_element_access - # Testing each_element - doc = Document.new File.new(fixture_path("project.xml")) - - each_test( doc, "/", 1 ) { |child| - assert_equal doc.name, child.name - } - each_test(doc, ".", 1) { |child| assert_equal doc, child } - each_test(doc.root, "..", 1) { |child| assert_equal doc, child } - each_test(doc.root, "*", 5) - each_test(doc, "Project/Datasets", 1) { |child| - assert_equal "Datasets", child.name - } - each_test(doc, "Project/Datasets/link", 2 ) - each_test(doc.root, "/Project/Description", 1) {|child| - assert_equal "Description", child.name - } - each_test(doc.root, "./Description",1 ) { |child| - assert_equal "Description",child.name - } - each_test(doc.root, "../Project",1 ) { |child| - assert_equal doc.root, child - } - #each_test(doc,".../link",2) {|child| assert_equal "link",child.name.to_s} - - # test get_element - first = doc.elements[ "Project" ] - assert_equal doc.root, first - second = doc.elements[ "Project" ].elements[1] - third = doc.elements[ "Project/Creator" ] - assert_equal second, third - fourth = doc.elements[ "Project/Datasets/link[@idref='18']" ] - assert_equal "Test data 1", fourth.attributes["name"] - - # Testing each_predicate - each_test( doc, "Project/Datasets/link[@idref='18']", 1 ) { |child| - assert_equal "Test data 1", child.attributes["name"] - } - - # testing next/previous_element - creator = doc.elements["//Creator"] - lm = creator.next_element - assert_equal "LastModifier", lm.name - assert_equal "Creator", lm.previous_element.name - end + def test_text + f = REXML::Formatters::Default.new + string = "Some text" + text = Text.new(string) + assert_equal(string, text.to_s) + text2 = Text.new(text) + assert_equal(text, text2) + #testing substitution + string = "0 < ( 1 & 1 )" + correct = "0 < ( 1 & 1 )" + text = Text.new(string, true) + f.write(text,out="") + assert_equal(correct, out) + + string = "Cats & dogs" + text = Text.new(string, false, nil, true) + assert_equal(string, text.to_s) + + string2 = "<a>#{string}</a>" + doc = Document.new( string2, { + :raw => %w{ a b } + } ) + f.write(doc,out="") + assert_equal(string2, out) + b = doc.root.add_element( "b" ) + b.text = string + assert_equal(string, b.get_text.to_s) + + c = doc.root.add_element("c") + c.text = string + assert_equal("Cats &amp; dogs", c.get_text.to_s) + + # test all + string = "<a>&<b><</b><c>><d>"</d></c></a>" + doc = Document.new(string, { :raw => :all }) + assert_equal( "&", doc.elements["/a"][0].to_s ) + assert_equal( "&", doc.elements["/a"].text ) + assert_equal( "<", doc.elements["/a/b"][0].to_s ) + assert_equal( "<", doc.elements["/a/b"].text ) + assert_equal( ">", doc.elements["/a/c"][0].to_s ) + assert_equal( ">", doc.elements["/a/c"].text ) + assert_equal( '"', doc.elements["//d"][0].to_s ) + assert_equal( '"', doc.elements["//d"].text ) + + # test some other stuff + doc = Document.new('<a><b/></a>') + doc.root.text = 'Sean' + assert_equal( '<a><b/>Sean</a>', doc.to_s ) + doc.root.text = 'Elliott' + assert_equal( '<a><b/>Elliott</a>', doc.to_s ) + doc.root.add_element( 'c' ) + assert_equal( '<a><b/>Elliott<c/></a>', doc.to_s ) + doc.root.text = 'Russell' + assert_equal( '<a><b/>Russell<c/></a>', doc.to_s ) + doc.root.text = nil + assert_equal( '<a><b/><c/></a>', doc.to_s ) + end - def test_child - sean = Element.new "Sean" - rubbell = Element.new "Rubbell" - elliott = sean.add_element "Elliott" - sean << rubbell - assert_equal elliott, rubbell.previous_sibling - assert_equal rubbell, elliott.next_sibling - - russell = Element.new "Russell" - rubbell.replace_with russell - assert_equal elliott, russell.previous_sibling - assert_equal russell, elliott.next_sibling - - assert_nil russell.document - assert_equal sean, russell.root - end + def test_text_frozen + string = "Frozen".freeze + text = Text.new(string) + assert_equal(string, text.to_s) + end - # Most of this class is tested elsewhere. Here are the methods which - # aren't used in any other class - def test_element - sean = Element.new "Sean" - string = "1) He's a great guy!" - sean.text = string - russell = Element.new "Russell" - sean << russell - - russell.attributes["email"] = "ser@germane-software.com" - assert_equal russell.attributes["email"], "ser@germane-software.com" - russell.attributes["webpage"] = "http://www.germane-software.com/~ser" - - assert sean.has_text?, "element should have text" - assert_equal sean.text, string - assert sean.has_elements?, "element should have one element" - string = "2) What a stud!" - sean.add_text string - sean.text = "3) Super programmer!" - sean.text = nil - assert sean.has_text?, "element should still have text" - assert_equal sean.text, string - - russell.delete_attribute "email" - assert_nil russell.attributes["email"] - russell.attributes.delete "webpage" - assert !russell.has_attributes?, "element should have no attributes" - end + def test_xmldecl + source = "<?xml version='1.0'?>" + # test args + # test no args + decl2 = XMLDecl.new + assert_equal source, decl2.to_s + # test XMLDecl + decl2 = XMLDecl.new "1.0" + assert_equal source, decl2.to_s + end - def test_no_format - source = "<a><b><c>blah</c><d/></b></a>" - out = "" - doc = Document.new( source ) - doc.write(out) - assert_equal(source, out) - end + def test_xmldecl_utf_16be_encoding_name + assert_equal("<?xml version='1.0' encoding='UTF-16'?>", + XMLDecl.new("1.0", "UTF-16").to_s) + end - def test_namespace - source = <<-EOF - <x xmlns:foo="http://www.bar.com/schema"> - </x> - EOF - doc = Document.new(source) - assert_equal("http://www.bar.com/schema", doc.root.namespace( "foo" )) - source = <<-EOF - <!-- bar namespace is "someuri" --> - <foo:bar xmlns="default" xmlns:foo="someuri"> - <!-- a namespace is "default" --> - <a/> - <!-- foo:b namespace is "someuri" --> - <foo:b> - <!-- c namespace is "default" --> - <c/> - </foo:b> - <!-- d namespace is "notdefault" --> - <d xmlns="notdefault"> - <!-- e namespace is "notdefault" --> - <e/> - <f xmlns=""> - <g/> - </f> - </d> - </foo:bar> - EOF - doc = Document.new source - assert_equal "someuri", doc.root.namespace - assert_equal "default", doc.root.elements[1].namespace - assert_equal "someuri", doc.root.elements[2].namespace - assert_equal "notdefault", doc.root.elements[ 3 ].namespace - - # Testing namespaces in attributes - source = <<-EOF - <a xmlns:b="uri"> - <b b:a="x" a="y"/> - <c xmlns="foo"> - </c> - </a> - EOF - doc = Document.new source - b = doc.root.elements["b"] - assert_equal "x", b.attributes["b:a"] - assert_equal "y", b.attributes["a"] - - doc = Document.new - doc.add_element "sean:blah" - doc.root.text = "Some text" - out = "" - doc.write(out) - assert_equal "<sean:blah>Some text</sean:blah>", out - end + def each_test( element, xpath, num_children ) + count = 0 + element.each_element( xpath ) { |child| + count += 1 + yield child if block_given? + } + assert_equal num_children, count + end + + # This is the biggest test, as the number of permutations of xpath are + # enormous. + def test_element_access + # Testing each_element + doc = Document.new File.new(fixture_path("project.xml")) + + each_test( doc, "/", 1 ) { |child| + assert_equal doc.name, child.name + } + each_test(doc, ".", 1) { |child| assert_equal doc, child } + each_test(doc.root, "..", 1) { |child| assert_equal doc, child } + each_test(doc.root, "*", 5) + each_test(doc, "Project/Datasets", 1) { |child| + assert_equal "Datasets", child.name + } + each_test(doc, "Project/Datasets/link", 2 ) + each_test(doc.root, "/Project/Description", 1) {|child| + assert_equal "Description", child.name + } + each_test(doc.root, "./Description",1 ) { |child| + assert_equal "Description",child.name + } + each_test(doc.root, "../Project",1 ) { |child| + assert_equal doc.root, child + } + #each_test(doc,".../link",2) {|child| assert_equal "link",child.name.to_s} + + # test get_element + first = doc.elements[ "Project" ] + assert_equal doc.root, first + second = doc.elements[ "Project" ].elements[1] + third = doc.elements[ "Project/Creator" ] + assert_equal second, third + fourth = doc.elements[ "Project/Datasets/link[@idref='18']" ] + assert_equal "Test data 1", fourth.attributes["name"] + + # Testing each_predicate + each_test( doc, "Project/Datasets/link[@idref='18']", 1 ) { |child| + assert_equal "Test data 1", child.attributes["name"] + } + + # testing next/previous_element + creator = doc.elements["//Creator"] + lm = creator.next_element + assert_equal "LastModifier", lm.name + assert_equal "Creator", lm.previous_element.name + end + def test_child + sean = Element.new "Sean" + rubbell = Element.new "Rubbell" + elliott = sean.add_element "Elliott" + sean << rubbell + assert_equal elliott, rubbell.previous_sibling + assert_equal rubbell, elliott.next_sibling + + russell = Element.new "Russell" + rubbell.replace_with russell + assert_equal elliott, russell.previous_sibling + assert_equal russell, elliott.next_sibling + + assert_nil russell.document + assert_equal sean, russell.root + end - def test_add_namespace - e = Element.new 'a' - e.add_namespace 'someuri' - e.add_namespace 'foo', 'otheruri' - e.add_namespace 'xmlns:bar', 'thirduri' - assert_equal 'someuri', e.attributes['xmlns'] - assert_equal 'otheruri', e.attributes['xmlns:foo'] - assert_equal 'thirduri', e.attributes['xmlns:bar'] - end + # Most of this class is tested elsewhere. Here are the methods which + # aren't used in any other class + def test_element + sean = Element.new "Sean" + string = "1) He's a great guy!" + sean.text = string + russell = Element.new "Russell" + sean << russell + + russell.attributes["email"] = "ser@germane-software.com" + assert_equal russell.attributes["email"], "ser@germane-software.com" + russell.attributes["webpage"] = "http://www.germane-software.com/~ser" + + assert sean.has_text?, "element should have text" + assert_equal sean.text, string + assert sean.has_elements?, "element should have one element" + string = "2) What a stud!" + sean.add_text string + sean.text = "3) Super programmer!" + sean.text = nil + assert sean.has_text?, "element should still have text" + assert_equal sean.text, string + + russell.delete_attribute "email" + assert_nil russell.attributes["email"] + russell.attributes.delete "webpage" + assert !russell.has_attributes?, "element should have no attributes" + end + def test_no_format + source = "<a><b><c>blah</c><d/></b></a>" + out = "" + doc = Document.new( source ) + doc.write(out) + assert_equal(source, out) + end - def test_big_documentation - f = File.new(fixture_path("documentation.xml")) - d = Document.new f - assert_equal "Sean Russell", d.elements["documentation/head/author"].text.tr("\n\t", " ").squeeze(" ") - out = "" - d.write out - end + def test_namespace + source = <<-EOF + <x xmlns:foo="http://www.bar.com/schema"> + </x> + EOF + doc = Document.new(source) + assert_equal("http://www.bar.com/schema", doc.root.namespace( "foo" )) + source = <<-EOF + <!-- bar namespace is "someuri" --> + <foo:bar xmlns="default" xmlns:foo="someuri"> + <!-- a namespace is "default" --> + <a/> + <!-- foo:b namespace is "someuri" --> + <foo:b> + <!-- c namespace is "default" --> + <c/> + </foo:b> + <!-- d namespace is "notdefault" --> + <d xmlns="notdefault"> + <!-- e namespace is "notdefault" --> + <e/> + <f xmlns=""> + <g/> + </f> + </d> + </foo:bar> + EOF + doc = Document.new source + assert_equal "someuri", doc.root.namespace + assert_equal "default", doc.root.elements[1].namespace + assert_equal "someuri", doc.root.elements[2].namespace + assert_equal "notdefault", doc.root.elements[ 3 ].namespace + + # Testing namespaces in attributes + source = <<-EOF + <a xmlns:b="uri"> + <b b:a="x" a="y"/> + <c xmlns="foo"> + </c> + </a> + EOF + doc = Document.new source + b = doc.root.elements["b"] + assert_equal "x", b.attributes["b:a"] + assert_equal "y", b.attributes["a"] + + doc = Document.new + doc.add_element "sean:blah" + doc.root.text = "Some text" + out = "" + doc.write(out) + assert_equal "<sean:blah>Some text</sean:blah>", out + end - def test_tutorial - doc = Document.new File.new(fixture_path("tutorial.xml")) - out = "" - doc.write out - end - def test_stream - c = Listener.new - Document.parse_stream( File.new(fixture_path("documentation.xml")), c ) - assert(c.ts, "Stream parsing apparantly didn't parse the whole file") - assert(c.te, "Stream parsing dropped end tag for documentation") + def test_add_namespace + e = Element.new 'a' + e.add_namespace 'someuri' + e.add_namespace 'foo', 'otheruri' + e.add_namespace 'xmlns:bar', 'thirduri' + assert_equal 'someuri', e.attributes['xmlns'] + assert_equal 'otheruri', e.attributes['xmlns:foo'] + assert_equal 'thirduri', e.attributes['xmlns:bar'] + end - Document.parse_stream("<a.b> <c/> </a.b>", c) - Document.parse_stream("<a><>&</a>", c) - assert_equal('<>&', c.normalize) - end + def test_big_documentation + f = File.new(fixture_path("documentation.xml")) + d = Document.new f + assert_equal "Sean Russell", d.elements["documentation/head/author"].text.tr("\n\t", " ").squeeze(" ") + out = "" + d.write out + end - def test_line - Document.new File.new(fixture_path("bad.xml")) - assert_fail "There should have been an error" - rescue Exception - # We should get here - assert($!.line == 5, "Should have been an error on line 5, "+ - "but was reported as being on line #{$!.line}" ) - end + def test_tutorial + doc = Document.new File.new(fixture_path("tutorial.xml")) + out = "" + doc.write out + end - def test_substitution - val = "a'b\"c" - el = Element.new("a") - el.attributes["x"] = val - REXML::Formatters::Default.new.write(el, out="") + def test_stream + c = Listener.new + Document.parse_stream( File.new(fixture_path("documentation.xml")), c ) + assert(c.ts, "Stream parsing apparantly didn't parse the whole file") + assert(c.te, "Stream parsing dropped end tag for documentation") - nel = Document.new( out) - assert_equal( val, nel.root.attributes["x"] ) - end + Document.parse_stream("<a.b> <c/> </a.b>", c) + + Document.parse_stream("<a><>&</a>", c) + assert_equal('<>&', c.normalize) + end - def test_exception - source = SourceFactory.create_from "<a/>" - p = ParseException.new( "dummy message", source ) - begin - raise "dummy" + def test_line + Document.new File.new(fixture_path("bad.xml")) + assert_fail "There should have been an error" rescue Exception - p.continued_exception = $! + # We should get here + assert($!.line == 5, "Should have been an error on line 5, "+ + "but was reported as being on line #{$!.line}" ) end - end - def test_bad_content - in_gt = '<root-el>content>content</root-el>' - in_lt = '<root-el>content<content</root-el>' + def test_substitution + val = "a'b\"c" + el = Element.new("a") + el.attributes["x"] = val + REXML::Formatters::Default.new.write(el, out="") - # This is OK - tree_gt = Document.new in_gt - assert_equal "content>content", tree_gt.elements[1].text - # This isn't - begin - Document.new in_lt - assert_fail "Should have gotten a parse error" - rescue ParseException + nel = Document.new( out) + assert_equal( val, nel.root.attributes["x"] ) end - end - - def test_iso_8859_1_output_function - out = "" - output = Output.new( out ) - koln_iso_8859_1 = "K\xF6ln" - koln_utf8 = "K\xc3\xb6ln" - source = Source.new( koln_iso_8859_1, 'iso-8859-1' ) - results = source.scan(/.*/)[0] - koln_utf8.force_encoding('UTF-8') if koln_utf8.respond_to?(:force_encoding) - assert_equal koln_utf8, results - output << results - if koln_iso_8859_1.respond_to?(:force_encoding) - koln_iso_8859_1.force_encoding('ISO-8859-1') - end - assert_equal koln_iso_8859_1, out - end - def test_attributes_each - doc = Document.new("<a xmlns:a='foo'><b x='1' y='2' z='3' a:x='4'/></a>") - count = 0 - doc.root.elements[1].attributes.each {|k,v| count += 1 } - assert_equal 4, count - end + def test_exception + source = SourceFactory.create_from "<a/>" + p = ParseException.new( "dummy message", source ) + begin + raise "dummy" + rescue Exception + p.continued_exception = $! + end + end - def test_delete_namespace - doc = Document.new "<a xmlns='1' xmlns:x='2'/>" - doc.root.delete_namespace - doc.root.delete_namespace 'x' - assert_equal "<a/>", doc.to_s - end + def test_bad_content + in_gt = '<root-el>content>content</root-el>' + in_lt = '<root-el>content<content</root-el>' - def test_each_element_with_attribute - doc = Document.new "<a><b id='1'/><c id='2'/><d id='1'/><e/></a>" - arry = [] - block = proc { |e| - assert arry.include?(e.name) - arry.delete e.name - } - # Yields b, c, d - arry = %w{b c d} - doc.root.each_element_with_attribute( 'id', &block ) - assert_equal 0, arry.size - # Yields b, d - arry = %w{b d} - doc.root.each_element_with_attribute( 'id', '1', &block ) - assert_equal 0, arry.size - # Yields b - arry = ['b'] - doc.root.each_element_with_attribute( 'id', '1', 1, &block ) - assert_equal 0, arry.size - # Yields d - arry = ['d'] - doc.root.each_element_with_attribute( 'id', '1', 0, 'd', &block ) - assert_equal 0, arry.size - end - def test_each_element_with_text - doc = Document.new '<a><b>b</b><c>b</c><d>d</d><e/></a>' - arry = [] - block = proc { |e| - assert arry.include?(e.name) - arry.delete e.name - } - # Yields b, c, d - arry = %w{b c d} - doc.root.each_element_with_text(&block) - assert_equal 0, arry.size - # Yields b, d - arry = %w{b c} - doc.root.each_element_with_text( 'b', &block ) - assert_equal 0, arry.size - # Yields b - arry = ['b'] - doc.root.each_element_with_text( 'b', 1, &block ) - assert_equal 0, arry.size - # Yields d - arry = ['d'] - doc.root.each_element_with_text( nil, 0, 'd', &block ) - assert_equal 0, arry.size - end + # This is OK + tree_gt = Document.new in_gt + assert_equal "content>content", tree_gt.elements[1].text + # This isn't + begin + Document.new in_lt + assert_fail "Should have gotten a parse error" + rescue ParseException + end + end - def test_element_parse_stream - s = Source.new( "<a>some text</a>" ) - l = Listener.new - class << l - def tag_start name, attributes - raise "Didn't find proper tag name" unless 'a'==name + def test_iso_8859_1_output_function + out = "" + output = Output.new( out ) + koln_iso_8859_1 = "K\xF6ln" + koln_utf8 = "K\xc3\xb6ln" + source = Source.new( koln_iso_8859_1, 'iso-8859-1' ) + results = source.scan(/.*/)[0] + koln_utf8.force_encoding('UTF-8') if koln_utf8.respond_to?(:force_encoding) + assert_equal koln_utf8, results + output << results + if koln_iso_8859_1.respond_to?(:force_encoding) + koln_iso_8859_1.force_encoding('ISO-8859-1') end + assert_equal koln_iso_8859_1, out end - Document::parse_stream(s, l) - end + def test_attributes_each + doc = Document.new("<a xmlns:a='foo'><b x='1' y='2' z='3' a:x='4'/></a>") + count = 0 + doc.root.elements[1].attributes.each {|k,v| count += 1 } + assert_equal 4, count + end - def test_deep_clone - a = Document.new( '<?xml version="1"?><a x="y"><b>text</b>text<c><d><e>text</e></d></c></a>' ) - b = a.deep_clone - assert_equal a.to_s, b.to_s + def test_delete_namespace + doc = Document.new "<a xmlns='1' xmlns:x='2'/>" + doc.root.delete_namespace + doc.root.delete_namespace 'x' + assert_equal "<a/>", doc.to_s + end - a = Document.new( '<a>some < text <b> more > text </b> > </a>' ) - b = a.deep_clone - assert_equal a.to_s, b.to_s - c = Document.new( b.to_s ) - assert_equal a.to_s, c.to_s - end + def test_each_element_with_attribute + doc = Document.new "<a><b id='1'/><c id='2'/><d id='1'/><e/></a>" + arry = [] + block = proc { |e| + assert arry.include?(e.name) + arry.delete e.name + } + # Yields b, c, d + arry = %w{b c d} + doc.root.each_element_with_attribute( 'id', &block ) + assert_equal 0, arry.size + # Yields b, d + arry = %w{b d} + doc.root.each_element_with_attribute( 'id', '1', &block ) + assert_equal 0, arry.size + # Yields b + arry = ['b'] + doc.root.each_element_with_attribute( 'id', '1', 1, &block ) + assert_equal 0, arry.size + # Yields d + arry = ['d'] + doc.root.each_element_with_attribute( 'id', '1', 0, 'd', &block ) + assert_equal 0, arry.size + end + def test_each_element_with_text + doc = Document.new '<a><b>b</b><c>b</c><d>d</d><e/></a>' + arry = [] + block = proc { |e| + assert arry.include?(e.name) + arry.delete e.name + } + # Yields b, c, d + arry = %w{b c d} + doc.root.each_element_with_text(&block) + assert_equal 0, arry.size + # Yields b, d + arry = %w{b c} + doc.root.each_element_with_text( 'b', &block ) + assert_equal 0, arry.size + # Yields b + arry = ['b'] + doc.root.each_element_with_text( 'b', 1, &block ) + assert_equal 0, arry.size + # Yields d + arry = ['d'] + doc.root.each_element_with_text( nil, 0, 'd', &block ) + assert_equal 0, arry.size + end + + def test_element_parse_stream + s = Source.new( "<a>some text</a>" ) + l = Listener.new + class << l + def tag_start name, attributes + raise "Didn't find proper tag name" unless 'a'==name + end + end + + Document::parse_stream(s, l) + end - def test_whitespace_before_root - a = <<EOL + def test_deep_clone + a = Document.new( '<?xml version="1"?><a x="y"><b>text</b>text<c><d><e>text</e></d></c></a>' ) + b = a.deep_clone + assert_equal a.to_s, b.to_s + + a = Document.new( '<a>some < text <b> more > text </b> > </a>' ) + b = a.deep_clone + assert_equal a.to_s, b.to_s + c = Document.new( b.to_s ) + assert_equal a.to_s, c.to_s + end + + def test_whitespace_before_root + a = <<EOL <?xml version='1.0'?> <blo> <wak> </wak> </blo> EOL - d = Document.new(a) - b = "" - d.write( b ) - assert_equal a,b - end + d = Document.new(a) + b = "" + d.write( b ) + assert_equal a,b + end - def test_entities - a = Document.new( '<a>eeü</a>' ) - assert_equal('eeü'.force_encoding("UTF-8"), a.root.text) - end + def test_entities + a = Document.new( '<a>eeü</a>' ) + assert_equal('eeü'.force_encoding("UTF-8"), a.root.text) + end - def test_element_decl - element_decl = Source.new("<!DOCTYPE foo [ + def test_element_decl + element_decl = Source.new("<!DOCTYPE foo [ <!ELEMENT bar (#PCDATA)> ]>") - doc = Document.new( element_decl ) - d = doc[0] - assert_equal("<!ELEMENT bar (#PCDATA)>", d.to_s.split(/\n/)[1].strip) - end + doc = Document.new( element_decl ) + d = doc[0] + assert_equal("<!ELEMENT bar (#PCDATA)>", d.to_s.split(/\n/)[1].strip) + end - def test_attlist_decl - doc = Document.new <<-EOL - <!DOCTYPE blah [ - <!ATTLIST blah - xmlns CDATA "foo"> - <!ATTLIST a - bar CDATA "gobble" - xmlns:one CDATA "two" - > - ]> - <a xmlns:three='xxx' three='yyy'><one:b/><three:c/></a> - EOL - assert_equal 'gobble', doc.root.attributes['bar'] - assert_equal 'xxx', doc.root.elements[2].namespace - assert_equal 'two', doc.root.elements[1].namespace - assert_equal 'foo', doc.root.namespace - - doc = Document.new <<-EOL - <?xml version="1.0"?> - <!DOCTYPE schema SYSTEM "XMLSchema.dtd" [ - <!ENTITY % p ''> - <!ENTITY % s ''> - <!ATTLIST schema - xmlns:svg CDATA #FIXED "http://www.w3.org/2000/svg" - xmlns:xlink CDATA #FIXED "http://www.w3.org/1999/xlink" - xmlns:xml CDATA #FIXED "http://www.w3.org/XML/1998/namespace" - >]> - <schema/> - EOL - prefixes = doc.root.prefixes.sort - correct = ['svg', 'xlink', 'xml'] - assert_equal correct, prefixes - end + def test_attlist_decl + doc = Document.new <<-EOL + <!DOCTYPE blah [ + <!ATTLIST blah + xmlns CDATA "foo"> + <!ATTLIST a + bar CDATA "gobble" + xmlns:one CDATA "two" + > + ]> + <a xmlns:three='xxx' three='yyy'><one:b/><three:c/></a> + EOL + assert_equal 'gobble', doc.root.attributes['bar'] + assert_equal 'xxx', doc.root.elements[2].namespace + assert_equal 'two', doc.root.elements[1].namespace + assert_equal 'foo', doc.root.namespace + + doc = Document.new <<-EOL + <?xml version="1.0"?> + <!DOCTYPE schema SYSTEM "XMLSchema.dtd" [ + <!ENTITY % p ''> + <!ENTITY % s ''> + <!ATTLIST schema + xmlns:svg CDATA #FIXED "http://www.w3.org/2000/svg" + xmlns:xlink CDATA #FIXED "http://www.w3.org/1999/xlink" + xmlns:xml CDATA #FIXED "http://www.w3.org/XML/1998/namespace" + >]> + <schema/> + EOL + prefixes = doc.root.prefixes.sort + correct = ['svg', 'xlink', 'xml'] + assert_equal correct, prefixes + end - def test_attlist_write - file=File.new(fixture_path("foo.xml")) - doc=Document.new file - out = '' - doc.write(out) - end + def test_attlist_write + file=File.new(fixture_path("foo.xml")) + doc=Document.new file + out = '' + doc.write(out) + end - def test_more_namespaces - assert_raise( REXML::UndefinedNamespaceException, - %Q{Should have gotten an Undefined Namespace error} ) { - Document.new("<r><p><n:c/></p></r>") - } - doc2 = Document.new("<r xmlns:n='1'><p><n:c/></p></r>") - es = XPath.match(doc2, '//c') - assert_equal 0, es.size - es = XPath.match(doc2, '//n:c') - assert_equal 1, es.size - doc2.root.add_namespace('m', '2') - doc2.root.add_element("m:o") - es = XPath.match(doc2, './/o') - assert_equal 0, es.size - es = XPath.match(doc2, '//n:c') - assert_equal 1, es.size - end + def test_more_namespaces + assert_raise( REXML::UndefinedNamespaceException, + %Q{Should have gotten an Undefined Namespace error} ) { + Document.new("<r><p><n:c/></p></r>") + } + doc2 = Document.new("<r xmlns:n='1'><p><n:c/></p></r>") + es = XPath.match(doc2, '//c') + assert_equal 0, es.size + es = XPath.match(doc2, '//n:c') + assert_equal 1, es.size + doc2.root.add_namespace('m', '2') + doc2.root.add_element("m:o") + es = XPath.match(doc2, './/o') + assert_equal 0, es.size + es = XPath.match(doc2, '//n:c') + assert_equal 1, es.size + end - def test_ticket_51 - doc = REXML::Document.new <<-EOL - <test xmlns='1' xmlns:x='1'> - <a>X</a> - <x:a>Y</x:a> - - <b xmlns='2'> - <a>Z</a> - </b> - </test> - EOL - - # The most common case. People not caring about the namespaces much. - assert_equal( "XY", XPath.match( doc, "/test/a/text()" ).join ) - assert_equal( "XY", XPath.match( doc, "/test/x:a/text()" ).join ) - # Surprising? I don't think so, if you believe my definition of the "common case" - assert_equal( "XYZ", XPath.match( doc, "//a/text()" ).join ) - - # These are the uncommon cases. Namespaces are actually important, so we define our own - # mappings, and pass them in. - assert_equal( "XY", XPath.match( doc, "/f:test/f:a/text()", { "f" => "1" } ).join ) - # The namespaces are defined, and override the original mappings - assert_equal( "", XPath.match( doc, "/test/a/text()", { "f" => "1" } ).join ) - assert_equal( "", XPath.match( doc, "/x:test/x:a/text()", { "f" => "1" } ).join ) - assert_equal( "", XPath.match( doc, "//a/text()", { "f" => "1" } ).join ) - end + def test_ticket_51 + doc = REXML::Document.new <<-EOL + <test xmlns='1' xmlns:x='1'> + <a>X</a> + <x:a>Y</x:a> + + <b xmlns='2'> + <a>Z</a> + </b> + </test> + EOL + + # The most common case. People not caring about the namespaces much. + assert_equal( "XY", XPath.match( doc, "/test/a/text()" ).join ) + assert_equal( "XY", XPath.match( doc, "/test/x:a/text()" ).join ) + # Surprising? I don't think so, if you believe my definition of the "common case" + assert_equal( "XYZ", XPath.match( doc, "//a/text()" ).join ) + + # These are the uncommon cases. Namespaces are actually important, so we define our own + # mappings, and pass them in. + assert_equal( "XY", XPath.match( doc, "/f:test/f:a/text()", { "f" => "1" } ).join ) + # The namespaces are defined, and override the original mappings + assert_equal( "", XPath.match( doc, "/test/a/text()", { "f" => "1" } ).join ) + assert_equal( "", XPath.match( doc, "/x:test/x:a/text()", { "f" => "1" } ).join ) + assert_equal( "", XPath.match( doc, "//a/text()", { "f" => "1" } ).join ) + end - def test_processing_instruction - d = Document.new("<a><?foo bar?><?foo2 bar2?><b><?foo3 bar3?></b><?foo4 bar4?></a>") - assert_equal 4, XPath.match(d, '//processing-instruction()' ).size - match = XPath.match(d, "//processing-instruction('foo3')" ) - assert_equal 1, match.size - assert_equal 'bar3', match[0].content - end + def test_processing_instruction + d = Document.new("<a><?foo bar?><?foo2 bar2?><b><?foo3 bar3?></b><?foo4 bar4?></a>") + assert_equal 4, XPath.match(d, '//processing-instruction()' ).size + match = XPath.match(d, "//processing-instruction('foo3')" ) + assert_equal 1, match.size + assert_equal 'bar3', match[0].content + end - def test_oses_with_bad_EOLs - Document.new("\n\n\n<?xml version='1.0'?>\n\n\n<a/>\n\n") - end + def test_oses_with_bad_EOLs + Document.new("\n\n\n<?xml version='1.0'?>\n\n\n<a/>\n\n") + end - # Contributed (with patch to fix bug) by Kouhei - def test_ignore_whitespace - source = "<a> <b/> abc <![CDATA[def]]> </a>" + # Contributed (with patch to fix bug) by Kouhei + def test_ignore_whitespace + source = "<a> <b/> abc <![CDATA[def]]> </a>" - context_all = {:ignore_whitespace_nodes => :all} - context_a = {:ignore_whitespace_nodes => %(a)} - context_b = {:ignore_whitespace_nodes => %(b)} + context_all = {:ignore_whitespace_nodes => :all} + context_a = {:ignore_whitespace_nodes => %(a)} + context_b = {:ignore_whitespace_nodes => %(b)} - tests = [[[" abc ", "def"], context_all], - [[" abc ", "def"], context_a], - [[" ", " abc ", "def", " "], context_b]] + tests = [[[" abc ", "def"], context_all], + [[" abc ", "def"], context_a], + [[" ", " abc ", "def", " "], context_b]] - tests.each do |test| - assert_equal(test[0], Document.new(source, test[1]).root.texts.collect{|x| - x.to_s}) + tests.each do |test| + assert_equal(test[0], Document.new(source, test[1]).root.texts.collect{|x| + x.to_s}) + end end - end - def test_0xD_in_preface - doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\x0D<opml version=\"1.0\">\x0D</opml>" - doc = Document.new doc - end + def test_0xD_in_preface + doc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\x0D<opml version=\"1.0\">\x0D</opml>" + doc = Document.new doc + end - def test_hyphens_in_doctype - doc = REXML::Document.new <<-EOQ - <?xml version="1.0"?> - <!DOCTYPE a-b-c> - <a-b-c> - <a/> - </a-b-c> - EOQ + def test_hyphens_in_doctype + doc = REXML::Document.new <<-EOQ + <?xml version="1.0"?> + <!DOCTYPE a-b-c> + <a-b-c> + <a/> + </a-b-c> + EOQ - assert_equal('a-b-c', doc.doctype.name) - end + assert_equal('a-b-c', doc.doctype.name) + end - def test_accents - docs = [ - %Q{<?xml version="1.0" encoding="ISO-8859-1"?> + def test_accents + docs = [ + %Q{<?xml version="1.0" encoding="ISO-8859-1"?> <gnuPod> <files> <file id="57" artist="Coralie Cl\357\277\275ent" /> </files> </gnuPod>}, - '<?xml version="1.0" encoding="ISO-8859-1"?> + '<?xml version="1.0" encoding="ISO-8859-1"?> <gnuPod> <files> <file id="71" album="Astrakan Caf" /> </files> </gnuPod>', - %Q{<?xml version="1.0" encoding="ISO-8859-1"?> + %Q{<?xml version="1.0" encoding="ISO-8859-1"?> <gnuPod> <files> <file id="71" album="Astrakan Caf\357\277\275eria" /> </files> </gnuPod>}, - %Q{<?xml version="1.0" encoding="ISO-8859-1"?> + %Q{<?xml version="1.0" encoding="ISO-8859-1"?> <gnuPod> <files> <file id="71" album="Astrakan Caf\357\277\275" /> </files> </gnuPod>} ] - docs.each_with_index { |d,i| - begin - REXML::Document.new(d) - rescue - puts "#{i} => #{docs[i]}" - raise - end - } - end + docs.each_with_index { |d,i| + begin + REXML::Document.new(d) + rescue + puts "#{i} => #{docs[i]}" + raise + end + } + end - def test_replace_text - e = REXML::Element.new( "a" ) - e.add_text( "foo" ) - assert_equal( "<a>foo</a>", e.to_s ) - e[0].value = "bar" - assert_equal( "<a>bar</a>", e.to_s ) - e[0].value = "<" - assert_equal( "<a><</a>", e.to_s ) - assert_equal( "<", e[0].value ) - end + def test_replace_text + e = REXML::Element.new( "a" ) + e.add_text( "foo" ) + assert_equal( "<a>foo</a>", e.to_s ) + e[0].value = "bar" + assert_equal( "<a>bar</a>", e.to_s ) + e[0].value = "<" + assert_equal( "<a><</a>", e.to_s ) + assert_equal( "<", e[0].value ) + end - def test_write_doctype - ## XML Document and Declaration - document = REXML::Document.new - xmldecl = REXML::XMLDecl.new("1.0", "UTF-8") - document.add(xmldecl) - s = "" - document.write(s) + def test_write_doctype + ## XML Document and Declaration + document = REXML::Document.new + xmldecl = REXML::XMLDecl.new("1.0", "UTF-8") + document.add(xmldecl) + s = "" + document.write(s) - ## XML Doctype - str = '<!DOCTYPE foo "bar">' - source = REXML::Source.new(str) - doctype = REXML::DocType.new(source) - document.add(doctype) - document.write(s) + ## XML Doctype + str = '<!DOCTYPE foo "bar">' + source = REXML::Source.new(str) + doctype = REXML::DocType.new(source) + document.add(doctype) + document.write(s) - ## Element - element = REXML::Element.new("hoge") - document.add(element) + ## Element + element = REXML::Element.new("hoge") + document.add(element) - document.write(s) - end + document.write(s) + end - def test_write_cdata - src = "<a>A</a>" - doc = REXML::Document.new( src ) - out = "" - doc.write( out ) - assert_equal( src, out ) - - src = "<a><![CDATA[A]]></a>" - doc = REXML::Document.new( src ) - out = "" - doc.write( out ) - assert_equal( src, out ) - end + def test_write_cdata + src = "<a>A</a>" + doc = REXML::Document.new( src ) + out = "" + doc.write( out ) + assert_equal( src, out ) + + src = "<a><![CDATA[A]]></a>" + doc = REXML::Document.new( src ) + out = "" + doc.write( out ) + assert_equal( src, out ) + end - def test_namespace_attributes - source = <<-EOL - <a xmlns:x="1"> - <x:b x:n="foo"/> - </a> - EOL - d = Document.new( source ) - assert_equal( 'foo', REXML::XPath.first(d.root, "//x:b/@x:n").value ) - assert_equal( nil, REXML::XPath.first(d.root, "//x:b/@x:n", {})) - end + def test_namespace_attributes + source = <<-EOL + <a xmlns:x="1"> + <x:b x:n="foo"/> + </a> + EOL + d = Document.new( source ) + assert_equal( 'foo', REXML::XPath.first(d.root, "//x:b/@x:n").value ) + assert_equal( nil, REXML::XPath.first(d.root, "//x:b/@x:n", {})) + end - def test_null_element_name - a = REXML::Document.new - assert_raise( RuntimeError ) { - a.add_element( nil ) - } - end + def test_null_element_name + a = REXML::Document.new + assert_raise( RuntimeError ) { + a.add_element( nil ) + } + end - def test_text_raw - # From the REXML tutorial - # (http://www.germane-software.com/software/rexml/test/data/tutorial.html) - doc = Document.new <<-EOL - <?xml version="1.0"?> - <!DOCTYPE schema SYSTEM "XMLSchema.dtd" [ - <!ENTITY % s 'Sean'> - ]> - <a/> - EOL - a = doc.root - - # This makes sure that RAW text nodes don't have their entity strings - # replaced - t = Text.new "Sean", false, nil, true - a.text = t - assert_equal( "Sean", t.to_s ) - assert_equal( "Sean", t.value ) - - # This makes sure that they do - t = Text.new "Sean", false, nil, false - a.text = t - assert_equal( "&s;", t.to_s ) - assert_equal( "Sean", t.value ) - - t = Text.new "&s;", false, nil, true - a.text = t - assert_equal( "&s;", t.to_s ) - assert_equal( "Sean", t.value ) - - t = Text.new "&s;", false, nil, true - a.text = t - assert_equal( "&s;", t.to_s ) - assert_equal( "Sean", t.value ) - - # Ticket #44 - t = REXML::Text.new( "&", false, nil, true ) - assert_equal( "&", t.to_s ) - - t = REXML::Text.new("&", false, false) - assert_equal( "&amp;", t.to_s ) - end + def test_text_raw + # From the REXML tutorial + # (http://www.germane-software.com/software/rexml/test/data/tutorial.html) + doc = Document.new <<-EOL + <?xml version="1.0"?> + <!DOCTYPE schema SYSTEM "XMLSchema.dtd" [ + <!ENTITY % s 'Sean'> + ]> + <a/> + EOL + a = doc.root + + # This makes sure that RAW text nodes don't have their entity strings + # replaced + t = Text.new "Sean", false, nil, true + a.text = t + assert_equal( "Sean", t.to_s ) + assert_equal( "Sean", t.value ) + + # This makes sure that they do + t = Text.new "Sean", false, nil, false + a.text = t + assert_equal( "&s;", t.to_s ) + assert_equal( "Sean", t.value ) + + t = Text.new "&s;", false, nil, true + a.text = t + assert_equal( "&s;", t.to_s ) + assert_equal( "Sean", t.value ) + + t = Text.new "&s;", false, nil, true + a.text = t + assert_equal( "&s;", t.to_s ) + assert_equal( "Sean", t.value ) + + # Ticket #44 + t = REXML::Text.new( "&", false, nil, true ) + assert_equal( "&", t.to_s ) + + t = REXML::Text.new("&", false, false) + assert_equal( "&amp;", t.to_s ) + end - def test_to_xpath - doc = REXML::Document.new( %q{<tag1> - <tag2 name="tag2"/> - <tag2 name="tag2"/> - </tag1>}) - names = %w{ /tag1/tag2[1] /tag1/tag2[2] } - doc.root.elements.each_with_index {|el, i| - assert_equal( names[i], el.xpath ) - } - end + def test_to_xpath + doc = REXML::Document.new( %q{<tag1> + <tag2 name="tag2"/> + <tag2 name="tag2"/> + </tag1>}) + names = %w{ /tag1/tag2[1] /tag1/tag2[2] } + doc.root.elements.each_with_index {|el, i| + assert_equal( names[i], el.xpath ) + } + end - def test_transitive - doc = REXML::Document.new( "<a/>") - s = "" - doc.write( s, 0, true ) - end + def test_transitive + doc = REXML::Document.new( "<a/>") + s = "" + doc.write( s, 0, true ) + end - # This is issue #40 - def test_replace_with - old = '<doc>old<foo/>old</doc>' - d = REXML::Document.new(old).root - new = REXML::Text.new('new',true,nil,true) - child = d.children[2] - child.replace_with(new) - assert_equal( new, d.children[2] ) - end + # This is issue #40 + def test_replace_with + old = '<doc>old<foo/>old</doc>' + d = REXML::Document.new(old).root + new = REXML::Text.new('new',true,nil,true) + child = d.children[2] + child.replace_with(new) + assert_equal( new, d.children[2] ) + end - def test_repeated_writes - a = IO.read(fixture_path("iso8859-1.xml")) - f = REXML::Formatters::Pretty.new + def test_repeated_writes + a = IO.read(fixture_path("iso8859-1.xml")) + f = REXML::Formatters::Pretty.new - xmldoc = REXML::Document.new( a ) - a_andre = xmldoc.elements['//image'].attributes['caption'] + xmldoc = REXML::Document.new( a ) + a_andre = xmldoc.elements['//image'].attributes['caption'] - f.write(xmldoc,b="") + f.write(xmldoc,b="") - xmldoc = REXML::Document.new(b) - b_andre = xmldoc.elements['//image'].attributes['caption'] - assert_equal( a_andre, b_andre ) + xmldoc = REXML::Document.new(b) + b_andre = xmldoc.elements['//image'].attributes['caption'] + assert_equal( a_andre, b_andre ) - f.write(xmldoc,c="") + f.write(xmldoc,c="") - xmldoc = REXML::Document.new(c) - c_andre = xmldoc.elements['//image'].attributes['caption'] - assert_equal( b_andre, c_andre ) + xmldoc = REXML::Document.new(c) + c_andre = xmldoc.elements['//image'].attributes['caption'] + assert_equal( b_andre, c_andre ) - o = Output.new(d="","UTF-8") - f.write(xmldoc,o) - assert_not_equal( c, d ) - end + o = Output.new(d="","UTF-8") + f.write(xmldoc,o) + assert_not_equal( c, d ) + end - def test_pretty_format_long_text_finite - n = 1_000_000 - long_text = 'aaaa ' * n - xml = "<doc>#{long_text}</doc>" - formatter = REXML::Formatters::Pretty.new - document = nil - begin - document = REXML::Document.new(xml) - rescue REXML::ParseException - skip_message = "skip this test because we can't check Pretty#wrap " + - "works without #<SystemStackError: stack level too deep> on " + - "small memory system. #<RegexpError: failed to allocate memory> " + - "will be raised on the system. See also [ruby-dev:42599]." - return skip_message - end - output = "" - formatter.write(document, output) - assert_equal("<doc>\n" + - ((" " + (" aaaa" * 15) + "\n") * (n / 15)) + - " " + ("aaaa " * (n % 15)) + "\n" + - "</doc>", - output) - end + def test_pretty_format_long_text_finite + n = 1_000_000 + long_text = 'aaaa ' * n + xml = "<doc>#{long_text}</doc>" + formatter = REXML::Formatters::Pretty.new + document = nil + begin + document = REXML::Document.new(xml) + rescue REXML::ParseException + skip_message = "skip this test because we can't check Pretty#wrap " + + "works without #<SystemStackError: stack level too deep> on " + + "small memory system. #<RegexpError: failed to allocate memory> " + + "will be raised on the system. See also [ruby-dev:42599]." + return skip_message + end + output = "" + formatter.write(document, output) + assert_equal("<doc>\n" + + ((" " + (" aaaa" * 15) + "\n") * (n / 15)) + + " " + ("aaaa " * (n % 15)) + "\n" + + "</doc>", + output) + end - def test_pretty_format_deep_indent - n = 6 - elements = "" - n.times do |i| - elements << "<element#{i}>" - elements << "element#{i} " * 5 - end - (n - 1).downto(0) do |i| - elements << "</element#{i}>" - end - xml = "<doc>#{elements}</doc>" - document = REXML::Document.new(xml) - formatter = REXML::Formatters::Pretty.new - formatter.width = 20 - output = "" - formatter.write(document, output) - assert_equal(<<-XML.strip, output) + def test_pretty_format_deep_indent + n = 6 + elements = "" + n.times do |i| + elements << "<element#{i}>" + elements << "element#{i} " * 5 + end + (n - 1).downto(0) do |i| + elements << "</element#{i}>" + end + xml = "<doc>#{elements}</doc>" + document = REXML::Document.new(xml) + formatter = REXML::Formatters::Pretty.new + formatter.width = 20 + output = "" + formatter.write(document, output) + assert_equal(<<-XML.strip, output) <doc> <element0> element0 @@ -1212,114 +1212,114 @@ EOL </element1> </element0> </doc> - XML - end + XML + end - def test_ticket_58 - doc = REXML::Document.new - doc << REXML::XMLDecl.default - doc << REXML::Element.new("a") + def test_ticket_58 + doc = REXML::Document.new + doc << REXML::XMLDecl.default + doc << REXML::Element.new("a") - str = "" - doc.write(str) + str = "" + doc.write(str) - assert_equal("<a/>", str) + assert_equal("<a/>", str) - doc = REXML::Document.new - doc << REXML::XMLDecl.new("1.0", "UTF-8") - doc << REXML::Element.new("a") + doc = REXML::Document.new + doc << REXML::XMLDecl.new("1.0", "UTF-8") + doc << REXML::Element.new("a") - str = "" - doc.write(str) + str = "" + doc.write(str) - assert_equal("<?xml version='1.0' encoding='UTF-8'?><a/>", str) - end + assert_equal("<?xml version='1.0' encoding='UTF-8'?><a/>", str) + end - # Incomplete tags should generate an error - def test_ticket_53 - assert_raise( REXML::ParseException ) { - REXML::Document.new( "<a><b></a>" ) - } - assert_raise( REXML::ParseException ) { - REXML::Document.new( "<a><b>" ) - } - assert_raise( REXML::ParseException ) { - REXML::Document.new( "<a><b/>" ) - } - end + # Incomplete tags should generate an error + def test_ticket_53 + assert_raise( REXML::ParseException ) { + REXML::Document.new( "<a><b></a>" ) + } + assert_raise( REXML::ParseException ) { + REXML::Document.new( "<a><b>" ) + } + assert_raise( REXML::ParseException ) { + REXML::Document.new( "<a><b/>" ) + } + end - def test_ticket_52 - source = "<!-- this is a single line comment -->" - d = REXML::Document.new(source) - d.write(k="") - assert_equal( source, k ) - - source = "<a><!-- Comment --></a>" - target = "<a>\n <!-- Comment -->\n</a>" - d = REXML::Document.new(source) - REXML::Formatters::Pretty.new(4).write(d,k="") - assert_equal( target, k ) - end + def test_ticket_52 + source = "<!-- this is a single line comment -->" + d = REXML::Document.new(source) + d.write(k="") + assert_equal( source, k ) + + source = "<a><!-- Comment --></a>" + target = "<a>\n <!-- Comment -->\n</a>" + d = REXML::Document.new(source) + REXML::Formatters::Pretty.new(4).write(d,k="") + assert_equal( target, k ) + end - def test_ticket_76 - src = "<div>at&t" - assert_raise( ParseException, %Q{"#{src}" is invalid XML} ) { - REXML::Document.new(src) - } - end + def test_ticket_76 + src = "<div>at&t" + assert_raise( ParseException, %Q{"#{src}" is invalid XML} ) { + REXML::Document.new(src) + } + end - def test_ticket_21 - src = "<foo bar=value/>" - assert_raise( ParseException, "invalid XML should be caught" ) { - Document.new(src) - } - begin - Document.new(src) - rescue - assert_match( /missing attribute quote/, $!.message ) + def test_ticket_21 + src = "<foo bar=value/>" + assert_raise( ParseException, "invalid XML should be caught" ) { + Document.new(src) + } + begin + Document.new(src) + rescue + assert_match( /missing attribute quote/, $!.message ) + end end - end - def test_ticket_63 - Document.new(File.new(fixture_path("t63-1.xml"))) - end + def test_ticket_63 + Document.new(File.new(fixture_path("t63-1.xml"))) + end - def test_ticket_75 - d = REXML::Document.new(File.new(fixture_path("t75.xml"))) - assert_equal("tree", d.root.name) - end + def test_ticket_75 + d = REXML::Document.new(File.new(fixture_path("t75.xml"))) + assert_equal("tree", d.root.name) + end - def test_ticket_48_part_II - f = REXML::Formatters::Pretty.new - #- rexml sanity check (bugs in ruby 1.8.4, ruby 1.8.6) - xmldoc = Document.new("<test/>") - xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, "UTF-8") - content = ['61c3a927223c3e26'].pack("H*") - content.force_encoding('UTF-8') if content.respond_to?(:force_encoding) - #- is some UTF-8 text but just to make sure my editor won't magically convert.. - xmldoc.root.add_attribute('attr', content) - f.write(xmldoc,out=[]) - - xmldoc = REXML::Document.new(out.join) - sanity1 = xmldoc.root.attributes['attr'] - f.write(xmldoc,out=[]) - - xmldoc = REXML::Document.new(out.join) - sanity2 = xmldoc.root.attributes['attr'] - f.write(xmldoc,out=[]) - - assert_equal( sanity1, sanity2 ) - end + def test_ticket_48_part_II + f = REXML::Formatters::Pretty.new + #- rexml sanity check (bugs in ruby 1.8.4, ruby 1.8.6) + xmldoc = Document.new("<test/>") + xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, "UTF-8") + content = ['61c3a927223c3e26'].pack("H*") + content.force_encoding('UTF-8') if content.respond_to?(:force_encoding) + #- is some UTF-8 text but just to make sure my editor won't magically convert.. + xmldoc.root.add_attribute('attr', content) + f.write(xmldoc,out=[]) + + xmldoc = REXML::Document.new(out.join) + sanity1 = xmldoc.root.attributes['attr'] + f.write(xmldoc,out=[]) + + xmldoc = REXML::Document.new(out.join) + sanity2 = xmldoc.root.attributes['attr'] + f.write(xmldoc,out=[]) + + assert_equal( sanity1, sanity2 ) + end - def test_ticket_88 - doc = REXML::Document.new("<?xml version=\"1.0\" encoding=\"shift_jis\"?>") - assert_equal("<?xml version='1.0' encoding='SHIFT_JIS'?>", doc.to_s) - doc = REXML::Document.new("<?xml version = \"1.0\" encoding = \"shift_jis\"?>") - assert_equal("<?xml version='1.0' encoding='SHIFT_JIS'?>", doc.to_s) - end + def test_ticket_88 + doc = REXML::Document.new("<?xml version=\"1.0\" encoding=\"shift_jis\"?>") + assert_equal("<?xml version='1.0' encoding='SHIFT_JIS'?>", doc.to_s) + doc = REXML::Document.new("<?xml version = \"1.0\" encoding = \"shift_jis\"?>") + assert_equal("<?xml version='1.0' encoding='SHIFT_JIS'?>", doc.to_s) + end - def test_ticket_85 - xml = <<ENDXML + def test_ticket_85 + xml = <<ENDXML <foo> <bar> <bob name='jimmy'/> @@ -1327,138 +1327,138 @@ EOL </foo> ENDXML - yml = "<foo> + yml = "<foo> <bar> <bob name='jimmy'/> </bar> </foo>" - # The pretty printer ignores all whitespace, anyway so output1 == output2 - f = REXML::Formatters::Pretty.new( 2 ) - d = Document.new( xml, :ignore_whitespace_nodes=>:all ) - f.write( d, output1="" ) + # The pretty printer ignores all whitespace, anyway so output1 == output2 + f = REXML::Formatters::Pretty.new( 2 ) + d = Document.new( xml, :ignore_whitespace_nodes=>:all ) + f.write( d, output1="" ) - d = Document.new( xml ) - f.write( d, output2="" ) + d = Document.new( xml ) + f.write( d, output2="" ) - # Output directives should override whitespace directives. - assert_equal( output1, output2 ) + # Output directives should override whitespace directives. + assert_equal( output1, output2 ) - # The base case. - d = Document.new(yml) - f.write( d, output3="" ) + # The base case. + d = Document.new(yml) + f.write( d, output3="" ) - assert_equal( output3.strip, output2.strip ) + assert_equal( output3.strip, output2.strip ) - d = Document.new(yml) - f.write( d, output4="" ) + d = Document.new(yml) + f.write( d, output4="" ) - assert_equal( output3.strip, output4.strip ) - end + assert_equal( output3.strip, output4.strip ) + end - def test_ticket_91 - source="<root> - <bah something='1' somethingelse='bah'> - <something>great</something> - </bah> - </root>" + def test_ticket_91 + source="<root> + <bah something='1' somethingelse='bah'> + <something>great</something> + </bah> + </root>" expected="<root> <bah something='1' somethingelse='bah'> <something>great</something> </bah> <bah/> </root>" - d = Document.new( source ) - d.root.add_element( "bah" ) - p=REXML::Formatters::Pretty.new(2) - p.compact = true # Don't add whitespace to text nodes unless necessary - p.write(d,out="") - assert_equal( expected, out ) - end + d = Document.new( source ) + d.root.add_element( "bah" ) + p=REXML::Formatters::Pretty.new(2) + p.compact = true # Don't add whitespace to text nodes unless necessary + p.write(d,out="") + assert_equal( expected, out ) + end - def test_ticket_95 - testd = REXML::Document.new "<a><b><c/><c/><c/></b></a>" - testd.write(out1="") - testd.elements["//c[2]"].xpath - testd.write(out2="") - assert_equal(out1,out2) - end + def test_ticket_95 + testd = REXML::Document.new "<a><b><c/><c/><c/></b></a>" + testd.write(out1="") + testd.elements["//c[2]"].xpath + testd.write(out2="") + assert_equal(out1,out2) + end - def test_ticket_102 - doc = REXML::Document.new '<doc xmlns="ns"><item name="foo"/></doc>' - assert_equal( "foo", doc.root.elements["item"].attribute("name","ns").to_s ) - assert_equal( "item", doc.root.elements["item[@name='foo']"].name ) - end + def test_ticket_102 + doc = REXML::Document.new '<doc xmlns="ns"><item name="foo"/></doc>' + assert_equal( "foo", doc.root.elements["item"].attribute("name","ns").to_s ) + assert_equal( "item", doc.root.elements["item[@name='foo']"].name ) + end - def test_ticket_14 - # Per .2.5 Node Tests of XPath spec - assert_raise( REXML::UndefinedNamespaceException, - %Q{Should have gotten an Undefined Namespace error} ) { - Document.new("<a><n:b/></a>") - } - end + def test_ticket_14 + # Per .2.5 Node Tests of XPath spec + assert_raise( REXML::UndefinedNamespaceException, + %Q{Should have gotten an Undefined Namespace error} ) { + Document.new("<a><n:b/></a>") + } + end - # 5.7 Text Nodes - # Character data is grouped into text nodes. As much character data as - # possible is grouped into each text node: a text node never has an - # immediately following or preceding sibling that is a text node. The - # string-value of a text node is the character data. A text node always has - # at least one character of data. - def test_ticket_105 - d = Document.new("<a/>") - d.root.add_text( "a" ) - d.root.add_text( "b" ) - assert_equal( 1, d.root.children.size ) - end + # 5.7 Text Nodes + # Character data is grouped into text nodes. As much character data as + # possible is grouped into each text node: a text node never has an + # immediately following or preceding sibling that is a text node. The + # string-value of a text node is the character data. A text node always has + # at least one character of data. + def test_ticket_105 + d = Document.new("<a/>") + d.root.add_text( "a" ) + d.root.add_text( "b" ) + assert_equal( 1, d.root.children.size ) + end - # phantom namespace same as default namespace - def test_ticket_121 - doc = REXML::Document.new( - '<doc xmlns="ns" xmlns:phantom="ns"><item name="foo">text</item></doc>' - ) - assert_equal 'text', doc.text( "/doc/item[@name='foo']" ) - assert_equal "name='foo'", - doc.root.elements["item"].attribute("name", "ns").inspect - assert_equal "<item name='foo'>text</item>", - doc.root.elements["item[@name='foo']"].to_s - end + # phantom namespace same as default namespace + def test_ticket_121 + doc = REXML::Document.new( + '<doc xmlns="ns" xmlns:phantom="ns"><item name="foo">text</item></doc>' + ) + assert_equal 'text', doc.text( "/doc/item[@name='foo']" ) + assert_equal "name='foo'", + doc.root.elements["item"].attribute("name", "ns").inspect + assert_equal "<item name='foo'>text</item>", + doc.root.elements["item[@name='foo']"].to_s + end - def test_ticket_135 - bean_element = REXML::Element.new("bean") - textToAdd = "(&(|(memberof=CN=somegroupabcdefgh,OU=OUsucks,DC=hookemhorns,DC=com)(mail=*someco.com))(acct=%u)(!(extraparameter:2.2.222.222222.2.2.222:=2)))" - bean_element.add_element("prop", {"key"=> "filter"}).add_text(textToAdd) - doc = REXML::Document.new - doc.add_element(bean_element) + def test_ticket_135 + bean_element = REXML::Element.new("bean") + textToAdd = "(&(|(memberof=CN=somegroupabcdefgh,OU=OUsucks,DC=hookemhorns,DC=com)(mail=*someco.com))(acct=%u)(!(extraparameter:2.2.222.222222.2.2.222:=2)))" + bean_element.add_element("prop", {"key"=> "filter"}).add_text(textToAdd) + doc = REXML::Document.new + doc.add_element(bean_element) - REXML::Formatters::Pretty.new(3).write( doc, out = "" ) + REXML::Formatters::Pretty.new(3).write( doc, out = "" ) - assert_equal "<bean>\n <prop key='filter'>\n (&#38;(|(memberof=CN=somegroupabcdefgh,OU=OUsucks,DC=hookemhorns,DC=com)(mail=*someco.com))(acct=%u)(!(extraparameter:2.2.222.222222.2.2.222:=2)))\n </prop>\n</bean>", out - end + assert_equal "<bean>\n <prop key='filter'>\n (&#38;(|(memberof=CN=somegroupabcdefgh,OU=OUsucks,DC=hookemhorns,DC=com)(mail=*someco.com))(acct=%u)(!(extraparameter:2.2.222.222222.2.2.222:=2)))\n </prop>\n</bean>", out + end - def test_ticket_138 - doc = REXML::Document.new( - '<svg xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" ' + - 'inkscape:version="0.44" version="1.0"/>' - ) - expected = { - "inkscape" => attribute("xmlns:inkscape", - "http://www.inkscape.org/namespaces/inkscape"), - "version" => { - "inkscape" => attribute("inkscape:version", "0.44"), - "" => attribute("version", "1.0"), - }, - } - assert_equal(expected, doc.root.attributes) - assert_equal(expected, REXML::Document.new(doc.root.to_s).root.attributes) - end + def test_ticket_138 + doc = REXML::Document.new( + '<svg xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" ' + + 'inkscape:version="0.44" version="1.0"/>' + ) + expected = { + "inkscape" => attribute("xmlns:inkscape", + "http://www.inkscape.org/namespaces/inkscape"), + "version" => { + "inkscape" => attribute("inkscape:version", "0.44"), + "" => attribute("version", "1.0"), + }, + } + assert_equal(expected, doc.root.attributes) + assert_equal(expected, REXML::Document.new(doc.root.to_s).root.attributes) + end - def test_empty_doc - assert(REXML::Document.new('').children.empty?) - end + def test_empty_doc + assert(REXML::Document.new('').children.empty?) + end - private - def attribute(name, value) - REXML::Attribute.new(name, value) + private + def attribute(name, value) + REXML::Attribute.new(name, value) + end end end -end diff --git a/test/rexml/test_doctype.rb b/test/rexml/test_doctype.rb index 63c2ed9ada..0b3ea11929 100644 --- a/test/rexml/test_doctype.rb +++ b/test/rexml/test_doctype.rb @@ -2,105 +2,105 @@ require 'test/unit' require 'rexml/document' module REXMLTests -class TestDocTypeAccessor < Test::Unit::TestCase - - def setup - @sysid = "urn:x-test:sysid1" - @notid1 = "urn:x-test:notation1" - @notid2 = "urn:x-test:notation2" - document_string1 = <<-"XMLEND" - <!DOCTYPE r SYSTEM "#{@sysid}" [ - <!NOTATION n1 SYSTEM "#{@notid1}"> - <!NOTATION n2 SYSTEM "#{@notid2}"> - ]> - <r/> - XMLEND - @doctype1 = REXML::Document.new(document_string1).doctype - - @pubid = "TEST_ID" - document_string2 = <<-"XMLEND" - <!DOCTYPE r PUBLIC "#{@pubid}"> - <r/> - XMLEND - @doctype2 = REXML::Document.new(document_string2).doctype - - document_string3 = <<-"XMLEND" - <!DOCTYPE r PUBLIC "#{@pubid}" "#{@sysid}"> - <r/> - XMLEND - @doctype3 = REXML::Document.new(document_string3).doctype + class TestDocTypeAccessor < Test::Unit::TestCase + + def setup + @sysid = "urn:x-test:sysid1" + @notid1 = "urn:x-test:notation1" + @notid2 = "urn:x-test:notation2" + document_string1 = <<-"XMLEND" + <!DOCTYPE r SYSTEM "#{@sysid}" [ + <!NOTATION n1 SYSTEM "#{@notid1}"> + <!NOTATION n2 SYSTEM "#{@notid2}"> + ]> + <r/> + XMLEND + @doctype1 = REXML::Document.new(document_string1).doctype + + @pubid = "TEST_ID" + document_string2 = <<-"XMLEND" + <!DOCTYPE r PUBLIC "#{@pubid}"> + <r/> + XMLEND + @doctype2 = REXML::Document.new(document_string2).doctype + + document_string3 = <<-"XMLEND" + <!DOCTYPE r PUBLIC "#{@pubid}" "#{@sysid}"> + <r/> + XMLEND + @doctype3 = REXML::Document.new(document_string3).doctype + + end + + def test_public + assert_equal(nil, @doctype1.public) + assert_equal(@pubid, @doctype2.public) + assert_equal(@pubid, @doctype3.public) + end + + def test_system + assert_equal(@sysid, @doctype1.system) + assert_equal(nil, @doctype2.system) + assert_equal(@sysid, @doctype3.system) + end + + def test_notation + assert_equal(@notid1, @doctype1.notation("n1").system) + assert_equal(@notid2, @doctype1.notation("n2").system) + end + + def test_notations + notations = @doctype1.notations + assert_equal(2, notations.length) + assert_equal(@notid1, find_notation(notations, "n1").system) + assert_equal(@notid2, find_notation(notations, "n2").system) + end + + def find_notation(notations, name) + notations.find { |notation| + name == notation.name + } + end end - def test_public - assert_equal(nil, @doctype1.public) - assert_equal(@pubid, @doctype2.public) - assert_equal(@pubid, @doctype3.public) + class TestNotationDeclPublic < Test::Unit::TestCase + def setup + @name = "vrml" + @id = "VRML 1.0" + @uri = "http://www.web3d.org/" + end + + def test_to_s + assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\">", + decl(@id, nil).to_s) + end + + def test_to_s_with_uri + assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\" \"#{@uri}\">", + decl(@id, @uri).to_s) + end + + private + def decl(id, uri) + REXML::NotationDecl.new(@name, "PUBLIC", id, uri) + end end - def test_system - assert_equal(@sysid, @doctype1.system) - assert_equal(nil, @doctype2.system) - assert_equal(@sysid, @doctype3.system) + class TestNotationDeclSystem < Test::Unit::TestCase + def setup + @name = "gif" + @id = "gif viewer" + end + + def test_to_s + assert_equal("<!NOTATION #{@name} SYSTEM \"#{@id}\">", + decl(@id).to_s) + end + + private + def decl(id) + REXML::NotationDecl.new(@name, "SYSTEM", id, nil) + end end - - def test_notation - assert_equal(@notid1, @doctype1.notation("n1").system) - assert_equal(@notid2, @doctype1.notation("n2").system) - end - - def test_notations - notations = @doctype1.notations - assert_equal(2, notations.length) - assert_equal(@notid1, find_notation(notations, "n1").system) - assert_equal(@notid2, find_notation(notations, "n2").system) - end - - def find_notation(notations, name) - notations.find { |notation| - name == notation.name - } - end - -end - -class TestNotationDeclPublic < Test::Unit::TestCase - def setup - @name = "vrml" - @id = "VRML 1.0" - @uri = "http://www.web3d.org/" - end - - def test_to_s - assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\">", - decl(@id, nil).to_s) - end - - def test_to_s_with_uri - assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\" \"#{@uri}\">", - decl(@id, @uri).to_s) - end - - private - def decl(id, uri) - REXML::NotationDecl.new(@name, "PUBLIC", id, uri) - end -end - -class TestNotationDeclSystem < Test::Unit::TestCase - def setup - @name = "gif" - @id = "gif viewer" - end - - def test_to_s - assert_equal("<!NOTATION #{@name} SYSTEM \"#{@id}\">", - decl(@id).to_s) - end - - private - def decl(id) - REXML::NotationDecl.new(@name, "SYSTEM", id, nil) - end -end end diff --git a/test/rexml/test_elements.rb b/test/rexml/test_elements.rb index 6a9b3bbdd2..f253a75daf 100644 --- a/test/rexml/test_elements.rb +++ b/test/rexml/test_elements.rb @@ -2,117 +2,117 @@ require 'test/unit/testcase' require 'rexml/document' module REXMLTests -class ElementsTester < Test::Unit::TestCase - include REXML - def test_accessor - doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>' - assert_equal 'b', doc.root.elements[1].name - assert_equal '1', doc.root.elements['c'].attributes['id'] - assert_equal '2', doc.root.elements[2,'c'].attributes['id'] - end + class ElementsTester < Test::Unit::TestCase + include REXML + def test_accessor + doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>' + assert_equal 'b', doc.root.elements[1].name + assert_equal '1', doc.root.elements['c'].attributes['id'] + assert_equal '2', doc.root.elements[2,'c'].attributes['id'] + end - def test_indexing - doc = Document.new '<a/>' - doc.root.elements[10] = Element.new('b') - assert_equal 'b', doc.root.elements[1].name - doc.root.elements[1] = Element.new('c') - assert_equal 'c', doc.root.elements[1].name - doc.root.elements['c'] = Element.new('d') - assert_equal 'd', doc.root.elements[1].name - end + def test_indexing + doc = Document.new '<a/>' + doc.root.elements[10] = Element.new('b') + assert_equal 'b', doc.root.elements[1].name + doc.root.elements[1] = Element.new('c') + assert_equal 'c', doc.root.elements[1].name + doc.root.elements['c'] = Element.new('d') + assert_equal 'd', doc.root.elements[1].name + end - def test_delete - doc = Document.new '<a><b/><c/><c id="1"/></a>' - block = proc { |str| - out = '' - doc.write out - assert_equal str, out - } - b = doc.root.elements[1] - doc.root.elements.delete b - block.call( "<a><c/><c id='1'/></a>" ) - doc.elements.delete("a/c[@id='1']") - block.call( '<a><c/></a>' ) - doc.root.elements.delete 1 - block.call( '<a/>' ) - end + def test_delete + doc = Document.new '<a><b/><c/><c id="1"/></a>' + block = proc { |str| + out = '' + doc.write out + assert_equal str, out + } + b = doc.root.elements[1] + doc.root.elements.delete b + block.call( "<a><c/><c id='1'/></a>" ) + doc.elements.delete("a/c[@id='1']") + block.call( '<a><c/></a>' ) + doc.root.elements.delete 1 + block.call( '<a/>' ) + end - def test_delete_all - doc = Document.new '<a><c/><c/><c/><c/></a>' - deleted = doc.elements.delete_all 'a/c' - assert_equal 4, deleted.size - end + def test_delete_all + doc = Document.new '<a><c/><c/><c/><c/></a>' + deleted = doc.elements.delete_all 'a/c' + assert_equal 4, deleted.size + end - def test_ticket_36 - doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" ) + def test_ticket_36 + doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" ) - deleted = doc.root.elements.delete_all( "xi:c" ) - assert_equal( 1, deleted.size ) + deleted = doc.root.elements.delete_all( "xi:c" ) + assert_equal( 1, deleted.size ) - doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" ) - deleted = doc.root.elements.delete_all( "//xi:c" ) - assert_equal( 2, deleted.size ) - end + doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" ) + deleted = doc.root.elements.delete_all( "//xi:c" ) + assert_equal( 2, deleted.size ) + end - def test_add - a = Element.new 'a' - a.elements.add Element.new('b') - assert_equal 'b', a.elements[1].name - a.elements.add 'c' - assert_equal 'c', a.elements[2].name - end + def test_add + a = Element.new 'a' + a.elements.add Element.new('b') + assert_equal 'b', a.elements[1].name + a.elements.add 'c' + assert_equal 'c', a.elements[2].name + end - def test_size - doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>' - assert_equal 6, doc.root.size - assert_equal 3, doc.root.elements.size - end + def test_size + doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>' + assert_equal 6, doc.root.size + assert_equal 3, doc.root.elements.size + end - def test_each - doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>' - count = 0 - block = proc {|e| count += 1} - doc.root.elements.each(&block) - assert_equal 6, count - count = 0 - doc.root.elements.each('b', &block) - assert_equal 2, count - count = 0 - doc.root.elements.each('child::node()', &block) - assert_equal 6, count - count = 0 - XPath.each(doc.root, 'child::node()', &block) - assert_equal 7, count - end + def test_each + doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>' + count = 0 + block = proc {|e| count += 1} + doc.root.elements.each(&block) + assert_equal 6, count + count = 0 + doc.root.elements.each('b', &block) + assert_equal 2, count + count = 0 + doc.root.elements.each('child::node()', &block) + assert_equal 6, count + count = 0 + XPath.each(doc.root, 'child::node()', &block) + assert_equal 7, count + end - def test_each_with_frozen_condition - doc = Document.new('<books><book name="Ruby"/><book name="XML"/></books>') - names = [] - doc.root.elements.each('book'.freeze) do |element| - names << element.attributes["name"] + def test_each_with_frozen_condition + doc = Document.new('<books><book name="Ruby"/><book name="XML"/></books>') + names = [] + doc.root.elements.each('book'.freeze) do |element| + names << element.attributes["name"] + end + assert_equal(["Ruby", "XML"], names) end - assert_equal(["Ruby", "XML"], names) - end - def test_to_a - doc = Document.new '<a>sean<b/>elliott<c/></a>' - assert_equal 2, doc.root.elements.to_a.size - assert_equal 2, doc.root.elements.to_a("child::node()").size - assert_equal 4, XPath.match(doc.root, "child::node()").size - end + def test_to_a + doc = Document.new '<a>sean<b/>elliott<c/></a>' + assert_equal 2, doc.root.elements.to_a.size + assert_equal 2, doc.root.elements.to_a("child::node()").size + assert_equal 4, XPath.match(doc.root, "child::node()").size + end - def test_collect - doc = Document.new( "<a><b id='1'/><b id='2'/></a>" ) - r = doc.elements.collect( "/a/b" ) { |e| e.attributes["id"].to_i } - assert_equal( [1,2], r ) - end + def test_collect + doc = Document.new( "<a><b id='1'/><b id='2'/></a>" ) + r = doc.elements.collect( "/a/b" ) { |e| e.attributes["id"].to_i } + assert_equal( [1,2], r ) + end - def test_inject - doc = Document.new( "<a><b id='1'/><b id='2'/></a>" ) - r = doc.elements.inject( "/a/b", 3 ) { |s, e| - s + e.attributes["id"].to_i - } - assert_equal 6, r + def test_inject + doc = Document.new( "<a><b id='1'/><b id='2'/></a>" ) + r = doc.elements.inject( "/a/b", 3 ) { |s, e| + s + e.attributes["id"].to_i + } + assert_equal 6, r + end end end -end diff --git a/test/rexml/test_encoding.rb b/test/rexml/test_encoding.rb index a08406782c..8205d0f366 100644 --- a/test/rexml/test_encoding.rb +++ b/test/rexml/test_encoding.rb @@ -6,91 +6,91 @@ require 'rexml/source' require 'rexml/document' module REXMLTests -class EncodingTester < Test::Unit::TestCase - include REXMLTestUtils - include REXML + class EncodingTester < Test::Unit::TestCase + include REXMLTestUtils + include REXML - def setup - @encoded_root = "<a><b>\346</b></a>" - @encoded = "<?xml version='1.0' encoding='ISO-8859-3'?>"+ - @encoded_root - @not_encoded = "<a><b>ĉ</b></a>" - end + def setup + @encoded_root = "<a><b>\346</b></a>" + @encoded = "<?xml version='1.0' encoding='ISO-8859-3'?>"+ + @encoded_root + @not_encoded = "<a><b>ĉ</b></a>" + end - # Given an encoded document, try to write out to that encoding - def test_encoded_in_encoded_out - doc = Document.new( @encoded ) - doc.write( out="" ) - out.force_encoding(::Encoding::ASCII_8BIT) - assert_equal( @encoded, out ) - end + # Given an encoded document, try to write out to that encoding + def test_encoded_in_encoded_out + doc = Document.new( @encoded ) + doc.write( out="" ) + out.force_encoding(::Encoding::ASCII_8BIT) + assert_equal( @encoded, out ) + end - # Given an encoded document, try to change the encoding and write it out - def test_encoded_in_change_out - doc = Document.new( @encoded ) - doc.xml_decl.encoding = "UTF-8" - assert_equal("UTF-8", doc.encoding) - REXML::Formatters::Default.new.write( doc.root, out="" ) - out.force_encoding(::Encoding::ASCII_8BIT) - assert_equal( @not_encoded, out ) - char = XPath.first( doc, "/a/b/text()" ).to_s - char.force_encoding(::Encoding::ASCII_8BIT) - assert_equal( "ĉ", char ) - end + # Given an encoded document, try to change the encoding and write it out + def test_encoded_in_change_out + doc = Document.new( @encoded ) + doc.xml_decl.encoding = "UTF-8" + assert_equal("UTF-8", doc.encoding) + REXML::Formatters::Default.new.write( doc.root, out="" ) + out.force_encoding(::Encoding::ASCII_8BIT) + assert_equal( @not_encoded, out ) + char = XPath.first( doc, "/a/b/text()" ).to_s + char.force_encoding(::Encoding::ASCII_8BIT) + assert_equal( "ĉ", char ) + end - # * Given an encoded document, try to write it to a different encoding - def test_encoded_in_different_out - doc = Document.new( @encoded ) - REXML::Formatters::Default.new.write( doc.root, Output.new( out="", "UTF-8" ) ) - out.force_encoding(::Encoding::ASCII_8BIT) - assert_equal( @not_encoded, out ) - end + # * Given an encoded document, try to write it to a different encoding + def test_encoded_in_different_out + doc = Document.new( @encoded ) + REXML::Formatters::Default.new.write( doc.root, Output.new( out="", "UTF-8" ) ) + out.force_encoding(::Encoding::ASCII_8BIT) + assert_equal( @not_encoded, out ) + end - # * Given a non-encoded document, change the encoding - def test_in_change_out - doc = Document.new( @not_encoded ) - doc.xml_decl.encoding = "ISO-8859-3" - assert_equal("ISO-8859-3", doc.encoding) - doc.write( out="" ) - out.force_encoding(::Encoding::ASCII_8BIT) - assert_equal( @encoded, out ) - end + # * Given a non-encoded document, change the encoding + def test_in_change_out + doc = Document.new( @not_encoded ) + doc.xml_decl.encoding = "ISO-8859-3" + assert_equal("ISO-8859-3", doc.encoding) + doc.write( out="" ) + out.force_encoding(::Encoding::ASCII_8BIT) + assert_equal( @encoded, out ) + end - # * Given a non-encoded document, write to a different encoding - def test_in_different_out - doc = Document.new( @not_encoded ) - doc.write( Output.new( out="", "ISO-8859-3" ) ) - out.force_encoding(::Encoding::ASCII_8BIT) - assert_equal( "<?xml version='1.0'?>#{@encoded_root}", out ) - end + # * Given a non-encoded document, write to a different encoding + def test_in_different_out + doc = Document.new( @not_encoded ) + doc.write( Output.new( out="", "ISO-8859-3" ) ) + out.force_encoding(::Encoding::ASCII_8BIT) + assert_equal( "<?xml version='1.0'?>#{@encoded_root}", out ) + end - # * Given an encoded document, accessing text and attribute nodes - # should provide UTF-8 text. - def test_in_different_access - doc = Document.new <<-EOL - <?xml version='1.0' encoding='ISO-8859-1'?> - <a a="\xFF">\xFF</a> - EOL - expect = "\303\277" - expect.force_encoding(::Encoding::UTF_8) - assert_equal( expect, doc.elements['a'].attributes['a'] ) - assert_equal( expect, doc.elements['a'].text ) - end + # * Given an encoded document, accessing text and attribute nodes + # should provide UTF-8 text. + def test_in_different_access + doc = Document.new <<-EOL + <?xml version='1.0' encoding='ISO-8859-1'?> + <a a="\xFF">\xFF</a> + EOL + expect = "\303\277" + expect.force_encoding(::Encoding::UTF_8) + assert_equal( expect, doc.elements['a'].attributes['a'] ) + assert_equal( expect, doc.elements['a'].text ) + end - def test_ticket_89 - doc = Document.new <<-EOL - <?xml version="1.0" encoding="CP-1252" ?> - <xml><foo></foo></xml> - EOL + def test_ticket_89 + doc = Document.new <<-EOL + <?xml version="1.0" encoding="CP-1252" ?> + <xml><foo></foo></xml> + EOL - REXML::Document.new doc - end + REXML::Document.new doc + end - def test_ticket_110 - utf16 = REXML::Document.new(File.new(fixture_path("ticket_110_utf16.xml"))) - assert_equal(utf16.encoding, "UTF-16") - assert( utf16[0].kind_of?(REXML::XMLDecl)) + def test_ticket_110 + utf16 = REXML::Document.new(File.new(fixture_path("ticket_110_utf16.xml"))) + assert_equal(utf16.encoding, "UTF-16") + assert( utf16[0].kind_of?(REXML::XMLDecl)) + end end end -end diff --git a/test/rexml/test_entity.rb b/test/rexml/test_entity.rb index 00272234f8..820e4f2b85 100644 --- a/test/rexml/test_entity.rb +++ b/test/rexml/test_entity.rb @@ -5,185 +5,185 @@ require 'rexml/entity' require 'rexml/source' module REXMLTests -class EntityTester < Test::Unit::TestCase - def test_parse_general_decl - simple = "<!ENTITY foo 'bar'>" - simple =~ /#{REXML::Entity::GEDECL}/ - assert $& - assert_equal simple, $& - - REXML::Entity::ENTITYDECL =~ simple - assert REXML::Entity::matches?(simple) - match = REXML::Entity::ENTITYDECL.match(simple) - assert_equal 'foo', match[1] - assert_equal "'bar'", match[2] - - simple = '<!ENTITY Pub-Status - "This is a pre-release of the specification.">' - assert REXML::Entity::matches?(simple) - match = REXML::Entity::ENTITYDECL.match(simple) - assert_equal 'Pub-Status', match[1] - assert_equal '"This is a pre-release of the specification."', match[2] - - txt = '"This is a - pre-release of <the> specification."' - simple = "<!ENTITY Pub-Status - #{txt}>" - assert REXML::Entity::matches?(simple) - match = REXML::Entity::ENTITYDECL.match(simple) - assert_equal 'Pub-Status', match[1] - assert_equal txt, match[2] - end + class EntityTester < Test::Unit::TestCase + def test_parse_general_decl + simple = "<!ENTITY foo 'bar'>" + simple =~ /#{REXML::Entity::GEDECL}/ + assert $& + assert_equal simple, $& + + REXML::Entity::ENTITYDECL =~ simple + assert REXML::Entity::matches?(simple) + match = REXML::Entity::ENTITYDECL.match(simple) + assert_equal 'foo', match[1] + assert_equal "'bar'", match[2] + + simple = '<!ENTITY Pub-Status + "This is a pre-release of the specification.">' + assert REXML::Entity::matches?(simple) + match = REXML::Entity::ENTITYDECL.match(simple) + assert_equal 'Pub-Status', match[1] + assert_equal '"This is a pre-release of the specification."', match[2] + + txt = '"This is a + pre-release of <the> specification."' + simple = "<!ENTITY Pub-Status + #{txt}>" + assert REXML::Entity::matches?(simple) + match = REXML::Entity::ENTITYDECL.match(simple) + assert_equal 'Pub-Status', match[1] + assert_equal txt, match[2] + end - def test_parse_external_decl - zero = '<!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml" >' - one = '<!ENTITY open-hatch - SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">' - two = '<!ENTITY open-hatch - PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" - "http://www.textuality.com/boilerplate/OpenHatch.xml">' - three = '<!ENTITY hatch-pic - SYSTEM "../grafix/OpenHatch.gif" - NDATA gif >' - assert REXML::Entity::matches?(zero) - assert REXML::Entity::matches?(one) - assert REXML::Entity::matches?(two) - assert REXML::Entity::matches?(three) - end + def test_parse_external_decl + zero = '<!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml" >' + one = '<!ENTITY open-hatch + SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">' + two = '<!ENTITY open-hatch + PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" + "http://www.textuality.com/boilerplate/OpenHatch.xml">' + three = '<!ENTITY hatch-pic + SYSTEM "../grafix/OpenHatch.gif" + NDATA gif >' + assert REXML::Entity::matches?(zero) + assert REXML::Entity::matches?(one) + assert REXML::Entity::matches?(two) + assert REXML::Entity::matches?(three) + end - def test_parse_entity - one = %q{<!ENTITY % YN '"Yes"'>} - two = %q{<!ENTITY WhatHeSaid "He said %YN;">} - assert REXML::Entity::matches?(one) - assert REXML::Entity::matches?(two) - end + def test_parse_entity + one = %q{<!ENTITY % YN '"Yes"'>} + two = %q{<!ENTITY WhatHeSaid "He said %YN;">} + assert REXML::Entity::matches?(one) + assert REXML::Entity::matches?(two) + end - def test_constructor - one = [ %q{<!ENTITY % YN '"Yes"'>}, - %q{<!ENTITY % YN2 "Yes">}, - %q{<!ENTITY WhatHeSaid "He said %YN;">}, - '<!ENTITY open-hatch - SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">', - '<!ENTITY open-hatch2 - PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" - "http://www.textuality.com/boilerplate/OpenHatch.xml">', - '<!ENTITY hatch-pic - SYSTEM "../grafix/OpenHatch.gif" - NDATA gif>' ] - source = %q{<!DOCTYPE foo [ - <!ENTITY % YN '"Yes"'> - <!ENTITY % YN2 "Yes"> - <!ENTITY WhatHeSaid "He said %YN;"> - <!ENTITY open-hatch - SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> - <!ENTITY open-hatch2 - PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" - "http://www.textuality.com/boilerplate/OpenHatch.xml"> - <!ENTITY hatch-pic - SYSTEM "../grafix/OpenHatch.gif" - NDATA gif> - ]>} - - d = REXML::Document.new( source ) - dt = d.doctype - c = 0 - dt.each do |child| - if child.kind_of? REXML::Entity - str = one[c].tr("\r\n\t", ' ').squeeze(" ") - assert_equal str, child.to_s - c+=1 + def test_constructor + one = [ %q{<!ENTITY % YN '"Yes"'>}, + %q{<!ENTITY % YN2 "Yes">}, + %q{<!ENTITY WhatHeSaid "He said %YN;">}, + '<!ENTITY open-hatch + SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">', + '<!ENTITY open-hatch2 + PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" + "http://www.textuality.com/boilerplate/OpenHatch.xml">', + '<!ENTITY hatch-pic + SYSTEM "../grafix/OpenHatch.gif" + NDATA gif>' ] + source = %q{<!DOCTYPE foo [ + <!ENTITY % YN '"Yes"'> + <!ENTITY % YN2 "Yes"> + <!ENTITY WhatHeSaid "He said %YN;"> + <!ENTITY open-hatch + SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> + <!ENTITY open-hatch2 + PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" + "http://www.textuality.com/boilerplate/OpenHatch.xml"> + <!ENTITY hatch-pic + SYSTEM "../grafix/OpenHatch.gif" + NDATA gif> + ]>} + + d = REXML::Document.new( source ) + dt = d.doctype + c = 0 + dt.each do |child| + if child.kind_of? REXML::Entity + str = one[c].tr("\r\n\t", ' ').squeeze(" ") + assert_equal str, child.to_s + c+=1 + end end end - end - def test_replace_entities - source = "<!DOCTYPE blah [\n<!ENTITY foo \"bar\">\n]><a>&foo;</a>" - doc = REXML::Document.new(source) - assert_equal 'bar', doc.root.text - out = '' - doc.write out - assert_equal source, out - end + def test_replace_entities + source = "<!DOCTYPE blah [\n<!ENTITY foo \"bar\">\n]><a>&foo;</a>" + doc = REXML::Document.new(source) + assert_equal 'bar', doc.root.text + out = '' + doc.write out + assert_equal source, out + end - def test_entity_string_limit - template = '<!DOCTYPE bomb [ <!ENTITY a "^" > ]> <bomb>$</bomb>' - len = 5120 # 5k per entity - template.sub!(/\^/, "B" * len) - - # 10k is OK - entities = '&a;' * 2 # 5k entity * 2 = 10k - xmldoc = REXML::Document.new(template.sub(/\$/, entities)) - assert_equal(len * 2, xmldoc.root.text.bytesize) - - # above 10k explodes - entities = '&a;' * 3 # 5k entity * 2 = 15k - xmldoc = REXML::Document.new(template.sub(/\$/, entities)) - assert_raises(RuntimeError) do - xmldoc.root.text + def test_entity_string_limit + template = '<!DOCTYPE bomb [ <!ENTITY a "^" > ]> <bomb>$</bomb>' + len = 5120 # 5k per entity + template.sub!(/\^/, "B" * len) + + # 10k is OK + entities = '&a;' * 2 # 5k entity * 2 = 10k + xmldoc = REXML::Document.new(template.sub(/\$/, entities)) + assert_equal(len * 2, xmldoc.root.text.bytesize) + + # above 10k explodes + entities = '&a;' * 3 # 5k entity * 2 = 15k + xmldoc = REXML::Document.new(template.sub(/\$/, entities)) + assert_raises(RuntimeError) do + xmldoc.root.text + end end - end - def test_raw - source = '<!DOCTYPE foo [ + def test_raw + source = '<!DOCTYPE foo [ <!ENTITY ent "replace"> ]><a>replace &ent;</a>' - doc = REXML::Document.new( source, {:raw=>:all}) - assert_equal('replace &ent;', doc.root.get_text.to_s) - assert_equal(source, doc.to_s) - end + doc = REXML::Document.new( source, {:raw=>:all}) + assert_equal('replace &ent;', doc.root.get_text.to_s) + assert_equal(source, doc.to_s) + end - def test_lazy_evaluation - source = '<!DOCTYPE foo [ + def test_lazy_evaluation + source = '<!DOCTYPE foo [ <!ENTITY ent "replace"> ]><a>replace &ent;</a>' - doc = REXML::Document.new( source ) - assert_equal(source, doc.to_s) - assert_equal("replace replace", doc.root.text) - assert_equal(source, doc.to_s) - end + doc = REXML::Document.new( source ) + assert_equal(source, doc.to_s) + assert_equal("replace replace", doc.root.text) + assert_equal(source, doc.to_s) + end - # Contributed (not only test, but bug fix!!) by Kouhei Sutou - def test_entity_replacement - source = %q{<!DOCTYPE foo [ - <!ENTITY % YN '"Yes"'> - <!ENTITY WhatHeSaid "He said %YN;">]> - <a>&WhatHeSaid;</a>} - - d = REXML::Document.new( source ) - dt = d.doctype - assert_equal( '"Yes"', dt.entities[ "YN" ].value ) - assert_equal( 'He said "Yes"', dt.entities[ "WhatHeSaid" ].value ) - assert_equal( 'He said "Yes"', d.elements[1].text ) - end + # Contributed (not only test, but bug fix!!) by Kouhei Sutou + def test_entity_replacement + source = %q{<!DOCTYPE foo [ + <!ENTITY % YN '"Yes"'> + <!ENTITY WhatHeSaid "He said %YN;">]> + <a>&WhatHeSaid;</a>} + + d = REXML::Document.new( source ) + dt = d.doctype + assert_equal( '"Yes"', dt.entities[ "YN" ].value ) + assert_equal( 'He said "Yes"', dt.entities[ "WhatHeSaid" ].value ) + assert_equal( 'He said "Yes"', d.elements[1].text ) + end - # More unit tests from Kouhei. I looove users who give me unit tests. - def test_entity_insertions - assert_equal("&", REXML::Text.new("&", false, nil, true).to_s) - #assert_equal("&", REXML::Text.new("&", false, false).to_s) - end + # More unit tests from Kouhei. I looove users who give me unit tests. + def test_entity_insertions + assert_equal("&", REXML::Text.new("&", false, nil, true).to_s) + #assert_equal("&", REXML::Text.new("&", false, false).to_s) + end - def test_single_pass_unnormalization # ticket 123 - assert_equal '&&', REXML::Text::unnormalize('&amp;&') - end + def test_single_pass_unnormalization # ticket 123 + assert_equal '&&', REXML::Text::unnormalize('&amp;&') + end - def test_entity_filter - document = REXML::Document.new(<<-XML) + def test_entity_filter + document = REXML::Document.new(<<-XML) <!DOCTYPE root [ <!ENTITY copy "(c)"> <!ENTITY release-year "2013"> ]> <root/> XML - respect_whitespace = false - parent = document.root - raw = false - entity_filter = ["copy"] - assert_equal("(c) &release-year;", - REXML::Text.new("(c) 2013", - respect_whitespace, - parent, - raw, - entity_filter).to_s) + respect_whitespace = false + parent = document.root + raw = false + entity_filter = ["copy"] + assert_equal("(c) &release-year;", + REXML::Text.new("(c) 2013", + respect_whitespace, + parent, + raw, + entity_filter).to_s) + end end end -end diff --git a/test/rexml/test_functions.rb b/test/rexml/test_functions.rb index da9a986bd9..bf501ff0c2 100644 --- a/test/rexml/test_functions.rb +++ b/test/rexml/test_functions.rb @@ -3,222 +3,222 @@ require "test/unit/testcase" require "rexml/document" module REXMLTests -class FunctionsTester < Test::Unit::TestCase - include REXML - def test_functions - # trivial text() test - # confuse-a-function - source = "<a>more <b id='1'/><b id='2'>dumb</b><b id='3'/><c/> text</a>" - doc = Document.new source - res = "" - XPath::each(doc.root, "text()") {|val| res << val.to_s} - assert_equal "more text", res - - res = XPath::first(doc.root, "b[last()]") - assert_equal '3', res.attributes['id'] - res = XPath::first(doc.root, "b[position()=2]") - assert_equal '2', res.attributes['id'] - res = XPath::first(doc.root, "*[name()='c']") - assert_equal "c", res.name - end + class FunctionsTester < Test::Unit::TestCase + include REXML + def test_functions + # trivial text() test + # confuse-a-function + source = "<a>more <b id='1'/><b id='2'>dumb</b><b id='3'/><c/> text</a>" + doc = Document.new source + res = "" + XPath::each(doc.root, "text()") {|val| res << val.to_s} + assert_equal "more text", res + + res = XPath::first(doc.root, "b[last()]") + assert_equal '3', res.attributes['id'] + res = XPath::first(doc.root, "b[position()=2]") + assert_equal '2', res.attributes['id'] + res = XPath::first(doc.root, "*[name()='c']") + assert_equal "c", res.name + end - # Contributed by Mike Stok - def test_starts_with - source = <<-EOF - <foo> - <a href="mailto:a@b.c">a@b.c</a> - <a href="http://www.foo.com">http://www.foo.com</a> - </foo> - EOF - doc = Document.new source - mailtos = doc.elements.to_a("//a[starts-with(@href, 'mailto:')]") - assert_equal 1, mailtos.size - assert_equal "mailto:a@b.c", mailtos[0].attributes['href'] - - ailtos = doc.elements.to_a("//a[starts-with(@href, 'ailto:')]") - assert_equal 0, ailtos.size - end + # Contributed by Mike Stok + def test_starts_with + source = <<-EOF + <foo> + <a href="mailto:a@b.c">a@b.c</a> + <a href="http://www.foo.com">http://www.foo.com</a> + </foo> + EOF + doc = Document.new source + mailtos = doc.elements.to_a("//a[starts-with(@href, 'mailto:')]") + assert_equal 1, mailtos.size + assert_equal "mailto:a@b.c", mailtos[0].attributes['href'] + + ailtos = doc.elements.to_a("//a[starts-with(@href, 'ailto:')]") + assert_equal 0, ailtos.size + end - def test_string_length - doc = Document.new <<-EOF - <AAA> - <Q/> - <SSSS/> - <BB/> - <CCC/> - <DDDDDDDD/> - <EEEE/> - </AAA> - EOF - assert doc, "create doc" - - set = doc.elements.to_a("//*[string-length(name()) = 3]") - assert_equal 2, set.size, "nodes with names length = 3" - - set = doc.elements.to_a("//*[string-length(name()) < 3]") - assert_equal 2, set.size, "nodes with names length < 3" - - set = doc.elements.to_a("//*[string-length(name()) > 3]") - assert_equal 3, set.size, "nodes with names length > 3" - end + def test_string_length + doc = Document.new <<-EOF + <AAA> + <Q/> + <SSSS/> + <BB/> + <CCC/> + <DDDDDDDD/> + <EEEE/> + </AAA> + EOF + assert doc, "create doc" + + set = doc.elements.to_a("//*[string-length(name()) = 3]") + assert_equal 2, set.size, "nodes with names length = 3" + + set = doc.elements.to_a("//*[string-length(name()) < 3]") + assert_equal 2, set.size, "nodes with names length < 3" + + set = doc.elements.to_a("//*[string-length(name()) > 3]") + assert_equal 3, set.size, "nodes with names length > 3" + end - # Test provided by Mike Stok - def test_contains - source = <<-EOF - <foo> - <a href="mailto:a@b.c">a@b.c</a> - <a href="http://www.foo.com">http://www.foo.com</a> - </foo> - EOF - doc = Document.new source - - [['o', 2], ['foo', 1], ['bar', 0]].each { |test| - search, expected = test - set = doc.elements.to_a("//a[contains(@href, '#{search}')]") - assert_equal expected, set.size - } - end + # Test provided by Mike Stok + def test_contains + source = <<-EOF + <foo> + <a href="mailto:a@b.c">a@b.c</a> + <a href="http://www.foo.com">http://www.foo.com</a> + </foo> + EOF + doc = Document.new source + + [['o', 2], ['foo', 1], ['bar', 0]].each { |test| + search, expected = test + set = doc.elements.to_a("//a[contains(@href, '#{search}')]") + assert_equal expected, set.size + } + end - # Mike Stok and Sean Russell - def test_substring - # examples from http://www.w3.org/TR/xpath#function-substring - doc = Document.new('<test string="12345" />') - - #puts XPath.first(d, 'node()[0 + 1]') - #d = Document.new("<a b='1'/>") - #puts XPath.first(d, 'a[0 mod 0]') - [ [1.5, 2.6, '234'], - [0, 3, '12'], - [0, '0 div 0', ''], - [1, '0 div 0', ''], - ['-42', '1 div 0', '12345'], - ['-1 div 0', '1 div 0', ''] - ].each { |start, length, expected| - set = doc.elements.to_a("//test[substring(@string, #{start}, #{length}) = '#{expected}']") - assert_equal 1, set.size, "#{start}, #{length}, '#{expected}'" - } - end + # Mike Stok and Sean Russell + def test_substring + # examples from http://www.w3.org/TR/xpath#function-substring + doc = Document.new('<test string="12345" />') + + #puts XPath.first(d, 'node()[0 + 1]') + #d = Document.new("<a b='1'/>") + #puts XPath.first(d, 'a[0 mod 0]') + [ [1.5, 2.6, '234'], + [0, 3, '12'], + [0, '0 div 0', ''], + [1, '0 div 0', ''], + ['-42', '1 div 0', '12345'], + ['-1 div 0', '1 div 0', ''] + ].each { |start, length, expected| + set = doc.elements.to_a("//test[substring(@string, #{start}, #{length}) = '#{expected}']") + assert_equal 1, set.size, "#{start}, #{length}, '#{expected}'" + } + end - def test_substring_angrez - testString = REXML::Functions::substring_after("helloworld","hello") - assert_equal( 'world', testString ) - end + def test_substring_angrez + testString = REXML::Functions::substring_after("helloworld","hello") + assert_equal( 'world', testString ) + end - def test_translate - source = <<-EOF - <doc> - <case name='w3c one' result='BAr' /> <!-- w3c --> - <case name='w3c two' result='AAA' /> <!-- w3c --> - <case name='alchemy' result="gold" /> <!-- mike --> - <case name='vbxml one' result='A Space Odyssey' /> - <case name='vbxml two' result='AbCdEf' /> - </doc> - EOF - - doc = Document.new(source) - - [ ['bar', 'abc', 'ABC', 'w3c one'], - ['--aaa--','abc-','ABC', 'w3c two'], - ['lead', 'dear language', 'doll groover', 'alchemy'], - ['A Space Odissei', 'i', 'y', 'vbxml one'], - ['abcdefg', 'aceg', 'ACE', 'vbxml two'], - ].each { |arg1, arg2, arg3, name| - translate = "translate('#{arg1}', '#{arg2}', '#{arg3}')" - set = doc.elements.to_a("//case[@result = #{translate}]") - assert_equal 1, set.size, translate - assert_equal name, set[0].attributes['name'] - } - end + def test_translate + source = <<-EOF + <doc> + <case name='w3c one' result='BAr' /> <!-- w3c --> + <case name='w3c two' result='AAA' /> <!-- w3c --> + <case name='alchemy' result="gold" /> <!-- mike --> + <case name='vbxml one' result='A Space Odyssey' /> + <case name='vbxml two' result='AbCdEf' /> + </doc> + EOF + + doc = Document.new(source) + + [ ['bar', 'abc', 'ABC', 'w3c one'], + ['--aaa--','abc-','ABC', 'w3c two'], + ['lead', 'dear language', 'doll groover', 'alchemy'], + ['A Space Odissei', 'i', 'y', 'vbxml one'], + ['abcdefg', 'aceg', 'ACE', 'vbxml two'], + ].each { |arg1, arg2, arg3, name| + translate = "translate('#{arg1}', '#{arg2}', '#{arg3}')" + set = doc.elements.to_a("//case[@result = #{translate}]") + assert_equal 1, set.size, translate + assert_equal name, set[0].attributes['name'] + } + end - def test_name - d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") - assert_equal 1, d.root.elements.to_a('*[name() = "b"]').size - assert_equal 1, d.elements.to_a('//*[name() = "x:b"]').size - end + def test_name + d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") + assert_equal 1, d.root.elements.to_a('*[name() = "b"]').size + assert_equal 1, d.elements.to_a('//*[name() = "x:b"]').size + end - def test_local_name - d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") - assert_equal 2, d.root.elements.to_a('*[local_name() = "b"]').size - assert_equal 2, d.elements.to_a('//*[local_name() = "b"]').size - end + def test_local_name + d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") + assert_equal 2, d.root.elements.to_a('*[local_name() = "b"]').size + assert_equal 2, d.elements.to_a('//*[local_name() = "b"]').size + end - def test_substring2 - doc = Document.new('<test string="12345" />') - assert_equal(1,doc.elements.to_a("//test[substring(@string,2)='2345']").size) - end + def test_substring2 + doc = Document.new('<test string="12345" />') + assert_equal(1,doc.elements.to_a("//test[substring(@string,2)='2345']").size) + end - # Submitted by Kouhei - def test_floor_ceiling_round - source = "<a><b id='1'/><b id='2'/><b id='3'/></a>" - doc = REXML::Document.new(source) - - id_1 = doc.elements["/a/b[@id='1']"] - id_2 = doc.elements["/a/b[@id='2']"] - id_3 = doc.elements["/a/b[@id='3']"] - - good = { - "floor" => [[], [id_1], [id_2], [id_3]], - "ceiling" => [[id_1], [id_2], [id_3], []], - "round" => [[id_1], [id_2], [id_3], []] - } - good.each do |key, value| - (0..3).each do |i| - xpath = "//b[number(@id) = #{key}(#{i+0.5})]" - assert_equal(value[i], REXML::XPath.match(doc, xpath)) + # Submitted by Kouhei + def test_floor_ceiling_round + source = "<a><b id='1'/><b id='2'/><b id='3'/></a>" + doc = REXML::Document.new(source) + + id_1 = doc.elements["/a/b[@id='1']"] + id_2 = doc.elements["/a/b[@id='2']"] + id_3 = doc.elements["/a/b[@id='3']"] + + good = { + "floor" => [[], [id_1], [id_2], [id_3]], + "ceiling" => [[id_1], [id_2], [id_3], []], + "round" => [[id_1], [id_2], [id_3], []] + } + good.each do |key, value| + (0..3).each do |i| + xpath = "//b[number(@id) = #{key}(#{i+0.5})]" + assert_equal(value[i], REXML::XPath.match(doc, xpath)) + end end - end - good["round"] = [[], [id_1], [id_2], [id_3]] - good.each do |key, value| - (0..3).each do |i| - xpath = "//b[number(@id) = #{key}(#{i+0.4})]" - assert_equal(value[i], REXML::XPath.match(doc, xpath)) + good["round"] = [[], [id_1], [id_2], [id_3]] + good.each do |key, value| + (0..3).each do |i| + xpath = "//b[number(@id) = #{key}(#{i+0.4})]" + assert_equal(value[i], REXML::XPath.match(doc, xpath)) + end end end - end - # Submitted by Kou - def test_lang - d = Document.new(<<-XML) - <a xml:lang="en"> - <b xml:lang="ja"> - <c xml:lang="fr"/> - <d/> - <e xml:lang="ja-JP"/> - <f xml:lang="en-US"/> - </b> - </a> - XML - - assert_equal(1, d.elements.to_a("//*[lang('fr')]").size) - assert_equal(3, d.elements.to_a("//*[lang('ja')]").size) - assert_equal(2, d.elements.to_a("//*[lang('en')]").size) - assert_equal(1, d.elements.to_a("//*[lang('en-us')]").size) - - d = Document.new(<<-XML) - <root> - <para xml:lang="en"/> - <div xml:lang="en"><para/></div> - <para xml:lang="EN"/> - <para xml:lang="en-us"/> - </root> - XML - - assert_equal(5, d.elements.to_a("//*[lang('en')]").size) - end + # Submitted by Kou + def test_lang + d = Document.new(<<-XML) + <a xml:lang="en"> + <b xml:lang="ja"> + <c xml:lang="fr"/> + <d/> + <e xml:lang="ja-JP"/> + <f xml:lang="en-US"/> + </b> + </a> + XML + + assert_equal(1, d.elements.to_a("//*[lang('fr')]").size) + assert_equal(3, d.elements.to_a("//*[lang('ja')]").size) + assert_equal(2, d.elements.to_a("//*[lang('en')]").size) + assert_equal(1, d.elements.to_a("//*[lang('en-us')]").size) + + d = Document.new(<<-XML) + <root> + <para xml:lang="en"/> + <div xml:lang="en"><para/></div> + <para xml:lang="EN"/> + <para xml:lang="en-us"/> + </root> + XML + + assert_equal(5, d.elements.to_a("//*[lang('en')]").size) + end - def test_ticket_60 - document = REXML::Document.new("<a><b>A</b><b>1</b></a>") - assert_equal( "A", REXML::XPath.first(document, '//b[.="A"]').text ) - assert_equal( "1", REXML::XPath.first(document, '//b[.="1"]').text ) - end + def test_ticket_60 + document = REXML::Document.new("<a><b>A</b><b>1</b></a>") + assert_equal( "A", REXML::XPath.first(document, '//b[.="A"]').text ) + assert_equal( "1", REXML::XPath.first(document, '//b[.="1"]').text ) + end - def test_normalize_space - source = "<a><!--COMMENT A--><b><!-- COMMENT A --></b></a>" - doc = REXML::Document.new(source) - predicate = "string(.)=normalize_space('\nCOMMENT \n A \n\n ')" - m = REXML::XPath.match(doc, "//comment()[#{predicate}]") - assert_equal( [REXML::Comment.new("COMMENT A")], m ) + def test_normalize_space + source = "<a><!--COMMENT A--><b><!-- COMMENT A --></b></a>" + doc = REXML::Document.new(source) + predicate = "string(.)=normalize_space('\nCOMMENT \n A \n\n ')" + m = REXML::XPath.match(doc, "//comment()[#{predicate}]") + assert_equal( [REXML::Comment.new("COMMENT A")], m ) + end end end -end diff --git a/test/rexml/test_functions_number.rb b/test/rexml/test_functions_number.rb index c2124a508d..0b5ec92f6c 100644 --- a/test/rexml/test_functions_number.rb +++ b/test/rexml/test_functions_number.rb @@ -3,32 +3,32 @@ require 'test/unit' require 'rexml/functions' module REXMLTests -class TC_Rexml_Functions_Number < Test::Unit::TestCase + class TC_Rexml_Functions_Number < Test::Unit::TestCase - def test_functions_number_int - telem = REXML::Element.new("elem") - telem.text="9" - assert_equal(9, REXML::Functions::number(telem)) + def test_functions_number_int + telem = REXML::Element.new("elem") + telem.text="9" + assert_equal(9, REXML::Functions::number(telem)) + end + def test_functions_number_float + telem = REXML::Element.new("elem") + telem.text="10.4" + assert_equal(10.4, REXML::Functions::number(telem)) + end + def test_functions_number_negative_int + telem = REXML::Element.new("elem") + telem.text="-9" + assert_equal(-9, REXML::Functions::number(telem)) + end + def test_functions_number_negative_float + telem = REXML::Element.new("elem") + telem.text="-9.13" + assert_equal(-9.13, REXML::Functions::number(telem)) + end + #def test_functions_number_scientific_notation + # telem = REXML::Element.new("elem") + # telem.text="9.13E12" + # assert_equal(9.13E12, REXML::Functions::number(telem)) + #end end - def test_functions_number_float - telem = REXML::Element.new("elem") - telem.text="10.4" - assert_equal(10.4, REXML::Functions::number(telem)) - end - def test_functions_number_negative_int - telem = REXML::Element.new("elem") - telem.text="-9" - assert_equal(-9, REXML::Functions::number(telem)) - end - def test_functions_number_negative_float - telem = REXML::Element.new("elem") - telem.text="-9.13" - assert_equal(-9.13, REXML::Functions::number(telem)) - end - #def test_functions_number_scientific_notation - # telem = REXML::Element.new("elem") - # telem.text="9.13E12" - # assert_equal(9.13E12, REXML::Functions::number(telem)) - #end -end end diff --git a/test/rexml/test_jaxen.rb b/test/rexml/test_jaxen.rb index a5053aac64..ab66139cb0 100644 --- a/test/rexml/test_jaxen.rb +++ b/test/rexml/test_jaxen.rb @@ -7,122 +7,122 @@ require "rexml/xpath" # ryan.a.cox@gmail.com module REXMLTests -class JaxenTester < Test::Unit::TestCase - include REXMLTestUtils - include REXML + class JaxenTester < Test::Unit::TestCase + include REXMLTestUtils + include REXML - def test_axis ; test("axis") ; end - def test_basic ; test("basic") ; end - def test_basicupdate ; test("basicupdate") ; end - def test_contents ; test("contents") ; end - def test_defaultNamespace ; test("defaultNamespace") ; end - def test_fibo ; test("fibo") ; end - def test_id ; test("id") ; end - def test_jaxen24 ; test("jaxen24") ; end - def test_lang ; test("lang") ; end - def test_message ; test("message") ; end - def test_moreover ; test("moreover") ; end - def test_much_ado ; test("much_ado") ; end - def test_namespaces ; test("namespaces") ; end - def test_nitf ; test("nitf") ; end - def test_numbers ; test("numbers") ; end - def test_pi ; test("pi") ; end - def test_pi2 ; test("pi2") ; end - def test_simple ; test("simple") ; end - def test_testNamespaces ; test("testNamespaces") ; end - def test_text ; test("text") ; end - def test_underscore ; test("underscore") ; end - def test_web ; test("web") ; end - def test_web2 ; test("web2") ; end + def test_axis ; test("axis") ; end + def test_basic ; test("basic") ; end + def test_basicupdate ; test("basicupdate") ; end + def test_contents ; test("contents") ; end + def test_defaultNamespace ; test("defaultNamespace") ; end + def test_fibo ; test("fibo") ; end + def test_id ; test("id") ; end + def test_jaxen24 ; test("jaxen24") ; end + def test_lang ; test("lang") ; end + def test_message ; test("message") ; end + def test_moreover ; test("moreover") ; end + def test_much_ado ; test("much_ado") ; end + def test_namespaces ; test("namespaces") ; end + def test_nitf ; test("nitf") ; end + def test_numbers ; test("numbers") ; end + def test_pi ; test("pi") ; end + def test_pi2 ; test("pi2") ; end + def test_simple ; test("simple") ; end + def test_testNamespaces ; test("testNamespaces") ; end + def test_text ; test("text") ; end + def test_underscore ; test("underscore") ; end + def test_web ; test("web") ; end + def test_web2 ; test("web2") ; end - private - def test( fname ) -# Dir.entries( xml_dir ).each { |fname| -# if fname =~ /\.xml$/ - file = File.new(fixture_path(fname+".xml")) - doc = Document.new( file ) - XPath.each( doc, "/tests/document" ) {|e| handleDocument(e)} -# end -# } - end + private + def test( fname ) +# Dir.entries( xml_dir ).each { |fname| +# if fname =~ /\.xml$/ + file = File.new(fixture_path(fname+".xml")) + doc = Document.new( file ) + XPath.each( doc, "/tests/document" ) {|e| handleDocument(e)} +# end +# } + end - # processes a tests/document/context node - def handleContext( testDoc, ctxElement) - testCtx = XPath.match( testDoc, ctxElement.attributes["select"] )[0] - namespaces = {} - if testCtx.class == Element - testCtx.prefixes.each { |pre| handleNamespace( testCtx, pre, namespaces ) } + # processes a tests/document/context node + def handleContext( testDoc, ctxElement) + testCtx = XPath.match( testDoc, ctxElement.attributes["select"] )[0] + namespaces = {} + if testCtx.class == Element + testCtx.prefixes.each { |pre| handleNamespace( testCtx, pre, namespaces ) } + end + variables = {} + XPath.each( ctxElement, "@*[namespace-uri() = 'http://jaxen.org/test-harness/var']") { |attrib| handleVariable(testCtx, variables, attrib) } + XPath.each( ctxElement, "valueOf") { |e| handleValueOf(testCtx, variables, namespaces, e) } + XPath.each( ctxElement, "test[not(@exception) or (@exception != 'true') ]") { |e| handleNominalTest(testCtx,variables, namespaces, e) } + XPath.each( ctxElement, "test[@exception = 'true']") { |e| handleExceptionalTest(testCtx,variables, namespaces, e) } end - variables = {} - XPath.each( ctxElement, "@*[namespace-uri() = 'http://jaxen.org/test-harness/var']") { |attrib| handleVariable(testCtx, variables, attrib) } - XPath.each( ctxElement, "valueOf") { |e| handleValueOf(testCtx, variables, namespaces, e) } - XPath.each( ctxElement, "test[not(@exception) or (@exception != 'true') ]") { |e| handleNominalTest(testCtx,variables, namespaces, e) } - XPath.each( ctxElement, "test[@exception = 'true']") { |e| handleExceptionalTest(testCtx,variables, namespaces, e) } - end - # processes a tests/document/context/valueOf or tests/document/context/test/valueOf node - def handleValueOf(ctx,variables, namespaces, valueOfElement) - expected = valueOfElement.text - got = XPath.match( ctx, valueOfElement.attributes["select"], namespaces, variables )[0] - assert_true( (got.nil? && expected.nil?) || !got.nil? ) - case got.class - when Element - assert_equal( got.class, Element ) - when Attribute, Text, Comment, TrueClass, FalseClass - assert_equal( expected, got.to_s ) - when Instruction - assert_equal( expected, got.content ) - when Fixnum - assert_equal( exected.to_f, got ) - when String - # normalize values for comparison - got = "" if got == nil or got == "" - expected = "" if expected == nil or expected == "" - assert_equal( expected, got ) - else - assert_fail( "Wassup?" ) + # processes a tests/document/context/valueOf or tests/document/context/test/valueOf node + def handleValueOf(ctx,variables, namespaces, valueOfElement) + expected = valueOfElement.text + got = XPath.match( ctx, valueOfElement.attributes["select"], namespaces, variables )[0] + assert_true( (got.nil? && expected.nil?) || !got.nil? ) + case got.class + when Element + assert_equal( got.class, Element ) + when Attribute, Text, Comment, TrueClass, FalseClass + assert_equal( expected, got.to_s ) + when Instruction + assert_equal( expected, got.content ) + when Fixnum + assert_equal( exected.to_f, got ) + when String + # normalize values for comparison + got = "" if got == nil or got == "" + expected = "" if expected == nil or expected == "" + assert_equal( expected, got ) + else + assert_fail( "Wassup?" ) + end end - end - # processes a tests/document/context/test node ( where @exception is false or doesn't exist ) - def handleNominalTest(ctx, variables, namespaces, testElement) - expected = testElement.attributes["count"] - got = XPath.match( ctx, testElement.attributes["select"], namespaces, variables ) - # might be a test with no count attribute, but nested valueOf elements - assert( expected == got.size.to_s ) if !expected.nil? + # processes a tests/document/context/test node ( where @exception is false or doesn't exist ) + def handleNominalTest(ctx, variables, namespaces, testElement) + expected = testElement.attributes["count"] + got = XPath.match( ctx, testElement.attributes["select"], namespaces, variables ) + # might be a test with no count attribute, but nested valueOf elements + assert( expected == got.size.to_s ) if !expected.nil? - XPath.each( testElement, "valueOf") { |e| - handleValueOf(got, variables, namespaces, e) - } - end + XPath.each( testElement, "valueOf") { |e| + handleValueOf(got, variables, namespaces, e) + } + end - # processes a tests/document/context/test node ( where @exception is true ) - def handleExceptionalTest(ctx, variables, namespaces, testElement) - assert_raise( Exception ) { - XPath.match( ctx, testElement.attributes["select"], namespaces, variables ) - } - end + # processes a tests/document/context/test node ( where @exception is true ) + def handleExceptionalTest(ctx, variables, namespaces, testElement) + assert_raise( Exception ) { + XPath.match( ctx, testElement.attributes["select"], namespaces, variables ) + } + end - # processes a tests/document node - def handleDocument(docElement) - puts "- Processing document: #{docElement.attributes['url']}" - testFile = File.new( docElement.attributes["url"] ) - testDoc = Document.new testFile - XPath.each( docElement, "context") { |e| handleContext(testDoc, e) } - end + # processes a tests/document node + def handleDocument(docElement) + puts "- Processing document: #{docElement.attributes['url']}" + testFile = File.new( docElement.attributes["url"] ) + testDoc = Document.new testFile + XPath.each( docElement, "context") { |e| handleContext(testDoc, e) } + end - # processes a variable definition in a namespace like <test var:foo="bar"> - def handleVariable( ctx, variables, attrib ) - puts "--- Found attribute: #{attrib.name}" - variables[attrib.name] = attrib.value - end + # processes a variable definition in a namespace like <test var:foo="bar"> + def handleVariable( ctx, variables, attrib ) + puts "--- Found attribute: #{attrib.name}" + variables[attrib.name] = attrib.value + end - # processes a namespace definition like <test xmlns:foo="fiz:bang:bam"> - def handleNamespace( ctx, prefix, namespaces ) - puts "--- Found namespace: #{prefix}" - namespaces[prefix] = ctx.namespaces[prefix] - end + # processes a namespace definition like <test xmlns:foo="fiz:bang:bam"> + def handleNamespace( ctx, prefix, namespaces ) + puts "--- Found namespace: #{prefix}" + namespaces[prefix] = ctx.namespaces[prefix] + end -end + end end diff --git a/test/rexml/test_light.rb b/test/rexml/test_light.rb index c47b9a60b1..b775eb79e9 100644 --- a/test/rexml/test_light.rb +++ b/test/rexml/test_light.rb @@ -3,104 +3,104 @@ require "rexml/light/node" require "rexml/parsers/lightparser" module REXMLTests -class LightTester < Test::Unit::TestCase - include REXMLTestUtils - include REXML::Light + class LightTester < Test::Unit::TestCase + include REXMLTestUtils + include REXML::Light - def test_parse_large - xml_string = fixture_path("documentation.xml") - parser = REXML::Parsers::LightParser.new(xml_string) - tag, content = parser.parse - assert_equal([:document, :text], [tag, content.first]) - end + def test_parse_large + xml_string = fixture_path("documentation.xml") + parser = REXML::Parsers::LightParser.new(xml_string) + tag, content = parser.parse + assert_equal([:document, :text], [tag, content.first]) + end - # FIXME INCOMPLETE - # This is because the light API is not yet ready to be used to produce - # trees. + # FIXME INCOMPLETE + # This is because the light API is not yet ready to be used to produce + # trees. =begin - def test_add_element - doc = Node.new - foo = doc.add_element( 'foo' ) - assert_equal( "foo", foo.name ) - end + def test_add_element + doc = Node.new + foo = doc.add_element( 'foo' ) + assert_equal( "foo", foo.name ) + end - def test_add_attribute - foo = Node.new( "a" ) - foo["attr"] = "bar" - assert_equal( "bar", foo["attr"] ) - end + def test_add_attribute + foo = Node.new( "a" ) + foo["attr"] = "bar" + assert_equal( "bar", foo["attr"] ) + end - def test_write_document - r = make_small_document - assert_equal( "<a><b/><c/></a>", r.to_s ) - end + def test_write_document + r = make_small_document + assert_equal( "<a><b/><c/></a>", r.to_s ) + end - def test_add_attribute_under_namespace - foo = Node.new("a") - foo["attr", "a"] = "1" - foo["attr", "b"] = "2" - foo["attr"] = "3" - assert_equal( '1', foo['attr', 'a'] ) - assert_equal( '2', foo['attr', 'b'] ) - assert_equal( '3', foo['attr'] ) - end + def test_add_attribute_under_namespace + foo = Node.new("a") + foo["attr", "a"] = "1" + foo["attr", "b"] = "2" + foo["attr"] = "3" + assert_equal( '1', foo['attr', 'a'] ) + assert_equal( '2', foo['attr', 'b'] ) + assert_equal( '3', foo['attr'] ) + end - def test_change_namespace_of_element - foo = Node.new - assert_equal( '', foo.namespace ) - foo.namespace = 'a' - assert_equal( 'a', foo.namespace ) - end + def test_change_namespace_of_element + foo = Node.new + assert_equal( '', foo.namespace ) + foo.namespace = 'a' + assert_equal( 'a', foo.namespace ) + end - def test_access_child_elements - foo = make_small_document - assert_equal( 1, foo.size ) - a = foo[0] - assert_equal( 2, a.size ) - assert_equal( 'b', a[0].name ) - assert_equal( 'c', a[1].name ) - end + def test_access_child_elements + foo = make_small_document + assert_equal( 1, foo.size ) + a = foo[0] + assert_equal( 2, a.size ) + assert_equal( 'b', a[0].name ) + assert_equal( 'c', a[1].name ) + end - def test_itterate_over_children - foo = make_small_document - ctr = 0 - foo[0].each { ctr += 1 } - assert_equal( 2, ctr ) - end + def test_itterate_over_children + foo = make_small_document + ctr = 0 + foo[0].each { ctr += 1 } + assert_equal( 2, ctr ) + end - def test_add_text - foo = Node.new( "a" ) - foo.add_text( "Sean" ) - sean = foo[0] - assert( sean.node_type == :text ) - end + def test_add_text + foo = Node.new( "a" ) + foo.add_text( "Sean" ) + sean = foo[0] + assert( sean.node_type == :text ) + end - def test_add_instruction - foo = Node.new( "a" ) - foo.add_instruction( "target", "value" ) - assert( foo[0].node_type == :processing_instruction ) - end + def test_add_instruction + foo = Node.new( "a" ) + foo.add_instruction( "target", "value" ) + assert( foo[0].node_type == :processing_instruction ) + end - def test_add_comment - foo = Node.new( "a" ) - foo.add_comment( "target", "value" ) - assert( foo[0].node_type == :comment ) - end + def test_add_comment + foo = Node.new( "a" ) + foo.add_comment( "target", "value" ) + assert( foo[0].node_type == :comment ) + end - def test_get_root - foo = Node.new( 'a' ) - 10.times { foo = foo.add_element('b') } - assert_equals( 'b', foo.name ) - assert_equals( 'a', foo.root.name ) - end + def test_get_root + foo = Node.new( 'a' ) + 10.times { foo = foo.add_element('b') } + assert_equals( 'b', foo.name ) + assert_equals( 'a', foo.root.name ) + end - def make_small_document - r = Node.new - a = r.add_element( "a" ) - a.add_element( 'b' ) - a.add_element( 'c' ) - r - end + def make_small_document + r = Node.new + a = r.add_element( "a" ) + a.add_element( 'b' ) + a.add_element( 'c' ) + r + end =end -end + end end diff --git a/test/rexml/test_lightparser.rb b/test/rexml/test_lightparser.rb index d492e0b456..4aa465b9fa 100644 --- a/test/rexml/test_lightparser.rb +++ b/test/rexml/test_lightparser.rb @@ -2,13 +2,13 @@ require_relative 'rexml_test_utils' require 'rexml/parsers/lightparser' module REXMLTests -class LightParserTester < Test::Unit::TestCase - include REXMLTestUtils - include REXML - def test_parsing - f = File.new(fixture_path("documentation.xml")) - parser = REXML::Parsers::LightParser.new( f ) - parser.parse + class LightParserTester < Test::Unit::TestCase + include REXMLTestUtils + include REXML + def test_parsing + f = File.new(fixture_path("documentation.xml")) + parser = REXML::Parsers::LightParser.new( f ) + parser.parse + end end end -end diff --git a/test/rexml/test_listener.rb b/test/rexml/test_listener.rb index 3d5c17e858..ea84e0edf5 100644 --- a/test/rexml/test_listener.rb +++ b/test/rexml/test_listener.rb @@ -6,126 +6,126 @@ require 'rexml/document' require 'rexml/streamlistener' module REXMLTests -class BaseTester < Test::Unit::TestCase - include REXMLTestUtils - def test_empty - return unless defined? @listener - # Empty. - t1 = %Q{<string></string>} - assert_equal( "", @listener.parse( t1 ), - "Empty" ) - end - - def test_space - return unless defined? @listener - # Space. - t2 = %Q{<string> </string>} - assert_equal( " ", @listener.parse( t2 ), - "Space" ) - end - - def test_whitespace - return unless defined? @listener - # Whitespaces. - t3 = %Q{<string>RE\n \t \n \t XML</string>} - assert_equal( "RE\n \t \n \t XML", @listener.parse( t3 ), - "Whitespaces" ) - end - - def test_leading_trailing_whitespace - return unless defined? @listener - # Leading and trailing whitespaces. - t4 = %Q{<string> REXML </string>} - assert_equal( " REXML ", @listener.parse( t4 ), - "Leading and trailing whitespaces" ) - end + class BaseTester < Test::Unit::TestCase + include REXMLTestUtils + def test_empty + return unless defined? @listener + # Empty. + t1 = %Q{<string></string>} + assert_equal( "", @listener.parse( t1 ), + "Empty" ) + end - def test_entity_reference - return unless defined? @listener - # Entity reference. - t5 = %Q{<string><>&lt;&gt;</string>} - assert_equal( "<><>", @listener.parse( t5 ), - "Entity reference" ) - end + def test_space + return unless defined? @listener + # Space. + t2 = %Q{<string> </string>} + assert_equal( " ", @listener.parse( t2 ), + "Space" ) + end - def test_character_reference - return unless defined? @listener - # Character reference. - t6 = %Q{<string>
</string>} - assert_equal( "\r", @listener.parse( t6 ), - "Character reference." ) - end + def test_whitespace + return unless defined? @listener + # Whitespaces. + t3 = %Q{<string>RE\n \t \n \t XML</string>} + assert_equal( "RE\n \t \n \t XML", @listener.parse( t3 ), + "Whitespaces" ) + end - def test_cr - return unless defined? @listener - # CR. - t7 = %Q{<string> \r\n \r \n </string>} - assert_equal( " \n \n \n ".unpack("C*").inspect, - @listener.parse( t7 ).unpack("C*").inspect, "CR" ) - end + def test_leading_trailing_whitespace + return unless defined? @listener + # Leading and trailing whitespaces. + t4 = %Q{<string> REXML </string>} + assert_equal( " REXML ", @listener.parse( t4 ), + "Leading and trailing whitespaces" ) + end - # The accent bug, and the code that exhibits the bug, was contributed by - # Guilhem Vellut - class AccentListener - def tag_start(name,attributes) - #p name - #p attributes + def test_entity_reference + return unless defined? @listener + # Entity reference. + t5 = %Q{<string><>&lt;&gt;</string>} + assert_equal( "<><>", @listener.parse( t5 ), + "Entity reference" ) end - def tag_end(name) - #p "/"+name + + def test_character_reference + return unless defined? @listener + # Character reference. + t6 = %Q{<string>
</string>} + assert_equal( "\r", @listener.parse( t6 ), + "Character reference." ) end - def xmldecl(a,b,c) - #puts "#{a} #{b} #{c}" + + def test_cr + return unless defined? @listener + # CR. + t7 = %Q{<string> \r\n \r \n </string>} + assert_equal( " \n \n \n ".unpack("C*").inspect, + @listener.parse( t7 ).unpack("C*").inspect, "CR" ) end - def text(tx) - #p tx + + # The accent bug, and the code that exhibits the bug, was contributed by + # Guilhem Vellut + class AccentListener + def tag_start(name,attributes) + #p name + #p attributes + end + def tag_end(name) + #p "/"+name + end + def xmldecl(a,b,c) + #puts "#{a} #{b} #{c}" + end + def text(tx) + #p tx + end end - end - def test_accents - source = %[<?xml version="1.0" encoding="ISO-8859-1"?> + def test_accents + source = %[<?xml version="1.0" encoding="ISO-8859-1"?> <g> <f a="\xE9" /> </g>] - doc = REXML::Document.new( source ) - a = doc.elements['/g/f'].attribute('a') - if a.value.respond_to? :force_encoding - a.value.force_encoding('binary') - end - assert_equal( "\xC3\xA9", a.value) - doc = REXML::Document.parse_stream( - File::new(fixture_path("stream_accents.xml")), - AccentListener::new - ) + doc = REXML::Document.new( source ) + a = doc.elements['/g/f'].attribute('a') + if a.value.respond_to? :force_encoding + a.value.force_encoding('binary') + end + assert_equal( "\xC3\xA9", a.value) + doc = REXML::Document.parse_stream( + File::new(fixture_path("stream_accents.xml")), + AccentListener::new + ) + end end -end -class MyREXMLListener - include REXML::StreamListener + class MyREXMLListener + include REXML::StreamListener - def initialize - @text = nil - end + def initialize + @text = nil + end - def parse( stringOrReadable ) - @text = "" - REXML::Document.parse_stream( stringOrReadable, self ) - @text - end + def parse( stringOrReadable ) + @text = "" + REXML::Document.parse_stream( stringOrReadable, self ) + @text + end - def text( text ) - @text << text + def text( text ) + @text << text + end end -end -class REXMLTester < BaseTester - def setup - @listener = MyREXMLListener.new - end + class REXMLTester < BaseTester + def setup + @listener = MyREXMLListener.new + end - def test_character_reference_2 - t6 = %Q{<string>
</string>} - assert_equal( t6.strip, REXML::Document.new(t6).to_s ) + def test_character_reference_2 + t6 = %Q{<string>
</string>} + assert_equal( t6.strip, REXML::Document.new(t6).to_s ) + end end end -end diff --git a/test/rexml/test_martin_fowler.rb b/test/rexml/test_martin_fowler.rb index 3025c74034..26db110869 100644 --- a/test/rexml/test_martin_fowler.rb +++ b/test/rexml/test_martin_fowler.rb @@ -2,8 +2,8 @@ require 'test/unit' require 'rexml/document' module REXMLTests -class OrderTester < Test::Unit::TestCase - DOC = <<END + class OrderTester < Test::Unit::TestCase + DOC = <<END <paper> <title>Remove this element and figs order differently</title> <figure src="fig1"/> @@ -17,23 +17,23 @@ class OrderTester < Test::Unit::TestCase </paper> END - def initialize n - @doc = REXML::Document.new(DOC) - @figs = REXML::XPath.match(@doc,'//figure') - @names = @figs.collect {|f| f.attributes['src']} - super + def initialize n + @doc = REXML::Document.new(DOC) + @figs = REXML::XPath.match(@doc,'//figure') + @names = @figs.collect {|f| f.attributes['src']} + super + end + def test_fig1 + assert_equal 'fig1', @figs[0].attributes['src'] + end + def test_fig2 + assert_equal 'fig2', @figs[1].attributes['src'] + end + def test_fig3 + assert_equal 'fig3', @figs[2].attributes['src'] + end + def test_fig4 + assert_equal 'fig4', @figs[3].attributes['src'] + end end - def test_fig1 - assert_equal 'fig1', @figs[0].attributes['src'] - end - def test_fig2 - assert_equal 'fig2', @figs[1].attributes['src'] - end - def test_fig3 - assert_equal 'fig3', @figs[2].attributes['src'] - end - def test_fig4 - assert_equal 'fig4', @figs[3].attributes['src'] - end -end end diff --git a/test/rexml/test_namespace.rb b/test/rexml/test_namespace.rb index 01d496f926..f5cd294568 100644 --- a/test/rexml/test_namespace.rb +++ b/test/rexml/test_namespace.rb @@ -3,38 +3,38 @@ require_relative "rexml_test_utils" require "rexml/document" module REXMLTests -class TestNamespace < Test::Unit::TestCase - include REXMLTestUtils - include REXML + class TestNamespace < Test::Unit::TestCase + include REXMLTestUtils + include REXML - def setup - @xsa_source = <<-EOL - <?xml version="1.0"?> - <?xsl stylesheet="blah.xsl"?> - <!-- The first line tests the XMLDecl, the second tests PI. - The next line tests DocType. This line tests comments. --> - <!DOCTYPE xsa PUBLIC - "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" - "http://www.garshol.priv.no/download/xsa/xsa.dtd"> + def setup + @xsa_source = <<-EOL + <?xml version="1.0"?> + <?xsl stylesheet="blah.xsl"?> + <!-- The first line tests the XMLDecl, the second tests PI. + The next line tests DocType. This line tests comments. --> + <!DOCTYPE xsa PUBLIC + "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" + "http://www.garshol.priv.no/download/xsa/xsa.dtd"> - <xsa> - <vendor id="blah"> - <name>Lars Marius Garshol</name> - <email>larsga@garshol.priv.no</email> - <url>http://www.stud.ifi.uio.no/~lmariusg/</url> - </vendor> - </xsa> - EOL - end + <xsa> + <vendor id="blah"> + <name>Lars Marius Garshol</name> + <email>larsga@garshol.priv.no</email> + <url>http://www.stud.ifi.uio.no/~lmariusg/</url> + </vendor> + </xsa> + EOL + end - def test_xml_namespace - xml = <<-XML + def test_xml_namespace + xml = <<-XML <?xml version="1.0" encoding="UTF-8"?> <root xmlns:xml="http://www.w3.org/XML/1998/namespace" /> XML - document = Document.new(xml) - assert_equal("http://www.w3.org/XML/1998/namespace", - document.root.namespace("xml")) + document = Document.new(xml) + assert_equal("http://www.w3.org/XML/1998/namespace", + document.root.namespace("xml")) + end end end -end diff --git a/test/rexml/test_order.rb b/test/rexml/test_order.rb index 9559c46ca4..628e75df62 100644 --- a/test/rexml/test_order.rb +++ b/test/rexml/test_order.rb @@ -6,10 +6,10 @@ rescue LoadError end module REXMLTests -class OrderTester < Test::Unit::TestCase - include REXMLTestUtils + class OrderTester < Test::Unit::TestCase + include REXMLTestUtils - TESTDOC = <<END + TESTDOC = <<END <a> <b/> <x id='1'/> @@ -21,87 +21,87 @@ class OrderTester < Test::Unit::TestCase </a> END - def setup - @doc = REXML::Document.new(TESTDOC) - @items = REXML::XPath.match(@doc,'//x') - end - def test_first_element - assert_equal '1', @items[0].attributes['id'] - end - def test_second_element - assert_equal '2', @items[1].attributes['id'] - end - def test_third_element - assert_equal '3', @items[2].attributes['id'] - end - def test_order - d = REXML::Document.new( "<a><x id='1'/><x id='2'/><x id='3'/> - <x id='4'/><x id='5'/></a>" ) - items = REXML::XPath.match( d, '//x' ) - assert_equal( %w{1 2 3 4 5}, items.collect{|e| e.attributes['id']} ) - d = REXML::Document.new( "<a> - <x><z><y id='1'/><y id='2'/></z><y id='3'/></x> - <x><y id='4'/></x></a>" ) - items = REXML::XPath.match( d, '//y' ) - assert_equal( %w{1 2 3 4}, items.collect{|e| e.attributes['id']} ) - end - # Provided by Tom Talbott - def test_more_ordering - doc = REXML::Document.new(Zlib::GzipReader.open(fixture_path('LostineRiver.kml.gz'), encoding: 'utf-8')) - actual = [ - "Head south from Phinney Ave N", - "Turn left at N 36th St", - "Turn right at Fremont Ave N", - "Continue on 4th Ave N", - "Turn left at Westlake Ave N", - "Bear right at 9th Ave N", - "Turn left at Mercer St", - "Take the I-5 ramp", - "Take the I-5 S ramp", - "Take the I-90 E exit #164 to Bellevue/Spokane/4th Ave S.", - "Take the I-90 E ramp to Bellevue/Spokane", - "Take exit #137 to Wanapum Dam/Richland", - "Bear right at WA-26", - "Bear right and head toward WA-243", - "Continue on WA-243", - "Bear right at WA-24", - "Continue on WA-240", - "Turn right at WA-240 E", - "Take the I-182 W ramp to Yakima (I-82)/Pendleton", - "Take the I-82 E ramp to Umatilla/Pendleton", - "Take the I-84 E ramp to Pendleton", - "Take the OR-82 exit #261 to La Grande/Elgin", - "Turn right at Island Ave", - "Continue on W 1st St", - "Turn left at N McAlister Rd", - "Bear right at OR-82", - "Continue on Wallowa Lake Hwy", - "Continue on OR-82", - "Continue on Ruckman Ave", - "Continue on OR-82", - "Continue on S 8th Ave", - "Turn right at Albany St", - "Continue on OR-82", - "Continue on Wallowa Lake Hwy", - "Continue on N Madison St", - "Bear left at W 1st St", - "Continue on Wallowa Lake Hwy", - "Continue on Water St", - "Bear right at Lostine River Rd", - "Bear right and head toward Lostine River Rd", - "Turn right at Lostine River Rd", - "Continue on NF-8210", - "Turn right and head toward NF-8210", - "Turn right at NF-8210", - "", - "Route" - ] - count = 0 - REXML::XPath.each( doc, "//Placemark") { |element| - n = element.elements["name"].text.squeeze(" ") - assert_equal( actual[count], n ) unless n =~ /Arrive at/ - count += 1 - } - end if defined?(Zlib::GzipReader) -end + def setup + @doc = REXML::Document.new(TESTDOC) + @items = REXML::XPath.match(@doc,'//x') + end + def test_first_element + assert_equal '1', @items[0].attributes['id'] + end + def test_second_element + assert_equal '2', @items[1].attributes['id'] + end + def test_third_element + assert_equal '3', @items[2].attributes['id'] + end + def test_order + d = REXML::Document.new( "<a><x id='1'/><x id='2'/><x id='3'/> + <x id='4'/><x id='5'/></a>" ) + items = REXML::XPath.match( d, '//x' ) + assert_equal( %w{1 2 3 4 5}, items.collect{|e| e.attributes['id']} ) + d = REXML::Document.new( "<a> + <x><z><y id='1'/><y id='2'/></z><y id='3'/></x> + <x><y id='4'/></x></a>" ) + items = REXML::XPath.match( d, '//y' ) + assert_equal( %w{1 2 3 4}, items.collect{|e| e.attributes['id']} ) + end + # Provided by Tom Talbott + def test_more_ordering + doc = REXML::Document.new(Zlib::GzipReader.open(fixture_path('LostineRiver.kml.gz'), encoding: 'utf-8')) + actual = [ + "Head south from Phinney Ave N", + "Turn left at N 36th St", + "Turn right at Fremont Ave N", + "Continue on 4th Ave N", + "Turn left at Westlake Ave N", + "Bear right at 9th Ave N", + "Turn left at Mercer St", + "Take the I-5 ramp", + "Take the I-5 S ramp", + "Take the I-90 E exit #164 to Bellevue/Spokane/4th Ave S.", + "Take the I-90 E ramp to Bellevue/Spokane", + "Take exit #137 to Wanapum Dam/Richland", + "Bear right at WA-26", + "Bear right and head toward WA-243", + "Continue on WA-243", + "Bear right at WA-24", + "Continue on WA-240", + "Turn right at WA-240 E", + "Take the I-182 W ramp to Yakima (I-82)/Pendleton", + "Take the I-82 E ramp to Umatilla/Pendleton", + "Take the I-84 E ramp to Pendleton", + "Take the OR-82 exit #261 to La Grande/Elgin", + "Turn right at Island Ave", + "Continue on W 1st St", + "Turn left at N McAlister Rd", + "Bear right at OR-82", + "Continue on Wallowa Lake Hwy", + "Continue on OR-82", + "Continue on Ruckman Ave", + "Continue on OR-82", + "Continue on S 8th Ave", + "Turn right at Albany St", + "Continue on OR-82", + "Continue on Wallowa Lake Hwy", + "Continue on N Madison St", + "Bear left at W 1st St", + "Continue on Wallowa Lake Hwy", + "Continue on Water St", + "Bear right at Lostine River Rd", + "Bear right and head toward Lostine River Rd", + "Turn right at Lostine River Rd", + "Continue on NF-8210", + "Turn right and head toward NF-8210", + "Turn right at NF-8210", + "", + "Route" + ] + count = 0 + REXML::XPath.each( doc, "//Placemark") { |element| + n = element.elements["name"].text.squeeze(" ") + assert_equal( actual[count], n ) unless n =~ /Arrive at/ + count += 1 + } + end if defined?(Zlib::GzipReader) + end end diff --git a/test/rexml/test_preceding_sibling.rb b/test/rexml/test_preceding_sibling.rb index c05eedb001..54fdd5b22e 100644 --- a/test/rexml/test_preceding_sibling.rb +++ b/test/rexml/test_preceding_sibling.rb @@ -3,38 +3,38 @@ require 'test/unit' require 'rexml/document' module REXMLTests -# daz - for report by Dan Kohn in: -# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/156328 -class XPathTesterDd < Test::Unit::TestCase - include REXML + # daz - for report by Dan Kohn in: + # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/156328 + class XPathTesterDd < Test::Unit::TestCase + include REXML - def setup - @@docDd = Document.new(<<-EOS, :ignore_whitespace_nodes => :all) - <a> - <b x='ab01A'> - <c y='abc01A'>Success</c> - </b> - <b x='ab02A' y='ab02B'> - <c>abc02C</c> - </b> - </a> - EOS - end + def setup + @@docDd = Document.new(<<-EOS, :ignore_whitespace_nodes => :all) + <a> + <b x='ab01A'> + <c y='abc01A'>Success</c> + </b> + <b x='ab02A' y='ab02B'> + <c>abc02C</c> + </b> + </a> + EOS + end - def test_Dd_preceding_sibling_children - arr = [] - XPath.each(@@docDd, "//b[@x='ab02A']/preceding-sibling::b/child::*") do |cell| - arr << cell.texts.join + def test_Dd_preceding_sibling_children + arr = [] + XPath.each(@@docDd, "//b[@x='ab02A']/preceding-sibling::b/child::*") do |cell| + arr << cell.texts.join + end + assert_equal( 'Success', arr.join ) end - assert_equal( 'Success', arr.join ) - end - def test_Dd_preceding_sibling_all - arr = [] - XPath.each(@@docDd, "//b[@x='ab02A']/preceding-sibling::*") do |cell| - arr << cell.to_s + def test_Dd_preceding_sibling_all + arr = [] + XPath.each(@@docDd, "//b[@x='ab02A']/preceding-sibling::*") do |cell| + arr << cell.to_s + end + assert_equal( "<b x='ab01A'><c y='abc01A'>Success</c></b>", arr.join ) end - assert_equal( "<b x='ab01A'><c y='abc01A'>Success</c></b>", arr.join ) end end -end diff --git a/test/rexml/test_pullparser.rb b/test/rexml/test_pullparser.rb index 83751f2a44..db336a16e5 100644 --- a/test/rexml/test_pullparser.rb +++ b/test/rexml/test_pullparser.rb @@ -3,100 +3,100 @@ require "test/unit/testcase" require 'rexml/parsers/pullparser' module REXMLTests -class PullParserTester < Test::Unit::TestCase - include REXML - def test_basics - source = '<?xml version="1.0"?> - <!DOCTYPE blah> - <a>foo <<b attribute="value">bar</b> nooo</a>' - parser = REXML::Parsers::PullParser.new(source) - res = { :text=>0 } - until parser.empty? - results = parser.pull - res[ :xmldecl ] = true if results.xmldecl? - res[ :doctype ] = true if results.doctype? - res[ :a ] = true if results.start_element? and results[0] == 'a' - if results.start_element? and results[0] == 'b' - res[ :b ] = true - assert_equal 'value', results[1]['attribute'] + class PullParserTester < Test::Unit::TestCase + include REXML + def test_basics + source = '<?xml version="1.0"?> + <!DOCTYPE blah> + <a>foo <<b attribute="value">bar</b> nooo</a>' + parser = REXML::Parsers::PullParser.new(source) + res = { :text=>0 } + until parser.empty? + results = parser.pull + res[ :xmldecl ] = true if results.xmldecl? + res[ :doctype ] = true if results.doctype? + res[ :a ] = true if results.start_element? and results[0] == 'a' + if results.start_element? and results[0] == 'b' + res[ :b ] = true + assert_equal 'value', results[1]['attribute'] + end + res[ :text ] += 1 if results.text? end - res[ :text ] += 1 if results.text? + [ :xmldecl, :doctype, :a, :b ].each { |tag| + assert res[tag] , "#{tag} wasn't processed" + } + assert_equal 4, res[ :text ] + rescue ParseException + puts $! end - [ :xmldecl, :doctype, :a, :b ].each { |tag| - assert res[tag] , "#{tag} wasn't processed" - } - assert_equal 4, res[ :text ] - rescue ParseException - puts $! - end - def test_bad_document - source = "<a><b></a>" - parser = REXML::Parsers::PullParser.new(source) - assert_raise(ParseException, "Parsing should have failed") { - parser.pull while parser.has_next? - } - end + def test_bad_document + source = "<a><b></a>" + parser = REXML::Parsers::PullParser.new(source) + assert_raise(ParseException, "Parsing should have failed") { + parser.pull while parser.has_next? + } + end - def test_entity_replacement - source = '<!DOCTYPE foo [ - <!ENTITY la "1234"> - <!ENTITY lala "--&la;--"> - <!ENTITY lalal "&la;&la;"> - ]><a><la>&la;</la><lala>&lala;</lala></a>' - pp = REXML::Parsers::PullParser.new( source ) - el_name = '' - while pp.has_next? - event = pp.pull - case event.event_type - when :start_element - el_name = event[0] - when :text - case el_name - when 'la' - assert_equal('1234', event[1]) - when 'lala' - assert_equal('--1234--', event[1]) + def test_entity_replacement + source = '<!DOCTYPE foo [ + <!ENTITY la "1234"> + <!ENTITY lala "--&la;--"> + <!ENTITY lalal "&la;&la;"> + ]><a><la>&la;</la><lala>&lala;</lala></a>' + pp = REXML::Parsers::PullParser.new( source ) + el_name = '' + while pp.has_next? + event = pp.pull + case event.event_type + when :start_element + el_name = event[0] + when :text + case el_name + when 'la' + assert_equal('1234', event[1]) + when 'lala' + assert_equal('--1234--', event[1]) + end end end end - end - def test_peek_unshift - source = "<a><b/></a>" - REXML::Parsers::PullParser.new(source) - # FINISH ME! - end + def test_peek_unshift + source = "<a><b/></a>" + REXML::Parsers::PullParser.new(source) + # FINISH ME! + end - def test_inspect - xml = '<a id="1"><b id="2">Hey</b></a>' - parser = Parsers::PullParser.new( xml ) - while parser.has_next? - pull_event = parser.pull - if pull_event.start_element? - peek = parser.peek() - peek.inspect + def test_inspect + xml = '<a id="1"><b id="2">Hey</b></a>' + parser = Parsers::PullParser.new( xml ) + while parser.has_next? + pull_event = parser.pull + if pull_event.start_element? + peek = parser.peek() + peek.inspect + end end end - end - def test_peek - xml = '<a id="1"><b id="2">Hey</b></a>' - parser = Parsers::PullParser.new( xml ) - names = %w{ a b } - while parser.has_next? - pull_event = parser.pull - if pull_event.start_element? - assert_equal( :start_element, pull_event.event_type ) - assert_equal( names.shift, pull_event[0] ) - if names[0] == 'b' - peek = parser.peek() - assert_equal( :start_element, peek.event_type ) - assert_equal( names[0], peek[0] ) + def test_peek + xml = '<a id="1"><b id="2">Hey</b></a>' + parser = Parsers::PullParser.new( xml ) + names = %w{ a b } + while parser.has_next? + pull_event = parser.pull + if pull_event.start_element? + assert_equal( :start_element, pull_event.event_type ) + assert_equal( names.shift, pull_event[0] ) + if names[0] == 'b' + peek = parser.peek() + assert_equal( :start_element, peek.event_type ) + assert_equal( names[0], peek[0] ) + end end end + assert_equal( 0, names.length ) end - assert_equal( 0, names.length ) end end -end diff --git a/test/rexml/test_rexml_issuezilla.rb b/test/rexml/test_rexml_issuezilla.rb index 59649ae090..8098646666 100644 --- a/test/rexml/test_rexml_issuezilla.rb +++ b/test/rexml/test_rexml_issuezilla.rb @@ -2,15 +2,15 @@ require_relative 'rexml_test_utils' require 'rexml/document' module REXMLTests -class TestIssuezillaParsing < Test::Unit::TestCase - include REXMLTestUtils - def test_rexml - doc = REXML::Document.new(File.new(fixture_path("ofbiz-issues-full-177.xml"))) - ctr = 1 - doc.root.each_element('//issue') do |issue| - assert_equal( ctr, issue.elements['issue_id'].text.to_i ) - ctr += 1 + class TestIssuezillaParsing < Test::Unit::TestCase + include REXMLTestUtils + def test_rexml + doc = REXML::Document.new(File.new(fixture_path("ofbiz-issues-full-177.xml"))) + ctr = 1 + doc.root.each_element('//issue') do |issue| + assert_equal( ctr, issue.elements['issue_id'].text.to_i ) + ctr += 1 + end end end end -end diff --git a/test/rexml/test_sax.rb b/test/rexml/test_sax.rb index 5cf1ec1132..f7e66951cb 100644 --- a/test/rexml/test_sax.rb +++ b/test/rexml/test_sax.rb @@ -4,277 +4,277 @@ require 'rexml/parsers/sax2parser' require 'rexml/document' module REXMLTests -class SAX2Tester < Test::Unit::TestCase - include REXMLTestUtils - include REXML - def test_characters - d = Document.new( "<A>@blah@</A>" ) - txt = d.root.text - p = Parsers::SAX2Parser.new "<A>@blah@</A>" - p.listen(:characters) {|x| assert_equal txt, x} - p.listen(:characters, ["A"]) {|x| assert_equal txt,x} - p.parse - end + class SAX2Tester < Test::Unit::TestCase + include REXMLTestUtils + include REXML + def test_characters + d = Document.new( "<A>@blah@</A>" ) + txt = d.root.text + p = Parsers::SAX2Parser.new "<A>@blah@</A>" + p.listen(:characters) {|x| assert_equal txt, x} + p.listen(:characters, ["A"]) {|x| assert_equal txt,x} + p.parse + end - def test_entity_replacement - source = '<!DOCTYPE foo [ - <!ENTITY la "1234"> - <!ENTITY lala "--&la;--"> - <!ENTITY lalal "&la;&la;"> - ]><a><la>&la;</la><lala>&lala;</lala></a>' - sax = Parsers::SAX2Parser.new( source ) - results = [] - sax.listen(:characters) {|x| results << x } - sax.parse - assert_equal 2, results.size - assert_equal '1234', results[0] - assert_equal '--1234--', results[1] - end + def test_entity_replacement + source = '<!DOCTYPE foo [ + <!ENTITY la "1234"> + <!ENTITY lala "--&la;--"> + <!ENTITY lalal "&la;&la;"> + ]><a><la>&la;</la><lala>&lala;</lala></a>' + sax = Parsers::SAX2Parser.new( source ) + results = [] + sax.listen(:characters) {|x| results << x } + sax.parse + assert_equal 2, results.size + assert_equal '1234', results[0] + assert_equal '--1234--', results[1] + end - def test_sax2 - f = File.new(fixture_path("documentation.xml")) - parser = Parsers::SAX2Parser.new( f ) - # Listen to all events on the following elements - count = 0 - blok = proc { |uri,localname,qname,attributes| - assert %w{ bugs todo }.include?(localname), - "Mismatched name; we got '#{qname}'\nArgs were:\n\tURI: #{uri}\n\tLOCALNAME: #{localname}\n\tQNAME: #{qname}\n\tATTRIBUTES: #{attributes.inspect}\n\tSELF=#{blok}" - count += 1 - } + def test_sax2 + f = File.new(fixture_path("documentation.xml")) + parser = Parsers::SAX2Parser.new( f ) + # Listen to all events on the following elements + count = 0 + blok = proc { |uri,localname,qname,attributes| + assert %w{ bugs todo }.include?(localname), + "Mismatched name; we got '#{qname}'\nArgs were:\n\tURI: #{uri}\n\tLOCALNAME: #{localname}\n\tQNAME: #{qname}\n\tATTRIBUTES: #{attributes.inspect}\n\tSELF=#{blok}" + count += 1 + } - start_document = 0 - end_document = 0 - parser.listen( :start_document ) { start_document += 1 } - parser.listen( :end_document ) { end_document += 1 } - parser.listen( :start_element, %w{ changelog bugs todo }, &blok ) - # Listen to all events on the following elements. Synonymous with - # listen( :start_element, %w{ ... } ) - parser.listen( %w{ changelog bugs todo }, &blok ) - # Listen for all start element events - parser.listen( :start_element ) { |uri,localname,qname,attributes| - } - listener = MySAX2Listener.new - # Listen for all events - parser.listen( listener ) - # Listen for all events on the given elements. Does not include children - # events. Regular expressions work as well! - parser.listen( %w{ /change/ bugs todo }, listener ) - # Test the deafening method - blok = proc { |uri,localname,qname,attributes| - assert_fail "This listener should have been deafened!" - } - parser.listen( %w{ changelog }, &blok ) - parser.deafen( &blok ) + start_document = 0 + end_document = 0 + parser.listen( :start_document ) { start_document += 1 } + parser.listen( :end_document ) { end_document += 1 } + parser.listen( :start_element, %w{ changelog bugs todo }, &blok ) + # Listen to all events on the following elements. Synonymous with + # listen( :start_element, %w{ ... } ) + parser.listen( %w{ changelog bugs todo }, &blok ) + # Listen for all start element events + parser.listen( :start_element ) { |uri,localname,qname,attributes| + } + listener = MySAX2Listener.new + # Listen for all events + parser.listen( listener ) + # Listen for all events on the given elements. Does not include children + # events. Regular expressions work as well! + parser.listen( %w{ /change/ bugs todo }, listener ) + # Test the deafening method + blok = proc { |uri,localname,qname,attributes| + assert_fail "This listener should have been deafened!" + } + parser.listen( %w{ changelog }, &blok ) + parser.deafen( &blok ) - tc = 0 - parser.listen( :characters, %w{version} ) {|text| - assert(text=~/@ANT_VERSION@/, "version was '#{text}'") - tc += 1 - } + tc = 0 + parser.listen( :characters, %w{version} ) {|text| + assert(text=~/@ANT_VERSION@/, "version was '#{text}'") + tc += 1 + } - begin - parser.parse - rescue => exception - if exception.kind_of? Test::Unit::AssertionFailedError - raise exception + begin + parser.parse + rescue => exception + if exception.kind_of? Test::Unit::AssertionFailedError + raise exception + end + puts $! + puts exception.backtrace end - puts $! - puts exception.backtrace + assert_equal 2, count + assert_equal 1, tc + assert_equal 1, start_document + assert_equal 1, end_document end - assert_equal 2, count - assert_equal 1, tc - assert_equal 1, start_document - assert_equal 1, end_document - end - # used by test_simple_doctype_listener - # submitted by Jeff Barczewski - class SimpleDoctypeListener - include REXML::SAX2Listener - attr_reader :name, :pub_sys, :long_name, :uri + # used by test_simple_doctype_listener + # submitted by Jeff Barczewski + class SimpleDoctypeListener + include REXML::SAX2Listener + attr_reader :name, :pub_sys, :long_name, :uri - def initialize - @name = @pub_sys = @long_name = @uri = nil - end + def initialize + @name = @pub_sys = @long_name = @uri = nil + end - def doctype(name, pub_sys, long_name, uri) - @name = name - @pub_sys = pub_sys - @long_name = long_name - @uri = uri + def doctype(name, pub_sys, long_name, uri) + @name = name + @pub_sys = pub_sys + @long_name = long_name + @uri = uri + end end - end - # test simple non-entity doctype in sax listener - # submitted by Jeff Barczewski - def test_simple_doctype_listener - xml = <<-END - <?xml version="1.0"?> - <!DOCTYPE greeting PUBLIC "Hello Greeting DTD" "http://foo/hello.dtd"> - <greeting>Hello, world!</greeting> - END - parser = Parsers::SAX2Parser.new(xml) - dtl = SimpleDoctypeListener.new - parser.listen(dtl) - tname = nil - tpub_sys = nil - tlong_name = nil - turi = nil - parser.listen(:doctype) do |name, pub_sys, long_name, uri| - tname = name - tpub_sys = pub_sys - tlong_name = long_name - turi = uri + # test simple non-entity doctype in sax listener + # submitted by Jeff Barczewski + def test_simple_doctype_listener + xml = <<-END + <?xml version="1.0"?> + <!DOCTYPE greeting PUBLIC "Hello Greeting DTD" "http://foo/hello.dtd"> + <greeting>Hello, world!</greeting> + END + parser = Parsers::SAX2Parser.new(xml) + dtl = SimpleDoctypeListener.new + parser.listen(dtl) + tname = nil + tpub_sys = nil + tlong_name = nil + turi = nil + parser.listen(:doctype) do |name, pub_sys, long_name, uri| + tname = name + tpub_sys = pub_sys + tlong_name = long_name + turi = uri + end + parser.parse + assert_equal 'greeting', tname, 'simple doctype block listener failed - incorrect name' + assert_equal 'PUBLIC', tpub_sys, 'simple doctype block listener failed - incorrect pub_sys' + assert_equal 'Hello Greeting DTD', tlong_name, 'simple doctype block listener failed - incorrect long_name' + assert_equal 'http://foo/hello.dtd', turi, 'simple doctype block listener failed - incorrect uri' + assert_equal 'greeting', dtl.name, 'simple doctype listener failed - incorrect name' + assert_equal 'PUBLIC', dtl.pub_sys, 'simple doctype listener failed - incorrect pub_sys' + assert_equal 'Hello Greeting DTD', dtl.long_name, 'simple doctype listener failed - incorrect long_name' + assert_equal 'http://foo/hello.dtd', dtl.uri, 'simple doctype listener failed - incorrect uri' end - parser.parse - assert_equal 'greeting', tname, 'simple doctype block listener failed - incorrect name' - assert_equal 'PUBLIC', tpub_sys, 'simple doctype block listener failed - incorrect pub_sys' - assert_equal 'Hello Greeting DTD', tlong_name, 'simple doctype block listener failed - incorrect long_name' - assert_equal 'http://foo/hello.dtd', turi, 'simple doctype block listener failed - incorrect uri' - assert_equal 'greeting', dtl.name, 'simple doctype listener failed - incorrect name' - assert_equal 'PUBLIC', dtl.pub_sys, 'simple doctype listener failed - incorrect pub_sys' - assert_equal 'Hello Greeting DTD', dtl.long_name, 'simple doctype listener failed - incorrect long_name' - assert_equal 'http://foo/hello.dtd', dtl.uri, 'simple doctype listener failed - incorrect uri' - end - # test doctype with missing name, should throw ParseException - # submitted by Jeff Barczewseki - def test_doctype_with_mising_name_throws_exception - xml = <<-END - <?xml version="1.0"?> - <!DOCTYPE > - <greeting>Hello, world!</greeting> - END - parser = Parsers::SAX2Parser.new(xml) - assert_raise(REXML::ParseException, 'doctype missing name did not throw ParseException') do - parser.parse + # test doctype with missing name, should throw ParseException + # submitted by Jeff Barczewseki + def test_doctype_with_mising_name_throws_exception + xml = <<-END + <?xml version="1.0"?> + <!DOCTYPE > + <greeting>Hello, world!</greeting> + END + parser = Parsers::SAX2Parser.new(xml) + assert_raise(REXML::ParseException, 'doctype missing name did not throw ParseException') do + parser.parse + end end - end - class KouListener - include REXML::SAX2Listener - attr_accessor :sdoc, :edoc - attr_reader :selem, :decl, :pi - def initialize - @sdoc = @edoc = @selem = false - @decl = 0 - @pi = 0 - end - def start_document - @sdoc = true - end - def end_document - @edoc = true - end - def xmldecl( *arg ) - @decl += 1 - end - def processing_instruction( *arg ) - @pi += 1 - end - def start_element( *arg ) - @selem = true + class KouListener + include REXML::SAX2Listener + attr_accessor :sdoc, :edoc + attr_reader :selem, :decl, :pi + def initialize + @sdoc = @edoc = @selem = false + @decl = 0 + @pi = 0 + end + def start_document + @sdoc = true + end + def end_document + @edoc = true + end + def xmldecl( *arg ) + @decl += 1 + end + def processing_instruction( *arg ) + @pi += 1 + end + def start_element( *arg ) + @selem = true + end end - end - # Submitted by Kou - def test_begin_end_document - parser = Parsers::SAX2Parser.new("<a/>") + # Submitted by Kou + def test_begin_end_document + parser = Parsers::SAX2Parser.new("<a/>") - kl = KouListener.new - parser.listen(kl) - sd = false - ed = false - parser.listen(:start_document) { sd = true } - parser.listen(:end_document) { ed = true } + kl = KouListener.new + parser.listen(kl) + sd = false + ed = false + parser.listen(:start_document) { sd = true } + parser.listen(:end_document) { ed = true } - parser.parse - assert( sd, ':start_document block failed' ) - assert( ed, ':end_document block failed' ) - assert( kl.sdoc, ':start_document listener failed' ) - assert( kl.edoc, ':end_document listener failed' ) - end + parser.parse + assert( sd, ':start_document block failed' ) + assert( ed, ':end_document block failed' ) + assert( kl.sdoc, ':start_document listener failed' ) + assert( kl.edoc, ':end_document listener failed' ) + end - # Submitted by Kou - def test_listen_before_start - # FIXME: the following comment should be a test for validity. (The xml declaration - # is invalid). - #parser = Parsers::SAX2Parser.new( "<?xml ?><?pi?><a><?pi?></a>") - parser = Parsers::SAX2Parser.new( "<?xml version='1.0'?><?pi?><a><?pi?></a>") - k1 = KouListener.new - parser.listen( k1 ) - xmldecl = false - pi = 0 - parser.listen( :xmldecl ) { xmldecl = true } - parser.listen( :processing_instruction ) { pi += 1 } + # Submitted by Kou + def test_listen_before_start + # FIXME: the following comment should be a test for validity. (The xml declaration + # is invalid). + #parser = Parsers::SAX2Parser.new( "<?xml ?><?pi?><a><?pi?></a>") + parser = Parsers::SAX2Parser.new( "<?xml version='1.0'?><?pi?><a><?pi?></a>") + k1 = KouListener.new + parser.listen( k1 ) + xmldecl = false + pi = 0 + parser.listen( :xmldecl ) { xmldecl = true } + parser.listen( :processing_instruction ) { pi += 1 } - parser.parse + parser.parse - assert( xmldecl, ':xmldecl failed' ) - assert_equal( 2, pi, ':processing_instruction failed' ) - assert( k1.decl, 'Listener for xmldecl failed' ) - assert_equal( 2, k1.pi, 'Listener for processing instruction failed' ) - end + assert( xmldecl, ':xmldecl failed' ) + assert_equal( 2, pi, ':processing_instruction failed' ) + assert( k1.decl, 'Listener for xmldecl failed' ) + assert_equal( 2, k1.pi, 'Listener for processing instruction failed' ) + end - def test_socket - require 'socket' + def test_socket + require 'socket' - server = TCPServer.new('127.0.0.1', 0) - socket = TCPSocket.new('127.0.0.1', server.addr[1]) + server = TCPServer.new('127.0.0.1', 0) + socket = TCPSocket.new('127.0.0.1', server.addr[1]) - ok = false - session = server.accept - session << '<foo>' - parser = REXML::Parsers::SAX2Parser.new(socket) - Fiber.new do - parser.listen(:start_element) do - ok = true - Fiber.yield - end - parser.parse - end.resume - assert(ok) - end + ok = false + session = server.accept + session << '<foo>' + parser = REXML::Parsers::SAX2Parser.new(socket) + Fiber.new do + parser.listen(:start_element) do + ok = true + Fiber.yield + end + parser.parse + end.resume + assert(ok) + end - def test_char_ref_sax2() - parser = REXML::Parsers::SAX2Parser.new('<ABC>ü</ABC>') - result = nil - parser.listen(:characters) {|text| result = text.unpack('U*')} - parser.parse() - assert_equal(1, result.size) - assert_equal(252, result[0]) - end + def test_char_ref_sax2() + parser = REXML::Parsers::SAX2Parser.new('<ABC>ü</ABC>') + result = nil + parser.listen(:characters) {|text| result = text.unpack('U*')} + parser.parse() + assert_equal(1, result.size) + assert_equal(252, result[0]) + end - def test_char_ref_dom() - doc = REXML::Document.new('<ABC>ü</ABC>') - result = doc.root.text.unpack('U*') - assert_equal(1, result.size) - assert_equal(252, result[0]) - end + def test_char_ref_dom() + doc = REXML::Document.new('<ABC>ü</ABC>') + result = doc.root.text.unpack('U*') + assert_equal(1, result.size) + assert_equal(252, result[0]) + end - class Ticket68 - include REXML::SAX2Listener - end - def test_ticket_68 - parser = REXML::Parsers::SAX2Parser.new(File.new(fixture_path('ticket_68.xml'))) - parser.listen( Ticket68.new ) - begin - parser.parse - rescue - p parser.source.position - p parser.source.current_line - puts $!.backtrace.join("\n") - flunk $!.message + class Ticket68 + include REXML::SAX2Listener + end + def test_ticket_68 + parser = REXML::Parsers::SAX2Parser.new(File.new(fixture_path('ticket_68.xml'))) + parser.listen( Ticket68.new ) + begin + parser.parse + rescue + p parser.source.position + p parser.source.current_line + puts $!.backtrace.join("\n") + flunk $!.message + end end end -end -class MySAX2Listener - include REXML::SAX2Listener -end + class MySAX2Listener + include REXML::SAX2Listener + end end diff --git a/test/rexml/test_stream.rb b/test/rexml/test_stream.rb index d9e622f00c..3164d91c91 100644 --- a/test/rexml/test_stream.rb +++ b/test/rexml/test_stream.rb @@ -4,126 +4,126 @@ require 'rexml/streamlistener' require 'stringio' module REXMLTests -class MyListener - include REXML::StreamListener -end + class MyListener + include REXML::StreamListener + end -class StreamTester < Test::Unit::TestCase - # Submitted by Han Holl - def test_listener - data = %Q{<session1 user="han" password="rootWeiler" />\n<session2 user="han" password="rootWeiler" />} + class StreamTester < Test::Unit::TestCase + # Submitted by Han Holl + def test_listener + data = %Q{<session1 user="han" password="rootWeiler" />\n<session2 user="han" password="rootWeiler" />} - b = RequestReader.new( data ) - b = RequestReader.new( data ) - end + b = RequestReader.new( data ) + b = RequestReader.new( data ) + end - def test_ticket_49 - source = StringIO.new( <<-EOL ) - <!DOCTYPE foo [ - <!ENTITY ent "replace"> - ]> - <a>&ent;</a> - EOL - REXML::Document.parse_stream(source, MyListener.new) - end + def test_ticket_49 + source = StringIO.new( <<-EOL ) + <!DOCTYPE foo [ + <!ENTITY ent "replace"> + ]> + <a>&ent;</a> + EOL + REXML::Document.parse_stream(source, MyListener.new) + end - def test_ticket_10 - source = StringIO.new( <<-EOL ) - <!DOCTYPE foo [ - <!ENTITY ent "replace"> - <!ATTLIST a - xmlns:human CDATA #FIXED "http://www.foo.com/human"> - <!ELEMENT bar (#PCDATA)> - <!NOTATION n1 PUBLIC "-//HM//NOTATION TEST1//EN" 'urn:x-henrikmartensson.org:test5'> - ]> - <a/> - EOL - listener = MyListener.new - class << listener - attr_accessor :events - def entitydecl( content ) - @events[ :entitydecl ] = true - end - def attlistdecl( element_name, attributes, raw_content ) - @events[ :attlistdecl ] = true - end - def elementdecl( content ) - @events[ :elementdecl ] = true + def test_ticket_10 + source = StringIO.new( <<-EOL ) + <!DOCTYPE foo [ + <!ENTITY ent "replace"> + <!ATTLIST a + xmlns:human CDATA #FIXED "http://www.foo.com/human"> + <!ELEMENT bar (#PCDATA)> + <!NOTATION n1 PUBLIC "-//HM//NOTATION TEST1//EN" 'urn:x-henrikmartensson.org:test5'> + ]> + <a/> + EOL + listener = MyListener.new + class << listener + attr_accessor :events + def entitydecl( content ) + @events[ :entitydecl ] = true + end + def attlistdecl( element_name, attributes, raw_content ) + @events[ :attlistdecl ] = true + end + def elementdecl( content ) + @events[ :elementdecl ] = true + end + def notationdecl( content ) + @events[ :notationdecl ] = true + end end - def notationdecl( content ) - @events[ :notationdecl ] = true - end - end - listener.events = {} + listener.events = {} - REXML::Document.parse_stream( source, listener ) + REXML::Document.parse_stream( source, listener ) - assert( listener.events[:entitydecl] ) - assert( listener.events[:attlistdecl] ) - assert( listener.events[:elementdecl] ) - assert( listener.events[:notationdecl] ) - end + assert( listener.events[:entitydecl] ) + assert( listener.events[:attlistdecl] ) + assert( listener.events[:elementdecl] ) + assert( listener.events[:notationdecl] ) + end - def test_entity - listener = MyListener.new - class << listener - attr_accessor :entities - def entity(content) - @entities << content + def test_entity + listener = MyListener.new + class << listener + attr_accessor :entities + def entity(content) + @entities << content + end end - end - listener.entities = [] + listener.entities = [] - source = StringIO.new(<<-XML) + source = StringIO.new(<<-XML) <!DOCTYPE root [ <!ENTITY % ISOLat2 SYSTEM "http://www.xml.com/iso/isolat2-xml.entities" > %ISOLat2; ]> <root/> - XML - REXML::Document.parse_stream(source, listener) + XML + REXML::Document.parse_stream(source, listener) - assert_equal(["ISOLat2"], listener.entities) + assert_equal(["ISOLat2"], listener.entities) + end end -end -# For test_listener -class RequestReader - attr_reader :doc - def initialize(io) - @stack = [] - @doc = nil - catch(:fini) do - REXML::Document.parse_stream(io, self) - raise IOError + # For test_listener + class RequestReader + attr_reader :doc + def initialize(io) + @stack = [] + @doc = nil + catch(:fini) do + REXML::Document.parse_stream(io, self) + raise IOError + end end - end - def tag_start(name, args) - if @doc - @stack.push(REXML::Element.new(name, @stack.last)) - else - @doc = REXML::Document.new("<#{name}/>") - @stack.push(@doc.root) + def tag_start(name, args) + if @doc + @stack.push(REXML::Element.new(name, @stack.last)) + else + @doc = REXML::Document.new("<#{name}/>") + @stack.push(@doc.root) + end + args.each do |attr,val| + @stack.last.add_attribute(attr, val) + end end - args.each do |attr,val| - @stack.last.add_attribute(attr, val) + def tag_end(name, *args) + @stack.pop + throw(:fini) if @stack.empty? + end + def text(str) + @stack.last.text = str + end + def comment(str) + end + def doctype( name, pub_sys, long_name, uri ) + end + def doctype_end end end - def tag_end(name, *args) - @stack.pop - throw(:fini) if @stack.empty? - end - def text(str) - @stack.last.text = str - end - def comment(str) - end - def doctype( name, pub_sys, long_name, uri ) - end - def doctype_end - end -end end diff --git a/test/rexml/test_text.rb b/test/rexml/test_text.rb index 9aa0e2f68e..52ee11ef78 100644 --- a/test/rexml/test_text.rb +++ b/test/rexml/test_text.rb @@ -1,21 +1,21 @@ require "rexml/text" module REXMLTests -class TextTester < Test::Unit::TestCase - include REXML + class TextTester < Test::Unit::TestCase + include REXML - def test_shift_operator_chain - text = Text.new("original\r\n") - text << "append1\r\n" << "append2\r\n" - assert_equal("original\nappend1\nappend2\n", text.to_s) - end + def test_shift_operator_chain + text = Text.new("original\r\n") + text << "append1\r\n" << "append2\r\n" + assert_equal("original\nappend1\nappend2\n", text.to_s) + end - def test_shift_operator_cache - text = Text.new("original\r\n") - text << "append1\r\n" << "append2\r\n" - assert_equal("original\nappend1\nappend2\n", text.to_s) - text << "append3\r\n" << "append4\r\n" - assert_equal("original\nappend1\nappend2\nappend3\nappend4\n", text.to_s) + def test_shift_operator_cache + text = Text.new("original\r\n") + text << "append1\r\n" << "append2\r\n" + assert_equal("original\nappend1\nappend2\n", text.to_s) + text << "append3\r\n" << "append4\r\n" + assert_equal("original\nappend1\nappend2\nappend3\nappend4\n", text.to_s) + end end end -end diff --git a/test/rexml/test_ticket_80.rb b/test/rexml/test_ticket_80.rb index bd588814b3..ffeece5692 100644 --- a/test/rexml/test_ticket_80.rb +++ b/test/rexml/test_ticket_80.rb @@ -10,9 +10,9 @@ require 'test/unit' require 'rexml/document' module REXMLTests -class Ticket80 < Test::Unit::TestCase + class Ticket80 < Test::Unit::TestCase - @@xmlstr = '<?xml version="1.0"?> + @@xmlstr = '<?xml version="1.0"?> <root xmlns="urn:some-xml-ns" xmlns:other="urn:some-other-xml-ns"> <l1-foo> <l2 value="foo-01"/> @@ -28,29 +28,29 @@ class Ticket80 < Test::Unit::TestCase </l1-bar> </root>' - #---------------------------------------------------------------------------- - def test_xpathNamespacedChildWildcard - # tests the "prefix:*" node test syntax - out = Array.new - REXML::XPath.each( REXML::Document.new(@@xmlstr), - '/ns:root/ns:*/ns:l2/@value', - { 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end - chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ] - assert_equal chk, out - end + #---------------------------------------------------------------------------- + def test_xpathNamespacedChildWildcard + # tests the "prefix:*" node test syntax + out = Array.new + REXML::XPath.each( REXML::Document.new(@@xmlstr), + '/ns:root/ns:*/ns:l2/@value', + { 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end + chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ] + assert_equal chk, out + end - #---------------------------------------------------------------------------- - def test_xpathNamespacedChildWildcardWorkaround - # tests a workaround for the "prefix:*" node test syntax - out = Array.new - REXML::XPath.each( REXML::Document.new(@@xmlstr), - '/ns:root/*[namespace-uri()="urn:some-xml-ns"]/ns:l2/@value', - { 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end - chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ] - assert_equal chk, out - end + #---------------------------------------------------------------------------- + def test_xpathNamespacedChildWildcardWorkaround + # tests a workaround for the "prefix:*" node test syntax + out = Array.new + REXML::XPath.each( REXML::Document.new(@@xmlstr), + '/ns:root/*[namespace-uri()="urn:some-xml-ns"]/ns:l2/@value', + { 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end + chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ] + assert_equal chk, out + end -end + end end #------------------------------------------------------------------------------ diff --git a/test/rexml/test_validation_rng.rb b/test/rexml/test_validation_rng.rb index 67abe20a48..8989fe2cbf 100644 --- a/test/rexml/test_validation_rng.rb +++ b/test/rexml/test_validation_rng.rb @@ -4,11 +4,11 @@ require "rexml/document" require "rexml/validation/relaxng" module REXMLTests -class RNGValidation < Test::Unit::TestCase - include REXML + class RNGValidation < Test::Unit::TestCase + include REXML - def test_validate - rng = %q{ + def test_validate + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -25,16 +25,16 @@ class RNGValidation < Test::Unit::TestCase </element> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A><B><C X="x"><E/><E/></C><D/></B></A>} ) - error( validator, %q{<A><B><D/><C X="x"/></B></A>} ) - end + no_error( validator, %q{<A><B><C X="x"><E/><E/></C><D/></B></A>} ) + error( validator, %q{<A><B><D/><C X="x"/></B></A>} ) + end - def test_sequence - rng = %q{ + def test_sequence + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -46,18 +46,18 @@ class RNGValidation < Test::Unit::TestCase </element> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B><C/><C/><D/></B></A>} ) - error( validator, %q{<A><B><D/><C/></B></A>} ) - error( validator, %q{<A><C/><D/></A>} ) - no_error( validator, %q{<A><B><C/><D/></B></A>} ) - end + error( validator, %q{<A><B><C/><C/><D/></B></A>} ) + error( validator, %q{<A><B><D/><C/></B></A>} ) + error( validator, %q{<A><C/><D/></A>} ) + no_error( validator, %q{<A><B><C/><D/></B></A>} ) + end - def test_choice - rng = %q{ + def test_choice + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -71,16 +71,16 @@ class RNGValidation < Test::Unit::TestCase </choice> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B><C/><D/></B></A>} ) - no_error( validator, %q{<A><B><D/></B></A>} ) - no_error( validator, %q{<A><B><C/></B></A>} ) - end + error( validator, %q{<A><B><C/><D/></B></A>} ) + no_error( validator, %q{<A><B><D/></B></A>} ) + no_error( validator, %q{<A><B><C/></B></A>} ) + end - def test_optional - rng = %q{ + def test_optional + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -91,17 +91,17 @@ class RNGValidation < Test::Unit::TestCase </optional> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B><C/></B></A>} ) - error( validator, %q{<A><B><D/></B></A>} ) - error( validator, %q{<A><B><C/><C/></B></A>} ) - end + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B><C/></B></A>} ) + error( validator, %q{<A><B><D/></B></A>} ) + error( validator, %q{<A><B><C/><C/></B></A>} ) + end - def test_zero_or_more - rng = %q{ + def test_zero_or_more + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -112,15 +112,15 @@ class RNGValidation < Test::Unit::TestCase </zeroOrMore> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B><C/></B></A>} ) - no_error( validator, %q{<A><B><C/><C/><C/></B></A>} ) - error( validator, %q{<A><B><D/></B></A>} ) - error( validator, %q{<A></A>} ) + } + validator = REXML::Validation::RelaxNG.new( rng ) + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B><C/></B></A>} ) + no_error( validator, %q{<A><B><C/><C/><C/></B></A>} ) + error( validator, %q{<A><B><D/></B></A>} ) + error( validator, %q{<A></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -134,17 +134,17 @@ class RNGValidation < Test::Unit::TestCase </zeroOrMore> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B><C/><D/></B></A>} ) - no_error( validator, %q{<A><B><C/><D/><C/><D/></B></A>} ) - error( validator, %q{<A><B><D/></B></A>} ) - end + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B><C/><D/></B></A>} ) + no_error( validator, %q{<A><B><C/><D/><C/><D/></B></A>} ) + error( validator, %q{<A><B><D/></B></A>} ) + end - def test_one_or_more - rng = %q{ + def test_one_or_more + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -155,34 +155,34 @@ class RNGValidation < Test::Unit::TestCase </oneOrMore> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) - - error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B><C/></B></A>} ) - no_error( validator, %q{<A><B><C/><C/><C/></B></A>} ) - error( validator, %q{<A><B><D/></B></A>} ) - error( validator, %q{<A></A>} ) - end + } + validator = REXML::Validation::RelaxNG.new( rng ) + + error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B><C/></B></A>} ) + no_error( validator, %q{<A><B><C/><C/><C/></B></A>} ) + error( validator, %q{<A><B><D/></B></A>} ) + error( validator, %q{<A></A>} ) + end - def test_attribute - rng = %q{ + def test_attribute + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <attribute name="X"/> <attribute name="Y"/> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A/>} ) - error( validator, %q{<A X=""/>} ) - no_error( validator, %q{<A X="1" Y="1"/>} ) - end + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A/>} ) + error( validator, %q{<A X=""/>} ) + no_error( validator, %q{<A X="1" Y="1"/>} ) + end - def test_choice_attributes - rng = %q{ + def test_choice_attributes + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <choice> @@ -190,17 +190,17 @@ class RNGValidation < Test::Unit::TestCase <attribute name="Y"/> </choice> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A X="1" Y="1"/>} ) - error( validator, %q{<A/>} ) - no_error( validator, %q{<A X="1"/>}) - no_error( validator, %q{<A Y="1"/>} ) - end + error( validator, %q{<A X="1" Y="1"/>} ) + error( validator, %q{<A/>} ) + no_error( validator, %q{<A X="1"/>}) + no_error( validator, %q{<A Y="1"/>} ) + end - def test_choice_attribute_element - rng = %q{ + def test_choice_attribute_element + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <choice> @@ -208,45 +208,45 @@ class RNGValidation < Test::Unit::TestCase <element name="B"/> </choice> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A X="1"><B/></A>} ) - error( validator, %q{<A/>} ) - no_error( validator, %q{<A X="1"/>}) - no_error( validator, %q{<A><B/></A>} ) - end + error( validator, %q{<A X="1"><B/></A>} ) + error( validator, %q{<A/>} ) + no_error( validator, %q{<A X="1"/>}) + no_error( validator, %q{<A><B/></A>} ) + end - def test_empty - rng = %q{ + def test_empty + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <empty/> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A>Text</A>} ) - no_error( validator, %q{<A/>}) - end + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A>Text</A>} ) + no_error( validator, %q{<A/>}) + end - def test_text_val - rng = %q{ + def test_text_val + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <text/> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A>Text</A>} ) - error( validator, %q{<A/>}) - end + error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A>Text</A>} ) + error( validator, %q{<A/>}) + end - def test_choice_text - rng = %q{ + def test_choice_text + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <choice> @@ -254,17 +254,17 @@ class RNGValidation < Test::Unit::TestCase <text/> </choice> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/>Text</A>} ) - error( validator, %q{<A>Text<B/></A>} ) - no_error( validator, %q{<A>Text</A>} ) - no_error( validator, %q{<A><B/></A>} ) - end + error( validator, %q{<A><B/>Text</A>} ) + error( validator, %q{<A>Text<B/></A>} ) + no_error( validator, %q{<A>Text</A>} ) + no_error( validator, %q{<A><B/></A>} ) + end - def test_group - rng = %q{ + def test_group + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <choice> @@ -275,15 +275,15 @@ class RNGValidation < Test::Unit::TestCase </group> </choice> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/><C/></A>} ) - error( validator, %q{<A><C/></A>} ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><C/><D/></A>} ) + error( validator, %q{<A><B/><C/></A>} ) + error( validator, %q{<A><C/></A>} ) + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><C/><D/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"/> @@ -292,33 +292,33 @@ class RNGValidation < Test::Unit::TestCase <element name="D"/> </group> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/><C/></A>} ) - error( validator, %q{<A><B/><D/></A>} ) - error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B/><C/><D/></A>} ) - end + error( validator, %q{<A><B/><C/></A>} ) + error( validator, %q{<A><B/><D/></A>} ) + error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B/><C/><D/></A>} ) + end - def test_value - # Values as text nodes - rng = %q{ + def test_value + # Values as text nodes + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> <value>VaLuE</value> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B>X</B></A>} ) - error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B>VaLuE</B></A>} ) + error( validator, %q{<A><B>X</B></A>} ) + error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B>VaLuE</B></A>} ) - # Values as text nodes, via choice - rng = %q{ + # Values as text nodes, via choice + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -328,32 +328,32 @@ class RNGValidation < Test::Unit::TestCase </choice> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A><B>XYZ</B></A>} ) - no_error( validator, %q{<A><B>Option 1</B></A>} ) - no_error( validator, %q{<A><B>Option 2</B></A>} ) + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A><B>XYZ</B></A>} ) + no_error( validator, %q{<A><B>Option 1</B></A>} ) + no_error( validator, %q{<A><B>Option 2</B></A>} ) - # Attribute values - rng = %q{ + # Attribute values + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <attribute name="B"> <value>VaLuE</value> </attribute> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A/>} ) - error( validator, %q{<A B=""/>} ) - error( validator, %q{<A B="Lala"/>} ) - no_error( validator, %q{<A B="VaLuE"/>} ) + error( validator, %q{<A/>} ) + error( validator, %q{<A B=""/>} ) + error( validator, %q{<A B="Lala"/>} ) + no_error( validator, %q{<A B="VaLuE"/>} ) - # Attribute values via choice - rng = %q{ + # Attribute values via choice + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <attribute name="B"> @@ -363,17 +363,17 @@ class RNGValidation < Test::Unit::TestCase </choice> </attribute> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A B=""/>} ) - error( validator, %q{<A B="Value"/>} ) - no_error( validator, %q{<A B="Option 1"></A>} ) - no_error( validator, %q{<A B="Option 2"/>} ) - end + error( validator, %q{<A B=""/>} ) + error( validator, %q{<A B="Value"/>} ) + no_error( validator, %q{<A B="Option 1"></A>} ) + no_error( validator, %q{<A B="Option 2"/>} ) + end - def test_interleave - rng = %q{ + def test_interleave + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -384,20 +384,20 @@ class RNGValidation < Test::Unit::TestCase </interleave> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) - - error( validator, %q{<A><B><C/></B></A>} ) - error( validator, %q{<A><B><C/><D/><C/></B></A>} ) - no_error( validator, %q{<A><B><C/><D/><E/></B></A>} ) - no_error( validator, %q{<A><B><E/><D/><C/></B></A>} ) - no_error( validator, %q{<A><B><D/><C/><E/></B></A>} ) - no_error( validator, %q{<A><B><E/><C/><D/></B></A>} ) - error( validator, %q{<A><B><E/><C/><D/><C/></B></A>} ) - end + } + validator = REXML::Validation::RelaxNG.new( rng ) - def test_mixed - rng = %q{ + error( validator, %q{<A><B><C/></B></A>} ) + error( validator, %q{<A><B><C/><D/><C/></B></A>} ) + no_error( validator, %q{<A><B><C/><D/><E/></B></A>} ) + no_error( validator, %q{<A><B><E/><D/><C/></B></A>} ) + no_error( validator, %q{<A><B><D/><C/><E/></B></A>} ) + no_error( validator, %q{<A><B><E/><C/><D/></B></A>} ) + error( validator, %q{<A><B><E/><C/><D/><C/></B></A>} ) + end + + def test_mixed + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="B"> @@ -406,15 +406,15 @@ class RNGValidation < Test::Unit::TestCase </mixed> </element> </element> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A><B>Text<D/></B></A>} ) - no_error( validator, %q{<A><B><D/>Text</B></A>} ) - end + no_error( validator, %q{<A><B>Text<D/></B></A>} ) + no_error( validator, %q{<A><B><D/>Text</B></A>} ) + end - def test_ref_sequence - rng = %q{ + def test_ref_sequence + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -430,15 +430,15 @@ class RNGValidation < Test::Unit::TestCase </element> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A><B X=''/><B X=''/></A>} ) - error( validator, %q{<A><B X=''/></A>} ) - end + no_error( validator, %q{<A><B X=''/><B X=''/></A>} ) + error( validator, %q{<A><B X=''/></A>} ) + end - def test_ref_choice - rng = %q{ + def test_ref_choice + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -454,15 +454,15 @@ class RNGValidation < Test::Unit::TestCase <element name="C"/> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><D/></A>} ) - error( validator, %q{<A><B/><C/></A>} ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><C/></A>} ) + error( validator, %q{<A><D/></A>} ) + error( validator, %q{<A><B/><C/></A>} ) + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><C/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -478,15 +478,15 @@ class RNGValidation < Test::Unit::TestCase </choice> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><D/></A>} ) - error( validator, %q{<A><B/><C/></A>} ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><C/></A>} ) + error( validator, %q{<A><D/></A>} ) + error( validator, %q{<A><B/><C/></A>} ) + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><C/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -503,18 +503,18 @@ class RNGValidation < Test::Unit::TestCase <element name="C"/> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/><C/></A>} ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><C/></A>} ) - no_error( validator, %q{<A><D/></A>} ) - end + error( validator, %q{<A><B/><C/></A>} ) + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><C/></A>} ) + no_error( validator, %q{<A><D/></A>} ) + end - def test_ref_zero_plus - rng = %q{ + def test_ref_zero_plus + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -531,15 +531,15 @@ class RNGValidation < Test::Unit::TestCase </element> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A/>} ) - no_error( validator, %q{<A><B X=''/></A>} ) - no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) + error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A/>} ) + no_error( validator, %q{<A><B X=''/></A>} ) + no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -556,18 +556,18 @@ class RNGValidation < Test::Unit::TestCase </zeroOrMore> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A/>} ) - no_error( validator, %q{<A><B X=''/></A>} ) - no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) - end + error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A/>} ) + no_error( validator, %q{<A><B X=''/></A>} ) + no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) + end - def test_ref_one_plus - rng = %q{ + def test_ref_one_plus + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -584,15 +584,15 @@ class RNGValidation < Test::Unit::TestCase </element> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A/>} ) - no_error( validator, %q{<A><B X=''/></A>} ) - no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A/>} ) + no_error( validator, %q{<A><B X=''/></A>} ) + no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -609,17 +609,17 @@ class RNGValidation < Test::Unit::TestCase </oneOrMore> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A/>} ) - no_error( validator, %q{<A><B X=''/></A>} ) - no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) - end + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A/>} ) + no_error( validator, %q{<A><B X=''/></A>} ) + no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) + end - def test_ref_interleave - rng = %q{ + def test_ref_interleave + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -635,16 +635,16 @@ class RNGValidation < Test::Unit::TestCase <element name="C"/> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A><C/></A>} ) - error( validator, %q{<A><C/><C/></A>} ) - no_error( validator, %q{<A><B/><C/></A>} ) - no_error( validator, %q{<A><C/><B/></A>} ) + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A><C/></A>} ) + error( validator, %q{<A><C/><C/></A>} ) + no_error( validator, %q{<A><B/><C/></A>} ) + no_error( validator, %q{<A><C/><B/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -660,16 +660,16 @@ class RNGValidation < Test::Unit::TestCase </interleave> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A><C/></A>} ) - error( validator, %q{<A><C/><C/></A>} ) - no_error( validator, %q{<A><B/><C/></A>} ) - no_error( validator, %q{<A><C/><B/></A>} ) + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A><C/></A>} ) + error( validator, %q{<A><C/><C/></A>} ) + no_error( validator, %q{<A><B/><C/></A>} ) + no_error( validator, %q{<A><C/><B/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -688,18 +688,18 @@ class RNGValidation < Test::Unit::TestCase <element name="C"/> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) - - error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A><C/></A>} ) - error( validator, %q{<A><C/><C/></A>} ) - no_error( validator, %q{<A><B/><C/></A>} ) - no_error( validator, %q{<A><C/><B/></A>} ) - end + } + validator = REXML::Validation::RelaxNG.new( rng ) - def test_ref_recurse - rng = %q{ + error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A><C/></A>} ) + error( validator, %q{<A><C/><C/></A>} ) + no_error( validator, %q{<A><B/><C/></A>} ) + no_error( validator, %q{<A><C/><B/></A>} ) + end + + def test_ref_recurse + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -716,16 +716,16 @@ class RNGValidation < Test::Unit::TestCase </element> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{<A></A>} ) - no_error( validator, %q{<A><B/></A>} ) - no_error( validator, %q{<A><B><B/></B></A>} ) - end + error( validator, %q{<A></A>} ) + no_error( validator, %q{<A><B/></A>} ) + no_error( validator, %q{<A><B><B/></B></A>} ) + end - def test_ref_optional - rng = %q{ + def test_ref_optional + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -741,15 +741,15 @@ class RNGValidation < Test::Unit::TestCase </element> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A></A>} ) - no_error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A><B/><B/></A>} ) - error( validator, %q{<A><C/></A>} ) + no_error( validator, %q{<A></A>} ) + no_error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A><B/><B/></A>} ) + error( validator, %q{<A><C/></A>} ) - rng = %q{ + rng = %q{ <?xml version="1.0" encoding="UTF-8"?> <grammar xmlns="http://relaxng.org/ns/structure/1.0"> <start> @@ -765,28 +765,28 @@ class RNGValidation < Test::Unit::TestCase </optional> </define> </grammar> - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{<A></A>} ) - no_error( validator, %q{<A><B/></A>} ) - error( validator, %q{<A><B/><B/></A>} ) - error( validator, %q{<A><C/></A>} ) - end + no_error( validator, %q{<A></A>} ) + no_error( validator, %q{<A><B/></A>} ) + error( validator, %q{<A><B/><B/></A>} ) + error( validator, %q{<A><C/></A>} ) + end - def error( validator, source ) - parser = REXML::Parsers::TreeParser.new( source ) - parser.add_listener( validator.reset ) - assert_raise( REXML::Validation::ValidationException, - "Expected a validation error" ) { parser.parse } - end + def error( validator, source ) + parser = REXML::Parsers::TreeParser.new( source ) + parser.add_listener( validator.reset ) + assert_raise( REXML::Validation::ValidationException, + "Expected a validation error" ) { parser.parse } + end - def no_error( validator, source ) - parser = REXML::Parsers::TreeParser.new( source ) - parser.add_listener( validator.reset ) - assert_nothing_raised { parser.parse } + def no_error( validator, source ) + parser = REXML::Parsers::TreeParser.new( source ) + parser.add_listener( validator.reset ) + assert_nothing_raised { parser.parse } + end end end -end diff --git a/test/rexml/test_xml_declaration.rb b/test/rexml/test_xml_declaration.rb index a7b7023ad4..a96d40c542 100644 --- a/test/rexml/test_xml_declaration.rb +++ b/test/rexml/test_xml_declaration.rb @@ -7,29 +7,29 @@ require "rexml/document" require "test/unit" module REXMLTests -class TestXmlDeclaration < Test::Unit::TestCase - def setup - xml = <<-'END_XML' - <?xml encoding= 'UTF-8' standalone='yes'?> - <root> - </root> - END_XML - @doc = REXML::Document.new xml - @root = @doc.root - @xml_declaration = @doc.children[0] - end + class TestXmlDeclaration < Test::Unit::TestCase + def setup + xml = <<-'END_XML' + <?xml encoding= 'UTF-8' standalone='yes'?> + <root> + </root> + END_XML + @doc = REXML::Document.new xml + @root = @doc.root + @xml_declaration = @doc.children[0] + end - def test_is_first_child - assert_kind_of(REXML::XMLDecl, @xml_declaration) - end + def test_is_first_child + assert_kind_of(REXML::XMLDecl, @xml_declaration) + end - def test_has_document_as_parent - assert_kind_of(REXML::Document, @xml_declaration.parent) - end + def test_has_document_as_parent + assert_kind_of(REXML::Document, @xml_declaration.parent) + end - def test_has_sibling - assert_kind_of(REXML::XMLDecl, @root.previous_sibling.previous_sibling) - assert_kind_of(REXML::Element, @xml_declaration.next_sibling.next_sibling) + def test_has_sibling + assert_kind_of(REXML::XMLDecl, @root.previous_sibling.previous_sibling) + assert_kind_of(REXML::Element, @xml_declaration.next_sibling.next_sibling) + end end end -end diff --git a/test/rexml/xpath/test_attribute.rb b/test/rexml/xpath/test_attribute.rb index 313910489b..95af4de399 100644 --- a/test/rexml/xpath/test_attribute.rb +++ b/test/rexml/xpath/test_attribute.rb @@ -2,28 +2,28 @@ require 'test/unit' require 'rexml/document' module REXMLTests -class TestXPathAttribute < Test::Unit::TestCase - def setup - @xml = <<-XML + class TestXPathAttribute < Test::Unit::TestCase + def setup + @xml = <<-XML <?xml version="1.0" encoding="UTF-8"?> <root> <child name="one">child1</child> <child name="two">child2</child> <child name="three">child3</child> </root> - XML - @document = REXML::Document.new(@xml) - end + XML + @document = REXML::Document.new(@xml) + end - def test_elements - root = @document.elements["root"] - second_child = root.elements["child[@name='two']"] - assert_equal("child2", second_child.text) - end + def test_elements + root = @document.elements["root"] + second_child = root.elements["child[@name='two']"] + assert_equal("child2", second_child.text) + end - def test_xpath_each - children = REXML::XPath.each(@document, "/root/child[@name='two']") - assert_equal(["child2"], children.collect(&:text)) + def test_xpath_each + children = REXML::XPath.each(@document, "/root/child[@name='two']") + assert_equal(["child2"], children.collect(&:text)) + end end end -end diff --git a/test/rexml/xpath/test_axis_preceding_sibling.rb b/test/rexml/xpath/test_axis_preceding_sibling.rb index faba177f95..273180772a 100644 --- a/test/rexml/xpath/test_axis_preceding_sibling.rb +++ b/test/rexml/xpath/test_axis_preceding_sibling.rb @@ -2,38 +2,38 @@ require "test/unit/testcase" require "rexml/document" module REXMLTests -class TestXPathAxisPredcedingSibling < Test::Unit::TestCase - include REXML - SOURCE = <<-EOF - <a id='1'> - <e id='2'> - <f id='3'/> - <f id='4'/> - <f id='5'/> - <f id='6'/> - </e> - </a> - EOF + class TestXPathAxisPredcedingSibling < Test::Unit::TestCase + include REXML + SOURCE = <<-EOF + <a id='1'> + <e id='2'> + <f id='3'/> + <f id='4'/> + <f id='5'/> + <f id='6'/> + </e> + </a> + EOF - def setup - @@doc = Document.new(SOURCE) unless defined? @@doc - end + def setup + @@doc = Document.new(SOURCE) unless defined? @@doc + end - def test_preceding_sibling_axis - context = XPath.first(@@doc,"/a/e/f[last()]") - assert_equal "6", context.attributes["id"] + def test_preceding_sibling_axis + context = XPath.first(@@doc,"/a/e/f[last()]") + assert_equal "6", context.attributes["id"] - prev = XPath.first(context, "preceding-sibling::f") - assert_equal "5", prev.attributes["id"] + prev = XPath.first(context, "preceding-sibling::f") + assert_equal "5", prev.attributes["id"] - prev = XPath.first(context, "preceding-sibling::f[1]") - assert_equal "5", prev.attributes["id"] + prev = XPath.first(context, "preceding-sibling::f[1]") + assert_equal "5", prev.attributes["id"] - prev = XPath.first(context, "preceding-sibling::f[2]") - assert_equal "4", prev.attributes["id"] + prev = XPath.first(context, "preceding-sibling::f[2]") + assert_equal "4", prev.attributes["id"] - prev = XPath.first(context, "preceding-sibling::f[3]") - assert_equal "3", prev.attributes["id"] + prev = XPath.first(context, "preceding-sibling::f[3]") + assert_equal "3", prev.attributes["id"] + end end end -end diff --git a/test/rexml/xpath/test_base.rb b/test/rexml/xpath/test_base.rb index 54559c979f..8ef5e4aff0 100644 --- a/test/rexml/xpath/test_base.rb +++ b/test/rexml/xpath/test_base.rb @@ -3,755 +3,755 @@ require_relative "../rexml_test_utils" require "rexml/document" module REXMLTests -class TestXPathBase < Test::Unit::TestCase - include REXMLTestUtils - include REXML - SOURCE = <<-EOF - <a id='1'> - <b id='2' x='y'> - <c id='3'/> - <c id='4'/> + class TestXPathBase < Test::Unit::TestCase + include REXMLTestUtils + include REXML + SOURCE = <<-EOF + <a id='1'> + <b id='2' x='y'> + <c id='3'/> + <c id='4'/> + </b> + <d id='5'> + <c id='6' x='y'/> + <c id='7'/> + <c id='8'/> + <q id='19'/> + </d> + <e id='9'> + <f id='10' a='b'/> + <f id='11' a='c'/> + <f id='12' a='d'> + <g id='13'/> + </f> + <f id='14' a='d'/> + </e> + <m id='15'> + <n id='16'> + <o id='17'> + <p id='18'/> + </o> + </n> + </m> + </a> + EOF + JENI_TENNISON = <<-EOJT + <a> + <b> + <c> + <d> + <e id='x'> + <f/> + </e> + </d> + </c> + <c> + <d> + <e id='y'/> + </d> + </c> + </b> + <b> + <c> + <d> + <e id='z'/> + </d> + </c> </b> - <d id='5'> - <c id='6' x='y'/> - <c id='7'/> - <c id='8'/> - <q id='19'/> - </d> - <e id='9'> - <f id='10' a='b'/> - <f id='11' a='c'/> - <f id='12' a='d'> - <g id='13'/> - </f> - <f id='14' a='d'/> - </e> - <m id='15'> - <n id='16'> - <o id='17'> - <p id='18'/> - </o> - </n> - </m> </a> - EOF - JENI_TENNISON = <<-EOJT - <a> - <b> - <c> - <d> - <e id='x'> - <f/> - </e> - </d> - </c> - <c> - <d> - <e id='y'/> - </d> - </c> - </b> - <b> - <c> - <d> - <e id='z'/> - </d> - </c> - </b> - </a> - EOJT - - def setup - @@doc = Document.new(SOURCE) unless defined? @@doc - @@jeni = Document.new( JENI_TENNISON ) unless defined? @@jeni - end + EOJT - def each_test( element, xpath ) - count = 0 - XPath::each( element, xpath ) { |child| - count += 1 - yield child if block_given? - } - count - end + def setup + @@doc = Document.new(SOURCE) unless defined? @@doc + @@jeni = Document.new( JENI_TENNISON ) unless defined? @@jeni + end - def test_descendant - doc = Document.new("<a><b><c id='1'/></b><d><b><c id='2'/></b></d></a>") - p = XPath.match( doc, "//c" ) - assert_equal( 2, p.size ) - p = XPath.first( @@doc, "//p" ) - assert_equal "p", p.name - c = each_test( @@doc, "//c" ) { |child| assert_equal "c", child.name } - assert_equal 5, c - c = each_test( @@doc.root, "b//c" ) { |child| - assert_equal "c", child.name - } - assert_equal 2, c - - doc = Document.new( "<a><z id='1'/><b><z id='11'/><z id='12'/></b><c><z id='21'/><z id='22'/><d><z id='31'/><z id='32'/></d></c></a>" ) - # //para[1] : all descendants which are the first para child of their parent - assert_equal( 4, XPath.match( doc, "//z[1]" ).size ) - # /descendant::para[1] : the first descendant para element - assert_equal( 1, XPath.match( doc, "/descendant::z[1]" ).size ) - end + def each_test( element, xpath ) + count = 0 + XPath::each( element, xpath ) { |child| + count += 1 + yield child if block_given? + } + count + end - def test_root - source = "<a><b/></a>" - doc = Document.new( source ) - assert_equal doc, doc.root_node - assert_equal "a", XPath::first( doc, "/" ).elements[1].name - end + def test_descendant + doc = Document.new("<a><b><c id='1'/></b><d><b><c id='2'/></b></d></a>") + p = XPath.match( doc, "//c" ) + assert_equal( 2, p.size ) + p = XPath.first( @@doc, "//p" ) + assert_equal "p", p.name + c = each_test( @@doc, "//c" ) { |child| assert_equal "c", child.name } + assert_equal 5, c + c = each_test( @@doc.root, "b//c" ) { |child| + assert_equal "c", child.name + } + assert_equal 2, c - def test_abbreviated_simple_child - assert_equal "a", XPath::first(@@doc, "a").name - end + doc = Document.new( "<a><z id='1'/><b><z id='11'/><z id='12'/></b><c><z id='21'/><z id='22'/><d><z id='31'/><z id='32'/></d></c></a>" ) + # //para[1] : all descendants which are the first para child of their parent + assert_equal( 4, XPath.match( doc, "//z[1]" ).size ) + # /descendant::para[1] : the first descendant para element + assert_equal( 1, XPath.match( doc, "/descendant::z[1]" ).size ) + end - def test_child - c = XPath::first( @@doc, "a/b/c" ) - assert_equal "c", c.name - assert_equal "3", XPath::first(@@doc, "a/b/c").attributes["id"] - end + def test_root + source = "<a><b/></a>" + doc = Document.new( source ) + assert_equal doc, doc.root_node + assert_equal "a", XPath::first( doc, "/" ).elements[1].name + end - def test_root_child - assert_equal "a", XPath::first(@@doc, "/a").name - c = XPath::first( @@doc, "a/b/c" ) - assert_equal "a", XPath::first(c, "/a").name - end + def test_abbreviated_simple_child + assert_equal "a", XPath::first(@@doc, "a").name + end - def test_root_children - c = XPath::first( @@doc, "a/b/c" ) - assert_equal "2", XPath::first(c, "/a/b").attributes["id"] - end + def test_child + c = XPath::first( @@doc, "a/b/c" ) + assert_equal "c", c.name + assert_equal "3", XPath::first(@@doc, "a/b/c").attributes["id"] + end - def test_abbreviated_step - c = XPath::first( @@doc, "a/b/c" ) - assert_equal("c", c.name) - assert_equal("a", XPath::first(@@doc.root, ".").name) - assert_equal("b", XPath::first(c, "..").name) - assert_equal("a", XPath::first(@@doc, "a/b/..").name) - - doc = REXML::Document.new(File.new(fixture_path("project.xml"))) - c = each_test(doc.root, "./Description" ) { |child| - assert_equal("Description",child.name) - } - assert_equal 1, c - end + def test_root_child + assert_equal "a", XPath::first(@@doc, "/a").name + c = XPath::first( @@doc, "a/b/c" ) + assert_equal "a", XPath::first(c, "/a").name + end - # Things that aren't tested elsewhere - def test_predicates - assert_equal "12", XPath::first(@@doc, "a/e/f[3]").attributes["id"] - assert_equal "13", XPath::first(@@doc, "a/e/f[3]/g").attributes["id"] - assert_equal "14", XPath::first(@@doc, "a/e/f[@a='d'][2]").attributes["id"] - assert_equal "14", XPath::first(@@doc, "a/e/f[@a='d'][@id='14']").attributes["id"] - assert_equal "a", XPath::first( @@doc, "*[name()='a' and @id='1']" ).name - c=each_test( @@doc, "//*[name()='f' and @a='d']") { |i| - assert_equal "f", i.name - } - assert_equal 2, c - c=each_test( @@doc, "//*[name()='m' or @a='d']") { |i| - assert ["m","f"].include?(i.name) - } - assert_equal 3, c - - assert_equal "b", XPath::first( @@doc, "//b[@x]" ).name - end + def test_root_children + c = XPath::first( @@doc, "a/b/c" ) + assert_equal "2", XPath::first(c, "/a/b").attributes["id"] + end - def test_node_type - doc = Document.new "<a><?foo bar?><!--comment-->text</a>" - #res = XPath::first(doc.root, "text()") - #assert_equal "text", res.to_s + def test_abbreviated_step + c = XPath::first( @@doc, "a/b/c" ) + assert_equal("c", c.name) + assert_equal("a", XPath::first(@@doc.root, ".").name) + assert_equal("b", XPath::first(c, "..").name) + assert_equal("a", XPath::first(@@doc, "a/b/..").name) - #res = XPath::first(doc, "*") - #assert_equal "a", res.name + doc = REXML::Document.new(File.new(fixture_path("project.xml"))) + c = each_test(doc.root, "./Description" ) { |child| + assert_equal("Description",child.name) + } + assert_equal 1, c + end - assert_equal( :processing_instruction, - XPath::first(doc.root, "processing-instruction()").node_type) - assert_equal( :comment, XPath::first(doc.root, "comment()").node_type) - end + # Things that aren't tested elsewhere + def test_predicates + assert_equal "12", XPath::first(@@doc, "a/e/f[3]").attributes["id"] + assert_equal "13", XPath::first(@@doc, "a/e/f[3]/g").attributes["id"] + assert_equal "14", XPath::first(@@doc, "a/e/f[@a='d'][2]").attributes["id"] + assert_equal "14", XPath::first(@@doc, "a/e/f[@a='d'][@id='14']").attributes["id"] + assert_equal "a", XPath::first( @@doc, "*[name()='a' and @id='1']" ).name + c=each_test( @@doc, "//*[name()='f' and @a='d']") { |i| + assert_equal "f", i.name + } + assert_equal 2, c + c=each_test( @@doc, "//*[name()='m' or @a='d']") { |i| + assert ["m","f"].include?(i.name) + } + assert_equal 3, c - def test_functions - # trivial text() test - # confuse-a-function - source = "<a>more <b id='1'/><b id='2'>dumb</b><b id='3'/><c/> text</a>" - doc = Document.new source - res = "" - #XPath::each(doc.root, "text()") {|val| res << val.to_s} - #assert_equal "more text", res - - #res = XPath::first(doc.root, "b[last()]") - #assert_equal '3', res.attributes['id'] - res = XPath::first(doc.root, "b[position()=2]") - assert_equal '2', res.attributes['id'] - res = XPath::first(doc.root, "*[name()='c']") - assert_equal "c", res.name - end + assert_equal "b", XPath::first( @@doc, "//b[@x]" ).name + end - def no_test_ancestor - doc = REXML::Document.new(File.new(fixture_path("testsrc.xml"))) - doc.elements.each("//item") { |el| print el.name - if el.attributes['x'] - puts " -- "+el.attributes['x'] - else - puts - end - } - doc.elements.each("//item/ancestor::") { |el| print el.name - if el.attributes['x'] - puts " -- "+el.attributes['x'] - else - puts - end - } - end + def test_node_type + doc = Document.new "<a><?foo bar?><!--comment-->text</a>" + #res = XPath::first(doc.root, "text()") + #assert_equal "text", res.to_s + + #res = XPath::first(doc, "*") + #assert_equal "a", res.name + + assert_equal( :processing_instruction, + XPath::first(doc.root, "processing-instruction()").node_type) + assert_equal( :comment, XPath::first(doc.root, "comment()").node_type) + end + + def test_functions + # trivial text() test + # confuse-a-function + source = "<a>more <b id='1'/><b id='2'>dumb</b><b id='3'/><c/> text</a>" + doc = Document.new source + res = "" + #XPath::each(doc.root, "text()") {|val| res << val.to_s} + #assert_equal "more text", res + + #res = XPath::first(doc.root, "b[last()]") + #assert_equal '3', res.attributes['id'] + res = XPath::first(doc.root, "b[position()=2]") + assert_equal '2', res.attributes['id'] + res = XPath::first(doc.root, "*[name()='c']") + assert_equal "c", res.name + end + + def no_test_ancestor + doc = REXML::Document.new(File.new(fixture_path("testsrc.xml"))) + doc.elements.each("//item") { |el| print el.name + if el.attributes['x'] + puts " -- "+el.attributes['x'] + else + puts + end + } + doc.elements.each("//item/ancestor::") { |el| print el.name + if el.attributes['x'] + puts " -- "+el.attributes['x'] + else + puts + end + } + end - # Here are some XPath tests that were originally submitted by ... - # The code has changed some, but the logic and the source documents are the - # same. - # This method reads a document from a file, and then a series of xpaths, - # also from a file. It then checks each xpath against the source file. - def test_more - xmlsource = fixture_path("testsrc.xml") - xpathtests = fixture_path("xp.tst") - - doc = REXML::Document.new(File.new(xmlsource)) - #results = "" - results = REXML::Document.new - results.add_element "test-results" - for line in File.new(xpathtests) - line.strip! - begin - doc.root - #puts "#"*80 - #print "\nDoing #{line} " ; $stdout.flush - doc.elements.each(line) do |el| - #print "." ; $stdout.flush - results.root << el.clone - #results << el.to_s + # Here are some XPath tests that were originally submitted by ... + # The code has changed some, but the logic and the source documents are the + # same. + # This method reads a document from a file, and then a series of xpaths, + # also from a file. It then checks each xpath against the source file. + def test_more + xmlsource = fixture_path("testsrc.xml") + xpathtests = fixture_path("xp.tst") + + doc = REXML::Document.new(File.new(xmlsource)) + #results = "" + results = REXML::Document.new + results.add_element "test-results" + for line in File.new(xpathtests) + line.strip! + begin + doc.root + #puts "#"*80 + #print "\nDoing #{line} " ; $stdout.flush + doc.elements.each(line) do |el| + #print "." ; $stdout.flush + results.root << el.clone + #results << el.to_s + end + #ObjectSpace.garbage_collect + GC::start + rescue Exception => z + #puts "\n'#{line}' failed" + fail("Error on line #{line}:\n#{z.message}\n"+z.backtrace[0,10].join("\n")) + #results.root.add_element( "error", {"path"=>line}).text = z.message+"\n"+z.backtrace[0,10].join("\n") + #results << "<error path='"+line+"'>"+z.message+"</error>" end - #ObjectSpace.garbage_collect - GC::start - rescue Exception => z - #puts "\n'#{line}' failed" - fail("Error on line #{line}:\n#{z.message}\n"+z.backtrace[0,10].join("\n")) - #results.root.add_element( "error", {"path"=>line}).text = z.message+"\n"+z.backtrace[0,10].join("\n") - #results << "<error path='"+line+"'>"+z.message+"</error>" end end - end - def test_axe_descendant - assert_equal "f", XPath::first( @@doc, "descendant::f").name - end + def test_axe_descendant + assert_equal "f", XPath::first( @@doc, "descendant::f").name + end - def test_axe_parent - q = XPath.first( @@doc, "a/d/c/parent::*/q" ) - assert_equal 19, q.attributes["id"].to_i - end + def test_axe_parent + q = XPath.first( @@doc, "a/d/c/parent::*/q" ) + assert_equal 19, q.attributes["id"].to_i + end - def test_abbreviated_attribute - assert_equal 'a', XPath::first( @@doc, "a[@id='1']" ).name - c = XPath::first( @@doc, "a/b/c[@id='4']" ) - assert_equal 'c', c.name - assert_equal '4', c.attributes['id'] + def test_abbreviated_attribute + assert_equal 'a', XPath::first( @@doc, "a[@id='1']" ).name + c = XPath::first( @@doc, "a/b/c[@id='4']" ) + assert_equal 'c', c.name + assert_equal '4', c.attributes['id'] - result = XPath::first( @@doc, "descendant::f[@a='c']") - assert_equal "11", result.attributes['id'] + result = XPath::first( @@doc, "descendant::f[@a='c']") + assert_equal "11", result.attributes['id'] - assert_equal "11", XPath::first(@@doc, "a/e/f[@a='c']").attributes["id"] - assert_equal "11", XPath::first(@@doc, "a/e/*[@a='c']").attributes["id"] - end + assert_equal "11", XPath::first(@@doc, "a/e/f[@a='c']").attributes["id"] + assert_equal "11", XPath::first(@@doc, "a/e/*[@a='c']").attributes["id"] + end - def test_axe_self - c = XPath::first( @@doc, "a/b/c" ) - assert c - assert_equal "c", c.name - assert_equal "c", XPath::first( c, "self::node()" ).name - end + def test_axe_self + c = XPath::first( @@doc, "a/b/c" ) + assert c + assert_equal "c", c.name + assert_equal "c", XPath::first( c, "self::node()" ).name + end - def test_axe_ancestor - doc = REXML::Document.new " - <a> - <b id='1'> - <c> - <b id='2'> - <d/> - </b> - </c> - </b> - </a>" + def test_axe_ancestor + doc = REXML::Document.new " + <a> + <b id='1'> + <c> + <b id='2'> + <d/> + </b> + </c> + </b> + </a>" + + d = XPath.first( doc, "//d" ) + assert_equal "d", d.name + b = each_test( d, "ancestor::b" ) { |el| + assert((1..2) === el.attributes['id'].to_i, + "Expected #{el.attributes['id']} to be either 1 or 2" + ) + } + assert_equal 2, b + end - d = XPath.first( doc, "//d" ) - assert_equal "d", d.name - b = each_test( d, "ancestor::b" ) { |el| - assert((1..2) === el.attributes['id'].to_i, - "Expected #{el.attributes['id']} to be either 1 or 2" - ) - } - assert_equal 2, b - end + def test_axe_child + m = XPath.first( @@doc, "a/child::m" ) + assert_equal 15, m.attributes['id'].to_i + end - def test_axe_child - m = XPath.first( @@doc, "a/child::m" ) - assert_equal 15, m.attributes['id'].to_i - end + def test_axe_attribute + a = XPath.first( @@doc, "a/attribute::id" ) + assert_equal "1", a.value + a = XPath.first( @@doc, "a/e/f[@id='14']/attribute::a" ) + assert_equal "d", a.value + end - def test_axe_attribute - a = XPath.first( @@doc, "a/attribute::id" ) - assert_equal "1", a.value - a = XPath.first( @@doc, "a/e/f[@id='14']/attribute::a" ) - assert_equal "d", a.value - end + def test_axe_sibling + doc = Document.new "<a><b><c/></b><e><f id='10'/><f id='11'/><f id='12'/></e></a>" + first_f = XPath.first( doc, "a/e/f" ) + assert first_f + assert_equal '10', first_f.attributes['id'] + next_f = XPath.first( doc, "a/e/f/following-sibling::node()" ) + assert_equal '11', next_f.attributes['id'] - def test_axe_sibling - doc = Document.new "<a><b><c/></b><e><f id='10'/><f id='11'/><f id='12'/></e></a>" - first_f = XPath.first( doc, "a/e/f" ) - assert first_f - assert_equal '10', first_f.attributes['id'] - next_f = XPath.first( doc, "a/e/f/following-sibling::node()" ) - assert_equal '11', next_f.attributes['id'] + b = XPath.first( doc, "a/e/preceding-sibling::node()" ) + assert_equal 'b', b.name + end - b = XPath.first( doc, "a/e/preceding-sibling::node()" ) - assert_equal 'b', b.name - end + def test_lang + doc = Document.new(File.new(fixture_path("lang0.xml"))) + #puts IO.read( "test/lang.xml" ) - def test_lang - doc = Document.new(File.new(fixture_path("lang0.xml"))) - #puts IO.read( "test/lang.xml" ) + #puts XPath.match( doc, "//language/*" ).size + c = each_test( doc, "//language/*" ) { |element| + #puts "#{element.name}: #{element.text}" + } + assert_equal 4, c + end - #puts XPath.match( doc, "//language/*" ).size - c = each_test( doc, "//language/*" ) { |element| - #puts "#{element.name}: #{element.text}" - } - assert_equal 4, c - end + def test_namespaces_1 + source = <<-EOF + <foo xmlns:ts="this" xmlns:tt="that"> + <ts:bar>this bar</ts:bar> + <tt:bar>that bar</tt:bar> + </foo> + EOF + doc = Document.new source + XPath.each( doc, "//bar" ) { + fail "'bar' should match nothing in this case" + } - def test_namespaces_1 - source = <<-EOF - <foo xmlns:ts="this" xmlns:tt="that"> - <ts:bar>this bar</ts:bar> - <tt:bar>that bar</tt:bar> - </foo> - EOF - doc = Document.new source - XPath.each( doc, "//bar" ) { - fail "'bar' should match nothing in this case" - } - - namespace = {"t"=>"this"} - results = XPath.first( doc, "//t:bar", namespace ) - assert_equal "this bar", results.text - end + namespace = {"t"=>"this"} + results = XPath.first( doc, "//t:bar", namespace ) + assert_equal "this bar", results.text + end - def test_namespaces_2 - source = <<-EOF - <foo xmlns:ts="this" xmlns:tt="that"> - <ts:bar>this bar</ts:bar> - <tt:bar>that bar</tt:bar> - </foo> - EOF - doc = Document.new source - res = XPath::first(doc, "//*[local_name()='bar']") - assert res, "looking for //*[name()='bar']" - assert_equal 'this', res.namespace - res = XPath::first(doc.root, "*[namespace_uri()='that']") - assert_equal 'that bar', res.text - end + def test_namespaces_2 + source = <<-EOF + <foo xmlns:ts="this" xmlns:tt="that"> + <ts:bar>this bar</ts:bar> + <tt:bar>that bar</tt:bar> + </foo> + EOF + doc = Document.new source + res = XPath::first(doc, "//*[local_name()='bar']") + assert res, "looking for //*[name()='bar']" + assert_equal 'this', res.namespace + res = XPath::first(doc.root, "*[namespace_uri()='that']") + assert_equal 'that bar', res.text + end - def test_complex - next_f = XPath.first( @@doc, "a/e/f[@id='11']/following-sibling::*" ) - assert_equal 12, next_f.attributes['id'].to_i - prev_f = XPath.first( @@doc, "a/e/f[@id='11']/preceding-sibling::*" ) - assert_equal 10, prev_f.attributes['id'].to_i - c = each_test( @@doc, "descendant-or-self::*[@x='y']" ) - assert_equal 2, c - end + def test_complex + next_f = XPath.first( @@doc, "a/e/f[@id='11']/following-sibling::*" ) + assert_equal 12, next_f.attributes['id'].to_i + prev_f = XPath.first( @@doc, "a/e/f[@id='11']/preceding-sibling::*" ) + assert_equal 10, prev_f.attributes['id'].to_i + c = each_test( @@doc, "descendant-or-self::*[@x='y']" ) + assert_equal 2, c + end - def test_grouping - t = XPath.first( @@doc, "a/d/*[name()='d' and (name()='f' or name()='q')]" ) - assert_nil t - t = XPath.first( @@doc, "a/d/*[(name()='d' and name()='f') or name()='q']" ) - assert_equal 'q', t.name - end + def test_grouping + t = XPath.first( @@doc, "a/d/*[name()='d' and (name()='f' or name()='q')]" ) + assert_nil t + t = XPath.first( @@doc, "a/d/*[(name()='d' and name()='f') or name()='q']" ) + assert_equal 'q', t.name + end - def test_preceding - d = Document.new "<a><b id='0'/><b id='2'/><b><c id='0'/><c id='1'/><c id='2'/></b><b id='1'/></a>" - start = XPath.first( d, "/a/b[@id='1']" ) - assert_equal 'b', start.name - c = XPath.first( start, "preceding::c" ) - assert_equal '2', c.attributes['id'] - - c1, c0 = XPath.match( d, "/a/b/c[@id='2']/preceding::node()" ) - assert_equal '1', c1.attributes['id'] - assert_equal '0', c0.attributes['id'] - - c2, c1, c0, b, b2, b0 = XPath.match( start, "preceding::node()" ) - - assert_equal 'c', c2.name - assert_equal 'c', c1.name - assert_equal 'c', c0.name - assert_equal 'b', b.name - assert_equal 'b', b2.name - assert_equal 'b', b0.name - - assert_equal '2', c2.attributes['id'] - assert_equal '1', c1.attributes['id'] - assert_equal '0', c0.attributes['id'] - assert b.attributes.empty? - assert_equal '2', b2.attributes['id'] - assert_equal '0', b0.attributes['id'] - - d = REXML::Document.new("<a><b/><c/><d/></a>") - matches = REXML::XPath.match(d, "/a/d/preceding::node()") - assert_equal("c", matches[0].name) - assert_equal("b", matches[1].name) - - s = "<a><b><c id='1'/></b><b><b><c id='2'/><c id='3'/></b><c id='4'/></b><c id='NOMATCH'><c id='5'/></c></a>" - d = REXML::Document.new(s) - c = REXML::XPath.match( d, "//c[@id = '5']") - cs = REXML::XPath.match( c, "preceding::c" ) - assert_equal( 4, cs.length ) - end + def test_preceding + d = Document.new "<a><b id='0'/><b id='2'/><b><c id='0'/><c id='1'/><c id='2'/></b><b id='1'/></a>" + start = XPath.first( d, "/a/b[@id='1']" ) + assert_equal 'b', start.name + c = XPath.first( start, "preceding::c" ) + assert_equal '2', c.attributes['id'] + + c1, c0 = XPath.match( d, "/a/b/c[@id='2']/preceding::node()" ) + assert_equal '1', c1.attributes['id'] + assert_equal '0', c0.attributes['id'] + + c2, c1, c0, b, b2, b0 = XPath.match( start, "preceding::node()" ) + + assert_equal 'c', c2.name + assert_equal 'c', c1.name + assert_equal 'c', c0.name + assert_equal 'b', b.name + assert_equal 'b', b2.name + assert_equal 'b', b0.name + + assert_equal '2', c2.attributes['id'] + assert_equal '1', c1.attributes['id'] + assert_equal '0', c0.attributes['id'] + assert b.attributes.empty? + assert_equal '2', b2.attributes['id'] + assert_equal '0', b0.attributes['id'] + + d = REXML::Document.new("<a><b/><c/><d/></a>") + matches = REXML::XPath.match(d, "/a/d/preceding::node()") + assert_equal("c", matches[0].name) + assert_equal("b", matches[1].name) + + s = "<a><b><c id='1'/></b><b><b><c id='2'/><c id='3'/></b><c id='4'/></b><c id='NOMATCH'><c id='5'/></c></a>" + d = REXML::Document.new(s) + c = REXML::XPath.match( d, "//c[@id = '5']") + cs = REXML::XPath.match( c, "preceding::c" ) + assert_equal( 4, cs.length ) + end - def test_following - d = Document.new "<a><b id='0'/><b/><b><c id='1'/><c id='2'/></b><b id='1'/></a>" - start = XPath.first( d, "/a/b[@id='0']" ) - assert_equal 'b', start.name - c = XPath.first( start, "following::c" ) - assert_equal '1', c.attributes['id'] - - s = "<a><b><c><d/></c><e/></b><f><g><h/><i/></g></f><i/></a>" - d = Document.new(s) - c = XPath.first(d, '/a/b/c') - assert_equal 'c', c.name - res = XPath.match( c, 'following::*' ) - assert_equal 6, res.size - res = XPath.match( c, 'following::i' ) - assert_equal 2, res.size - end + def test_following + d = Document.new "<a><b id='0'/><b/><b><c id='1'/><c id='2'/></b><b id='1'/></a>" + start = XPath.first( d, "/a/b[@id='0']" ) + assert_equal 'b', start.name + c = XPath.first( start, "following::c" ) + assert_equal '1', c.attributes['id'] + + s = "<a><b><c><d/></c><e/></b><f><g><h/><i/></g></f><i/></a>" + d = Document.new(s) + c = XPath.first(d, '/a/b/c') + assert_equal 'c', c.name + res = XPath.match( c, 'following::*' ) + assert_equal 6, res.size + res = XPath.match( c, 'following::i' ) + assert_equal 2, res.size + end - # The following three paths were provided by - # Jeni Tennison <jeni@jenitennison.com> - # a consultant who is also an XSL and XPath expert - #def test_child_cubed - # els = @@jeni.elements.to_a("*****") - # assert_equal 3, els.size - #end - - #def test_div_2 - # results = doc.elements.to_a("/ div 2") - #end - - #def test_nested_predicates - # puts @@jeni.root.elements[1].elements[1].name - # results = @@jeni.root.elements[1].elements[1].elements.to_a("../following-sibling::*[*[name() = name(current())]]") - # puts results - #end - - # Contributed by Mike Stok - def test_starts_with - source = <<-EOF - <foo> - <a href="mailto:a@b.c">a@b.c</a> - <a href="http://www.foo.com">http://www.foo.com</a> - </foo> - EOF - doc = Document.new source - mailtos = doc.elements.to_a("//a[starts-with(@href, 'mailto:')]") - assert_equal 1, mailtos.size - assert_equal "mailto:a@b.c", mailtos[0].attributes['href'] - - ailtos = doc.elements.to_a("//a[starts-with(@href, 'ailto:')]") - assert_equal 0, ailtos.size - end + # The following three paths were provided by + # Jeni Tennison <jeni@jenitennison.com> + # a consultant who is also an XSL and XPath expert + #def test_child_cubed + # els = @@jeni.elements.to_a("*****") + # assert_equal 3, els.size + #end + + #def test_div_2 + # results = doc.elements.to_a("/ div 2") + #end + + #def test_nested_predicates + # puts @@jeni.root.elements[1].elements[1].name + # results = @@jeni.root.elements[1].elements[1].elements.to_a("../following-sibling::*[*[name() = name(current())]]") + # puts results + #end + + # Contributed by Mike Stok + def test_starts_with + source = <<-EOF + <foo> + <a href="mailto:a@b.c">a@b.c</a> + <a href="http://www.foo.com">http://www.foo.com</a> + </foo> + EOF + doc = Document.new source + mailtos = doc.elements.to_a("//a[starts-with(@href, 'mailto:')]") + assert_equal 1, mailtos.size + assert_equal "mailto:a@b.c", mailtos[0].attributes['href'] + + ailtos = doc.elements.to_a("//a[starts-with(@href, 'ailto:')]") + assert_equal 0, ailtos.size + end - def test_toms_text_node - file = "<a>A<b>B</b><c>C<d>D</d>E</c>F</a>" - doc = Document.new(file) - assert_equal 'A', XPath.first(doc[0], 'text()').to_s - assert_equal 'AF', XPath.match(doc[0], 'text()').collect { |n| - n.to_s - }.join('') - assert_equal 'B', XPath.first(doc[0], 'b/text()').to_s - assert_equal 'D', XPath.first(doc[0], '//d/text()').to_s - assert_equal 'ABCDEF', XPath.match(doc[0], '//text()').collect {|n| - n.to_s - }.join('') - end + def test_toms_text_node + file = "<a>A<b>B</b><c>C<d>D</d>E</c>F</a>" + doc = Document.new(file) + assert_equal 'A', XPath.first(doc[0], 'text()').to_s + assert_equal 'AF', XPath.match(doc[0], 'text()').collect { |n| + n.to_s + }.join('') + assert_equal 'B', XPath.first(doc[0], 'b/text()').to_s + assert_equal 'D', XPath.first(doc[0], '//d/text()').to_s + assert_equal 'ABCDEF', XPath.match(doc[0], '//text()').collect {|n| + n.to_s + }.join('') + end - def test_string_length - doc = Document.new <<-EOF - <AAA> - <Q/> - <SSSS/> - <BB/> - <CCC/> - <DDDDDDDD/> - <EEEE/> - </AAA> - EOF - assert doc, "create doc" - - set = doc.elements.to_a("//*[string-length(name()) = 3]") - assert_equal 2, set.size, "nodes with names length = 3" - - set = doc.elements.to_a("//*[string-length(name()) < 3]") - assert_equal 2, set.size, "nodes with names length < 3" - - set = doc.elements.to_a("//*[string-length(name()) > 3]") - assert_equal 3, set.size, "nodes with names length > 3" - end + def test_string_length + doc = Document.new <<-EOF + <AAA> + <Q/> + <SSSS/> + <BB/> + <CCC/> + <DDDDDDDD/> + <EEEE/> + </AAA> + EOF + assert doc, "create doc" + + set = doc.elements.to_a("//*[string-length(name()) = 3]") + assert_equal 2, set.size, "nodes with names length = 3" + + set = doc.elements.to_a("//*[string-length(name()) < 3]") + assert_equal 2, set.size, "nodes with names length < 3" + + set = doc.elements.to_a("//*[string-length(name()) > 3]") + assert_equal 3, set.size, "nodes with names length > 3" + end - # Test provided by Mike Stok - def test_contains - source = <<-EOF - <foo> - <a href="mailto:a@b.c">a@b.c</a> - <a href="http://www.foo.com">http://www.foo.com</a> - </foo> - EOF - doc = Document.new source - - [ - #['o', 2], - ['foo', 1], ['bar', 0]].each { |search, expected| - set = doc.elements.to_a("//a[contains(@href, '#{search}')]") - assert_equal expected, set.size - } - end + # Test provided by Mike Stok + def test_contains + source = <<-EOF + <foo> + <a href="mailto:a@b.c">a@b.c</a> + <a href="http://www.foo.com">http://www.foo.com</a> + </foo> + EOF + doc = Document.new source + + [ + #['o', 2], + ['foo', 1], ['bar', 0]].each { |search, expected| + set = doc.elements.to_a("//a[contains(@href, '#{search}')]") + assert_equal expected, set.size + } + end - # Mike Stok and Sean Russell - def test_substring - # examples from http://www.w3.org/TR/xpath#function-substring - doc = Document.new('<test string="12345" />') - - Document.new("<a b='1'/>") - #puts XPath.first(d, 'node()[0 + 1]') - #d = Document.new("<a b='1'/>") - #puts XPath.first(d, 'a[0 mod 0]') - [ [1.5, 2.6, '234'], - [0, 3, '12'], - [0, '0 div 0', ''], - [1, '0 div 0', ''], - ['-42', '1 div 0', '12345'], - ['-1 div 0', '1 div 0', ''] - ].each { |start, length, expected| - set = doc.elements.to_a("//test[substring(@string, #{start}, #{length}) = '#{expected}']") - assert_equal 1, set.size, "#{start}, #{length}, '#{expected}'" - } - end + # Mike Stok and Sean Russell + def test_substring + # examples from http://www.w3.org/TR/xpath#function-substring + doc = Document.new('<test string="12345" />') + + Document.new("<a b='1'/>") + #puts XPath.first(d, 'node()[0 + 1]') + #d = Document.new("<a b='1'/>") + #puts XPath.first(d, 'a[0 mod 0]') + [ [1.5, 2.6, '234'], + [0, 3, '12'], + [0, '0 div 0', ''], + [1, '0 div 0', ''], + ['-42', '1 div 0', '12345'], + ['-1 div 0', '1 div 0', ''] + ].each { |start, length, expected| + set = doc.elements.to_a("//test[substring(@string, #{start}, #{length}) = '#{expected}']") + assert_equal 1, set.size, "#{start}, #{length}, '#{expected}'" + } + end - def test_translate - source = <<-EOF - <doc> - <case name='w3c one' result='BAr' /> <!-- w3c --> - <case name='w3c two' result='AAA' /> <!-- w3c --> - <case name='alchemy' result="gold" /> <!-- mike --> - <case name='vbxml one' result='A Space Odyssey' /> - <case name='vbxml two' result='AbCdEf' /> - </doc> - EOF - - doc = Document.new(source) - - [ ['bar', 'abc', 'ABC', 'w3c one'], - ['--aaa--','abc-','ABC', 'w3c two'], - ['lead', 'dear language', 'doll groover', 'alchemy'], - ['A Space Odissei', 'i', 'y', 'vbxml one'], - ['abcdefg', 'aceg', 'ACE', 'vbxml two'], - ].each { |arg1, arg2, arg3, name| - translate = "translate('#{arg1}', '#{arg2}', '#{arg3}')" - set = doc.elements.to_a("//case[@result = #{translate}]") - assert_equal 1, set.size, translate - assert_equal name, set[0].attributes['name'] - } - end + def test_translate + source = <<-EOF + <doc> + <case name='w3c one' result='BAr' /> <!-- w3c --> + <case name='w3c two' result='AAA' /> <!-- w3c --> + <case name='alchemy' result="gold" /> <!-- mike --> + <case name='vbxml one' result='A Space Odyssey' /> + <case name='vbxml two' result='AbCdEf' /> + </doc> + EOF + + doc = Document.new(source) + + [ ['bar', 'abc', 'ABC', 'w3c one'], + ['--aaa--','abc-','ABC', 'w3c two'], + ['lead', 'dear language', 'doll groover', 'alchemy'], + ['A Space Odissei', 'i', 'y', 'vbxml one'], + ['abcdefg', 'aceg', 'ACE', 'vbxml two'], + ].each { |arg1, arg2, arg3, name| + translate = "translate('#{arg1}', '#{arg2}', '#{arg3}')" + set = doc.elements.to_a("//case[@result = #{translate}]") + assert_equal 1, set.size, translate + assert_equal name, set[0].attributes['name'] + } + end - def test_math - d = Document.new( '<a><b/><c/></a>' ) - assert XPath.first( d.root, 'node()[1]' ) - assert_equal 'b', XPath.first( d.root, 'node()[1]' ).name - assert XPath.first( d.root, 'node()[0 + 1]' ) - assert_equal 'b', XPath.first( d.root, './node()[0 + 1]' ).name - assert XPath.first( d.root, 'node()[1 + 1]' ) - assert_equal 'c', XPath.first( d.root, './node()[1 + 1]' ).name - assert XPath.first( d.root, 'node()[4 div 2]' ) - assert_equal 'c', XPath.first( d.root, './node()[4 div 2]' ).name - assert XPath.first( d.root, 'node()[2 - 1]' ) - assert_equal 'b', XPath.first( d.root, './node()[2 - 1]' ).name - assert XPath.first( d.root, 'node()[5 mod 2]' ) - assert_equal 'b', XPath.first( d.root, './node()[5 mod 2]' ).name - assert XPath.first( d.root, 'node()[8 mod 3]' ) - assert_equal 'c', XPath.first( d.root, './node()[8 mod 3]' ).name - assert XPath.first( d.root, 'node()[1 * 2]' ) - assert_equal 'c', XPath.first( d.root, './node()[1 * 2]' ).name - assert XPath.first( d.root, 'node()[2 + -1]' ) - assert_equal 'b', XPath.first( d.root, './node()[2 + -1]' ).name - end + def test_math + d = Document.new( '<a><b/><c/></a>' ) + assert XPath.first( d.root, 'node()[1]' ) + assert_equal 'b', XPath.first( d.root, 'node()[1]' ).name + assert XPath.first( d.root, 'node()[0 + 1]' ) + assert_equal 'b', XPath.first( d.root, './node()[0 + 1]' ).name + assert XPath.first( d.root, 'node()[1 + 1]' ) + assert_equal 'c', XPath.first( d.root, './node()[1 + 1]' ).name + assert XPath.first( d.root, 'node()[4 div 2]' ) + assert_equal 'c', XPath.first( d.root, './node()[4 div 2]' ).name + assert XPath.first( d.root, 'node()[2 - 1]' ) + assert_equal 'b', XPath.first( d.root, './node()[2 - 1]' ).name + assert XPath.first( d.root, 'node()[5 mod 2]' ) + assert_equal 'b', XPath.first( d.root, './node()[5 mod 2]' ).name + assert XPath.first( d.root, 'node()[8 mod 3]' ) + assert_equal 'c', XPath.first( d.root, './node()[8 mod 3]' ).name + assert XPath.first( d.root, 'node()[1 * 2]' ) + assert_equal 'c', XPath.first( d.root, './node()[1 * 2]' ).name + assert XPath.first( d.root, 'node()[2 + -1]' ) + assert_equal 'b', XPath.first( d.root, './node()[2 + -1]' ).name + end - def test_name - assert_raise( UndefinedNamespaceException, "x should be undefined" ) { - REXML::Document.new("<a x='foo'><b/><x:b/></a>") - } - d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") - assert_equal 1, d.root.elements.to_a('*[name() = "b"]').size - assert_equal 1, d.elements.to_a('//*[name() = "x:b"]').size - end + def test_name + assert_raise( UndefinedNamespaceException, "x should be undefined" ) { + REXML::Document.new("<a x='foo'><b/><x:b/></a>") + } + d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") + assert_equal 1, d.root.elements.to_a('*[name() = "b"]').size + assert_equal 1, d.elements.to_a('//*[name() = "x:b"]').size + end - def test_local_name - d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") - assert_equal 2, d.root.elements.to_a('*[local_name() = "b"]').size - assert_equal 2, d.elements.to_a('//*[local_name() = "b"]').size - end + def test_local_name + d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") + assert_equal 2, d.root.elements.to_a('*[local_name() = "b"]').size + assert_equal 2, d.elements.to_a('//*[local_name() = "b"]').size + end - def test_comparisons - source = "<a><b id='1'/><b id='2'/><b id='3'/></a>" - doc = REXML::Document.new(source) - - # NOTE TO SER: check that number() is required - assert_equal 2, REXML::XPath.match(doc, "//b[number(@id) > 1]").size - assert_equal 3, REXML::XPath.match(doc, "//b[number(@id) >= 1]").size - assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) <= 1]").size - assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) = (1 * 1)]").size - assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) = (1 mod 2)]").size - assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) = (4 div 2)]").size - end + def test_comparisons + source = "<a><b id='1'/><b id='2'/><b id='3'/></a>" + doc = REXML::Document.new(source) + + # NOTE TO SER: check that number() is required + assert_equal 2, REXML::XPath.match(doc, "//b[number(@id) > 1]").size + assert_equal 3, REXML::XPath.match(doc, "//b[number(@id) >= 1]").size + assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) <= 1]").size + assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) = (1 * 1)]").size + assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) = (1 mod 2)]").size + assert_equal 1, REXML::XPath.match(doc, "//b[number(@id) = (4 div 2)]").size + end - # Contributed by Kouhei - def test_substring_before - doc = Document.new("<r><a/><b/><c/></r>") - assert_equal("a", doc.root.elements.to_a("*[name()=substring-before('abc', 'b')]")[0].name) - assert_equal("c", doc.root.elements.to_a("*[name()=substring-after('abc', 'b')]")[0].name) - end + # Contributed by Kouhei + def test_substring_before + doc = Document.new("<r><a/><b/><c/></r>") + assert_equal("a", doc.root.elements.to_a("*[name()=substring-before('abc', 'b')]")[0].name) + assert_equal("c", doc.root.elements.to_a("*[name()=substring-after('abc', 'b')]")[0].name) + end - def test_spaces - doc = Document.new("<a> - <b> - <c id='a'/> - </b> - <c id='b'/> - </a>") - assert_equal( 1, REXML::XPath.match(doc, - "//*[local-name()='c' and @id='b']").size ) - assert_equal( 1, REXML::XPath.match(doc, - "//*[ local-name()='c' and @id='b' ]").size ) - assert_equal( 1, REXML::XPath.match(doc, - "//*[ local-name() = 'c' and @id = 'b' ]").size ) - assert_equal( 1, - REXML::XPath.match(doc, '/a/c[@id]').size ) - assert_equal( 1, - REXML::XPath.match(doc, '/a/c[(@id)]').size ) - assert_equal( 1, - REXML::XPath.match(doc, '/a/c[ @id ]').size ) - assert_equal( 1, - REXML::XPath.match(doc, '/a/c[ (@id) ]').size ) - assert_equal( 1, - REXML::XPath.match(doc, '/a/c[( @id )]').size ) - assert_equal( 1, REXML::XPath.match(doc.root, - '/a/c[ ( @id ) ]').size ) - assert_equal( 1, REXML::XPath.match(doc, - '/a/c [ ( @id ) ] ').size ) - assert_equal( 1, REXML::XPath.match(doc, - ' / a / c [ ( @id ) ] ').size ) - end + def test_spaces + doc = Document.new("<a> + <b> + <c id='a'/> + </b> + <c id='b'/> + </a>") + assert_equal( 1, REXML::XPath.match(doc, + "//*[local-name()='c' and @id='b']").size ) + assert_equal( 1, REXML::XPath.match(doc, + "//*[ local-name()='c' and @id='b' ]").size ) + assert_equal( 1, REXML::XPath.match(doc, + "//*[ local-name() = 'c' and @id = 'b' ]").size ) + assert_equal( 1, + REXML::XPath.match(doc, '/a/c[@id]').size ) + assert_equal( 1, + REXML::XPath.match(doc, '/a/c[(@id)]').size ) + assert_equal( 1, + REXML::XPath.match(doc, '/a/c[ @id ]').size ) + assert_equal( 1, + REXML::XPath.match(doc, '/a/c[ (@id) ]').size ) + assert_equal( 1, + REXML::XPath.match(doc, '/a/c[( @id )]').size ) + assert_equal( 1, REXML::XPath.match(doc.root, + '/a/c[ ( @id ) ]').size ) + assert_equal( 1, REXML::XPath.match(doc, + '/a/c [ ( @id ) ] ').size ) + assert_equal( 1, REXML::XPath.match(doc, + ' / a / c [ ( @id ) ] ').size ) + end - def test_text_nodes - # source = "<root> - #<child/> - #<child>test</child> - #</root>" - source = "<root><child>test</child></root>" - d = REXML::Document.new( source ) - r = REXML::XPath.match( d, %q{/root/child[text()="test"]} ) - assert_equal( 1, r.size ) - assert_equal( "child", r[0].name ) - assert_equal( "test", r[0].text ) - end + def test_text_nodes + # source = "<root> + #<child/> + #<child>test</child> + #</root>" + source = "<root><child>test</child></root>" + d = REXML::Document.new( source ) + r = REXML::XPath.match( d, %q{/root/child[text()="test"]} ) + assert_equal( 1, r.size ) + assert_equal( "child", r[0].name ) + assert_equal( "test", r[0].text ) + end - def test_auto_string_value - source = "<root><foo/><title>Introduction</title></root>" - d = REXML::Document.new( source ) - #r = REXML::XPath.match( d, %q{/root[title="Introduction"]} ) - #assert_equal( 1, r.size ) - source = "<a><b/><c/><c>test</c></a>" - d = REXML::Document.new( source ) - r = REXML::XPath.match( d, %q{/a[c='test']} ) - assert_equal( 1, r.size ) - r = REXML::XPath.match( d, %q{a[c='test']} ) - assert_equal( 1, r.size ) - r = d.elements["/a[c='test']"] - assert_not_nil( r ) - r = d.elements["a[c='test']"] - assert_not_nil( r ) - r = d.elements["a[c='xtest']"] - assert_nil( r ) - r = REXML::XPath.match( d, %q{a[c='xtest']} ) - assert_equal( 0, r.size ) - end + def test_auto_string_value + source = "<root><foo/><title>Introduction</title></root>" + d = REXML::Document.new( source ) + #r = REXML::XPath.match( d, %q{/root[title="Introduction"]} ) + #assert_equal( 1, r.size ) + source = "<a><b/><c/><c>test</c></a>" + d = REXML::Document.new( source ) + r = REXML::XPath.match( d, %q{/a[c='test']} ) + assert_equal( 1, r.size ) + r = REXML::XPath.match( d, %q{a[c='test']} ) + assert_equal( 1, r.size ) + r = d.elements["/a[c='test']"] + assert_not_nil( r ) + r = d.elements["a[c='test']"] + assert_not_nil( r ) + r = d.elements["a[c='xtest']"] + assert_nil( r ) + r = REXML::XPath.match( d, %q{a[c='xtest']} ) + assert_equal( 0, r.size ) + end - def test_ordering - source = "<a><b><c id='1'/><c id='2'/></b><b><d id='1'/><d id='2'/></b></a>" - d = REXML::Document.new( source ) - r = REXML::XPath.match( d, %q{/a/*/*[1]} ) - assert_equal( 1, r.size ) - r.each { |el| assert_equal( '1', el.attribute('id').value ) } - end + def test_ordering + source = "<a><b><c id='1'/><c id='2'/></b><b><d id='1'/><d id='2'/></b></a>" + d = REXML::Document.new( source ) + r = REXML::XPath.match( d, %q{/a/*/*[1]} ) + assert_equal( 1, r.size ) + r.each { |el| assert_equal( '1', el.attribute('id').value ) } + end - def test_descendant_or_self_ordering - source = "<a> - <b> - <c id='1'/> - <c id='2'/> - </b> - <b> - <d id='1'> - <c id='3'/> - </d> - <d id='2'> - <e> - <c id='4'/> - </e> - </d> - </b> - </a>" - d = REXML::Document.new( source ) - cs = XPath.match( d, "/descendant-or-self::c" ) - assert_equal( 4, cs.length ) - 1.upto(4) {|x| assert_equal( x.to_s, cs[x-1].attributes['id'] ) } - end + def test_descendant_or_self_ordering + source = "<a> + <b> + <c id='1'/> + <c id='2'/> + </b> + <b> + <d id='1'> + <c id='3'/> + </d> + <d id='2'> + <e> + <c id='4'/> + </e> + </d> + </b> + </a>" + d = REXML::Document.new( source ) + cs = XPath.match( d, "/descendant-or-self::c" ) + assert_equal( 4, cs.length ) + 1.upto(4) {|x| assert_equal( x.to_s, cs[x-1].attributes['id'] ) } + end - def test_and - d = Document.new %q{<doc><route run='*' title='HNO' - destination='debian_production1' date='*' edition='*' - source='debian_satellite1'/></doc>} - assert_equal( nil, d.root.elements["route[@run='0']"] ) - assert_equal( nil, d.root.elements["route[@run='0' and @title='HNO']"] ) - end + def test_and + d = Document.new %q{<doc><route run='*' title='HNO' + destination='debian_production1' date='*' edition='*' + source='debian_satellite1'/></doc>} + assert_equal( nil, d.root.elements["route[@run='0']"] ) + assert_equal( nil, d.root.elements["route[@run='0' and @title='HNO']"] ) + end - def test_numbers - d = Document.new %q{<a x="0" y="*" z="4e" w="e4" v="a"/>} - - xp1 = "/a[ @x = 0 ]" - xp2 = "/a[ @x = '0' ]" - xp3 = "/a[ (@x + 1) = 1 ]" - xp4 = "/a[ @y = 0 ]" - xp5 = "/a[ (@z + 1) = 5 ]" - xp6 = "/a[ (@w + 1) = 5 ]" - xp7 = "/a[ (@v + 1) = 1 ]" - xp8 = "/a[ @n = 0 ]" - - assert_equal( 1, XPath.match( d, xp1 ).length ) - assert_equal( 1, XPath.match( d, xp2 ).length ) - assert_equal( 1, XPath.match( d, xp3 ).length ) - assert_equal( 0, XPath.match( d, xp4 ).length ) - assert_equal( 0, XPath.match( d, xp5 ).length ) - assert_equal( 0, XPath.match( d, xp6 ).length ) - assert_equal( 0, XPath.match( d, xp7 ).length ) - assert_equal( 0, XPath.match( d, xp8 ).length ) - end + def test_numbers + d = Document.new %q{<a x="0" y="*" z="4e" w="e4" v="a"/>} + + xp1 = "/a[ @x = 0 ]" + xp2 = "/a[ @x = '0' ]" + xp3 = "/a[ (@x + 1) = 1 ]" + xp4 = "/a[ @y = 0 ]" + xp5 = "/a[ (@z + 1) = 5 ]" + xp6 = "/a[ (@w + 1) = 5 ]" + xp7 = "/a[ (@v + 1) = 1 ]" + xp8 = "/a[ @n = 0 ]" + + assert_equal( 1, XPath.match( d, xp1 ).length ) + assert_equal( 1, XPath.match( d, xp2 ).length ) + assert_equal( 1, XPath.match( d, xp3 ).length ) + assert_equal( 0, XPath.match( d, xp4 ).length ) + assert_equal( 0, XPath.match( d, xp5 ).length ) + assert_equal( 0, XPath.match( d, xp6 ).length ) + assert_equal( 0, XPath.match( d, xp7 ).length ) + assert_equal( 0, XPath.match( d, xp8 ).length ) + end - def test_tobis_preceding - doc_string = '<a> + def test_tobis_preceding + doc_string = '<a> <b/> <c> <d/> @@ -759,58 +759,58 @@ class TestXPathBase < Test::Unit::TestCase </c> </a>' - doc = Document.new(doc_string) + doc = Document.new(doc_string) - # e = REXML::XPath.first(doc,'/a/c/e') - e = doc.root.get_elements('/a/c/e')[0] - assert_equal( 1, e.get_elements('preceding-sibling::*').length ) - assert_equal( 2, XPath.match(e, 'preceding::*').length ) - end + # e = REXML::XPath.first(doc,'/a/c/e') + e = doc.root.get_elements('/a/c/e')[0] + assert_equal( 1, e.get_elements('preceding-sibling::*').length ) + assert_equal( 2, XPath.match(e, 'preceding::*').length ) + end - def test_filtering - #doc=Document.new("<a><b><c1/><c2/></b><b><c3/><c4/></b><b><c5/><c6/></b></a>") - #assert_equal( 3, XPath.match( doc, '/a/b/*[1]' ).length ) - #assert_equal( 2, XPath.match( doc, '/a/b/following-sibling::*[1]' ).length ) - end + def test_filtering + #doc=Document.new("<a><b><c1/><c2/></b><b><c3/><c4/></b><b><c5/><c6/></b></a>") + #assert_equal( 3, XPath.match( doc, '/a/b/*[1]' ).length ) + #assert_equal( 2, XPath.match( doc, '/a/b/following-sibling::*[1]' ).length ) + end - # Submitted by Alex - def test_union - data = %Q{<div id="the_div"> + # Submitted by Alex + def test_union + data = %Q{<div id="the_div"> <span id="the_span"> <strong id="the_strong">a</strong> </span> <em id="the_em2">b</em> </div>} - rd = REXML::Document.new( data ) - #union = rd.get_elements("/div/span | /div/em") - #assert_equal(2, union.length, "/div/span | /div/em" ) - union = rd.get_elements('//*[name()="em" or name()="strong"]') - assert_equal(2, union.length, 'name() and "or" failed') - union = rd.get_elements('//em|//strong') - assert_equal(2, union.length, - 'Both tag types are returned by XPath union operator') - end + rd = REXML::Document.new( data ) + #union = rd.get_elements("/div/span | /div/em") + #assert_equal(2, union.length, "/div/span | /div/em" ) + union = rd.get_elements('//*[name()="em" or name()="strong"]') + assert_equal(2, union.length, 'name() and "or" failed') + union = rd.get_elements('//em|//strong') + assert_equal(2, union.length, + 'Both tag types are returned by XPath union operator') + end - def test_union2 - src = <<-EOL + def test_union2 + src = <<-EOL <div id="the_div"> <span id="the_span"> <strong id="the_strong">a</strong> </span> <em id="the_em2">b</em> </div> - EOL - rd = REXML::Document.new( src ) - union = rd.get_elements('//em|//strong') - assert_equal(2, union.length, - 'Both tag types are returned by XPath union operator') - end + EOL + rd = REXML::Document.new( src ) + union = rd.get_elements('//em|//strong') + assert_equal(2, union.length, + 'Both tag types are returned by XPath union operator') + end - def test_a_star_star_one - string = <<-EOL + def test_a_star_star_one + string = <<-EOL <a> <b> <c1/> @@ -825,97 +825,97 @@ class TestXPathBase < Test::Unit::TestCase <f/> </b> </a> - EOL - d = REXML::Document.new( string ) - c1 = XPath.match( d, '/a/*/*[1]' ) - assert_equal( 1, c1.length ) - assert_equal( 'c1', c1[0].name ) - end - - def test_sum - d = Document.new("<a>"+ - "<b>1</b><b>2</b><b>3</b>"+ - "<c><d>1</d><d>2</d></c>"+ - "<e att='1'/><e att='2'/>"+ - "</a>") + EOL + d = REXML::Document.new( string ) + c1 = XPath.match( d, '/a/*/*[1]' ) + assert_equal( 1, c1.length ) + assert_equal( 'c1', c1[0].name ) + end - for v,p in [[6, "sum(/a/b)"], - [9, "sum(//b | //d)"], - [3, "sum(/a/e/@*)"] ] - assert_equal( v, XPath::match( d, p ).first ) + def test_sum + d = Document.new("<a>"+ + "<b>1</b><b>2</b><b>3</b>"+ + "<c><d>1</d><d>2</d></c>"+ + "<e att='1'/><e att='2'/>"+ + "</a>") + + for v,p in [[6, "sum(/a/b)"], + [9, "sum(//b | //d)"], + [3, "sum(/a/e/@*)"] ] + assert_equal( v, XPath::match( d, p ).first ) + end end - end - def test_xpath_namespace - d = REXML::Document.new("<tag1 xmlns='ns1'><tag2 xmlns='ns2'/><tada>xa</tada></tag1>") - x = d.root - num = 0 - x.each_element('tada') { num += 1 } - assert_equal(1, num) - end + def test_xpath_namespace + d = REXML::Document.new("<tag1 xmlns='ns1'><tag2 xmlns='ns2'/><tada>xa</tada></tag1>") + x = d.root + num = 0 + x.each_element('tada') { num += 1 } + assert_equal(1, num) + end - def test_ticket_39 - doc = REXML::Document.new( <<-EOL ) - <rss> - <channel> - <!-- removing the namespace declaration makes the test pass --> - <convertLineBreaks xmlns="http://www.blogger.com/atom/ns#">true</convertLineBreaks> - <item> - <title>Item 1</title> - </item> - <item> - <title>Item 2</title> - <pubDate>Thu, 13 Oct 2005 19:59:00 +0000</pubDate> - </item> - <item> - <title>Item 3</title> - </item> - </channel> - </rss> - EOL - root_node = XPath.first(doc, "rss") - assert_not_nil root_node - channel_node = XPath.first(root_node, "channel") - assert_not_nil channel_node - items = XPath.match(channel_node, "*") - assert_equal 4, items.size - items = XPath.match(channel_node, "item") - assert_equal 3, items.size # fails - end + def test_ticket_39 + doc = REXML::Document.new( <<-EOL ) + <rss> + <channel> + <!-- removing the namespace declaration makes the test pass --> + <convertLineBreaks xmlns="http://www.blogger.com/atom/ns#">true</convertLineBreaks> + <item> + <title>Item 1</title> + </item> + <item> + <title>Item 2</title> + <pubDate>Thu, 13 Oct 2005 19:59:00 +0000</pubDate> + </item> + <item> + <title>Item 3</title> + </item> + </channel> + </rss> + EOL + root_node = XPath.first(doc, "rss") + assert_not_nil root_node + channel_node = XPath.first(root_node, "channel") + assert_not_nil channel_node + items = XPath.match(channel_node, "*") + assert_equal 4, items.size + items = XPath.match(channel_node, "item") + assert_equal 3, items.size # fails + end - def test_ticket_42 - source = "<a></a>" - doc = Document.new(source) - bElem = Element.new('b') - doc.root.add_element(bElem) - doc.elements.each('//b[name(..) = "a"]') { |x| - assert_equal x,bElem - } - end + def test_ticket_42 + source = "<a></a>" + doc = Document.new(source) + bElem = Element.new('b') + doc.root.add_element(bElem) + doc.elements.each('//b[name(..) = "a"]') { |x| + assert_equal x,bElem + } + end - def test_ticket_56 - namespaces = {'h' => 'http://www.w3.org/1999/xhtml'} + def test_ticket_56 + namespaces = {'h' => 'http://www.w3.org/1999/xhtml'} - finaldoc = REXML::Document.new(File.read(fixture_path('google.2.xml'))) + finaldoc = REXML::Document.new(File.read(fixture_path('google.2.xml'))) - column_headers = [] + column_headers = [] - REXML::XPath.each(finaldoc, '//h:form[@action="ModifyCampaign"]//h:th', - namespaces) do |el| - node = REXML::XPath.first(el, 'h:a/text()', namespaces) - column_headers << (node ? node.value : nil) + REXML::XPath.each(finaldoc, '//h:form[@action="ModifyCampaign"]//h:th', + namespaces) do |el| + node = REXML::XPath.first(el, 'h:a/text()', namespaces) + column_headers << (node ? node.value : nil) + end + column_headers.map! { |h| h.to_s.strip.chomp } + expected = ["", "", "Current Status", "Current Budget", + "Clicks", "Impr.", "CTR", "Avg. CPC", "Cost", "Conv. Rate", + "Cost/Conv."] + assert_equal( expected, column_headers ) end - column_headers.map! { |h| h.to_s.strip.chomp } - expected = ["", "", "Current Status", "Current Budget", - "Clicks", "Impr.", "CTR", "Avg. CPC", "Cost", "Conv. Rate", - "Cost/Conv."] - assert_equal( expected, column_headers ) - end - def test_ticket_70 - string = <<EOF + def test_ticket_70 + string = <<EOF <mydoc> @@ -929,134 +929,134 @@ text</someelement> </mydoc> EOF - doc = Document.new string - assert_equal( 1, XPath.match( doc, "//someelement[contains(@attribute,'1.10')]" ).length ) - end + doc = Document.new string + assert_equal( 1, XPath.match( doc, "//someelement[contains(@attribute,'1.10')]" ).length ) + end - def test_ticket_43 - #url = http://news.search.yahoo.com/news/rss?p=market&ei=UTF-8&fl=0&x=wrt + def test_ticket_43 + #url = http://news.search.yahoo.com/news/rss?p=market&ei=UTF-8&fl=0&x=wrt - sum = Document.new(File.new(fixture_path("yahoo.xml"))).elements.to_a("//item").size - assert_equal( 10, sum ) + sum = Document.new(File.new(fixture_path("yahoo.xml"))).elements.to_a("//item").size + assert_equal( 10, sum ) - text = Document.new(File.new(fixture_path("yahoo.xml"))).elements.to_a(%Q{//title[contains(text(), "'")]}).collect{|e| e.text}.join - assert_equal( "Broward labor market's a solid performer (Miami Herald)", text ) - end + text = Document.new(File.new(fixture_path("yahoo.xml"))).elements.to_a(%Q{//title[contains(text(), "'")]}).collect{|e| e.text}.join + assert_equal( "Broward labor market's a solid performer (Miami Herald)", text ) + end - def test_ticket_57 - data = "<?xml version='1.0'?><a:x xmlns:a='1'><a:y p='p' q='q'><a:z>zzz</a:z></a:y></a:x>" + def test_ticket_57 + data = "<?xml version='1.0'?><a:x xmlns:a='1'><a:y p='p' q='q'><a:z>zzz</a:z></a:y></a:x>" - r = Document.new(data) + r = Document.new(data) - assert_equal(Text, REXML::XPath.first(r,"a:x/a:y[@p='p' and @q='q']/a:z/text()").class) - assert_equal("zzz", REXML::XPath.first(r,"a:x/a:y[@p='p' and @q='q']/a:z/text()").to_s) - end + assert_equal(Text, REXML::XPath.first(r,"a:x/a:y[@p='p' and @q='q']/a:z/text()").class) + assert_equal("zzz", REXML::XPath.first(r,"a:x/a:y[@p='p' and @q='q']/a:z/text()").to_s) + end - def test_ticket_59 - data = "<a> - <c id='1'/> - <c id='2'/> - <b> - <c id='3'/> - </b> - <c id='4'/> - <b> + def test_ticket_59 + data = "<a> + <c id='1'/> + <c id='2'/> <b> - <c id='5'/> + <c id='3'/> </b> - <c id='6'/> - </b> - <c id='7'/> - <b> + <c id='4'/> <b> - <c id='8'/> <b> - <c id='9'/> + <c id='5'/> + </b> + <c id='6'/> + </b> + <c id='7'/> + <b> + <b> + <c id='8'/> <b> - <c id='10'/> + <c id='9'/> + <b> + <c id='10'/> + </b> + <c id='11'/> </b> - <c id='11'/> </b> </b> - </b> - <c id='12'/> - </a>" - d = Document.new(data) - res = d.elements.to_a( "//c" ).collect {|e| e.attributes['id'].to_i} - assert_equal( res, res.sort ) - end + <c id='12'/> + </a>" + d = Document.new(data) + res = d.elements.to_a( "//c" ).collect {|e| e.attributes['id'].to_i} + assert_equal( res, res.sort ) + end - def ticket_61_fixture(doc, xpath) - matches = [] - doc.elements.each(xpath) do |element| - matches << element - assert_equal('Add', element.text) - assert_equal('ButtonText', element.attributes['class']) + def ticket_61_fixture(doc, xpath) + matches = [] + doc.elements.each(xpath) do |element| + matches << element + assert_equal('Add', element.text) + assert_equal('ButtonText', element.attributes['class']) + end + assert_equal(1, matches.length) end - assert_equal(1, matches.length) - end - def test_ticket_61_text - file = File.open(fixture_path("ticket_61.xml")) - doc = REXML::Document.new file - ticket_61_fixture( doc, "//div[text()='Add' and @class='ButtonText']" ) - end + def test_ticket_61_text + file = File.open(fixture_path("ticket_61.xml")) + doc = REXML::Document.new file + ticket_61_fixture( doc, "//div[text()='Add' and @class='ButtonText']" ) + end - def test_ticket_61_contains - file = File.open(fixture_path("ticket_61.xml")) - doc = REXML::Document.new file - ticket_61_fixture( doc, "//div[contains(.,'Add') and @class='ButtonText']" ) - end + def test_ticket_61_contains + file = File.open(fixture_path("ticket_61.xml")) + doc = REXML::Document.new file + ticket_61_fixture( doc, "//div[contains(.,'Add') and @class='ButtonText']" ) + end - def test_namespaces_0 - d = Document.new(%q{<x:a xmlns:x="y"/>}) - assert_equal( 1, XPath.match( d, "//x:a" ).size ) - assert_equal( 1, XPath.match( d, "//x:*" ).size ) - end + def test_namespaces_0 + d = Document.new(%q{<x:a xmlns:x="y"/>}) + assert_equal( 1, XPath.match( d, "//x:a" ).size ) + assert_equal( 1, XPath.match( d, "//x:*" ).size ) + end - def test_ticket_71 - doc = Document.new(%Q{<root xmlns:ns1="xyz" xmlns:ns2="123"><element ns1:attrname="foo" ns2:attrname="bar"/></root>}) - el = doc.root.elements[1] - assert_equal( "element", el.name ) - el2 = XPath.first( doc.root, "element[@ns:attrname='foo']", { 'ns' => "xyz" } ) - assert_equal( el, el2 ) - end + def test_ticket_71 + doc = Document.new(%Q{<root xmlns:ns1="xyz" xmlns:ns2="123"><element ns1:attrname="foo" ns2:attrname="bar"/></root>}) + el = doc.root.elements[1] + assert_equal( "element", el.name ) + el2 = XPath.first( doc.root, "element[@ns:attrname='foo']", { 'ns' => "xyz" } ) + assert_equal( el, el2 ) + end - def test_ticket_78 - doc = <<-EOT - <root> - <element> - <tag x='1'>123</tag> - </element> - <element> - <tag x='2'>123a</tag> - </element> - </root> - EOT - seq = %w{BEGIN 123 END BEGIN 123a END} - - xmlDoc = Document.new(doc) - - ["//element[tag='123']/tag", "//element[tag='123a']/tag"].each do |query| - assert_equal( "BEGIN", seq.shift ) - XPath.each(xmlDoc, query) { |element| - assert_equal( seq.shift, element.text ) - } - assert_equal( "END", seq.shift ) + def test_ticket_78 + doc = <<-EOT + <root> + <element> + <tag x='1'>123</tag> + </element> + <element> + <tag x='2'>123a</tag> + </element> + </root> + EOT + seq = %w{BEGIN 123 END BEGIN 123a END} + + xmlDoc = Document.new(doc) + + ["//element[tag='123']/tag", "//element[tag='123a']/tag"].each do |query| + assert_equal( "BEGIN", seq.shift ) + XPath.each(xmlDoc, query) { |element| + assert_equal( seq.shift, element.text ) + } + assert_equal( "END", seq.shift ) + end end - end - def test_ticket_79 - source = "<a><b><c>test</c></b><b><c>3</c></b></a>" - d = REXML::Document.new( source ) - r = REXML::XPath.match( d, %q{/a/b[c='test']} ) - assert_equal(1, r.size()) - r = REXML::XPath.match( d, %q{/a/b[c='3']} ) - assert_equal(1, r.size()) - end + def test_ticket_79 + source = "<a><b><c>test</c></b><b><c>3</c></b></a>" + d = REXML::Document.new( source ) + r = REXML::XPath.match( d, %q{/a/b[c='test']} ) + assert_equal(1, r.size()) + r = REXML::XPath.match( d, %q{/a/b[c='3']} ) + assert_equal(1, r.size()) + end - def test_or_and - doc = " + def test_or_and + doc = " <html> <head> <title>test</title> @@ -1069,13 +1069,13 @@ EOF </html> " - xmldoc = REXML::Document.new(doc) - xpath = "descendant::node()[(local-name()='link' or local-name()='a') and @rel='sub']" - hrefs = [] - xmldoc.elements.each(xpath) do |element| - hrefs << element.attributes["href"] + xmldoc = REXML::Document.new(doc) + xpath = "descendant::node()[(local-name()='link' or local-name()='a') and @rel='sub']" + hrefs = [] + xmldoc.elements.each(xpath) do |element| + hrefs << element.attributes["href"] + end + assert_equal(["/"], hrefs, "Bug #3842 [ruby-core:32447]") end - assert_equal(["/"], hrefs, "Bug #3842 [ruby-core:32447]") end end -end diff --git a/test/rexml/xpath/test_node.rb b/test/rexml/xpath/test_node.rb index f0109be9ff..aec2de1cfe 100644 --- a/test/rexml/xpath/test_node.rb +++ b/test/rexml/xpath/test_node.rb @@ -5,38 +5,38 @@ require_relative "../rexml_test_utils" require "rexml/document" module REXMLTests -class TestXPathNode < Test::Unit::TestCase - def matches(xml, xpath) - document = REXML::Document.new(xml) - REXML::XPath.each(document, xpath).collect(&:to_s) - end + class TestXPathNode < Test::Unit::TestCase + def matches(xml, xpath) + document = REXML::Document.new(xml) + REXML::XPath.each(document, xpath).collect(&:to_s) + end - class TestQName < self - def test_ascii - xml = <<-XML + class TestQName < self + def test_ascii + xml = <<-XML <?xml version="1.0" encoding="UTF-8"?> <root> <ascii> <child>child</child> </ascii> </root> - XML - assert_equal(["<child>child</child>"], - matches(xml, "/root/ascii/child")) - end + XML + assert_equal(["<child>child</child>"], + matches(xml, "/root/ascii/child")) + end - def test_non_ascii - xml = <<-XML + def test_non_ascii + xml = <<-XML <?xml version="1.0" encoding="UTF-8"?> <root> <non-àscii> <child>child</child> </non-àscii> </root> - XML - assert_equal(["<child>child</child>"], - matches(xml, "/root/non-àscii/child")) + XML + assert_equal(["<child>child</child>"], + matches(xml, "/root/non-àscii/child")) + end end end end -end diff --git a/test/rexml/xpath/test_predicate.rb b/test/rexml/xpath/test_predicate.rb index 4cbf244d74..287e131c54 100644 --- a/test/rexml/xpath/test_predicate.rb +++ b/test/rexml/xpath/test_predicate.rb @@ -4,60 +4,60 @@ require "rexml/xpath" require "rexml/parsers/xpathparser" module REXMLTests -class TestXPathPredicate < Test::Unit::TestCase - include REXML - SRC=<<-EOL - <article> - <section role="subdivision" id="1"> - <para>free flowing text.</para> - </section> - <section role="division"> - <section role="subdivision" id="2"> - <para>free flowing text.</para> - </section> - <section role="division"> - <para>free flowing text.</para> - </section> - </section> - </article> - EOL + class TestXPathPredicate < Test::Unit::TestCase + include REXML + SRC=<<-EOL + <article> + <section role="subdivision" id="1"> + <para>free flowing text.</para> + </section> + <section role="division"> + <section role="subdivision" id="2"> + <para>free flowing text.</para> + </section> + <section role="division"> + <para>free flowing text.</para> + </section> + </section> + </article> + EOL - def setup - @doc = REXML::Document.new( SRC ) - @parser = REXML::Parsers::XPathParser.new + def setup + @doc = REXML::Document.new( SRC ) + @parser = REXML::Parsers::XPathParser.new - end + end - def test_predicates_parent - path = '//section[../self::section[@role="division"]]' - m = do_path( path ) - assert_equal( 2, m.size ) - assert_equal( "2", m[0].attributes["id"] ) - assert_nil( m[1].attributes["id"] ) - end + def test_predicates_parent + path = '//section[../self::section[@role="division"]]' + m = do_path( path ) + assert_equal( 2, m.size ) + assert_equal( "2", m[0].attributes["id"] ) + assert_nil( m[1].attributes["id"] ) + end - def test_predicates_single - path = '//section[@role="subdivision" and not(../self::section[@role="division"])]' - m = do_path( path ) - assert_equal( 1, m.size ) - assert_equal( "1", m[0].attributes["id"] ) - end + def test_predicates_single + path = '//section[@role="subdivision" and not(../self::section[@role="division"])]' + m = do_path( path ) + assert_equal( 1, m.size ) + assert_equal( "1", m[0].attributes["id"] ) + end - def test_predicates_multi - path = '//section[@role="subdivision"][not(../self::section[@role="division"])]' - m = do_path( path ) - assert_equal( 1, m.size ) - assert_equal( "1", m[0].attributes["id"] ) - end + def test_predicates_multi + path = '//section[@role="subdivision"][not(../self::section[@role="division"])]' + m = do_path( path ) + assert_equal( 1, m.size ) + assert_equal( "1", m[0].attributes["id"] ) + end - def do_path( path ) - m = REXML::XPath.match( @doc, path ) - #puts path, @parser.parse( path ).inspect - return m - end + def do_path( path ) + m = REXML::XPath.match( @doc, path ) + #puts path, @parser.parse( path ).inspect + return m + end - def test_get_no_siblings_terminal_nodes - source = <<-XML + def test_get_no_siblings_terminal_nodes + source = <<-XML <a> <b number='1' str='abc'>TEXT1</b> <c number='1'/> @@ -68,15 +68,15 @@ class TestXPathPredicate < Test::Unit::TestCase </c> </a> XML - doc = REXML::Document.new(source) - predicate = "count(child::node()|" + - "following-sibling::node()|" + - "preceding-sibling::node())=0" - m = REXML::XPath.match(doc, "/descendant-or-self::node()[#{predicate}]") - assert_equal( [REXML::Text.new("TEXT1"), - REXML::Text.new("TEXT2"), - REXML::Comment.new("COMMENT")], - m ) + doc = REXML::Document.new(source) + predicate = "count(child::node()|" + + "following-sibling::node()|" + + "preceding-sibling::node())=0" + m = REXML::XPath.match(doc, "/descendant-or-self::node()[#{predicate}]") + assert_equal( [REXML::Text.new("TEXT1"), + REXML::Text.new("TEXT2"), + REXML::Comment.new("COMMENT")], + m ) + end end end -end diff --git a/test/rexml/xpath/test_text.rb b/test/rexml/xpath/test_text.rb index cf65130854..46aba3c2ef 100644 --- a/test/rexml/xpath/test_text.rb +++ b/test/rexml/xpath/test_text.rb @@ -4,71 +4,71 @@ require 'rexml/element' require 'rexml/xpath' module REXMLTests -class TestXPathText < Test::Unit::TestCase - def setup - @doc = REXML::Document.new - end + class TestXPathText < Test::Unit::TestCase + def setup + @doc = REXML::Document.new + end - def tear_down - end + def tear_down + end - def test_text_as_element - node1 = REXML::Element.new('a', @doc) - node2 = REXML::Element.new('b', node1) - REXML::Text.new('test', false, node2) - assert_equal(1, @doc.elements.size, "doc owns 1 element node1") - assert_same(node1, @doc.elements[1], "doc owns 1 element node1") - assert_equal(1, node1.elements.size, "node1 owns 1 element node2") - assert_same(node2, node1.elements[1], "node1 owns 1 element node2") - assert_equal(1, node2.size, "node2 owns 1 text element") - end + def test_text_as_element + node1 = REXML::Element.new('a', @doc) + node2 = REXML::Element.new('b', node1) + REXML::Text.new('test', false, node2) + assert_equal(1, @doc.elements.size, "doc owns 1 element node1") + assert_same(node1, @doc.elements[1], "doc owns 1 element node1") + assert_equal(1, node1.elements.size, "node1 owns 1 element node2") + assert_same(node2, node1.elements[1], "node1 owns 1 element node2") + assert_equal(1, node2.size, "node2 owns 1 text element") + end - def test_text_in_xpath_query - node1 = REXML::Element.new('a', @doc) - node2 = REXML::Element.new('b', node1) - textnode = REXML::Text.new('test', false, node2) - textnode.parent = node2 # should be unnecessary - nodes = @doc.get_elements('//b') - assert_equal(1, nodes.size, "document has one element") - # why doesn't this query work right? - nodes = REXML::XPath.match(@doc, '//text()') - assert_equal(1, nodes.size, "//text() should yield one Text element") - assert_equal(REXML::Text, nodes[0].class) - end + def test_text_in_xpath_query + node1 = REXML::Element.new('a', @doc) + node2 = REXML::Element.new('b', node1) + textnode = REXML::Text.new('test', false, node2) + textnode.parent = node2 # should be unnecessary + nodes = @doc.get_elements('//b') + assert_equal(1, nodes.size, "document has one element") + # why doesn't this query work right? + nodes = REXML::XPath.match(@doc, '//text()') + assert_equal(1, nodes.size, "//text() should yield one Text element") + assert_equal(REXML::Text, nodes[0].class) + end - def test_comment_in_xpath_query - node1 = REXML::Element.new('a', @doc) - node2 = REXML::Element.new('b', node1) - commentnode = REXML::Comment.new('test', node2) - nodes = REXML::XPath.match(@doc, '//comment()') - assert_equal(1, nodes.size, "//comment() should yield one Comment element") - assert_same commentnode, nodes[0] - end + def test_comment_in_xpath_query + node1 = REXML::Element.new('a', @doc) + node2 = REXML::Element.new('b', node1) + commentnode = REXML::Comment.new('test', node2) + nodes = REXML::XPath.match(@doc, '//comment()') + assert_equal(1, nodes.size, "//comment() should yield one Comment element") + assert_same commentnode, nodes[0] + end - def test_parentage - node1 = REXML::Element.new('a', @doc) - assert_same(@doc, node1.parent, "node1 parent is document") - node2 = REXML::Element.new('b', node1) - assert_same(node1, node2.parent, "node2 parent is node1") - textnode = REXML::Text.new('test', false, node2) - # why isn't the text's parent node2? - # Also look at Comment, etc. - assert_same(node2, textnode.parent) - comment = REXML::Comment.new('Test comment', node2) - assert_same(node2, comment.parent) - end + def test_parentage + node1 = REXML::Element.new('a', @doc) + assert_same(@doc, node1.parent, "node1 parent is document") + node2 = REXML::Element.new('b', node1) + assert_same(node1, node2.parent, "node2 parent is node1") + textnode = REXML::Text.new('test', false, node2) + # why isn't the text's parent node2? + # Also look at Comment, etc. + assert_same(node2, textnode.parent) + comment = REXML::Comment.new('Test comment', node2) + assert_same(node2, comment.parent) + end - def test_ancestors - node1 = REXML::Element.new('a', @doc) - node2 = REXML::Element.new('b', node1) - textnode = REXML::Text.new('test', false, node2) - #textnode.parent = node2 # should be unnecessary - assert_same node2, textnode.parent - nodes = @doc.get_elements('//b/ancestor::*') - assert_equal(1, nodes.size, "<b> has one element ancestor") - nodes = @doc.get_elements('//b/ancestor::node()') - assert_equal(2, nodes.size, "<b> has two node ancestors") - assert nodes[1].kind_of?(REXML::Document) + def test_ancestors + node1 = REXML::Element.new('a', @doc) + node2 = REXML::Element.new('b', node1) + textnode = REXML::Text.new('test', false, node2) + #textnode.parent = node2 # should be unnecessary + assert_same node2, textnode.parent + nodes = @doc.get_elements('//b/ancestor::*') + assert_equal(1, nodes.size, "<b> has one element ancestor") + nodes = @doc.get_elements('//b/ancestor::node()') + assert_equal(2, nodes.size, "<b> has two node ancestors") + assert nodes[1].kind_of?(REXML::Document) + end end end -end |