From ba3d2f4ac20bec871fe96a393d923d0cbb0fd96a Mon Sep 17 00:00:00 2001 From: kou Date: Tue, 27 May 2014 13:10:55 +0000 Subject: * test/rexml/test_contrib.rb: Indent. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@46174 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- test/rexml/parse/test_document_type_declaration.rb | 56 +- test/rexml/parse/test_notation_declaration.rb | 118 +- test/rexml/test_attributes.rb | 342 +-- test/rexml/test_attributes_mixin.rb | 48 +- test/rexml/test_changing_encoding.rb | 66 +- test/rexml/test_contrib.rb | 880 +++---- test/rexml/test_core.rb | 2454 ++++++++++---------- test/rexml/test_doctype.rb | 190 +- test/rexml/test_elements.rb | 196 +- test/rexml/test_encoding.rb | 150 +- test/rexml/test_entity.rb | 312 +-- test/rexml/test_functions.rb | 400 ++-- test/rexml/test_functions_number.rb | 52 +- test/rexml/test_jaxen.rb | 208 +- test/rexml/test_light.rb | 170 +- test/rexml/test_lightparser.rb | 16 +- test/rexml/test_listener.rb | 202 +- test/rexml/test_martin_fowler.rb | 40 +- test/rexml/test_namespace.rb | 54 +- test/rexml/test_order.rb | 172 +- test/rexml/test_preceding_sibling.rb | 56 +- test/rexml/test_pullparser.rb | 160 +- test/rexml/test_rexml_issuezilla.rb | 18 +- test/rexml/test_sax.rb | 472 ++-- test/rexml/test_stream.rb | 194 +- test/rexml/test_text.rb | 28 +- test/rexml/test_ticket_80.rb | 46 +- test/rexml/test_validation_rng.rb | 616 ++--- test/rexml/test_xml_declaration.rb | 42 +- test/rexml/xpath/test_attribute.rb | 30 +- test/rexml/xpath/test_axis_preceding_sibling.rb | 54 +- test/rexml/xpath/test_base.rb | 1820 +++++++-------- test/rexml/xpath/test_node.rb | 36 +- test/rexml/xpath/test_predicate.rb | 114 +- test/rexml/xpath/test_text.rb | 120 +- 35 files changed, 4966 insertions(+), 4966 deletions(-) (limited to 'test/rexml') 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 - 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) - 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) - 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) - 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 - XML - end - - def parse(internal_subset) - REXML::Document.new(xml(internal_subset)).doctype - end - - class TestCommon < self - def test_name - doctype = parse("") - assert_equal("name", doctype.notation("name").name) + XML end - end - class TestExternalID < self - class TestSystem < self - def test_single_quote - doctype = parse(<<-INTERNAL_SUBSET) - - 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) - - INTERNAL_SUBSET - assert_equal("system-literal", doctype.notation("name").system) + class TestCommon < self + def test_name + doctype = parse("") + 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) - + 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) - + 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) - - INTERNAL_SUBSET - assert_equal("system-literal", doctype.notation("name").system) + class TestPublic < self + class TestPublicIDLiteral < self + def test_single_quote + doctype = parse(<<-INTERNAL_SUBSET) + + INTERNAL_SUBSET + assert_equal("public-id-literal", doctype.notation("name").public) + end + + def test_double_quote + doctype = parse(<<-INTERNAL_SUBSET) + + 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) + + INTERNAL_SUBSET + assert_equal("system-literal", doctype.notation("name").system) + end + + def test_double_quote + doctype = parse(<<-INTERNAL_SUBSET) - 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) - 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) - 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("") - 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('') - 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("") + 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('') - 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('') + 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('') - 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('') + 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("") - assert_equal 4, doc.root.attributes.length - end + def test_get_attribute + doc = Document.new('') + 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("") - 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("") + assert_equal 4, doc.root.attributes.length + end - def test_delete - doc = Document.new("") - 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("") + 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("") + 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("") - 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##) - s = doc.to_s - assert(s =~ /h1='1'2''/) - assert(s =~ /h2='1"2'/) - end + def test_prefixes + doc = Document.new("") + 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 - - - - XML + # Contributed by Mike Stok + def test_values_with_apostrophes + doc = Document.new(%q##) + s = doc.to_s + assert(s =~ /h1='1'2''/) + assert(s =~ /h2='1"2'/) end - REXML::Document.new("") - 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 + + + + 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("") + 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{}) - assert_equal( %q{}, d.to_s ) - d.root.context[:attribute_quote] = :quote - assert_equal( %q{}, d.to_s ) + def test_amp_and_lf_attributes + attr_test('name','value with LF & ampersand') + end - d = Document.new(%q{}) - assert_equal( %q{}, d.to_s ) - d.root.context[:attribute_quote] = :quote - assert_equal( %q{}, d.to_s ) - end + def test_quoting + d = Document.new(%q{}) + assert_equal( %q{}, d.to_s ) + d.root.context[:attribute_quote] = :quote + assert_equal( %q{}, 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{}) + assert_equal( %q{}, d.to_s ) + d.root.context[:attribute_quote] = :quote + assert_equal( %q{}, 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) @@ -209,14 +209,14 @@ class AttributesTester < Test::Unit::TestCase other-attribute="other-value"/> 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" - - 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" + + 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 = < @@ -32,7 +32,7 @@ class ContribTester < Test::Unit::TestCase DELIMITER - XML_STRING_02 = < english @@ -52,205 +52,205 @@ DELIMITER DELIMITER - # Tobias Reif - def test_bad_doctype_Tobias - source = <<-EOF - --> - - - ' + # Tobias Reif + def test_bad_doctype_Tobias + source = <<-EOF + --> + + + ' + > + ] > - ] - > - 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 - - - - - - - - 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 + + + + + + + + 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 - def test_complex_xpath_Tobias - source = <<-EOF - - - - - - - - - - - - - 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 + def test_complex_xpath_Tobias + source = <<-EOF + + + + + + + + + + + + + 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" - 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" + 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 - def test_other_xpath_Tobias - schema = <<-DELIM - - - - - - - - - - - - - - - - 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 + def test_other_xpath_Tobias + schema = <<-DELIM + + + + + + + + + + + + + + + + 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 'Thomas, David; Hunt, Andrew' - 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 'Thomas, David; Hunt, Andrew' + 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('Thomas, David; Hunt, Andrew') - 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('Thomas, David; Hunt, Andrew') + 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 'Thomas, David; Hunt, Andrew' - # 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 'Thomas, David; Hunt, Andrew' + # 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 = " + def test_xpath_03_TobiasReif + doc = Document.new XML_STRING_02.dup + desired_result_string = " english Addison-Wesley Programming Ruby. The Pragmatic Programmer's Guide Book 2000 " - 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 = "#{koln_iso}" - source_utf = "#{koln_utf}" - - 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 = "#{koln_iso}" + source_utf = "#{koln_utf}" + + 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 Technik @@ -266,254 +266,254 @@ Die Technik ist das R\xFCckgrat der meisten Gesch\xFCftsprozesse bei Home of the 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 '

Dummy title

' + 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 '

Dummy title

' - 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('

') - doc = REXML::Document.new('

3

') - - [['/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('

') + doc = REXML::Document.new('

3

') + + [['/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 - - - - - - - - - - - - - ]> - - - - - uga.rb - 0444 - &rbconfig.libdir;/rexml - ... the file here - - - booga.h - 0444 - &rbconfig.includedir; - ... the file here - - - foo.so - 0555 - &rbconfig.sitearchdir;/rexml - Li4uIHRoZSBmaWxlIGhlcmU=\n - - - - - 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 + + + + + + + + + + + + + ]> + + + + + uga.rb + 0444 + &rbconfig.libdir;/rexml + ... the file here + + + booga.h + 0444 + &rbconfig.includedir; + ... the file here + + + foo.so + 0555 + &rbconfig.sitearchdir;/rexml + Li4uIHRoZSBmaWxlIGhlcmU=\n + + + + + 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 - 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{ + def test_maintain_dtd + src = %q{ %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 = "test" - 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 = "test" + 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 = 'abcødef' - 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 = 'abcødef' + 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{ + def test_pos + require 'tempfile' + Tempfile.create("tidal") {|testfile| + testdata = %Q{
760 50 @@ -521,63 +521,63 @@ EOL } - 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( '' ) - b = a.deep_clone - assert_equal a.to_s, b.to_s - end + def test_deep_clone + a = Document.new( '' ) + b = a.deep_clone + assert_equal a.to_s, b.to_s + end - def test_double_escaping - data = 'AT&T' - xml = "" + def test_double_escaping + data = 'AT&T' + xml = "" - 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 = "ab" + def test_ticket_12 + cfg = "ab" - 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 ' - -' - 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 - # 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 ' + + ' + 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 + # 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 - - - - - - - - Lars Marius Garshol - larsga@garshol.priv.no - http://www.stud.ifi.uio.no/~lmariusg/ - - - EOL - end + class Tester < Test::Unit::TestCase + include REXMLTestUtils + include REXML + def setup + @xsa_source = <<-EOL + + + + + + + + Lars Marius Garshol + larsga@garshol.priv.no + http://www.stud.ifi.uio.no/~lmariusg/ + + + EOL + end - def test_bad_markup - [ - " foo ", - '<0/>', - '&', - '&a', -# '&a;', # FIXME - '', - '', - '', - '', - '', - '', - '', - "", - "\f", - "", - "\000", + def test_bad_markup + [ + " foo ", + '<0/>', + '&', + '&a', +# '&a;', # FIXME + '', + '', + '', + '', + '', + '', + '', + "", + "\f", + "", + "\000", # FIXME '', - '', - '￿', + '', + '￿', # FIXME '', # FIXME '', - ].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( "" ) - #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 = 'blah' - 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 - text = "this is a {target[@name='test']/@value} test" - source = <<-EOL - - - 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().join(' '), e.to_s - end + def test_attribute + # Testing constructors + #a = Attribute.new "hello", "dolly" + #b = Attribute.new a + #d = Document.new( "" ) + #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 = 'blah' + 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 + text = "this is a {target[@name='test']/@value} test" + source = <<-EOL + + + 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().join(' '), e.to_s + end - source = "" - 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 = "" + d = REXML::Document.new( source ) - def test_comment - string = "This is a new comment!" - source = "" - 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("") - } - assert_raise(ParseException) { - REXML::Document.new("" + 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("") + } + assert_raise(ParseException) { + REXML::Document.new(" - - - - - - - - - - - - - - - - - - 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 - - - - - - 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 "Some text", 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 = "blah" + 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 + + + EOF + doc = Document.new(source) + assert_equal("http://www.bar.com/schema", doc.root.namespace( "foo" )) + source = <<-EOF + + + + + + + + + + + + + + + + + + + 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 + + + + + + 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 "Some text", 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(" ", c) - Document.parse_stream("<>&", 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(" ", c) + + Document.parse_stream("<>&", c) + assert_equal('<>&', c.normalize) + end - def test_exception - source = SourceFactory.create_from "" - 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 = 'content>content' - in_lt = 'content' + 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("") - count = 0 - doc.root.elements[1].attributes.each {|k,v| count += 1 } - assert_equal 4, count - end + def test_exception + source = SourceFactory.create_from "" + p = ParseException.new( "dummy message", source ) + begin + raise "dummy" + rescue Exception + p.continued_exception = $! + end + end - def test_delete_namespace - doc = Document.new "" - doc.root.delete_namespace - doc.root.delete_namespace 'x' - assert_equal "", doc.to_s - end + def test_bad_content + in_gt = 'content>content' + in_lt = 'content' - def test_each_element_with_attribute - doc = Document.new "" - 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 'bbd' - 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( "some text" ) - 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("") + count = 0 + doc.root.elements[1].attributes.each {|k,v| count += 1 } + assert_equal 4, count + end - def test_deep_clone - a = Document.new( 'texttexttext' ) - b = a.deep_clone - assert_equal a.to_s, b.to_s + def test_delete_namespace + doc = Document.new "" + doc.root.delete_namespace + doc.root.delete_namespace 'x' + assert_equal "", doc.to_s + end - a = Document.new( 'some < text more > text > ' ) - 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 "" + 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 'bbd' + 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( "some text" ) + 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 = <texttexttext' ) + b = a.deep_clone + assert_equal a.to_s, b.to_s + + a = Document.new( 'some < text more > text > ' ) + 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 - 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( 'eeü' ) - assert_equal('eeü'.force_encoding("UTF-8"), a.root.text) - end + def test_entities + a = Document.new( 'eeü' ) + assert_equal('eeü'.force_encoding("UTF-8"), a.root.text) + end - def test_element_decl - element_decl = Source.new(" ]>") - doc = Document.new( element_decl ) - d = doc[0] - assert_equal("", d.to_s.split(/\n/)[1].strip) - end + doc = Document.new( element_decl ) + d = doc[0] + assert_equal("", d.to_s.split(/\n/)[1].strip) + end - def test_attlist_decl - doc = Document.new <<-EOL - - - ]> - - 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 - - - - ]> - - EOL - prefixes = doc.root.prefixes.sort - correct = ['svg', 'xlink', 'xml'] - assert_equal correct, prefixes - end + def test_attlist_decl + doc = Document.new <<-EOL + + + ]> + + 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 + + + + ]> + + 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("

") - } - doc2 = Document.new("

") - 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("

") + } + doc2 = Document.new("

") + 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 - - X - Y - - - Z - - - 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 + + X + Y + + + Z + + + 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("") - 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("") + 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\n\n\n\n\n") - end + def test_oses_with_bad_EOLs + Document.new("\n\n\n\n\n\n\n\n") + end - # Contributed (with patch to fix bug) by Kouhei - def test_ignore_whitespace - source = " abc " + # Contributed (with patch to fix bug) by Kouhei + def test_ignore_whitespace + source = " abc " - 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 = "\x0D\x0D" - doc = Document.new doc - end + def test_0xD_in_preface + doc = "\x0D\x0D" + doc = Document.new doc + end - def test_hyphens_in_doctype - doc = REXML::Document.new <<-EOQ - - - - - - EOQ + def test_hyphens_in_doctype + doc = REXML::Document.new <<-EOQ + + + + + + EOQ - assert_equal('a-b-c', doc.doctype.name) - end + assert_equal('a-b-c', doc.doctype.name) + end - def test_accents - docs = [ - %Q{ + def test_accents + docs = [ + %Q{ }, - ' + ' ', - %Q{ + %Q{ }, - %Q{ + %Q{ } ] - 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( "foo", e.to_s ) - e[0].value = "bar" - assert_equal( "bar", e.to_s ) - e[0].value = "<" - assert_equal( "<", e.to_s ) - assert_equal( "<", e[0].value ) - end + def test_replace_text + e = REXML::Element.new( "a" ) + e.add_text( "foo" ) + assert_equal( "foo", e.to_s ) + e[0].value = "bar" + assert_equal( "bar", e.to_s ) + e[0].value = "<" + assert_equal( "<", 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 = '' - source = REXML::Source.new(str) - doctype = REXML::DocType.new(source) - document.add(doctype) - document.write(s) + ## XML Doctype + str = '' + 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" - doc = REXML::Document.new( src ) - out = "" - doc.write( out ) - assert_equal( src, out ) - - src = "" - doc = REXML::Document.new( src ) - out = "" - doc.write( out ) - assert_equal( src, out ) - end + def test_write_cdata + src = "A" + doc = REXML::Document.new( src ) + out = "" + doc.write( out ) + assert_equal( src, out ) + + src = "" + doc = REXML::Document.new( src ) + out = "" + doc.write( out ) + assert_equal( src, out ) + end - def test_namespace_attributes - source = <<-EOL - - - - 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 + + + + 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 - - - ]> - - 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 + + + ]> + + 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{ - - - }) - 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{ + + + }) + 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( "") - s = "" - doc.write( s, 0, true ) - end + def test_transitive + doc = REXML::Document.new( "") + s = "" + doc.write( s, 0, true ) + end - # This is issue #40 - def test_replace_with - old = 'oldold' - 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 = 'oldold' + 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 = "#{long_text}" - 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 # on " + - "small memory system. # " + - "will be raised on the system. See also [ruby-dev:42599]." - return skip_message - end - output = "" - formatter.write(document, output) - assert_equal("\n" + - ((" " + (" aaaa" * 15) + "\n") * (n / 15)) + - " " + ("aaaa " * (n % 15)) + "\n" + - "", - output) - end + def test_pretty_format_long_text_finite + n = 1_000_000 + long_text = 'aaaa ' * n + xml = "#{long_text}" + 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 # on " + + "small memory system. # " + + "will be raised on the system. See also [ruby-dev:42599]." + return skip_message + end + output = "" + formatter.write(document, output) + assert_equal("\n" + + ((" " + (" aaaa" * 15) + "\n") * (n / 15)) + + " " + ("aaaa " * (n % 15)) + "\n" + + "", + output) + end - def test_pretty_format_deep_indent - n = 6 - elements = "" - n.times do |i| - elements << "" - elements << "element#{i} " * 5 - end - (n - 1).downto(0) do |i| - elements << "" - end - xml = "#{elements}" - 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 << "" + elements << "element#{i} " * 5 + end + (n - 1).downto(0) do |i| + elements << "" + end + xml = "#{elements}" + document = REXML::Document.new(xml) + formatter = REXML::Formatters::Pretty.new + formatter.width = 20 + output = "" + formatter.write(document, output) + assert_equal(<<-XML.strip, output) element0 @@ -1212,114 +1212,114 @@ EOL - 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("", str) + assert_equal("", 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("", str) - end + assert_equal("", str) + end - # Incomplete tags should generate an error - def test_ticket_53 - assert_raise( REXML::ParseException ) { - REXML::Document.new( "" ) - } - assert_raise( REXML::ParseException ) { - REXML::Document.new( "" ) - } - assert_raise( REXML::ParseException ) { - REXML::Document.new( "" ) - } - end + # Incomplete tags should generate an error + def test_ticket_53 + assert_raise( REXML::ParseException ) { + REXML::Document.new( "" ) + } + assert_raise( REXML::ParseException ) { + REXML::Document.new( "" ) + } + assert_raise( REXML::ParseException ) { + REXML::Document.new( "" ) + } + end - def test_ticket_52 - source = "" - d = REXML::Document.new(source) - d.write(k="") - assert_equal( source, k ) - - source = "" - target = "\n \n" - d = REXML::Document.new(source) - REXML::Formatters::Pretty.new(4).write(d,k="") - assert_equal( target, k ) - end + def test_ticket_52 + source = "" + d = REXML::Document.new(source) + d.write(k="") + assert_equal( source, k ) + + source = "" + target = "\n \n" + d = REXML::Document.new(source) + REXML::Formatters::Pretty.new(4).write(d,k="") + assert_equal( target, k ) + end - def test_ticket_76 - src = "
at&t" - assert_raise( ParseException, %Q{"#{src}" is invalid XML} ) { - REXML::Document.new(src) - } - end + def test_ticket_76 + src = "
at&t" + assert_raise( ParseException, %Q{"#{src}" is invalid XML} ) { + REXML::Document.new(src) + } + end - def test_ticket_21 - src = "" - 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 = "" + 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("") - 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("") + 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("") - assert_equal("", doc.to_s) - doc = REXML::Document.new("") - assert_equal("", doc.to_s) - end + def test_ticket_88 + doc = REXML::Document.new("") + assert_equal("", doc.to_s) + doc = REXML::Document.new("") + assert_equal("", doc.to_s) + end - def test_ticket_85 - xml = < @@ -1327,138 +1327,138 @@ EOL ENDXML - yml = " + yml = " " - # 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=" - - great - - " + def test_ticket_91 + source=" + + great + + " expected=" great " - 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 "" - testd.write(out1="") - testd.elements["//c[2]"].xpath - testd.write(out2="") - assert_equal(out1,out2) - end + def test_ticket_95 + testd = REXML::Document.new "" + testd.write(out1="") + testd.elements["//c[2]"].xpath + testd.write(out2="") + assert_equal(out1,out2) + end - def test_ticket_102 - doc = REXML::Document.new '' - 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 '' + 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("") - } - 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("") + } + 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("") - 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("") + 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( - 'text' - ) - assert_equal 'text', doc.text( "/doc/item[@name='foo']" ) - assert_equal "name='foo'", - doc.root.elements["item"].attribute("name", "ns").inspect - assert_equal "text", - doc.root.elements["item[@name='foo']"].to_s - end + # phantom namespace same as default namespace + def test_ticket_121 + doc = REXML::Document.new( + 'text' + ) + assert_equal 'text', doc.text( "/doc/item[@name='foo']" ) + assert_equal "name='foo'", + doc.root.elements["item"].attribute("name", "ns").inspect + assert_equal "text", + 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 "\n \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 \n", out - end + assert_equal "\n \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 \n", out + end - def test_ticket_138 - doc = REXML::Document.new( - '' - ) - 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( + '' + ) + 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" - - - ]> - - XMLEND - @doctype1 = REXML::Document.new(document_string1).doctype - - @pubid = "TEST_ID" - document_string2 = <<-"XMLEND" - - - XMLEND - @doctype2 = REXML::Document.new(document_string2).doctype - - document_string3 = <<-"XMLEND" - - - 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" + + + ]> + + XMLEND + @doctype1 = REXML::Document.new(document_string1).doctype + + @pubid = "TEST_ID" + document_string2 = <<-"XMLEND" + + + XMLEND + @doctype2 = REXML::Document.new(document_string2).doctype + + document_string3 = <<-"XMLEND" + + + 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("", + decl(@id, nil).to_s) + end + + def test_to_s_with_uri + assert_equal("", + 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("", + 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("", - decl(@id, nil).to_s) - end - - def test_to_s_with_uri - assert_equal("", - 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("", - 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 '' - 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 '' + 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 '' - 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 '' + 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 '' - block = proc { |str| - out = '' - doc.write out - assert_equal str, out - } - b = doc.root.elements[1] - doc.root.elements.delete b - block.call( "" ) - doc.elements.delete("a/c[@id='1']") - block.call( '' ) - doc.root.elements.delete 1 - block.call( '' ) - end + def test_delete + doc = Document.new '' + block = proc { |str| + out = '' + doc.write out + assert_equal str, out + } + b = doc.root.elements[1] + doc.root.elements.delete b + block.call( "" ) + doc.elements.delete("a/c[@id='1']") + block.call( '' ) + doc.root.elements.delete 1 + block.call( '' ) + end - def test_delete_all - doc = Document.new '' - deleted = doc.elements.delete_all 'a/c' - assert_equal 4, deleted.size - end + def test_delete_all + doc = Document.new '' + deleted = doc.elements.delete_all 'a/c' + assert_equal 4, deleted.size + end - def test_ticket_36 - doc = Document.new( "" ) + def test_ticket_36 + doc = Document.new( "" ) - 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( "" ) - deleted = doc.root.elements.delete_all( "//xi:c" ) - assert_equal( 2, deleted.size ) - end + doc = Document.new( "" ) + 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 'seanelliottrussell' - assert_equal 6, doc.root.size - assert_equal 3, doc.root.elements.size - end + def test_size + doc = Document.new 'seanelliottrussell' + assert_equal 6, doc.root.size + assert_equal 3, doc.root.elements.size + end - def test_each - doc = Document.new 'sean' - 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 'sean' + 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('') - names = [] - doc.root.elements.each('book'.freeze) do |element| - names << element.attributes["name"] + def test_each_with_frozen_condition + doc = Document.new('') + 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 'seanelliott' - 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 'seanelliott' + 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( "" ) - r = doc.elements.collect( "/a/b" ) { |e| e.attributes["id"].to_i } - assert_equal( [1,2], r ) - end + def test_collect + doc = Document.new( "" ) + r = doc.elements.collect( "/a/b" ) { |e| e.attributes["id"].to_i } + assert_equal( [1,2], r ) + end - def test_inject - doc = Document.new( "" ) - 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( "" ) + 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 = "\346" - @encoded = ""+ - @encoded_root - @not_encoded = "ĉ" - end + def setup + @encoded_root = "\346" + @encoded = ""+ + @encoded_root + @not_encoded = "ĉ" + 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( "#{@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( "#{@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 - - \xFF - 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 + + \xFF + 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 - - - EOL + def test_ticket_89 + doc = Document.new <<-EOL + + + 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 = "" - 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 = '' - 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 specification."' - simple = "" - 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 = "" + 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 = '' + 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 specification."' + simple = "" + 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 = '' - one = '' - two = '' - three = '' - 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 = '' + one = '' + two = '' + three = '' + 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{} - two = %q{} - assert REXML::Entity::matches?(one) - assert REXML::Entity::matches?(two) - end + def test_parse_entity + one = %q{} + two = %q{} + assert REXML::Entity::matches?(one) + assert REXML::Entity::matches?(two) + end - def test_constructor - one = [ %q{}, - %q{}, - %q{}, - '', - '', - '' ] - source = %q{ - - - - - - ]>} - - 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{}, + %q{}, + %q{}, + '', + '', + '' ] + source = %q{ + + + + + + ]>} + + 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 = "\n]>&foo;" - 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 = "\n]>&foo;" + 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 = ' ]> $' - 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 = ' ]> $' + 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 = ' ]>replace &ent;' - 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 = ' ]>replace &ent;' - 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{ - ]> - &WhatHeSaid;} - - 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{ + ]> + &WhatHeSaid;} + + 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) ]> 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 = "more dumb text" - 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 = "more dumb text" + 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 - - a@b.c - http://www.foo.com - - 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 + + a@b.c + http://www.foo.com + + 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 - - - - - - - - - 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 + + + + + + + + + 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 - - a@b.c - http://www.foo.com - - 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 + + a@b.c + http://www.foo.com + + 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('') - - #puts XPath.first(d, 'node()[0 + 1]') - #d = Document.new("") - #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('') + + #puts XPath.first(d, 'node()[0 + 1]') + #d = Document.new("") + #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 - - - - - - - - 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 + + + + + + + + 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("") - 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("") + 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("") - 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("") + 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('') - assert_equal(1,doc.elements.to_a("//test[substring(@string,2)='2345']").size) - end + def test_substring2 + doc = Document.new('') + assert_equal(1,doc.elements.to_a("//test[substring(@string,2)='2345']").size) + end - # Submitted by Kouhei - def test_floor_ceiling_round - source = "" - 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 = "" + 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) - - - - - - - - - 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) - - -
- - -
- XML - - assert_equal(5, d.elements.to_a("//*[lang('en')]").size) - end + # Submitted by Kou + def test_lang + d = Document.new(<<-XML) + + + + + + + + + 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) + + +
+ + +
+ XML + + assert_equal(5, d.elements.to_a("//*[lang('en')]").size) + end - def test_ticket_60 - document = REXML::Document.new("A1") - 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("A1") + 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 = "" - 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 = "" + 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 - def handleVariable( ctx, variables, attrib ) - puts "--- Found attribute: #{attrib.name}" - variables[attrib.name] = attrib.value - end + # processes a variable definition in a namespace like + def handleVariable( ctx, variables, attrib ) + puts "--- Found attribute: #{attrib.name}" + variables[attrib.name] = attrib.value + end - # processes a namespace definition like - def handleNamespace( ctx, prefix, namespaces ) - puts "--- Found namespace: #{prefix}" - namespaces[prefix] = ctx.namespaces[prefix] - end + # processes a namespace definition like + 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( "", r.to_s ) - end + def test_write_document + r = make_small_document + assert_equal( "", 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{} - assert_equal( "", @listener.parse( t1 ), - "Empty" ) - end - - def test_space - return unless defined? @listener - # Space. - t2 = %Q{ } - assert_equal( " ", @listener.parse( t2 ), - "Space" ) - end - - def test_whitespace - return unless defined? @listener - # Whitespaces. - t3 = %Q{RE\n \t \n \t XML} - 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{ REXML } - 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{} + assert_equal( "", @listener.parse( t1 ), + "Empty" ) + end - def test_entity_reference - return unless defined? @listener - # Entity reference. - t5 = %Q{<>&lt;&gt;} - assert_equal( "<><>", @listener.parse( t5 ), - "Entity reference" ) - end + def test_space + return unless defined? @listener + # Space. + t2 = %Q{ } + assert_equal( " ", @listener.parse( t2 ), + "Space" ) + end - def test_character_reference - return unless defined? @listener - # Character reference. - t6 = %Q{ } - assert_equal( "\r", @listener.parse( t6 ), - "Character reference." ) - end + def test_whitespace + return unless defined? @listener + # Whitespaces. + t3 = %Q{RE\n \t \n \t XML} + assert_equal( "RE\n \t \n \t XML", @listener.parse( t3 ), + "Whitespaces" ) + end - def test_cr - return unless defined? @listener - # CR. - t7 = %Q{ \r\n \r \n } - 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{ REXML } + 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{<>&lt;&gt;} + 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{ } + 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{ \r\n \r \n } + 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 = %[ + def test_accents + source = %[ ] - 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{ } - assert_equal( t6.strip, REXML::Document.new(t6).to_s ) + def test_character_reference_2 + t6 = %Q{ } + 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 = < Remove this element and figs order differently
@@ -17,23 +17,23 @@ class OrderTester < Test::Unit::TestCase 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 - - - - + def setup + @xsa_source = <<-EOL + + + + - - - Lars Marius Garshol - larsga@garshol.priv.no - http://www.stud.ifi.uio.no/~lmariusg/ - - - EOL - end + + + Lars Marius Garshol + larsga@garshol.priv.no + http://www.stud.ifi.uio.no/~lmariusg/ + + + EOL + end - def test_xml_namespace - xml = <<-XML + def test_xml_namespace + xml = <<-XML 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 = < @@ -21,87 +21,87 @@ class OrderTester < Test::Unit::TestCase 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( " - " ) - items = REXML::XPath.match( d, '//x' ) - assert_equal( %w{1 2 3 4 5}, items.collect{|e| e.attributes['id']} ) - d = REXML::Document.new( " - - " ) - 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( " + " ) + items = REXML::XPath.match( d, '//x' ) + assert_equal( %w{1 2 3 4 5}, items.collect{|e| e.attributes['id']} ) + d = REXML::Document.new( " + + " ) + 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) - - - Success - - - abc02C - - - EOS - end + def setup + @@docDd = Document.new(<<-EOS, :ignore_whitespace_nodes => :all) + + + Success + + + abc02C + + + 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( "Success", arr.join ) end - assert_equal( "Success", 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 = ' - - foo <bar nooo' - 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 = ' + + foo <bar nooo' + 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 = "" - 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 = "" + 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 = ' - - - ]>&la;&lala;' - 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 = ' + + + ]>&la;&lala;' + 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 = "" - REXML::Parsers::PullParser.new(source) - # FINISH ME! - end + def test_peek_unshift + source = "" + REXML::Parsers::PullParser.new(source) + # FINISH ME! + end - def test_inspect - xml = 'Hey' - 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 = 'Hey' + 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 = 'Hey' - 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 = 'Hey' + 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( "@blah@" ) - txt = d.root.text - p = Parsers::SAX2Parser.new "@blah@" - 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( "@blah@" ) + txt = d.root.text + p = Parsers::SAX2Parser.new "@blah@" + 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 = ' - - - ]>&la;&lala;' - 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 = ' + + + ]>&la;&lala;' + 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 - - - Hello, world! - 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 + + + Hello, world! + 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 - - - Hello, world! - 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 + + + Hello, world! + 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("") + # Submitted by Kou + def test_begin_end_document + parser = Parsers::SAX2Parser.new("") - 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( "") - parser = Parsers::SAX2Parser.new( "") - 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( "") + parser = Parsers::SAX2Parser.new( "") + 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 << '' - 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 << '' + 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('ü') - 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('ü') + 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('ü') - 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('ü') + 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{\n} + class StreamTester < Test::Unit::TestCase + # Submitted by Han Holl + def test_listener + data = %Q{\n} - 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 ) - - ]> - &ent; - EOL - REXML::Document.parse_stream(source, MyListener.new) - end + def test_ticket_49 + source = StringIO.new( <<-EOL ) + + ]> + &ent; + EOL + REXML::Document.parse_stream(source, MyListener.new) + end - def test_ticket_10 - source = StringIO.new( <<-EOL ) - - - - - ]> - - 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 ) + + + + + ]> + + 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) %ISOLat2; ]> - 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 = ' + @@xmlstr = ' @@ -28,29 +28,29 @@ class Ticket80 < Test::Unit::TestCase ' - #---------------------------------------------------------------------------- - 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{ @@ -25,16 +25,16 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - error( validator, %q{} ) - end + no_error( validator, %q{} ) + error( validator, %q{} ) + end - def test_sequence - rng = %q{ + def test_sequence + rng = %q{ @@ -46,18 +46,18 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_choice - rng = %q{ + def test_choice + rng = %q{ @@ -71,16 +71,16 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_optional - rng = %q{ + def test_optional + rng = %q{ @@ -91,17 +91,17 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - end + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + end - def test_zero_or_more - rng = %q{ + def test_zero_or_more + rng = %q{ @@ -112,15 +112,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) + } + validator = REXML::Validation::RelaxNG.new( rng ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -134,17 +134,17 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - end + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + end - def test_one_or_more - rng = %q{ + def test_one_or_more + rng = %q{ @@ -155,34 +155,34 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) - - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - end + } + validator = REXML::Validation::RelaxNG.new( rng ) + + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + end - def test_attribute - rng = %q{ + def test_attribute + rng = %q{ - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_choice_attributes - rng = %q{ + def test_choice_attributes + rng = %q{ @@ -190,17 +190,17 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{}) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{}) + no_error( validator, %q{} ) + end - def test_choice_attribute_element - rng = %q{ + def test_choice_attribute_element + rng = %q{ @@ -208,45 +208,45 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{}) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{}) + no_error( validator, %q{} ) + end - def test_empty - rng = %q{ + def test_empty + rng = %q{ - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{Text} ) - no_error( validator, %q{}) - end + error( validator, %q{} ) + error( validator, %q{Text} ) + no_error( validator, %q{}) + end - def test_text_val - rng = %q{ + def test_text_val + rng = %q{ - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - no_error( validator, %q{Text} ) - error( validator, %q{}) - end + error( validator, %q{} ) + no_error( validator, %q{Text} ) + error( validator, %q{}) + end - def test_choice_text - rng = %q{ + def test_choice_text + rng = %q{ @@ -254,17 +254,17 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{Text} ) - error( validator, %q{Text} ) - no_error( validator, %q{Text} ) - no_error( validator, %q{} ) - end + error( validator, %q{Text} ) + error( validator, %q{Text} ) + no_error( validator, %q{Text} ) + no_error( validator, %q{} ) + end - def test_group - rng = %q{ + def test_group + rng = %q{ @@ -275,15 +275,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -292,33 +292,33 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_value - # Values as text nodes - rng = %q{ + def test_value + # Values as text nodes + rng = %q{ VaLuE - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{X} ) - error( validator, %q{} ) - no_error( validator, %q{VaLuE} ) + error( validator, %q{X} ) + error( validator, %q{} ) + no_error( validator, %q{VaLuE} ) - # Values as text nodes, via choice - rng = %q{ + # Values as text nodes, via choice + rng = %q{ @@ -328,32 +328,32 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{XYZ} ) - no_error( validator, %q{Option 1} ) - no_error( validator, %q{Option 2} ) + error( validator, %q{} ) + error( validator, %q{XYZ} ) + no_error( validator, %q{Option 1} ) + no_error( validator, %q{Option 2} ) - # Attribute values - rng = %q{ + # Attribute values + rng = %q{ VaLuE - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) - # Attribute values via choice - rng = %q{ + # Attribute values via choice + rng = %q{ @@ -363,17 +363,17 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_interleave - rng = %q{ + def test_interleave + rng = %q{ @@ -384,20 +384,20 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) - - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - end + } + validator = REXML::Validation::RelaxNG.new( rng ) - def test_mixed - rng = %q{ + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + end + + def test_mixed + rng = %q{ @@ -406,15 +406,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{Text} ) - no_error( validator, %q{Text} ) - end + no_error( validator, %q{Text} ) + no_error( validator, %q{Text} ) + end - def test_ref_sequence - rng = %q{ + def test_ref_sequence + rng = %q{ @@ -430,15 +430,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - error( validator, %q{} ) - end + no_error( validator, %q{} ) + error( validator, %q{} ) + end - def test_ref_choice - rng = %q{ + def test_ref_choice + rng = %q{ @@ -454,15 +454,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -478,15 +478,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -503,18 +503,18 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_ref_zero_plus - rng = %q{ + def test_ref_zero_plus + rng = %q{ @@ -531,15 +531,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -556,18 +556,18 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_ref_one_plus - rng = %q{ + def test_ref_one_plus + rng = %q{ @@ -584,15 +584,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -609,17 +609,17 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_ref_interleave - rng = %q{ + def test_ref_interleave + rng = %q{ @@ -635,16 +635,16 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -660,16 +660,16 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -688,18 +688,18 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) - - error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + } + validator = REXML::Validation::RelaxNG.new( rng ) - def test_ref_recurse - rng = %q{ + error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end + + def test_ref_recurse + rng = %q{ @@ -716,16 +716,16 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - error( validator, %q{} ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - end + error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + end - def test_ref_optional - rng = %q{ + def test_ref_optional + rng = %q{ @@ -741,15 +741,15 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) - rng = %q{ + rng = %q{ @@ -765,28 +765,28 @@ class RNGValidation < Test::Unit::TestCase - } - validator = REXML::Validation::RelaxNG.new( rng ) + } + validator = REXML::Validation::RelaxNG.new( rng ) - no_error( validator, %q{} ) - no_error( validator, %q{} ) - error( validator, %q{} ) - error( validator, %q{} ) - end + no_error( validator, %q{} ) + no_error( validator, %q{} ) + error( validator, %q{} ) + error( validator, %q{} ) + 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' - - - - 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' + + + + 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 child1 child2 child3 - 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 - - - - - - - - - EOF + class TestXPathAxisPredcedingSibling < Test::Unit::TestCase + include REXML + SOURCE = <<-EOF + + + + + + + + + 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 - - - - + class TestXPathBase < Test::Unit::TestCase + include REXMLTestUtils + include REXML + SOURCE = <<-EOF + + + + + + + + + + + + + + + + + + + + + + +

+ + + + + EOF + JENI_TENNISON = <<-EOJT + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - -

- - - - EOF - JENI_TENNISON = <<-EOJT - - - - - - - - - - - - - - - - - - - - - - - - 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("") - 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( "" ) - # //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 = "" - 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("") + 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( "" ) + # //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 = "" + 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 "text" - #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 = "more dumb text" - 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 "text" + #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 = "more dumb text" + 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 << ""+z.message+"" 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 << ""+z.message+"" 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 " - - - - - - - - - " + def test_axe_ancestor + doc = REXML::Document.new " + + + + + + + + + " + + 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 "" + 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 "" - 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 + + this bar + that bar + + EOF + doc = Document.new source + XPath.each( doc, "//bar" ) { + fail "'bar' should match nothing in this case" + } - def test_namespaces_1 - source = <<-EOF - - this bar - that bar - - 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 - - this bar - that bar - - 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 + + this bar + that bar + + 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 "" - 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("") - matches = REXML::XPath.match(d, "/a/d/preceding::node()") - assert_equal("c", matches[0].name) - assert_equal("b", matches[1].name) - - s = "" - 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 "" + 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("") + matches = REXML::XPath.match(d, "/a/d/preceding::node()") + assert_equal("c", matches[0].name) + assert_equal("b", matches[1].name) + + s = "" + 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 "" - 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 = "" - 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 "" + 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 = "" + 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 - # 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 - - a@b.c - http://www.foo.com - - 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 + # 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 + + a@b.c + http://www.foo.com + + 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 = "ABCDEF" - 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 = "ABCDEF" + 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 - - - - - - - - - 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 + + + + + + + + + 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 - - a@b.c - http://www.foo.com - - 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 + + a@b.c + http://www.foo.com + + 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('') - - Document.new("") - #puts XPath.first(d, 'node()[0 + 1]') - #d = Document.new("") - #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('') + + Document.new("") + #puts XPath.first(d, 'node()[0 + 1]') + #d = Document.new("") + #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 - - - - - - - - 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 + + + + + + + + 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( '' ) - 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( '' ) + 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("") - } - d = REXML::Document.new("") - 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("") + } + d = REXML::Document.new("") + 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("") - 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("") + 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 = "" - 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 = "" + 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("") - 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("") + 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(" - - - - - ") - 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(" + + + + + ") + 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 = " - # - #test - #" - source = "test" - 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 = " + # + #test + #" + source = "test" + 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 = "Introduction" - d = REXML::Document.new( source ) - #r = REXML::XPath.match( d, %q{/root[title="Introduction"]} ) - #assert_equal( 1, r.size ) - source = "test" - 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 = "Introduction" + d = REXML::Document.new( source ) + #r = REXML::XPath.match( d, %q{/root[title="Introduction"]} ) + #assert_equal( 1, r.size ) + source = "test" + 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 = "" - 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 = "" + 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 = " - - - - - - - - - - - - - - - " - 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 = " + + + + + + + + + + + + + + + " + 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{} - 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{} + 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{} - - 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{} + + 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 = ' + def test_tobis_preceding + doc_string = ' @@ -759,58 +759,58 @@ class TestXPathBase < Test::Unit::TestCase ' - 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("") - #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("") + #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{

+ # Submitted by Alex + def test_union + data = %Q{
a b
} - 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
a b
- 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 @@ -825,97 +825,97 @@ class TestXPathBase < Test::Unit::TestCase - 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(""+ - "123"+ - "12"+ - ""+ - "") + 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(""+ + "123"+ + "12"+ + ""+ + "") + + 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("xa") - x = d.root - num = 0 - x.each_element('tada') { num += 1 } - assert_equal(1, num) - end + def test_xpath_namespace + d = REXML::Document.new("xa") + 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 ) - - - - true - - Item 1 - - - Item 2 - Thu, 13 Oct 2005 19:59:00 +0000 - - - Item 3 - - - - 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 ) + + + + true + + Item 1 + + + Item 2 + Thu, 13 Oct 2005 19:59:00 +0000 + + + Item 3 + + + + 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 = "" - 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 = "" + 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 = < @@ -929,134 +929,134 @@ text 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 = "zzz" + def test_ticket_57 + data = "zzz" - 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 = " - - - - - - - + def test_ticket_59 + data = " + + - + - - - - + - - + + + + + + + + - + + + + + - -
- - " - d = Document.new(data) - res = d.elements.to_a( "//c" ).collect {|e| e.attributes['id'].to_i} - assert_equal( res, res.sort ) - end + + " + 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{}) - 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{}) + 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{}) - 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{}) + 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 - - - 123 - - - 123a - - - 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 + + + 123 + + + 123a + + + 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 = "test3" - 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 = "test3" + 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 = " test @@ -1069,13 +1069,13 @@ EOF " - 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 child - XML - assert_equal(["child"], - matches(xml, "/root/ascii/child")) - end + XML + assert_equal(["child"], + matches(xml, "/root/ascii/child")) + end - def test_non_ascii - xml = <<-XML + def test_non_ascii + xml = <<-XML child - XML - assert_equal(["child"], - matches(xml, "/root/non-àscii/child")) + XML + assert_equal(["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 -
-
- free flowing text. -
-
-
- free flowing text. -
-
- free flowing text. -
-
-
- EOL + class TestXPathPredicate < Test::Unit::TestCase + include REXML + SRC=<<-EOL +
+
+ free flowing text. +
+
+
+ free flowing text. +
+
+ free flowing text. +
+
+
+ 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 TEXT1 @@ -68,15 +68,15 @@ class TestXPathPredicate < Test::Unit::TestCase 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, " has one element ancestor") - nodes = @doc.get_elements('//b/ancestor::node()') - assert_equal(2, nodes.size, " 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, " has one element ancestor") + nodes = @doc.get_elements('//b/ancestor::node()') + assert_equal(2, nodes.size, " has two node ancestors") + assert nodes[1].kind_of?(REXML::Document) + end end end -end -- cgit v1.2.3