* test/rexml/test_contrib.rb: Indent.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@46174 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
kou 2014-05-27 13:10:55 +00:00
parent 313fa18033
commit ba3d2f4ac2
36 changed files with 5153 additions and 5149 deletions

View file

@ -1,3 +1,7 @@
Tue May 27 22:10:30 2014 Kouhei Sutou <kou@cozmixng.org>
* test/rexml/test_contrib.rb: Indent.
Tue May 27 21:28:16 2014 NARUSE, Yui <naruse@ruby-lang.org> Tue May 27 21:28:16 2014 NARUSE, Yui <naruse@ruby-lang.org>
* ext/socket/ifaddr.c (ifaddr_inspect_flags): support IFF_SIMPLEX. * ext/socket/ifaddr.c (ifaddr_inspect_flags): support IFF_SIMPLEX.

View file

@ -2,48 +2,48 @@ require "test/unit"
require "rexml/document" require "rexml/document"
module REXMLTests module REXMLTests
class TestParseDocumentTypeDeclaration < Test::Unit::TestCase class TestParseDocumentTypeDeclaration < Test::Unit::TestCase
private private
def xml(internal_subset) def xml(internal_subset)
<<-XML <<-XML
<!DOCTYPE r SYSTEM "urn:x-rexml:test" [ <!DOCTYPE r SYSTEM "urn:x-rexml:test" [
#{internal_subset} #{internal_subset}
]> ]>
<r/> <r/>
XML XML
end end
def parse(internal_subset) def parse(internal_subset)
REXML::Document.new(xml(internal_subset)).doctype REXML::Document.new(xml(internal_subset)).doctype
end end
class TestMixed < self class TestMixed < self
def test_entity_element def test_entity_element
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!ENTITY entity-name "entity content"> <!ENTITY entity-name "entity content">
<!ELEMENT element-name EMPTY> <!ELEMENT element-name EMPTY>
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal([REXML::Entity, REXML::ElementDecl], assert_equal([REXML::Entity, REXML::ElementDecl],
doctype.children.collect(&:class)) doctype.children.collect(&:class))
end end
def test_attlist_entity def test_attlist_entity
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!ATTLIST attribute-list-name attribute-name CDATA #REQUIRED> <!ATTLIST attribute-list-name attribute-name CDATA #REQUIRED>
<!ENTITY entity-name "entity content"> <!ENTITY entity-name "entity content">
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal([REXML::AttlistDecl, REXML::Entity], assert_equal([REXML::AttlistDecl, REXML::Entity],
doctype.children.collect(&:class)) doctype.children.collect(&:class))
end end
def test_notation_attlist def test_notation_attlist
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION notation-name SYSTEM "system-literal"> <!NOTATION notation-name SYSTEM "system-literal">
<!ATTLIST attribute-list-name attribute-name CDATA #REQUIRED> <!ATTLIST attribute-list-name attribute-name CDATA #REQUIRED>
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal([REXML::NotationDecl, REXML::AttlistDecl], assert_equal([REXML::NotationDecl, REXML::AttlistDecl],
doctype.children.collect(&:class)) doctype.children.collect(&:class))
end
end end
end end
end end
end

View file

@ -2,98 +2,98 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class TestParseNotationDeclaration < Test::Unit::TestCase class TestParseNotationDeclaration < Test::Unit::TestCase
private private
def xml(internal_subset) def xml(internal_subset)
<<-XML <<-XML
<!DOCTYPE r SYSTEM "urn:x-henrikmartensson:test" [ <!DOCTYPE r SYSTEM "urn:x-henrikmartensson:test" [
#{internal_subset} #{internal_subset}
]> ]>
<r/> <r/>
XML XML
end
def parse(internal_subset)
REXML::Document.new(xml(internal_subset)).doctype
end
class TestCommon < self
def test_name
doctype = parse("<!NOTATION name PUBLIC 'urn:public-id'>")
assert_equal("name", doctype.notation("name").name)
end end
end
class TestExternalID < self def parse(internal_subset)
class TestSystem < self REXML::Document.new(xml(internal_subset)).doctype
def test_single_quote end
doctype = parse(<<-INTERNAL_SUBSET)
class TestCommon < self
def test_name
doctype = parse("<!NOTATION name PUBLIC 'urn:public-id'>")
assert_equal("name", doctype.notation("name").name)
end
end
class TestExternalID < self
class TestSystem < self
def test_single_quote
doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION name SYSTEM 'system-literal'> <!NOTATION name SYSTEM 'system-literal'>
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal("system-literal", doctype.notation("name").system) assert_equal("system-literal", doctype.notation("name").system)
end end
def test_double_quote def test_double_quote
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION name SYSTEM "system-literal"> <!NOTATION name SYSTEM "system-literal">
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal("system-literal", doctype.notation("name").system) assert_equal("system-literal", doctype.notation("name").system)
end
end end
end
class TestPublic < self class TestPublic < self
class TestPublicIDLiteral < self class TestPublicIDLiteral < self
def test_single_quote def test_single_quote
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION name PUBLIC 'public-id-literal' "system-literal"> <!NOTATION name PUBLIC 'public-id-literal' "system-literal">
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal("public-id-literal", doctype.notation("name").public) assert_equal("public-id-literal", doctype.notation("name").public)
end end
def test_double_quote def test_double_quote
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION name PUBLIC "public-id-literal" "system-literal"> <!NOTATION name PUBLIC "public-id-literal" "system-literal">
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal("public-id-literal", doctype.notation("name").public) assert_equal("public-id-literal", doctype.notation("name").public)
end
end end
end
class TestSystemLiteral < self class TestSystemLiteral < self
def test_single_quote def test_single_quote
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION name PUBLIC "public-id-literal" 'system-literal'> <!NOTATION name PUBLIC "public-id-literal" 'system-literal'>
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal("system-literal", doctype.notation("name").system) assert_equal("system-literal", doctype.notation("name").system)
end end
def test_double_quote def test_double_quote
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION name PUBLIC "public-id-literal" "system-literal"> <!NOTATION name PUBLIC "public-id-literal" "system-literal">
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal("system-literal", doctype.notation("name").system) assert_equal("system-literal", doctype.notation("name").system)
end
end end
end end
end
class TestMixed < self class TestMixed < self
def test_system_public def test_system_public
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION system-name SYSTEM "system-literal"> <!NOTATION system-name SYSTEM "system-literal">
<!NOTATION public-name PUBLIC "public-id-literal" 'system-literal'> <!NOTATION public-name PUBLIC "public-id-literal" 'system-literal'>
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal(["system-name", "public-name"], assert_equal(["system-name", "public-name"],
doctype.notations.collect(&:name)) doctype.notations.collect(&:name))
end end
def test_public_system def test_public_system
doctype = parse(<<-INTERNAL_SUBSET) doctype = parse(<<-INTERNAL_SUBSET)
<!NOTATION public-name PUBLIC "public-id-literal" 'system-literal'> <!NOTATION public-name PUBLIC "public-id-literal" 'system-literal'>
<!NOTATION system-name SYSTEM "system-literal"> <!NOTATION system-name SYSTEM "system-literal">
INTERNAL_SUBSET INTERNAL_SUBSET
assert_equal(["public-name", "system-name"], assert_equal(["public-name", "system-name"],
doctype.notations.collect(&:name)) doctype.notations.collect(&:name))
end
end end
end end
end end
end end
end

View file

@ -2,203 +2,203 @@ require 'test/unit/testcase'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class AttributesTester < Test::Unit::TestCase class AttributesTester < Test::Unit::TestCase
include REXML include REXML
def test_accessor def test_accessor
doc = Document.new("<a xmlns:foo='a' xmlns:bar='b' foo:att='1' bar:att='2' att='3'/>") doc = Document.new("<a xmlns:foo='a' xmlns:bar='b' foo:att='1' bar:att='2' att='3'/>")
assert_equal '3', doc.root.attributes['att'] assert_equal '3', doc.root.attributes['att']
assert_equal '2', doc.root.attributes['bar:att'] assert_equal '2', doc.root.attributes['bar:att']
doc.root.attributes['att'] = 5 doc.root.attributes['att'] = 5
assert_equal '5', doc.root.attributes['att'] assert_equal '5', doc.root.attributes['att']
end
def test_each_attribute
doc = Document.new('<a x="1" y="2"/>')
doc.root.attributes.each_attribute {|attr|
if attr.expanded_name == 'x'
assert_equal '1', attr.value
elsif attr.expanded_name == 'y'
assert_equal '2', attr.value
else
assert_fail "No such attribute!!"
end
}
end
def test_each
doc = Document.new('<a x="1" y="2"/>')
doc.root.attributes.each {|name, value|
if name == 'x'
assert_equal '1', value
elsif name == 'y'
assert_equal '2', value
else
assert_fail "No such attribute!!"
end
}
end
def test_get_attribute
doc = Document.new('<a xmlns:x="a" x:foo="1" foo="2" bar="3"/>')
assert_equal '2', doc.root.attributes.get_attribute("foo").value
assert_equal '1', doc.root.attributes.get_attribute("x:foo").value
end
def test_size
doc = Document.new("<a xmlns:foo='a' x='1' y='2' foo:x='3'/>")
assert_equal 4, doc.root.attributes.length
end
def test_setter
doc = Document.new("<a xmlns:x='a' x:foo='1' foo='3'/>")
doc.root.attributes['y:foo'] = '2'
assert_equal '2', doc.root.attributes['y:foo']
doc.root.attributes['foo'] = '4'
assert_equal '4', doc.root.attributes['foo']
doc.root.attributes['x:foo'] = nil
assert_equal 3, doc.root.attributes.size
end
def test_delete
doc = Document.new("<a xmlns:y='a' xmlns:x='b' xmlns:z='c' y:foo='0' x:foo='1' foo='3' z:foo='4'/>")
doc.root.attributes.delete 'foo'
assert_equal 6, doc.root.attributes.size
assert_equal '1', doc.root.attributes['x:foo']
doc.root.attributes.delete 'x:foo'
assert_equal 5, doc.root.attributes.size
attr = doc.root.attributes.get_attribute('y:foo')
doc.root.attributes.delete attr
assert_equal 4, doc.root.attributes.size
assert_equal '4', doc.root.attributes['z:foo']
end
def test_prefixes
doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' z='glorp' x:k='gru'/>")
prefixes = doc.root.attributes.prefixes
assert_equal 2, prefixes.size
assert_equal 0, (prefixes - ['x', 'y']).size
end
# Contributed by Mike Stok
def test_values_with_apostrophes
doc = Document.new(%q#<tag h1="1'2'" h2='1"2'/>#)
s = doc.to_s
assert(s =~ /h1='1&apos;2&apos;'/)
assert(s =~ /h2='1"2'/)
end
# Submitted by Kou
def test_namespace_conflict
assert_raise( ParseException,
"Declaring two attributes with the same namespace should be an error" ) do
REXML::Document.new <<-XML
<x xmlns:n1="http://www.w3.org"
xmlns:n2="http://www.w3.org" >
<bad n1:a="1" n2:a="2" />
</x>
XML
end end
REXML::Document.new("<a xmlns:a='a' xmlns:b='a'></a>") def test_each_attribute
end doc = Document.new('<a x="1" y="2"/>')
doc.root.attributes.each_attribute {|attr|
if attr.expanded_name == 'x'
assert_equal '1', attr.value
elsif attr.expanded_name == 'y'
assert_equal '2', attr.value
else
assert_fail "No such attribute!!"
end
}
end
# Submitted by Kou def test_each
def test_attribute_deletion doc = Document.new('<a x="1" y="2"/>')
e = REXML::Element.new doc.root.attributes.each {|name, value|
e.add_namespace("a", "http://a/") if name == 'x'
e.add_namespace("b", "http://b/") assert_equal '1', value
e.add_attributes({"c" => "cc", "a:c" => "cC", "b:c" => "CC"}) elsif name == 'y'
assert_equal '2', value
else
assert_fail "No such attribute!!"
end
}
end
e.attributes.delete("c") def test_get_attribute
assert_nil(e.attributes.get_attribute("c")) doc = Document.new('<a xmlns:x="a" x:foo="1" foo="2" bar="3"/>')
assert_equal '2', doc.root.attributes.get_attribute("foo").value
assert_equal '1', doc.root.attributes.get_attribute("x:foo").value
end
before_size = e.attributes.size def test_size
e.attributes.delete("c") doc = Document.new("<a xmlns:foo='a' x='1' y='2' foo:x='3'/>")
assert_nil(e.attributes.get_attribute("c")) assert_equal 4, doc.root.attributes.length
assert_equal(before_size, e.attributes.size) end
e.attributes.delete(e.attributes.get_attribute("a:c")) def test_setter
assert_nil(e.attributes.get_attribute("a:c")) doc = Document.new("<a xmlns:x='a' x:foo='1' foo='3'/>")
doc.root.attributes['y:foo'] = '2'
assert_equal '2', doc.root.attributes['y:foo']
doc.root.attributes['foo'] = '4'
assert_equal '4', doc.root.attributes['foo']
doc.root.attributes['x:foo'] = nil
assert_equal 3, doc.root.attributes.size
end
e.attributes.delete("b:c") def test_delete
assert_nil(e.attributes.get_attribute("b:c")) doc = Document.new("<a xmlns:y='a' xmlns:x='b' xmlns:z='c' y:foo='0' x:foo='1' foo='3' z:foo='4'/>")
doc.root.attributes.delete 'foo'
assert_equal 6, doc.root.attributes.size
assert_equal '1', doc.root.attributes['x:foo']
before_size = e.attributes.size doc.root.attributes.delete 'x:foo'
e.attributes.delete(e.attributes.get_attribute("b:c")) assert_equal 5, doc.root.attributes.size
assert_nil(e.attributes.get_attribute("b:c"))
assert_equal(before_size, e.attributes.size)
before_size = e.attributes.size attr = doc.root.attributes.get_attribute('y:foo')
e.attributes.delete("c") doc.root.attributes.delete attr
assert_nil(e.attributes.get_attribute("c")) assert_equal 4, doc.root.attributes.size
assert_equal(before_size, e.attributes.size)
e.add_attribute("c", "cc") assert_equal '4', doc.root.attributes['z:foo']
end
e.attributes.delete(e.attributes.get_attribute("c")) def test_prefixes
assert_nil(e.attributes.get_attribute("c")) doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' z='glorp' x:k='gru'/>")
end prefixes = doc.root.attributes.prefixes
assert_equal 2, prefixes.size
assert_equal 0, (prefixes - ['x', 'y']).size
end
# Submitted by Kou # Contributed by Mike Stok
def test_element_usage def test_values_with_apostrophes
attr = Attribute.new("name", "value") doc = Document.new(%q#<tag h1="1'2'" h2='1"2'/>#)
elem = Element.new("elem") s = doc.to_s
a = Attribute.new(attr, elem) assert(s =~ /h1='1&apos;2&apos;'/)
assert_equal(elem, a.element) assert(s =~ /h2='1"2'/)
end end
def attr_test(attr_name,attr_value) # Submitted by Kou
a1 = REXML::Attribute.new(attr_name,attr_value) def test_namespace_conflict
assert_raise( ParseException,
"Declaring two attributes with the same namespace should be an error" ) do
REXML::Document.new <<-XML
<x xmlns:n1="http://www.w3.org"
xmlns:n2="http://www.w3.org" >
<bad n1:a="1" n2:a="2" />
</x>
XML
end
s1 = a1.value REXML::Document.new("<a xmlns:a='a' xmlns:b='a'></a>")
s2 = a1.value end
#p s1 # Submitted by Kou
#p s2 def test_attribute_deletion
assert_equal(s1,s2) 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"})
a2 = REXML::Attribute.new(attr_name,attr_value) e.attributes.delete("c")
assert_nil(e.attributes.get_attribute("c"))
a2.to_s # NB invocation of to_s before_size = e.attributes.size
s1 = a2.value e.attributes.delete("c")
s2 = a2.value assert_nil(e.attributes.get_attribute("c"))
assert_equal(before_size, e.attributes.size)
#p s1 e.attributes.delete(e.attributes.get_attribute("a:c"))
#p s2 assert_nil(e.attributes.get_attribute("a:c"))
assert_equal(s1,s2)
end
def test_amp_attributes e.attributes.delete("b:c")
attr_test('name','value with &amp; ampersand only') assert_nil(e.attributes.get_attribute("b:c"))
end
def test_amp_and_lf_attributes before_size = e.attributes.size
attr_test('name','value with LF &#x000a; &amp; ampersand') e.attributes.delete(e.attributes.get_attribute("b:c"))
end assert_nil(e.attributes.get_attribute("b:c"))
assert_equal(before_size, e.attributes.size)
def test_quoting before_size = e.attributes.size
d = Document.new(%q{<a x='1' y="2"/>}) e.attributes.delete("c")
assert_equal( %q{<a x='1' y='2'/>}, d.to_s ) assert_nil(e.attributes.get_attribute("c"))
d.root.context[:attribute_quote] = :quote assert_equal(before_size, e.attributes.size)
assert_equal( %q{<a x="1" y="2"/>}, d.to_s )
d = Document.new(%q{<a x='1' y="2"><b z='3'/></a>}) e.add_attribute("c", "cc")
assert_equal( %q{<a x='1' y='2'><b z='3'/></a>}, d.to_s )
d.root.context[:attribute_quote] = :quote
assert_equal( %q{<a x="1" y="2"><b z="3"/></a>}, d.to_s )
end
def test_ticket_127 e.attributes.delete(e.attributes.get_attribute("c"))
doc = Document.new assert_nil(e.attributes.get_attribute("c"))
doc.add_element 'a', { 'v' => 'x & y' } end
assert doc.to_s.index(';')
end
def test_to_a_with_namespaces # Submitted by Kou
document = Document.new(<<-XML) def test_element_usage
attr = Attribute.new("name", "value")
elem = Element.new("elem")
a = Attribute.new(attr, elem)
assert_equal(elem, a.element)
end
def attr_test(attr_name,attr_value)
a1 = REXML::Attribute.new(attr_name,attr_value)
s1 = a1.value
s2 = a1.value
#p s1
#p s2
assert_equal(s1,s2)
a2 = REXML::Attribute.new(attr_name,attr_value)
a2.to_s # NB invocation of to_s
s1 = a2.value
s2 = a2.value
#p s1
#p s2
assert_equal(s1,s2)
end
def test_amp_attributes
attr_test('name','value with &amp; ampersand only')
end
def test_amp_and_lf_attributes
attr_test('name','value with LF &#x000a; &amp; ampersand')
end
def test_quoting
d = Document.new(%q{<a x='1' y="2"/>})
assert_equal( %q{<a x='1' y='2'/>}, d.to_s )
d.root.context[:attribute_quote] = :quote
assert_equal( %q{<a x="1" y="2"/>}, d.to_s )
d = Document.new(%q{<a x='1' y="2"><b z='3'/></a>})
assert_equal( %q{<a x='1' y='2'><b z='3'/></a>}, d.to_s )
d.root.context[:attribute_quote] = :quote
assert_equal( %q{<a x="1" y="2"><b z="3"/></a>}, d.to_s )
end
def test_ticket_127
doc = Document.new
doc.add_element 'a', { 'v' => 'x & y' }
assert doc.to_s.index(';')
end
def test_to_a_with_namespaces
document = Document.new(<<-XML)
<root <root
xmlns:ns1="http://example.org/ns1" xmlns:ns1="http://example.org/ns1"
xmlns:ns2="http://example.org/ns2"> xmlns:ns2="http://example.org/ns2">
@ -209,14 +209,14 @@ class AttributesTester < Test::Unit::TestCase
other-attribute="other-value"/> other-attribute="other-value"/>
</root> </root>
XML XML
child = document.root.elements["child"] child = document.root.elements["child"]
assert_equal([ assert_equal([
"attribute='no-ns'", "attribute='no-ns'",
"ns1:attribute='ns1'", "ns1:attribute='ns1'",
"ns2:attribute='ns2'", "ns2:attribute='ns2'",
"other-attribute='other-value'", "other-attribute='other-value'",
], ],
child.attributes.to_a.collect(&:to_string).sort) child.attributes.to_a.collect(&:to_string).sort)
end
end end
end end
end

View file

@ -2,30 +2,30 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class TestAttributes < Test::Unit::TestCase class TestAttributes < Test::Unit::TestCase
def setup def setup
@ns_a = "urn:x-test:a" @ns_a = "urn:x-test:a"
@ns_b = "urn:x-test:b" @ns_b = "urn:x-test:b"
element_string = <<-"XMLEND" element_string = <<-"XMLEND"
<test xmlns:a="#{@ns_a}" <test xmlns:a="#{@ns_a}"
xmlns:b="#{@ns_b}" xmlns:b="#{@ns_b}"
a = "1" a = "1"
b = '2' b = '2'
a:c = "3" a:c = "3"
a:d = '4' a:d = '4'
a:e = "5" a:e = "5"
b:f = "6"/> b:f = "6"/>
XMLEND XMLEND
@attributes = REXML::Document.new(element_string).root.attributes @attributes = REXML::Document.new(element_string).root.attributes
end end
def test_get_attribute_ns def test_get_attribute_ns
assert_equal("1", @attributes.get_attribute_ns("", "a").value) assert_equal("1", @attributes.get_attribute_ns("", "a").value)
assert_equal("2", @attributes.get_attribute_ns("", "b").value) assert_equal("2", @attributes.get_attribute_ns("", "b").value)
assert_equal("3", @attributes.get_attribute_ns(@ns_a, "c").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("4", @attributes.get_attribute_ns(@ns_a, "d").value)
assert_equal("5", @attributes.get_attribute_ns(@ns_a, "e").value) assert_equal("5", @attributes.get_attribute_ns(@ns_a, "e").value)
assert_equal("6", @attributes.get_attribute_ns(@ns_b, "f").value) assert_equal("6", @attributes.get_attribute_ns(@ns_b, "f").value)
end
end end
end end
end

View file

@ -3,42 +3,42 @@
require 'rexml/encoding' require 'rexml/encoding'
module REXMLTests module REXMLTests
class ChangingEncodings < Test::Unit::TestCase class ChangingEncodings < Test::Unit::TestCase
def initialize a def initialize a
@u = 'テスト ほげ ふが 美しい' @u = 'テスト ほげ ふが 美しい'
@e = @u.encode("EUC-JP") @e = @u.encode("EUC-JP")
@f = Foo.new @f = Foo.new
super super
end end
class Foo class Foo
include REXML::Encoding include REXML::Encoding
end end
# Note that these tests must be executed in order for the third one to # Note that these tests must be executed in order for the third one to
# actually test anything. # actually test anything.
def test_0_euc def test_0_euc
@f.encoding = 'EUC-JP' @f.encoding = 'EUC-JP'
assert_equal( @u, @f.decode(@e) ) assert_equal( @u, @f.decode(@e) )
# This doesn't happen anymore, for some reason # This doesn't happen anymore, for some reason
#assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) { #assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) {
# @f.decode(@u) == @u # @f.decode(@u) == @u
#} #}
end end
def test_1_utf def test_1_utf
@f.encoding = 'UTF-8' @f.encoding = 'UTF-8'
assert_not_equal( @u, @f.decode( @e ) ) assert_not_equal( @u, @f.decode( @e ) )
assert_equal( @u, @f.decode( @u ) ) assert_equal( @u, @f.decode( @u ) )
end end
def test_2_euc def test_2_euc
@f.encoding = 'EUC-JP' @f.encoding = 'EUC-JP'
assert_equal( @u, @f.decode(@e) ) assert_equal( @u, @f.decode(@e) )
# This doesn't happen anymore, for some reason # This doesn't happen anymore, for some reason
#assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) { #assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) {
# @f.decode(@u) == @u # @f.decode(@u) == @u
#} #}
end
end end
end end
end

View file

@ -7,11 +7,11 @@ require "rexml/parseexception"
require "rexml/formatters/default" require "rexml/formatters/default"
module REXMLTests module REXMLTests
class ContribTester < Test::Unit::TestCase class ContribTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML include REXML
XML_STRING_01 = <<DELIMITER XML_STRING_01 = <<DELIMITER
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<biblio> <biblio>
<entry type="Book"> <entry type="Book">
@ -32,7 +32,7 @@ class ContribTester < Test::Unit::TestCase
</biblio> </biblio>
DELIMITER DELIMITER
XML_STRING_02 = <<DELIMITER XML_STRING_02 = <<DELIMITER
<biblio> <biblio>
<entry type="Book"> <entry type="Book">
<language>english</language> <language>english</language>
@ -52,205 +52,205 @@ DELIMITER
</biblio> </biblio>
DELIMITER DELIMITER
# Tobias Reif <tobiasreif@pinkjuice.com> # Tobias Reif <tobiasreif@pinkjuice.com>
def test_bad_doctype_Tobias def test_bad_doctype_Tobias
source = <<-EOF source = <<-EOF
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/SVG/DTD/svg10.dtd" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"
[ [
<!-- <!ENTITY % fast-slow "0 0 .5 1">--> <!-- <!ENTITY % fast-slow "0 0 .5 1">-->
<!--<!ENTITY % slow-fast ".5 0 1 1">--> <!--<!ENTITY % slow-fast ".5 0 1 1">-->
<!ENTITY hover_ani <!ENTITY hover_ani
'<animateTransform attributeName="transform" '<animateTransform attributeName="transform"
type="scale" restart="whenNotActive" values="1;0.96" type="scale" restart="whenNotActive" values="1;0.96"
dur="0.5s" calcMode="spline" keySplines="0 0 .5 1" dur="0.5s" calcMode="spline" keySplines="0 0 .5 1"
fill="freeze" begin="mouseover"/> fill="freeze" begin="mouseover"/>
<animateTransform attributeName="transform" <animateTransform attributeName="transform"
type="scale" restart="whenNotActive" values="0.96;1" type="scale" restart="whenNotActive" values="0.96;1"
dur="0.5s" calcMode="spline" keySplines=".5 0 1 1" dur="0.5s" calcMode="spline" keySplines=".5 0 1 1"
fill="freeze" begin="mouseover+0.5s"/>' fill="freeze" begin="mouseover+0.5s"/>'
>
]
> >
] EOF
> doc = REXML::Document.new source
EOF doc.write(out="")
doc = REXML::Document.new source assert(out[/>\'>/] != nil, "Couldn't find >'>")
doc.write(out="") assert(out[/\]>/] != nil, "Couldn't find ]>")
assert(out[/>\'>/] != nil, "Couldn't find >'>") end
assert(out[/\]>/] != nil, "Couldn't find ]>")
end
# Peter Verhage # Peter Verhage
def test_namespace_Peter def test_namespace_Peter
source = <<-EOF source = <<-EOF
<?xml version="1.0"?> <?xml version="1.0"?>
<config:myprog-config xmlns:config="http://someurl/program/version"> <config:myprog-config xmlns:config="http://someurl/program/version">
<!-- main options --> <!-- main options -->
<config:main> <config:main>
<config:parameter name="name" value="value"/> <config:parameter name="name" value="value"/>
</config:main> </config:main>
</config:myprog-config> </config:myprog-config>
EOF EOF
doc = REXML::Document.new source doc = REXML::Document.new source
assert_equal "myprog-config", doc.root.name assert_equal "myprog-config", doc.root.name
count = 0 count = 0
REXML::XPath.each(doc, "x:myprog-config/x:main/x:parameter", REXML::XPath.each(doc, "x:myprog-config/x:main/x:parameter",
{"x"=>"http://someurl/program/version"}) { |element| {"x"=>"http://someurl/program/version"}) { |element|
assert_equal "name", element.attributes["name"] assert_equal "name", element.attributes["name"]
count += 1; count += 1;
} }
assert_equal 1, count assert_equal 1, count
assert_equal "myprog-config", doc.elements["config:myprog-config"].name assert_equal "myprog-config", doc.elements["config:myprog-config"].name
end end
# Tobias Reif <tobiasreif@pinkjuice.com> # Tobias Reif <tobiasreif@pinkjuice.com>
def test_complex_xpath_Tobias def test_complex_xpath_Tobias
source = <<-EOF source = <<-EOF
<root> <root>
<foo> <foo>
<bar style="baz"/> <bar style="baz"/>
<blah style="baz"/> <blah style="baz"/>
<blam style="baz"/> <blam style="baz"/>
</foo> </foo>
<wax> <wax>
<fudge> <fudge>
<noodle/> <noodle/>
</fudge> </fudge>
</wax> </wax>
</root> </root>
EOF EOF
# elements that have child elements # elements that have child elements
# but not grandchildren # but not grandchildren
# and not children that don't have a style attribute # and not children that don't have a style attribute
# and not children that have a unique style attribute # and not children that have a unique style attribute
complex_path = "*[* "+ complex_path = "*[* "+
"and not(*/node()) "+ "and not(*/node()) "+
"and not(*[not(@style)]) "+ "and not(*[not(@style)]) "+
"and not(*/@style != */@style)]" "and not(*/@style != */@style)]"
doc = REXML::Document.new source doc = REXML::Document.new source
results = REXML::XPath.match( doc.root, complex_path ) results = REXML::XPath.match( doc.root, complex_path )
assert(results) assert(results)
assert_equal 1, results.size assert_equal 1, results.size
assert_equal "foo", results[0].name assert_equal "foo", results[0].name
end end
# "Chris Morris" <chrismo@charter.net> # "Chris Morris" <chrismo@charter.net>
def test_extra_newline_on_read_Chris def test_extra_newline_on_read_Chris
text = 'test text' text = 'test text'
e = REXML::Element.new('Test') e = REXML::Element.new('Test')
e.add_text(text) e.add_text(text)
REXML::Formatters::Default.new.write(e,out="") REXML::Formatters::Default.new.write(e,out="")
doc = REXML::Document.new(out) doc = REXML::Document.new(out)
outtext = doc.root.text outtext = doc.root.text
assert_equal(text, outtext) assert_equal(text, outtext)
end end
# Tobias Reif <tobiasreif@pinkjuice.com> # Tobias Reif <tobiasreif@pinkjuice.com>
def test_other_xpath_Tobias def test_other_xpath_Tobias
schema = <<-DELIM schema = <<-DELIM
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"> elementFormDefault="qualified">
<xs:element name="rect"> <xs:element name="rect">
<xs:complexType> <xs:complexType>
<xs:attribute name="width" type="xs:byte" use="required"/> <xs:attribute name="width" type="xs:byte" use="required"/>
<xs:attribute name="height" type="xs:byte" use="required"/> <xs:attribute name="height" type="xs:byte" use="required"/>
</xs:complexType> </xs:complexType>
</xs:element> </xs:element>
<xs:element name="svg"> <xs:element name="svg">
<xs:complexType> <xs:complexType>
<xs:sequence> <xs:sequence>
<xs:element ref="rect"/> <xs:element ref="rect"/>
</xs:sequence> </xs:sequence>
</xs:complexType> </xs:complexType>
</xs:element> </xs:element>
</xs:schema> </xs:schema>
DELIM DELIM
doc = REXML::Document.new schema doc = REXML::Document.new schema
result = REXML::XPath.first(doc.root, 'xs:element[descendant::xs:element[@ref]]') result = REXML::XPath.first(doc.root, 'xs:element[descendant::xs:element[@ref]]')
assert result assert result
assert_equal "svg", result.attributes['name'] assert_equal "svg", result.attributes['name']
result = REXML::XPath.first(doc, 'element[descendant::element[@ref]]') result = REXML::XPath.first(doc, 'element[descendant::element[@ref]]')
assert_nil result assert_nil result
end end
#this first test succeeds, to check if stuff is set up correctly #this first test succeeds, to check if stuff is set up correctly
def test_xpath_01_TobiasReif def test_xpath_01_TobiasReif
doc = Document.new XML_STRING_01.dup doc = Document.new XML_STRING_01.dup
desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>' desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>'
xpath = '//author' xpath = '//author'
result = XPath.first(doc, xpath) result = XPath.first(doc, xpath)
assert_equal desired_result.to_s, result.to_s assert_equal desired_result.to_s, result.to_s
end end
def test_xpath_whitespace_TobiasReif def test_xpath_whitespace_TobiasReif
# same as above, with whitespace in XPath # same as above, with whitespace in XPath
doc = Document.new(XML_STRING_01.dup) doc = Document.new(XML_STRING_01.dup)
desired_result = Document.new('<author>Thomas, David; Hunt, Andrew</author>') desired_result = Document.new('<author>Thomas, David; Hunt, Andrew</author>')
xpath = "\/\/author\n \n" xpath = "\/\/author\n \n"
result = XPath.first(doc, xpath) result = XPath.first(doc, xpath)
failure_message = "\n[[[TR: AFAIK, whitespace should be allowed]]]\n" failure_message = "\n[[[TR: AFAIK, whitespace should be allowed]]]\n"
assert_equal(desired_result.to_s, result.to_s, failure_message) assert_equal(desired_result.to_s, result.to_s, failure_message)
end end
def test_xpath_02_TobiasReif def test_xpath_02_TobiasReif
doc = Document.new XML_STRING_01.dup doc = Document.new XML_STRING_01.dup
desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>' desired_result = Document.new '<author>Thomas, David; Hunt, Andrew</author>'
# Could that quirky # Could that quirky
# Programmer',&quot;'&quot;,'s # Programmer',&quot;'&quot;,'s
# be handled automatically, somehow? # be handled automatically, somehow?
# Or is there a simpler way? (the below XPath should match the author element above, # Or is there a simpler way? (the below XPath should match the author element above,
# AFAIK; I tested it inside an XSLT) # AFAIK; I tested it inside an XSLT)
xpath = %q{/biblio/entry[ xpath = %q{/biblio/entry[
title/text()=concat('Programming Ruby. The Pragmatic Programmer',"'",'s Guide') title/text()=concat('Programming Ruby. The Pragmatic Programmer',"'",'s Guide')
and and
year='2000' year='2000'
]/author} ]/author}
result = XPath.first(doc, xpath) result = XPath.first(doc, xpath)
failure_message = "\nHow to handle the apos inside the string inside the XPath?\nXPath = #{xpath}\n" 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 assert_equal desired_result.to_s, result.to_s, failure_message
end end
def test_xpath_03_TobiasReif def test_xpath_03_TobiasReif
doc = Document.new XML_STRING_02.dup doc = Document.new XML_STRING_02.dup
desired_result_string = "<entry type='Book'> desired_result_string = "<entry type='Book'>
<language>english</language> <language>english</language>
<publisher>Addison-Wesley</publisher> <publisher>Addison-Wesley</publisher>
<title>Programming Ruby. The Pragmatic Programmer's Guide</title> <title>Programming Ruby. The Pragmatic Programmer's Guide</title>
<type>Book</type> <type>Book</type>
<year>2000</year> <year>2000</year>
</entry>" </entry>"
Document.new desired_result_string Document.new desired_result_string
xpath = "/biblio/entry[not(author)]" xpath = "/biblio/entry[not(author)]"
result = XPath.first(doc, xpath) result = XPath.first(doc, xpath)
assert_equal desired_result_string, result.to_s assert_equal desired_result_string, result.to_s
end
def test_umlaut
koln_iso = "K\xf6ln"
koln_utf = "K\xc3\xb6ln"
source_iso = "<?xml version='1.0' encoding='ISO-8859-1'?><test>#{koln_iso}</test>"
source_utf = "<?xml version='1.0' encoding='UTF-8'?><test>#{koln_utf}</test>"
if String.method_defined? :encode
koln_iso.force_encoding('iso-8859-1')
koln_utf.force_encoding('utf-8')
source_iso.force_encoding('iso-8859-1')
source_utf.force_encoding('utf-8')
end end
doc = REXML::Document.new(source_iso) def test_umlaut
assert_equal('ISO-8859-1', doc.xml_decl.encoding) koln_iso = "K\xf6ln"
assert_equal(koln_utf, doc.root.text) koln_utf = "K\xc3\xb6ln"
doc.write(out="") source_iso = "<?xml version='1.0' encoding='ISO-8859-1'?><test>#{koln_iso}</test>"
assert_equal(source_iso, out ) source_utf = "<?xml version='1.0' encoding='UTF-8'?><test>#{koln_utf}</test>"
doc.xml_decl.encoding = 'UTF-8'
doc.write(out="")
assert_equal(source_utf, out)
doc = Document.new <<-EOF 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
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<intranet> <intranet>
<position><aktuell datum="01-10-11">Technik</aktuell></position> <position><aktuell datum="01-10-11">Technik</aktuell></position>
@ -266,254 +266,254 @@ Die Technik ist das R\xFCckgrat der meisten Gesch\xFCftsprozesse bei Home of the
</nebenspalte> </nebenspalte>
</intranet> </intranet>
EOF EOF
tn = XPath.first(doc, "//nebenspalte/text()[2]") tn = XPath.first(doc, "//nebenspalte/text()[2]")
expected_iso = "N\xFCtzliches von Flashern f\xFCr Flasher." expected_iso = "N\xFCtzliches von Flashern f\xFCr Flasher."
expected_utf = expected_iso.unpack('C*').pack('U*') expected_utf = expected_iso.unpack('C*').pack('U*')
expected_iso.force_encoding(::Encoding::ISO_8859_1) expected_iso.force_encoding(::Encoding::ISO_8859_1)
expected_utf.force_encoding(::Encoding::UTF_8) expected_utf.force_encoding(::Encoding::UTF_8)
assert_equal(expected_utf, tn.to_s.strip) assert_equal(expected_utf, tn.to_s.strip)
f = REXML::Formatters::Default.new f = REXML::Formatters::Default.new
f.write( tn, Output.new(o = "", "ISO-8859-1") ) f.write( tn, Output.new(o = "", "ISO-8859-1") )
assert_equal(expected_iso, o.strip) assert_equal(expected_iso, o.strip)
doc = Document.new File.new(fixture_path('xmlfile-bug.xml')) doc = Document.new File.new(fixture_path('xmlfile-bug.xml'))
tn = XPath.first(doc, "//nebenspalte/text()[2]") tn = XPath.first(doc, "//nebenspalte/text()[2]")
assert_equal(expected_utf, tn.to_s.strip) assert_equal(expected_utf, tn.to_s.strip)
f.write( tn, Output.new(o = "", "ISO-8859-1") ) f.write( tn, Output.new(o = "", "ISO-8859-1") )
assert_equal(expected_iso, o.strip) assert_equal(expected_iso, o.strip)
end
def test_element_cloning_namespace_Chris
aDoc = REXML::Document.new '<h1 tpl:content="title" xmlns:tpl="1">Dummy title</h1>'
anElement = anElement = aDoc.elements[1]
elementAttrPrefix = anElement.attributes.get_attribute('content').prefix
aClone = anElement.clone
cloneAttrPrefix = aClone.attributes.get_attribute('content').prefix
assert_equal( elementAttrPrefix , cloneAttrPrefix )
end
def test_namespaces_in_attlist_tobias
in_string = File.open(fixture_path('foo.xml'), 'r') do |file|
file.read
end end
doc = Document.new in_string def test_element_cloning_namespace_Chris
aDoc = REXML::Document.new '<h1 tpl:content="title" xmlns:tpl="1">Dummy title</h1>'
assert_nil XPath.first(doc,'//leg') anElement = anElement = aDoc.elements[1]
assert_equal 'http://www.foo.com/human', doc.root.elements[1].namespace elementAttrPrefix = anElement.attributes.get_attribute('content').prefix
assert_equal 'human leg',
XPath.first(doc, '//x:leg/text()', {'x'=>'http://www.foo.com/human'}).to_s
end
# Alun ap Rhisiart aClone = anElement.clone
def test_less_than_in_element_content cloneAttrPrefix = aClone.attributes.get_attribute('content').prefix
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 assert_equal( elementAttrPrefix , cloneAttrPrefix )
def test_various_xpath end
#@doc = REXML::Document.new('<r a="1"><p><c b="2"/></p></r>')
doc = REXML::Document.new('<r a="1"><p><c b="2">3</c></p></r>')
[['/r', REXML::Element], def test_namespaces_in_attlist_tobias
['/r/p/c', REXML::Element], in_string = File.open(fixture_path('foo.xml'), 'r') do |file|
['/r/attribute::a', Attribute], file.read
['/r/@a', Attribute], end
['/r/attribute::*', Attribute],
['/r/@*', Attribute], doc = Document.new in_string
['/r/p/c/attribute::b', Attribute],
['/r/p/c/@b', Attribute], assert_nil XPath.first(doc,'//leg')
['/r/p/c/attribute::*', Attribute], assert_equal 'http://www.foo.com/human', doc.root.elements[1].namespace
['/r/p/c/@*', Attribute], assert_equal 'human leg',
['//c/attribute::b', Attribute], XPath.first(doc, '//x:leg/text()', {'x'=>'http://www.foo.com/human'}).to_s
['//c/@b', Attribute], end
['//c/attribute::*', Attribute],
['//c/@*', Attribute], # Alun ap Rhisiart
['.//node()', REXML::Node ], def test_less_than_in_element_content
['.//node()[@a]', REXML::Element ], source = File.new(fixture_path('ProductionSupport.xml'))
['.//node()[@a="1"]', REXML::Element ], h = Hash.new
['.//node()[@b]', REXML::Element ], # no show, why? doc = REXML::Document.new source
['.//node()[@b="2"]', REXML::Element ] doc.elements.each("//CommonError") { |el|
].each do |xpath,kind| h[el.elements['Key'].text] = 'okay'
begin }
REXML::XPath.each( doc, xpath ) do |what| assert(h.include?('MotorInsuranceContract(Object)>>#error:'))
assert_kind_of( kind, what, "\n\nWrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n\n" ) end
# XPaths provided by Thomas Sawyer
def test_various_xpath
#@doc = REXML::Document.new('<r a="1"><p><c b="2"/></p></r>')
doc = REXML::Document.new('<r a="1"><p><c b="2">3</c></p></r>')
[['/r', REXML::Element],
['/r/p/c', REXML::Element],
['/r/attribute::a', Attribute],
['/r/@a', Attribute],
['/r/attribute::*', Attribute],
['/r/@*', Attribute],
['/r/p/c/attribute::b', Attribute],
['/r/p/c/@b', Attribute],
['/r/p/c/attribute::*', Attribute],
['/r/p/c/@*', Attribute],
['//c/attribute::b', Attribute],
['//c/@b', Attribute],
['//c/attribute::*', Attribute],
['//c/@*', Attribute],
['.//node()', REXML::Node ],
['.//node()[@a]', REXML::Element ],
['.//node()[@a="1"]', REXML::Element ],
['.//node()[@b]', REXML::Element ], # no show, why?
['.//node()[@b="2"]', REXML::Element ]
].each do |xpath,kind|
begin
REXML::XPath.each( doc, xpath ) do |what|
assert_kind_of( kind, what, "\n\nWrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n\n" )
end
rescue Exception
puts "PATH WAS: #{xpath}"
raise
end
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"
end
rescue Exception
puts "PATH WAS: #{xpath}"
raise
end end
rescue Exception
puts "PATH WAS: #{xpath}"
raise
end end
end end
[ def test_entities_Holden_Glova
['/r', 'attribute::a', Attribute ], document = <<-EOL
['/r', '@a', Attribute ], <?xml version="1.0" encoding="UTF-8"?>
['/r', 'attribute::*', Attribute ], <!DOCTYPE rubynet [
['/r', '@*', Attribute ], <!ENTITY rbconfig.MAJOR "1">
['/r/p/c', 'attribute::b', Attribute ], <!ENTITY rbconfig.MINOR "7">
['/r/p/c', '@b', Attribute ], <!ENTITY rbconfig.TEENY "2">
['/r/p/c', 'attribute::*', Attribute ], <!ENTITY rbconfig.ruby_version "&rbconfig.MAJOR;.&rbconfig.MINOR;">
['/r/p/c', '@*', Attribute ] <!ENTITY rbconfig.arch "i386-freebsd5">
].each do |nodepath, xpath, kind| <!ENTITY rbconfig.prefix "/usr/local">
begin <!ENTITY rbconfig.libdir "&rbconfig.prefix;/lib">
context = REXML::XPath.first(doc, nodepath) <!ENTITY rbconfig.includedir "&rbconfig.prefix;/include">
REXML::XPath.each( context, xpath ) do |what| <!ENTITY rbconfig.sitedir "&rbconfig.prefix;/lib/ruby/site_ruby">
assert_kind_of kind, what, "Wrong type (#{what.class}) returned for #{xpath} (expected #{kind.name})\n" <!ENTITY rbconfig.sitelibdir "&rbconfig.sitedir;/&rbconfig.ruby_version;">
end <!ENTITY rbconfig.sitearchdir "&rbconfig.sitelibdir;/&rbconfig.arch;">
rescue Exception ]>
puts "PATH WAS: #{xpath}" <rubynet>
raise <pkg version="version1.0">
<files>
<file>
<filename>uga.rb</filename>
<mode>0444</mode>
<path>&rbconfig.libdir;/rexml</path>
<content encoding="xml">... the file here</content>
</file>
<file>
<filename>booga.h</filename>
<mode>0444</mode>
<path>&rbconfig.includedir;</path>
<content encoding="xml">... the file here</content>
</file>
<file>
<filename>foo.so</filename>
<mode>0555</mode>
<path>&rbconfig.sitearchdir;/rexml</path>
<content encoding="mime64">Li4uIHRoZSBmaWxlIGhlcmU=\n</content>
</file>
</files>
</pkg>
</rubynet>
EOL
file_xpath = '/rubynet/pkg/files/file'
root = REXML::Document.new(document)
root.elements.each(file_xpath) do |metadata|
text = metadata.elements['path'].get_text.value
assert text !~ /&rbconfig/, "'#{text}' failed"
end end
end
end
def test_entities_Holden_Glova #Error occurred in test_package_file_opens(TC_PackageInstall):
document = <<-EOL # ArgumentError:
<?xml version="1.0" encoding="UTF-8"?> #illegal access mode &rbconfig.prefix;/lib/rexml
<!DOCTYPE rubynet [ #
<!ENTITY rbconfig.MAJOR "1"> #[synack@Evergreen] src $ ruby --version
<!ENTITY rbconfig.MINOR "7"> #ruby 1.6.7 (2002-03-01) [i686-linux-gnu]
<!ENTITY rbconfig.TEENY "2"> #
<!ENTITY rbconfig.ruby_version "&rbconfig.MAJOR;.&rbconfig.MINOR;"> #It looks like it expanded the first entity, but didn't reparse it for more
<!ENTITY rbconfig.arch "i386-freebsd5"> #entities. possible bug - or have I mucked this up?
<!ENTITY rbconfig.prefix "/usr/local">
<!ENTITY rbconfig.libdir "&rbconfig.prefix;/lib">
<!ENTITY rbconfig.includedir "&rbconfig.prefix;/include">
<!ENTITY rbconfig.sitedir "&rbconfig.prefix;/lib/ruby/site_ruby">
<!ENTITY rbconfig.sitelibdir "&rbconfig.sitedir;/&rbconfig.ruby_version;">
<!ENTITY rbconfig.sitearchdir "&rbconfig.sitelibdir;/&rbconfig.arch;">
]>
<rubynet>
<pkg version="version1.0">
<files>
<file>
<filename>uga.rb</filename>
<mode>0444</mode>
<path>&rbconfig.libdir;/rexml</path>
<content encoding="xml">... the file here</content>
</file>
<file>
<filename>booga.h</filename>
<mode>0444</mode>
<path>&rbconfig.includedir;</path>
<content encoding="xml">... the file here</content>
</file>
<file>
<filename>foo.so</filename>
<mode>0555</mode>
<path>&rbconfig.sitearchdir;/rexml</path>
<content encoding="mime64">Li4uIHRoZSBmaWxlIGhlcmU=\n</content>
</file>
</files>
</pkg>
</rubynet>
EOL
file_xpath = '/rubynet/pkg/files/file'
root = REXML::Document.new(document)
root.elements.each(file_xpath) do |metadata|
text = metadata.elements['path'].get_text.value
assert text !~ /&rbconfig/, "'#{text}' failed"
end end
#Error occurred in test_package_file_opens(TC_PackageInstall): def test_whitespace_after_xml_decl
# ArgumentError: Document.new <<EOL
#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
<?xml version='1.0'?> <?xml version='1.0'?>
<blo> <blo>
<wak> <wak>
</wak> </wak>
</blo> </blo>
EOL EOL
end end
def test_external_entity def test_external_entity
xp = '//channel/title' xp = '//channel/title'
%w{working.rss broken.rss}.each do |path| %w{working.rss broken.rss}.each do |path|
File.open(File.join(fixture_path(path))) do |file| File.open(File.join(fixture_path(path))) do |file|
doc = REXML::Document.new file.readlines.join('') doc = REXML::Document.new file.readlines.join('')
# check to make sure everything is kosher # check to make sure everything is kosher
assert_equal( doc.root.class, REXML::Element ) assert_equal( doc.root.class, REXML::Element )
assert_equal( doc.root.elements.class, REXML::Elements ) assert_equal( doc.root.elements.class, REXML::Elements )
# get the title of the feed # get the title of the feed
assert( doc.root.elements[xp].kind_of?( REXML::Element ) ) assert( doc.root.elements[xp].kind_of?( REXML::Element ) )
end
end end
end end
end
def test_maintain_dtd def test_maintain_dtd
src = %q{<?xml version="1.0" encoding="UTF-8"?> src = %q{<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ivattacks SYSTEM "../../ivacm.dtd" [ <!DOCTYPE ivattacks SYSTEM "../../ivacm.dtd" [
<!ENTITY % extern-packages SYSTEM "../../ivpackages.dtd"> <!ENTITY % extern-packages SYSTEM "../../ivpackages.dtd">
<!ENTITY % extern-packages SYSTEM "../../common-declarations.dtd"> <!ENTITY % extern-packages SYSTEM "../../common-declarations.dtd">
%extern-packages; %extern-packages;
%extern-common; %extern-common;
]>} ]>}
doc = Document.new( src ) doc = Document.new( src )
doc.write( out="" ) doc.write( out="" )
src = src.tr('"', "'") src = src.tr('"', "'")
out = out.tr('"', "'") out = out.tr('"', "'")
assert_equal( src, out ) assert_equal( src, out )
end end
def test_text_nodes_nomatch def test_text_nodes_nomatch
source = "<root><child>test</child></root>" source = "<root><child>test</child></root>"
d = REXML::Document.new( source ) d = REXML::Document.new( source )
r = REXML::XPath.match( d, %q{/root/child[text()="no-test"]} ) r = REXML::XPath.match( d, %q{/root/child[text()="no-test"]} )
assert_equal( 0, r.size ) assert_equal( 0, r.size )
end end
def test_raw_Terje_Elde def test_raw_Terje_Elde
f = REXML::Formatters::Default.new f = REXML::Formatters::Default.new
txt = 'abc&#248;def' txt = 'abc&#248;def'
a = Text.new( txt,false,nil,true ) a = Text.new( txt,false,nil,true )
f.write(a,out="") f.write(a,out="")
assert_equal( txt, out ) assert_equal( txt, out )
txt = '<sean><russell>abc&#248;def</russell></sean>' txt = '<sean><russell>abc&#248;def</russell></sean>'
a = Document.new( txt, { :raw => ["russell"] } ) a = Document.new( txt, { :raw => ["russell"] } )
f.write(a,out="") f.write(a,out="")
assert_equal( txt, out ) assert_equal( txt, out )
end end
def test_indenting_error def test_indenting_error
a=Element.new("test1") a=Element.new("test1")
b=Element.new("test2") b=Element.new("test2")
c=Element.new("test3") c=Element.new("test3")
b << c b << c
a << b a << b
REXML::Formatters::Pretty.new.write(a,"") REXML::Formatters::Pretty.new.write(a,"")
end end
def test_pos def test_pos
require 'tempfile' require 'tempfile'
Tempfile.create("tidal") {|testfile| Tempfile.create("tidal") {|testfile|
testdata = %Q{<calibration> testdata = %Q{<calibration>
<section name="parameters"> <section name="parameters">
<param name="barpress">760</param> <param name="barpress">760</param>
<param name="hertz">50</param> <param name="hertz">50</param>
@ -521,63 +521,63 @@ EOL
</calibration> </calibration>
} }
testfile.puts testdata testfile.puts testdata
testfile.rewind testfile.rewind
assert_nothing_raised do assert_nothing_raised do
REXML::Document.new(testfile) REXML::Document.new(testfile)
end end
} }
end end
def test_deep_clone def test_deep_clone
a = Document.new( '<?xml version="1.0"?><!DOCTYPE html PUBLIC a = Document.new( '<?xml version="1.0"?><!DOCTYPE html PUBLIC
"-//W3C//DTD "-//W3C//DTD
XHTML 1.0 Transitional//EN" XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html
xmlns="http:///www.w3.org/1999/xhtml"></html>' ) xmlns="http:///www.w3.org/1999/xhtml"></html>' )
b = a.deep_clone b = a.deep_clone
assert_equal a.to_s, b.to_s assert_equal a.to_s, b.to_s
end end
def test_double_escaping def test_double_escaping
data = '<title>AT&amp;T</title>' data = '<title>AT&amp;T</title>'
xml = "<description><![CDATA[#{data}]]></description>" xml = "<description><![CDATA[#{data}]]></description>"
doc = REXML::Document.new(xml) doc = REXML::Document.new(xml)
description = doc.find {|e| e.name=="description"} description = doc.find {|e| e.name=="description"}
assert_equal data, description.text assert_equal data, description.text
end end
def test_ticket_12 def test_ticket_12
cfg = "<element><anotherelement><child1>a</child1><child2>b</child2></anotherelement></element>" cfg = "<element><anotherelement><child1>a</child1><child2>b</child2></anotherelement></element>"
config = REXML::Document.new( cfg ) config = REXML::Document.new( cfg )
assert_equal( "a", config.elements[ "//child1" ].text ) assert_equal( "a", config.elements[ "//child1" ].text )
end end
=begin =begin
# This is a silly test, and is low priority # This is a silly test, and is low priority
def test_namespace_serialization_tobi_reif def test_namespace_serialization_tobi_reif
doc = Document.new '<doc xmlns:b="http://www.foo.foo"> doc = Document.new '<doc xmlns:b="http://www.foo.foo">
<b:p/> <b:p/>
</doc>' </doc>'
ns = 'http://www.foo.foo' ns = 'http://www.foo.foo'
ns_declaration={'f'=>ns} ns_declaration={'f'=>ns}
returned = XPath.match(doc,'//f:p',ns_declaration) returned = XPath.match(doc,'//f:p',ns_declaration)
# passes: # passes:
assert( (returned[0].namespace==ns), 'namespace should be '+ns) assert( (returned[0].namespace==ns), 'namespace should be '+ns)
serialized = returned.to_s serialized = returned.to_s
serialized_and_parsed = Document.new(serialized) serialized_and_parsed = Document.new(serialized)
puts 'serialized: '+serialized puts 'serialized: '+serialized
# ... currently brings <b:p/> # ... currently brings <b:p/>
# prefix b is undeclared (!) # prefix b is undeclared (!)
assert( (serialized_and_parsed.namespace==ns), assert( (serialized_and_parsed.namespace==ns),
'namespace should still be '+ns.inspect+ 'namespace should still be '+ns.inspect+
' and not '+serialized_and_parsed.namespace.inspect) ' and not '+serialized_and_parsed.namespace.inspect)
# ... currently results in a failure: # ... currently results in a failure:
# 'namespace should still be "http://www.foo.foo" and not ""' # 'namespace should still be "http://www.foo.foo" and not ""'
end end
=end =end
end end
end end

File diff suppressed because it is too large Load diff

View file

@ -2,105 +2,105 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class TestDocTypeAccessor < Test::Unit::TestCase class TestDocTypeAccessor < Test::Unit::TestCase
def setup def setup
@sysid = "urn:x-test:sysid1" @sysid = "urn:x-test:sysid1"
@notid1 = "urn:x-test:notation1" @notid1 = "urn:x-test:notation1"
@notid2 = "urn:x-test:notation2" @notid2 = "urn:x-test:notation2"
document_string1 = <<-"XMLEND" document_string1 = <<-"XMLEND"
<!DOCTYPE r SYSTEM "#{@sysid}" [ <!DOCTYPE r SYSTEM "#{@sysid}" [
<!NOTATION n1 SYSTEM "#{@notid1}"> <!NOTATION n1 SYSTEM "#{@notid1}">
<!NOTATION n2 SYSTEM "#{@notid2}"> <!NOTATION n2 SYSTEM "#{@notid2}">
]> ]>
<r/> <r/>
XMLEND XMLEND
@doctype1 = REXML::Document.new(document_string1).doctype @doctype1 = REXML::Document.new(document_string1).doctype
@pubid = "TEST_ID" @pubid = "TEST_ID"
document_string2 = <<-"XMLEND" document_string2 = <<-"XMLEND"
<!DOCTYPE r PUBLIC "#{@pubid}"> <!DOCTYPE r PUBLIC "#{@pubid}">
<r/> <r/>
XMLEND XMLEND
@doctype2 = REXML::Document.new(document_string2).doctype @doctype2 = REXML::Document.new(document_string2).doctype
document_string3 = <<-"XMLEND" document_string3 = <<-"XMLEND"
<!DOCTYPE r PUBLIC "#{@pubid}" "#{@sysid}"> <!DOCTYPE r PUBLIC "#{@pubid}" "#{@sysid}">
<r/> <r/>
XMLEND XMLEND
@doctype3 = REXML::Document.new(document_string3).doctype @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 end
def test_public class TestNotationDeclPublic < Test::Unit::TestCase
assert_equal(nil, @doctype1.public) def setup
assert_equal(@pubid, @doctype2.public) @name = "vrml"
assert_equal(@pubid, @doctype3.public) @id = "VRML 1.0"
@uri = "http://www.web3d.org/"
end
def test_to_s
assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\">",
decl(@id, nil).to_s)
end
def test_to_s_with_uri
assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\" \"#{@uri}\">",
decl(@id, @uri).to_s)
end
private
def decl(id, uri)
REXML::NotationDecl.new(@name, "PUBLIC", id, uri)
end
end end
def test_system class TestNotationDeclSystem < Test::Unit::TestCase
assert_equal(@sysid, @doctype1.system) def setup
assert_equal(nil, @doctype2.system) @name = "gif"
assert_equal(@sysid, @doctype3.system) @id = "gif viewer"
end end
def test_notation def test_to_s
assert_equal(@notid1, @doctype1.notation("n1").system) assert_equal("<!NOTATION #{@name} SYSTEM \"#{@id}\">",
assert_equal(@notid2, @doctype1.notation("n2").system) decl(@id).to_s)
end end
def test_notations private
notations = @doctype1.notations def decl(id)
assert_equal(2, notations.length) REXML::NotationDecl.new(@name, "SYSTEM", id, nil)
assert_equal(@notid1, find_notation(notations, "n1").system) end
assert_equal(@notid2, find_notation(notations, "n2").system)
end
def find_notation(notations, name)
notations.find { |notation|
name == notation.name
}
end
end
class TestNotationDeclPublic < Test::Unit::TestCase
def setup
@name = "vrml"
@id = "VRML 1.0"
@uri = "http://www.web3d.org/"
end
def test_to_s
assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\">",
decl(@id, nil).to_s)
end
def test_to_s_with_uri
assert_equal("<!NOTATION #{@name} PUBLIC \"#{@id}\" \"#{@uri}\">",
decl(@id, @uri).to_s)
end
private
def decl(id, uri)
REXML::NotationDecl.new(@name, "PUBLIC", id, uri)
end end
end end
class TestNotationDeclSystem < Test::Unit::TestCase
def setup
@name = "gif"
@id = "gif viewer"
end
def test_to_s
assert_equal("<!NOTATION #{@name} SYSTEM \"#{@id}\">",
decl(@id).to_s)
end
private
def decl(id)
REXML::NotationDecl.new(@name, "SYSTEM", id, nil)
end
end
end

View file

@ -2,117 +2,117 @@ require 'test/unit/testcase'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class ElementsTester < Test::Unit::TestCase class ElementsTester < Test::Unit::TestCase
include REXML include REXML
def test_accessor def test_accessor
doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>' doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>'
assert_equal 'b', doc.root.elements[1].name assert_equal 'b', doc.root.elements[1].name
assert_equal '1', doc.root.elements['c'].attributes['id'] assert_equal '1', doc.root.elements['c'].attributes['id']
assert_equal '2', doc.root.elements[2,'c'].attributes['id'] assert_equal '2', doc.root.elements[2,'c'].attributes['id']
end
def test_indexing
doc = Document.new '<a/>'
doc.root.elements[10] = Element.new('b')
assert_equal 'b', doc.root.elements[1].name
doc.root.elements[1] = Element.new('c')
assert_equal 'c', doc.root.elements[1].name
doc.root.elements['c'] = Element.new('d')
assert_equal 'd', doc.root.elements[1].name
end
def test_delete
doc = Document.new '<a><b/><c/><c id="1"/></a>'
block = proc { |str|
out = ''
doc.write out
assert_equal str, out
}
b = doc.root.elements[1]
doc.root.elements.delete b
block.call( "<a><c/><c id='1'/></a>" )
doc.elements.delete("a/c[@id='1']")
block.call( '<a><c/></a>' )
doc.root.elements.delete 1
block.call( '<a/>' )
end
def test_delete_all
doc = Document.new '<a><c/><c/><c/><c/></a>'
deleted = doc.elements.delete_all 'a/c'
assert_equal 4, deleted.size
end
def test_ticket_36
doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" )
deleted = doc.root.elements.delete_all( "xi:c" )
assert_equal( 1, deleted.size )
doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" )
deleted = doc.root.elements.delete_all( "//xi:c" )
assert_equal( 2, deleted.size )
end
def test_add
a = Element.new 'a'
a.elements.add Element.new('b')
assert_equal 'b', a.elements[1].name
a.elements.add 'c'
assert_equal 'c', a.elements[2].name
end
def test_size
doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>'
assert_equal 6, doc.root.size
assert_equal 3, doc.root.elements.size
end
def test_each
doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>'
count = 0
block = proc {|e| count += 1}
doc.root.elements.each(&block)
assert_equal 6, count
count = 0
doc.root.elements.each('b', &block)
assert_equal 2, count
count = 0
doc.root.elements.each('child::node()', &block)
assert_equal 6, count
count = 0
XPath.each(doc.root, 'child::node()', &block)
assert_equal 7, count
end
def test_each_with_frozen_condition
doc = Document.new('<books><book name="Ruby"/><book name="XML"/></books>')
names = []
doc.root.elements.each('book'.freeze) do |element|
names << element.attributes["name"]
end end
assert_equal(["Ruby", "XML"], names)
end
def test_to_a def test_indexing
doc = Document.new '<a>sean<b/>elliott<c/></a>' doc = Document.new '<a/>'
assert_equal 2, doc.root.elements.to_a.size doc.root.elements[10] = Element.new('b')
assert_equal 2, doc.root.elements.to_a("child::node()").size assert_equal 'b', doc.root.elements[1].name
assert_equal 4, XPath.match(doc.root, "child::node()").size doc.root.elements[1] = Element.new('c')
end 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_collect def test_delete
doc = Document.new( "<a><b id='1'/><b id='2'/></a>" ) doc = Document.new '<a><b/><c/><c id="1"/></a>'
r = doc.elements.collect( "/a/b" ) { |e| e.attributes["id"].to_i } block = proc { |str|
assert_equal( [1,2], r ) out = ''
end doc.write out
assert_equal str, out
}
b = doc.root.elements[1]
doc.root.elements.delete b
block.call( "<a><c/><c id='1'/></a>" )
doc.elements.delete("a/c[@id='1']")
block.call( '<a><c/></a>' )
doc.root.elements.delete 1
block.call( '<a/>' )
end
def test_inject def test_delete_all
doc = Document.new( "<a><b id='1'/><b id='2'/></a>" ) doc = Document.new '<a><c/><c/><c/><c/></a>'
r = doc.elements.inject( "/a/b", 3 ) { |s, e| deleted = doc.elements.delete_all 'a/c'
s + e.attributes["id"].to_i assert_equal 4, deleted.size
} end
assert_equal 6, r
def test_ticket_36
doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" )
deleted = doc.root.elements.delete_all( "xi:c" )
assert_equal( 1, deleted.size )
doc = Document.new( "<a xmlns:xi='foo'><b><xi:c id='1'/></b><xi:c id='2'/></a>" )
deleted = doc.root.elements.delete_all( "//xi:c" )
assert_equal( 2, deleted.size )
end
def test_add
a = Element.new 'a'
a.elements.add Element.new('b')
assert_equal 'b', a.elements[1].name
a.elements.add 'c'
assert_equal 'c', a.elements[2].name
end
def test_size
doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>'
assert_equal 6, doc.root.size
assert_equal 3, doc.root.elements.size
end
def test_each
doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>'
count = 0
block = proc {|e| count += 1}
doc.root.elements.each(&block)
assert_equal 6, count
count = 0
doc.root.elements.each('b', &block)
assert_equal 2, count
count = 0
doc.root.elements.each('child::node()', &block)
assert_equal 6, count
count = 0
XPath.each(doc.root, 'child::node()', &block)
assert_equal 7, count
end
def test_each_with_frozen_condition
doc = Document.new('<books><book name="Ruby"/><book name="XML"/></books>')
names = []
doc.root.elements.each('book'.freeze) do |element|
names << element.attributes["name"]
end
assert_equal(["Ruby", "XML"], names)
end
def test_to_a
doc = Document.new '<a>sean<b/>elliott<c/></a>'
assert_equal 2, doc.root.elements.to_a.size
assert_equal 2, doc.root.elements.to_a("child::node()").size
assert_equal 4, XPath.match(doc.root, "child::node()").size
end
def test_collect
doc = Document.new( "<a><b id='1'/><b id='2'/></a>" )
r = doc.elements.collect( "/a/b" ) { |e| e.attributes["id"].to_i }
assert_equal( [1,2], r )
end
def test_inject
doc = Document.new( "<a><b id='1'/><b id='2'/></a>" )
r = doc.elements.inject( "/a/b", 3 ) { |s, e|
s + e.attributes["id"].to_i
}
assert_equal 6, r
end
end end
end end
end

View file

@ -6,91 +6,91 @@ require 'rexml/source'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class EncodingTester < Test::Unit::TestCase class EncodingTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML include REXML
def setup def setup
@encoded_root = "<a><b>\346</b></a>" @encoded_root = "<a><b>\346</b></a>"
@encoded = "<?xml version='1.0' encoding='ISO-8859-3'?>"+ @encoded = "<?xml version='1.0' encoding='ISO-8859-3'?>"+
@encoded_root @encoded_root
@not_encoded = "<a><b>ĉ</b></a>" @not_encoded = "<a><b>ĉ</b></a>"
end end
# Given an encoded document, try to write out to that encoding # Given an encoded document, try to write out to that encoding
def test_encoded_in_encoded_out def test_encoded_in_encoded_out
doc = Document.new( @encoded ) doc = Document.new( @encoded )
doc.write( out="" ) doc.write( out="" )
out.force_encoding(::Encoding::ASCII_8BIT) out.force_encoding(::Encoding::ASCII_8BIT)
assert_equal( @encoded, out ) assert_equal( @encoded, out )
end end
# Given an encoded document, try to change the encoding and write it out # Given an encoded document, try to change the encoding and write it out
def test_encoded_in_change_out def test_encoded_in_change_out
doc = Document.new( @encoded ) doc = Document.new( @encoded )
doc.xml_decl.encoding = "UTF-8" doc.xml_decl.encoding = "UTF-8"
assert_equal("UTF-8", doc.encoding) assert_equal("UTF-8", doc.encoding)
REXML::Formatters::Default.new.write( doc.root, out="" ) REXML::Formatters::Default.new.write( doc.root, out="" )
out.force_encoding(::Encoding::ASCII_8BIT) out.force_encoding(::Encoding::ASCII_8BIT)
assert_equal( @not_encoded, out ) assert_equal( @not_encoded, out )
char = XPath.first( doc, "/a/b/text()" ).to_s char = XPath.first( doc, "/a/b/text()" ).to_s
char.force_encoding(::Encoding::ASCII_8BIT) char.force_encoding(::Encoding::ASCII_8BIT)
assert_equal( "ĉ", char ) assert_equal( "ĉ", char )
end end
# * Given an encoded document, try to write it to a different encoding # * Given an encoded document, try to write it to a different encoding
def test_encoded_in_different_out def test_encoded_in_different_out
doc = Document.new( @encoded ) doc = Document.new( @encoded )
REXML::Formatters::Default.new.write( doc.root, Output.new( out="", "UTF-8" ) ) REXML::Formatters::Default.new.write( doc.root, Output.new( out="", "UTF-8" ) )
out.force_encoding(::Encoding::ASCII_8BIT) out.force_encoding(::Encoding::ASCII_8BIT)
assert_equal( @not_encoded, out ) assert_equal( @not_encoded, out )
end end
# * Given a non-encoded document, change the encoding # * Given a non-encoded document, change the encoding
def test_in_change_out def test_in_change_out
doc = Document.new( @not_encoded ) doc = Document.new( @not_encoded )
doc.xml_decl.encoding = "ISO-8859-3" doc.xml_decl.encoding = "ISO-8859-3"
assert_equal("ISO-8859-3", doc.encoding) assert_equal("ISO-8859-3", doc.encoding)
doc.write( out="" ) doc.write( out="" )
out.force_encoding(::Encoding::ASCII_8BIT) out.force_encoding(::Encoding::ASCII_8BIT)
assert_equal( @encoded, out ) assert_equal( @encoded, out )
end end
# * Given a non-encoded document, write to a different encoding # * Given a non-encoded document, write to a different encoding
def test_in_different_out def test_in_different_out
doc = Document.new( @not_encoded ) doc = Document.new( @not_encoded )
doc.write( Output.new( out="", "ISO-8859-3" ) ) doc.write( Output.new( out="", "ISO-8859-3" ) )
out.force_encoding(::Encoding::ASCII_8BIT) out.force_encoding(::Encoding::ASCII_8BIT)
assert_equal( "<?xml version='1.0'?>#{@encoded_root}", out ) assert_equal( "<?xml version='1.0'?>#{@encoded_root}", out )
end end
# * Given an encoded document, accessing text and attribute nodes # * Given an encoded document, accessing text and attribute nodes
# should provide UTF-8 text. # should provide UTF-8 text.
def test_in_different_access def test_in_different_access
doc = Document.new <<-EOL doc = Document.new <<-EOL
<?xml version='1.0' encoding='ISO-8859-1'?> <?xml version='1.0' encoding='ISO-8859-1'?>
<a a="\xFF">\xFF</a> <a a="\xFF">\xFF</a>
EOL EOL
expect = "\303\277" expect = "\303\277"
expect.force_encoding(::Encoding::UTF_8) expect.force_encoding(::Encoding::UTF_8)
assert_equal( expect, doc.elements['a'].attributes['a'] ) assert_equal( expect, doc.elements['a'].attributes['a'] )
assert_equal( expect, doc.elements['a'].text ) assert_equal( expect, doc.elements['a'].text )
end end
def test_ticket_89 def test_ticket_89
doc = Document.new <<-EOL doc = Document.new <<-EOL
<?xml version="1.0" encoding="CP-1252" ?> <?xml version="1.0" encoding="CP-1252" ?>
<xml><foo></foo></xml> <xml><foo></foo></xml>
EOL EOL
REXML::Document.new doc REXML::Document.new doc
end end
def test_ticket_110 def test_ticket_110
utf16 = REXML::Document.new(File.new(fixture_path("ticket_110_utf16.xml"))) utf16 = REXML::Document.new(File.new(fixture_path("ticket_110_utf16.xml")))
assert_equal(utf16.encoding, "UTF-16") assert_equal(utf16.encoding, "UTF-16")
assert( utf16[0].kind_of?(REXML::XMLDecl)) assert( utf16[0].kind_of?(REXML::XMLDecl))
end
end end
end end
end

View file

@ -5,185 +5,185 @@ require 'rexml/entity'
require 'rexml/source' require 'rexml/source'
module REXMLTests module REXMLTests
class EntityTester < Test::Unit::TestCase class EntityTester < Test::Unit::TestCase
def test_parse_general_decl def test_parse_general_decl
simple = "<!ENTITY foo 'bar'>" simple = "<!ENTITY foo 'bar'>"
simple =~ /#{REXML::Entity::GEDECL}/ simple =~ /#{REXML::Entity::GEDECL}/
assert $& assert $&
assert_equal simple, $& assert_equal simple, $&
REXML::Entity::ENTITYDECL =~ simple REXML::Entity::ENTITYDECL =~ simple
assert REXML::Entity::matches?(simple) assert REXML::Entity::matches?(simple)
match = REXML::Entity::ENTITYDECL.match(simple) match = REXML::Entity::ENTITYDECL.match(simple)
assert_equal 'foo', match[1] assert_equal 'foo', match[1]
assert_equal "'bar'", match[2] assert_equal "'bar'", match[2]
simple = '<!ENTITY Pub-Status simple = '<!ENTITY Pub-Status
"This is a pre-release of the specification.">' "This is a pre-release of the specification.">'
assert REXML::Entity::matches?(simple) assert REXML::Entity::matches?(simple)
match = REXML::Entity::ENTITYDECL.match(simple) match = REXML::Entity::ENTITYDECL.match(simple)
assert_equal 'Pub-Status', match[1] assert_equal 'Pub-Status', match[1]
assert_equal '"This is a pre-release of the specification."', match[2] assert_equal '"This is a pre-release of the specification."', match[2]
txt = '"This is a txt = '"This is a
pre-release of <the> specification."' pre-release of <the> specification."'
simple = "<!ENTITY Pub-Status simple = "<!ENTITY Pub-Status
#{txt}>" #{txt}>"
assert REXML::Entity::matches?(simple) assert REXML::Entity::matches?(simple)
match = REXML::Entity::ENTITYDECL.match(simple) match = REXML::Entity::ENTITYDECL.match(simple)
assert_equal 'Pub-Status', match[1] assert_equal 'Pub-Status', match[1]
assert_equal txt, match[2] assert_equal txt, match[2]
end end
def test_parse_external_decl def test_parse_external_decl
zero = '<!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml" >' zero = '<!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml" >'
one = '<!ENTITY open-hatch one = '<!ENTITY open-hatch
SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">' SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">'
two = '<!ENTITY open-hatch two = '<!ENTITY open-hatch
PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN"
"http://www.textuality.com/boilerplate/OpenHatch.xml">' "http://www.textuality.com/boilerplate/OpenHatch.xml">'
three = '<!ENTITY hatch-pic three = '<!ENTITY hatch-pic
SYSTEM "../grafix/OpenHatch.gif" SYSTEM "../grafix/OpenHatch.gif"
NDATA gif >' NDATA gif >'
assert REXML::Entity::matches?(zero) assert REXML::Entity::matches?(zero)
assert REXML::Entity::matches?(one) assert REXML::Entity::matches?(one)
assert REXML::Entity::matches?(two) assert REXML::Entity::matches?(two)
assert REXML::Entity::matches?(three) assert REXML::Entity::matches?(three)
end end
def test_parse_entity def test_parse_entity
one = %q{<!ENTITY % YN '"Yes"'>} one = %q{<!ENTITY % YN '"Yes"'>}
two = %q{<!ENTITY WhatHeSaid "He said %YN;">} two = %q{<!ENTITY WhatHeSaid "He said %YN;">}
assert REXML::Entity::matches?(one) assert REXML::Entity::matches?(one)
assert REXML::Entity::matches?(two) assert REXML::Entity::matches?(two)
end end
def test_constructor def test_constructor
one = [ %q{<!ENTITY % YN '"Yes"'>}, one = [ %q{<!ENTITY % YN '"Yes"'>},
%q{<!ENTITY % YN2 "Yes">}, %q{<!ENTITY % YN2 "Yes">},
%q{<!ENTITY WhatHeSaid "He said %YN;">}, %q{<!ENTITY WhatHeSaid "He said %YN;">},
'<!ENTITY open-hatch '<!ENTITY open-hatch
SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">', SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">',
'<!ENTITY open-hatch2 '<!ENTITY open-hatch2
PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN"
"http://www.textuality.com/boilerplate/OpenHatch.xml">', "http://www.textuality.com/boilerplate/OpenHatch.xml">',
'<!ENTITY hatch-pic '<!ENTITY hatch-pic
SYSTEM "../grafix/OpenHatch.gif" SYSTEM "../grafix/OpenHatch.gif"
NDATA gif>' ] NDATA gif>' ]
source = %q{<!DOCTYPE foo [ source = %q{<!DOCTYPE foo [
<!ENTITY % YN '"Yes"'> <!ENTITY % YN '"Yes"'>
<!ENTITY % YN2 "Yes"> <!ENTITY % YN2 "Yes">
<!ENTITY WhatHeSaid "He said %YN;"> <!ENTITY WhatHeSaid "He said %YN;">
<!ENTITY open-hatch <!ENTITY open-hatch
SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">
<!ENTITY open-hatch2 <!ENTITY open-hatch2
PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN"
"http://www.textuality.com/boilerplate/OpenHatch.xml"> "http://www.textuality.com/boilerplate/OpenHatch.xml">
<!ENTITY hatch-pic <!ENTITY hatch-pic
SYSTEM "../grafix/OpenHatch.gif" SYSTEM "../grafix/OpenHatch.gif"
NDATA gif> NDATA gif>
]>} ]>}
d = REXML::Document.new( source ) d = REXML::Document.new( source )
dt = d.doctype dt = d.doctype
c = 0 c = 0
dt.each do |child| dt.each do |child|
if child.kind_of? REXML::Entity if child.kind_of? REXML::Entity
str = one[c].tr("\r\n\t", ' ').squeeze(" ") str = one[c].tr("\r\n\t", ' ').squeeze(" ")
assert_equal str, child.to_s assert_equal str, child.to_s
c+=1 c+=1
end
end end
end end
end
def test_replace_entities def test_replace_entities
source = "<!DOCTYPE blah [\n<!ENTITY foo \"bar\">\n]><a>&foo;</a>" source = "<!DOCTYPE blah [\n<!ENTITY foo \"bar\">\n]><a>&foo;</a>"
doc = REXML::Document.new(source) doc = REXML::Document.new(source)
assert_equal 'bar', doc.root.text assert_equal 'bar', doc.root.text
out = '' out = ''
doc.write out doc.write out
assert_equal source, out assert_equal source, out
end
def test_entity_string_limit
template = '<!DOCTYPE bomb [ <!ENTITY a "^" > ]> <bomb>$</bomb>'
len = 5120 # 5k per entity
template.sub!(/\^/, "B" * len)
# 10k is OK
entities = '&a;' * 2 # 5k entity * 2 = 10k
xmldoc = REXML::Document.new(template.sub(/\$/, entities))
assert_equal(len * 2, xmldoc.root.text.bytesize)
# above 10k explodes
entities = '&a;' * 3 # 5k entity * 2 = 15k
xmldoc = REXML::Document.new(template.sub(/\$/, entities))
assert_raises(RuntimeError) do
xmldoc.root.text
end end
end
def test_raw def test_entity_string_limit
source = '<!DOCTYPE foo [ template = '<!DOCTYPE bomb [ <!ENTITY a "^" > ]> <bomb>$</bomb>'
len = 5120 # 5k per entity
template.sub!(/\^/, "B" * len)
# 10k is OK
entities = '&a;' * 2 # 5k entity * 2 = 10k
xmldoc = REXML::Document.new(template.sub(/\$/, entities))
assert_equal(len * 2, xmldoc.root.text.bytesize)
# above 10k explodes
entities = '&a;' * 3 # 5k entity * 2 = 15k
xmldoc = REXML::Document.new(template.sub(/\$/, entities))
assert_raises(RuntimeError) do
xmldoc.root.text
end
end
def test_raw
source = '<!DOCTYPE foo [
<!ENTITY ent "replace"> <!ENTITY ent "replace">
]><a>replace &ent;</a>' ]><a>replace &ent;</a>'
doc = REXML::Document.new( source, {:raw=>:all}) doc = REXML::Document.new( source, {:raw=>:all})
assert_equal('replace &ent;', doc.root.get_text.to_s) assert_equal('replace &ent;', doc.root.get_text.to_s)
assert_equal(source, doc.to_s) assert_equal(source, doc.to_s)
end end
def test_lazy_evaluation def test_lazy_evaluation
source = '<!DOCTYPE foo [ source = '<!DOCTYPE foo [
<!ENTITY ent "replace"> <!ENTITY ent "replace">
]><a>replace &ent;</a>' ]><a>replace &ent;</a>'
doc = REXML::Document.new( source ) doc = REXML::Document.new( source )
assert_equal(source, doc.to_s) assert_equal(source, doc.to_s)
assert_equal("replace replace", doc.root.text) assert_equal("replace replace", doc.root.text)
assert_equal(source, doc.to_s) assert_equal(source, doc.to_s)
end end
# Contributed (not only test, but bug fix!!) by Kouhei Sutou # Contributed (not only test, but bug fix!!) by Kouhei Sutou
def test_entity_replacement def test_entity_replacement
source = %q{<!DOCTYPE foo [ source = %q{<!DOCTYPE foo [
<!ENTITY % YN '"Yes"'> <!ENTITY % YN '"Yes"'>
<!ENTITY WhatHeSaid "He said %YN;">]> <!ENTITY WhatHeSaid "He said %YN;">]>
<a>&WhatHeSaid;</a>} <a>&WhatHeSaid;</a>}
d = REXML::Document.new( source ) d = REXML::Document.new( source )
dt = d.doctype dt = d.doctype
assert_equal( '"Yes"', dt.entities[ "YN" ].value ) assert_equal( '"Yes"', dt.entities[ "YN" ].value )
assert_equal( 'He said "Yes"', dt.entities[ "WhatHeSaid" ].value ) assert_equal( 'He said "Yes"', dt.entities[ "WhatHeSaid" ].value )
assert_equal( 'He said "Yes"', d.elements[1].text ) assert_equal( 'He said "Yes"', d.elements[1].text )
end end
# More unit tests from Kouhei. I looove users who give me unit tests. # More unit tests from Kouhei. I looove users who give me unit tests.
def test_entity_insertions def test_entity_insertions
assert_equal("&amp;", REXML::Text.new("&amp;", false, nil, true).to_s) assert_equal("&amp;", REXML::Text.new("&amp;", false, nil, true).to_s)
#assert_equal("&", REXML::Text.new("&amp;", false, false).to_s) #assert_equal("&", REXML::Text.new("&amp;", false, false).to_s)
end end
def test_single_pass_unnormalization # ticket 123 def test_single_pass_unnormalization # ticket 123
assert_equal '&amp;&', REXML::Text::unnormalize('&#38;amp;&amp;') assert_equal '&amp;&', REXML::Text::unnormalize('&#38;amp;&amp;')
end end
def test_entity_filter def test_entity_filter
document = REXML::Document.new(<<-XML) document = REXML::Document.new(<<-XML)
<!DOCTYPE root [ <!DOCTYPE root [
<!ENTITY copy "(c)"> <!ENTITY copy "(c)">
<!ENTITY release-year "2013"> <!ENTITY release-year "2013">
]> ]>
<root/> <root/>
XML XML
respect_whitespace = false respect_whitespace = false
parent = document.root parent = document.root
raw = false raw = false
entity_filter = ["copy"] entity_filter = ["copy"]
assert_equal("(c) &release-year;", assert_equal("(c) &release-year;",
REXML::Text.new("(c) 2013", REXML::Text.new("(c) 2013",
respect_whitespace, respect_whitespace,
parent, parent,
raw, raw,
entity_filter).to_s) entity_filter).to_s)
end
end end
end end
end

View file

@ -3,222 +3,222 @@ require "test/unit/testcase"
require "rexml/document" require "rexml/document"
module REXMLTests module REXMLTests
class FunctionsTester < Test::Unit::TestCase class FunctionsTester < Test::Unit::TestCase
include REXML include REXML
def test_functions def test_functions
# trivial text() test # trivial text() test
# confuse-a-function # confuse-a-function
source = "<a>more <b id='1'/><b id='2'>dumb</b><b id='3'/><c/> text</a>" source = "<a>more <b id='1'/><b id='2'>dumb</b><b id='3'/><c/> text</a>"
doc = Document.new source doc = Document.new source
res = "" res = ""
XPath::each(doc.root, "text()") {|val| res << val.to_s} XPath::each(doc.root, "text()") {|val| res << val.to_s}
assert_equal "more text", res assert_equal "more text", res
res = XPath::first(doc.root, "b[last()]") res = XPath::first(doc.root, "b[last()]")
assert_equal '3', res.attributes['id'] assert_equal '3', res.attributes['id']
res = XPath::first(doc.root, "b[position()=2]") res = XPath::first(doc.root, "b[position()=2]")
assert_equal '2', res.attributes['id'] assert_equal '2', res.attributes['id']
res = XPath::first(doc.root, "*[name()='c']") res = XPath::first(doc.root, "*[name()='c']")
assert_equal "c", res.name assert_equal "c", res.name
end end
# Contributed by Mike Stok # Contributed by Mike Stok
def test_starts_with def test_starts_with
source = <<-EOF source = <<-EOF
<foo> <foo>
<a href="mailto:a@b.c">a@b.c</a> <a href="mailto:a@b.c">a@b.c</a>
<a href="http://www.foo.com">http://www.foo.com</a> <a href="http://www.foo.com">http://www.foo.com</a>
</foo> </foo>
EOF EOF
doc = Document.new source doc = Document.new source
mailtos = doc.elements.to_a("//a[starts-with(@href, 'mailto:')]") mailtos = doc.elements.to_a("//a[starts-with(@href, 'mailto:')]")
assert_equal 1, mailtos.size assert_equal 1, mailtos.size
assert_equal "mailto:a@b.c", mailtos[0].attributes['href'] assert_equal "mailto:a@b.c", mailtos[0].attributes['href']
ailtos = doc.elements.to_a("//a[starts-with(@href, 'ailto:')]") ailtos = doc.elements.to_a("//a[starts-with(@href, 'ailto:')]")
assert_equal 0, ailtos.size assert_equal 0, ailtos.size
end end
def test_string_length def test_string_length
doc = Document.new <<-EOF doc = Document.new <<-EOF
<AAA> <AAA>
<Q/> <Q/>
<SSSS/> <SSSS/>
<BB/> <BB/>
<CCC/> <CCC/>
<DDDDDDDD/> <DDDDDDDD/>
<EEEE/> <EEEE/>
</AAA> </AAA>
EOF EOF
assert doc, "create doc" assert doc, "create doc"
set = doc.elements.to_a("//*[string-length(name()) = 3]") set = doc.elements.to_a("//*[string-length(name()) = 3]")
assert_equal 2, set.size, "nodes with names length = 3" assert_equal 2, set.size, "nodes with names length = 3"
set = doc.elements.to_a("//*[string-length(name()) < 3]") set = doc.elements.to_a("//*[string-length(name()) < 3]")
assert_equal 2, set.size, "nodes with names length < 3" assert_equal 2, set.size, "nodes with names length < 3"
set = doc.elements.to_a("//*[string-length(name()) > 3]") set = doc.elements.to_a("//*[string-length(name()) > 3]")
assert_equal 3, set.size, "nodes with names length > 3" assert_equal 3, set.size, "nodes with names length > 3"
end end
# Test provided by Mike Stok # Test provided by Mike Stok
def test_contains def test_contains
source = <<-EOF source = <<-EOF
<foo> <foo>
<a href="mailto:a@b.c">a@b.c</a> <a href="mailto:a@b.c">a@b.c</a>
<a href="http://www.foo.com">http://www.foo.com</a> <a href="http://www.foo.com">http://www.foo.com</a>
</foo> </foo>
EOF EOF
doc = Document.new source doc = Document.new source
[['o', 2], ['foo', 1], ['bar', 0]].each { |test| [['o', 2], ['foo', 1], ['bar', 0]].each { |test|
search, expected = test search, expected = test
set = doc.elements.to_a("//a[contains(@href, '#{search}')]") set = doc.elements.to_a("//a[contains(@href, '#{search}')]")
assert_equal expected, set.size assert_equal expected, set.size
} }
end end
# Mike Stok and Sean Russell # Mike Stok and Sean Russell
def test_substring def test_substring
# examples from http://www.w3.org/TR/xpath#function-substring # examples from http://www.w3.org/TR/xpath#function-substring
doc = Document.new('<test string="12345" />') doc = Document.new('<test string="12345" />')
#puts XPath.first(d, 'node()[0 + 1]') #puts XPath.first(d, 'node()[0 + 1]')
#d = Document.new("<a b='1'/>") #d = Document.new("<a b='1'/>")
#puts XPath.first(d, 'a[0 mod 0]') #puts XPath.first(d, 'a[0 mod 0]')
[ [1.5, 2.6, '234'], [ [1.5, 2.6, '234'],
[0, 3, '12'], [0, 3, '12'],
[0, '0 div 0', ''], [0, '0 div 0', ''],
[1, '0 div 0', ''], [1, '0 div 0', ''],
['-42', '1 div 0', '12345'], ['-42', '1 div 0', '12345'],
['-1 div 0', '1 div 0', ''] ['-1 div 0', '1 div 0', '']
].each { |start, length, expected| ].each { |start, length, expected|
set = doc.elements.to_a("//test[substring(@string, #{start}, #{length}) = '#{expected}']") set = doc.elements.to_a("//test[substring(@string, #{start}, #{length}) = '#{expected}']")
assert_equal 1, set.size, "#{start}, #{length}, '#{expected}'" assert_equal 1, set.size, "#{start}, #{length}, '#{expected}'"
} }
end end
def test_substring_angrez def test_substring_angrez
testString = REXML::Functions::substring_after("helloworld","hello") testString = REXML::Functions::substring_after("helloworld","hello")
assert_equal( 'world', testString ) assert_equal( 'world', testString )
end end
def test_translate def test_translate
source = <<-EOF source = <<-EOF
<doc> <doc>
<case name='w3c one' result='BAr' /> <!-- w3c --> <case name='w3c one' result='BAr' /> <!-- w3c -->
<case name='w3c two' result='AAA' /> <!-- w3c --> <case name='w3c two' result='AAA' /> <!-- w3c -->
<case name='alchemy' result="gold" /> <!-- mike --> <case name='alchemy' result="gold" /> <!-- mike -->
<case name='vbxml one' result='A Space Odyssey' /> <case name='vbxml one' result='A Space Odyssey' />
<case name='vbxml two' result='AbCdEf' /> <case name='vbxml two' result='AbCdEf' />
</doc> </doc>
EOF EOF
doc = Document.new(source) doc = Document.new(source)
[ ['bar', 'abc', 'ABC', 'w3c one'], [ ['bar', 'abc', 'ABC', 'w3c one'],
['--aaa--','abc-','ABC', 'w3c two'], ['--aaa--','abc-','ABC', 'w3c two'],
['lead', 'dear language', 'doll groover', 'alchemy'], ['lead', 'dear language', 'doll groover', 'alchemy'],
['A Space Odissei', 'i', 'y', 'vbxml one'], ['A Space Odissei', 'i', 'y', 'vbxml one'],
['abcdefg', 'aceg', 'ACE', 'vbxml two'], ['abcdefg', 'aceg', 'ACE', 'vbxml two'],
].each { |arg1, arg2, arg3, name| ].each { |arg1, arg2, arg3, name|
translate = "translate('#{arg1}', '#{arg2}', '#{arg3}')" translate = "translate('#{arg1}', '#{arg2}', '#{arg3}')"
set = doc.elements.to_a("//case[@result = #{translate}]") set = doc.elements.to_a("//case[@result = #{translate}]")
assert_equal 1, set.size, translate assert_equal 1, set.size, translate
assert_equal name, set[0].attributes['name'] assert_equal name, set[0].attributes['name']
} }
end end
def test_name def test_name
d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>")
assert_equal 1, d.root.elements.to_a('*[name() = "b"]').size assert_equal 1, d.root.elements.to_a('*[name() = "b"]').size
assert_equal 1, d.elements.to_a('//*[name() = "x:b"]').size assert_equal 1, d.elements.to_a('//*[name() = "x:b"]').size
end end
def test_local_name def test_local_name
d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>") d = REXML::Document.new("<a xmlns:x='foo'><b/><x:b/></a>")
assert_equal 2, d.root.elements.to_a('*[local_name() = "b"]').size assert_equal 2, d.root.elements.to_a('*[local_name() = "b"]').size
assert_equal 2, d.elements.to_a('//*[local_name() = "b"]').size assert_equal 2, d.elements.to_a('//*[local_name() = "b"]').size
end end
def test_substring2 def test_substring2
doc = Document.new('<test string="12345" />') doc = Document.new('<test string="12345" />')
assert_equal(1,doc.elements.to_a("//test[substring(@string,2)='2345']").size) assert_equal(1,doc.elements.to_a("//test[substring(@string,2)='2345']").size)
end end
# Submitted by Kouhei # Submitted by Kouhei
def test_floor_ceiling_round def test_floor_ceiling_round
source = "<a><b id='1'/><b id='2'/><b id='3'/></a>" source = "<a><b id='1'/><b id='2'/><b id='3'/></a>"
doc = REXML::Document.new(source) doc = REXML::Document.new(source)
id_1 = doc.elements["/a/b[@id='1']"] id_1 = doc.elements["/a/b[@id='1']"]
id_2 = doc.elements["/a/b[@id='2']"] id_2 = doc.elements["/a/b[@id='2']"]
id_3 = doc.elements["/a/b[@id='3']"] id_3 = doc.elements["/a/b[@id='3']"]
good = { good = {
"floor" => [[], [id_1], [id_2], [id_3]], "floor" => [[], [id_1], [id_2], [id_3]],
"ceiling" => [[id_1], [id_2], [id_3], []], "ceiling" => [[id_1], [id_2], [id_3], []],
"round" => [[id_1], [id_2], [id_3], []] "round" => [[id_1], [id_2], [id_3], []]
} }
good.each do |key, value| good.each do |key, value|
(0..3).each do |i| (0..3).each do |i|
xpath = "//b[number(@id) = #{key}(#{i+0.5})]" xpath = "//b[number(@id) = #{key}(#{i+0.5})]"
assert_equal(value[i], REXML::XPath.match(doc, xpath)) assert_equal(value[i], REXML::XPath.match(doc, xpath))
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))
end
end end
end end
good["round"] = [[], [id_1], [id_2], [id_3]] # Submitted by Kou
good.each do |key, value| def test_lang
(0..3).each do |i| d = Document.new(<<-XML)
xpath = "//b[number(@id) = #{key}(#{i+0.4})]" <a xml:lang="en">
assert_equal(value[i], REXML::XPath.match(doc, xpath)) <b xml:lang="ja">
end <c xml:lang="fr"/>
<d/>
<e xml:lang="ja-JP"/>
<f xml:lang="en-US"/>
</b>
</a>
XML
assert_equal(1, d.elements.to_a("//*[lang('fr')]").size)
assert_equal(3, d.elements.to_a("//*[lang('ja')]").size)
assert_equal(2, d.elements.to_a("//*[lang('en')]").size)
assert_equal(1, d.elements.to_a("//*[lang('en-us')]").size)
d = Document.new(<<-XML)
<root>
<para xml:lang="en"/>
<div xml:lang="en"><para/></div>
<para xml:lang="EN"/>
<para xml:lang="en-us"/>
</root>
XML
assert_equal(5, d.elements.to_a("//*[lang('en')]").size)
end
def test_ticket_60
document = REXML::Document.new("<a><b>A</b><b>1</b></a>")
assert_equal( "A", REXML::XPath.first(document, '//b[.="A"]').text )
assert_equal( "1", REXML::XPath.first(document, '//b[.="1"]').text )
end
def test_normalize_space
source = "<a><!--COMMENT A--><b><!-- COMMENT A --></b></a>"
doc = REXML::Document.new(source)
predicate = "string(.)=normalize_space('\nCOMMENT \n A \n\n ')"
m = REXML::XPath.match(doc, "//comment()[#{predicate}]")
assert_equal( [REXML::Comment.new("COMMENT A")], m )
end end
end end
# Submitted by Kou
def test_lang
d = Document.new(<<-XML)
<a xml:lang="en">
<b xml:lang="ja">
<c xml:lang="fr"/>
<d/>
<e xml:lang="ja-JP"/>
<f xml:lang="en-US"/>
</b>
</a>
XML
assert_equal(1, d.elements.to_a("//*[lang('fr')]").size)
assert_equal(3, d.elements.to_a("//*[lang('ja')]").size)
assert_equal(2, d.elements.to_a("//*[lang('en')]").size)
assert_equal(1, d.elements.to_a("//*[lang('en-us')]").size)
d = Document.new(<<-XML)
<root>
<para xml:lang="en"/>
<div xml:lang="en"><para/></div>
<para xml:lang="EN"/>
<para xml:lang="en-us"/>
</root>
XML
assert_equal(5, d.elements.to_a("//*[lang('en')]").size)
end
def test_ticket_60
document = REXML::Document.new("<a><b>A</b><b>1</b></a>")
assert_equal( "A", REXML::XPath.first(document, '//b[.="A"]').text )
assert_equal( "1", REXML::XPath.first(document, '//b[.="1"]').text )
end
def test_normalize_space
source = "<a><!--COMMENT A--><b><!-- COMMENT A --></b></a>"
doc = REXML::Document.new(source)
predicate = "string(.)=normalize_space('\nCOMMENT \n A \n\n ')"
m = REXML::XPath.match(doc, "//comment()[#{predicate}]")
assert_equal( [REXML::Comment.new("COMMENT A")], m )
end
end
end end

View file

@ -3,32 +3,32 @@ require 'test/unit'
require 'rexml/functions' require 'rexml/functions'
module REXMLTests module REXMLTests
class TC_Rexml_Functions_Number < Test::Unit::TestCase class TC_Rexml_Functions_Number < Test::Unit::TestCase
def test_functions_number_int def test_functions_number_int
telem = REXML::Element.new("elem") telem = REXML::Element.new("elem")
telem.text="9" telem.text="9"
assert_equal(9, REXML::Functions::number(telem)) 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 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 end

View file

@ -7,122 +7,122 @@ require "rexml/xpath"
# ryan.a.cox@gmail.com # ryan.a.cox@gmail.com
module REXMLTests module REXMLTests
class JaxenTester < Test::Unit::TestCase class JaxenTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML include REXML
def test_axis ; test("axis") ; end def test_axis ; test("axis") ; end
def test_basic ; test("basic") ; end def test_basic ; test("basic") ; end
def test_basicupdate ; test("basicupdate") ; end def test_basicupdate ; test("basicupdate") ; end
def test_contents ; test("contents") ; end def test_contents ; test("contents") ; end
def test_defaultNamespace ; test("defaultNamespace") ; end def test_defaultNamespace ; test("defaultNamespace") ; end
def test_fibo ; test("fibo") ; end def test_fibo ; test("fibo") ; end
def test_id ; test("id") ; end def test_id ; test("id") ; end
def test_jaxen24 ; test("jaxen24") ; end def test_jaxen24 ; test("jaxen24") ; end
def test_lang ; test("lang") ; end def test_lang ; test("lang") ; end
def test_message ; test("message") ; end def test_message ; test("message") ; end
def test_moreover ; test("moreover") ; end def test_moreover ; test("moreover") ; end
def test_much_ado ; test("much_ado") ; end def test_much_ado ; test("much_ado") ; end
def test_namespaces ; test("namespaces") ; end def test_namespaces ; test("namespaces") ; end
def test_nitf ; test("nitf") ; end def test_nitf ; test("nitf") ; end
def test_numbers ; test("numbers") ; end def test_numbers ; test("numbers") ; end
def test_pi ; test("pi") ; end def test_pi ; test("pi") ; end
def test_pi2 ; test("pi2") ; end def test_pi2 ; test("pi2") ; end
def test_simple ; test("simple") ; end def test_simple ; test("simple") ; end
def test_testNamespaces ; test("testNamespaces") ; end def test_testNamespaces ; test("testNamespaces") ; end
def test_text ; test("text") ; end def test_text ; test("text") ; end
def test_underscore ; test("underscore") ; end def test_underscore ; test("underscore") ; end
def test_web ; test("web") ; end def test_web ; test("web") ; end
def test_web2 ; test("web2") ; end def test_web2 ; test("web2") ; end
private private
def test( fname ) def test( fname )
# Dir.entries( xml_dir ).each { |fname| # Dir.entries( xml_dir ).each { |fname|
# if fname =~ /\.xml$/ # if fname =~ /\.xml$/
file = File.new(fixture_path(fname+".xml")) file = File.new(fixture_path(fname+".xml"))
doc = Document.new( file ) doc = Document.new( file )
XPath.each( doc, "/tests/document" ) {|e| handleDocument(e)} XPath.each( doc, "/tests/document" ) {|e| handleDocument(e)}
# end # 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 ) }
end 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 # processes a tests/document/context node
def handleValueOf(ctx,variables, namespaces, valueOfElement) def handleContext( testDoc, ctxElement)
expected = valueOfElement.text testCtx = XPath.match( testDoc, ctxElement.attributes["select"] )[0]
got = XPath.match( ctx, valueOfElement.attributes["select"], namespaces, variables )[0] namespaces = {}
assert_true( (got.nil? && expected.nil?) || !got.nil? ) if testCtx.class == Element
case got.class testCtx.prefixes.each { |pre| handleNamespace( testCtx, pre, namespaces ) }
when Element end
assert_equal( got.class, Element ) variables = {}
when Attribute, Text, Comment, TrueClass, FalseClass XPath.each( ctxElement, "@*[namespace-uri() = 'http://jaxen.org/test-harness/var']") { |attrib| handleVariable(testCtx, variables, attrib) }
assert_equal( expected, got.to_s ) XPath.each( ctxElement, "valueOf") { |e| handleValueOf(testCtx, variables, namespaces, e) }
when Instruction XPath.each( ctxElement, "test[not(@exception) or (@exception != 'true') ]") { |e| handleNominalTest(testCtx,variables, namespaces, e) }
assert_equal( expected, got.content ) XPath.each( ctxElement, "test[@exception = 'true']") { |e| handleExceptionalTest(testCtx,variables, namespaces, e) }
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
# 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
# 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
# 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 variable definition in a namespace like <test var:foo="bar">
def handleVariable( ctx, variables, attrib )
puts "--- Found attribute: #{attrib.name}"
variables[attrib.name] = attrib.value
end
# processes a namespace definition like <test xmlns:foo="fiz:bang:bam">
def handleNamespace( ctx, prefix, namespaces )
puts "--- Found namespace: #{prefix}"
namespaces[prefix] = ctx.namespaces[prefix]
end
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?
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 node
def handleDocument(docElement)
puts "- Processing document: #{docElement.attributes['url']}"
testFile = File.new( docElement.attributes["url"] )
testDoc = Document.new testFile
XPath.each( docElement, "context") { |e| handleContext(testDoc, e) }
end
# processes a variable definition in a namespace like <test var:foo="bar">
def handleVariable( ctx, variables, attrib )
puts "--- Found attribute: #{attrib.name}"
variables[attrib.name] = attrib.value
end
# processes a namespace definition like <test xmlns:foo="fiz:bang:bam">
def handleNamespace( ctx, prefix, namespaces )
puts "--- Found namespace: #{prefix}"
namespaces[prefix] = ctx.namespaces[prefix]
end
end
end end

View file

@ -3,104 +3,104 @@ require "rexml/light/node"
require "rexml/parsers/lightparser" require "rexml/parsers/lightparser"
module REXMLTests module REXMLTests
class LightTester < Test::Unit::TestCase class LightTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML::Light include REXML::Light
def test_parse_large def test_parse_large
xml_string = fixture_path("documentation.xml") xml_string = fixture_path("documentation.xml")
parser = REXML::Parsers::LightParser.new(xml_string) parser = REXML::Parsers::LightParser.new(xml_string)
tag, content = parser.parse tag, content = parser.parse
assert_equal([:document, :text], [tag, content.first]) assert_equal([:document, :text], [tag, content.first])
end end
# FIXME INCOMPLETE # FIXME INCOMPLETE
# This is because the light API is not yet ready to be used to produce # This is because the light API is not yet ready to be used to produce
# trees. # trees.
=begin =begin
def test_add_element def test_add_element
doc = Node.new doc = Node.new
foo = doc.add_element( 'foo' ) foo = doc.add_element( 'foo' )
assert_equal( "foo", foo.name ) assert_equal( "foo", foo.name )
end end
def test_add_attribute def test_add_attribute
foo = Node.new( "a" ) foo = Node.new( "a" )
foo["attr"] = "bar" foo["attr"] = "bar"
assert_equal( "bar", foo["attr"] ) assert_equal( "bar", foo["attr"] )
end end
def test_write_document def test_write_document
r = make_small_document r = make_small_document
assert_equal( "<a><b/><c/></a>", r.to_s ) assert_equal( "<a><b/><c/></a>", r.to_s )
end end
def test_add_attribute_under_namespace def test_add_attribute_under_namespace
foo = Node.new("a") foo = Node.new("a")
foo["attr", "a"] = "1" foo["attr", "a"] = "1"
foo["attr", "b"] = "2" foo["attr", "b"] = "2"
foo["attr"] = "3" foo["attr"] = "3"
assert_equal( '1', foo['attr', 'a'] ) assert_equal( '1', foo['attr', 'a'] )
assert_equal( '2', foo['attr', 'b'] ) assert_equal( '2', foo['attr', 'b'] )
assert_equal( '3', foo['attr'] ) assert_equal( '3', foo['attr'] )
end end
def test_change_namespace_of_element def test_change_namespace_of_element
foo = Node.new foo = Node.new
assert_equal( '', foo.namespace ) assert_equal( '', foo.namespace )
foo.namespace = 'a' foo.namespace = 'a'
assert_equal( 'a', foo.namespace ) assert_equal( 'a', foo.namespace )
end end
def test_access_child_elements def test_access_child_elements
foo = make_small_document foo = make_small_document
assert_equal( 1, foo.size ) assert_equal( 1, foo.size )
a = foo[0] a = foo[0]
assert_equal( 2, a.size ) assert_equal( 2, a.size )
assert_equal( 'b', a[0].name ) assert_equal( 'b', a[0].name )
assert_equal( 'c', a[1].name ) assert_equal( 'c', a[1].name )
end end
def test_itterate_over_children def test_itterate_over_children
foo = make_small_document foo = make_small_document
ctr = 0 ctr = 0
foo[0].each { ctr += 1 } foo[0].each { ctr += 1 }
assert_equal( 2, ctr ) assert_equal( 2, ctr )
end end
def test_add_text def test_add_text
foo = Node.new( "a" ) foo = Node.new( "a" )
foo.add_text( "Sean" ) foo.add_text( "Sean" )
sean = foo[0] sean = foo[0]
assert( sean.node_type == :text ) assert( sean.node_type == :text )
end end
def test_add_instruction def test_add_instruction
foo = Node.new( "a" ) foo = Node.new( "a" )
foo.add_instruction( "target", "value" ) foo.add_instruction( "target", "value" )
assert( foo[0].node_type == :processing_instruction ) assert( foo[0].node_type == :processing_instruction )
end end
def test_add_comment def test_add_comment
foo = Node.new( "a" ) foo = Node.new( "a" )
foo.add_comment( "target", "value" ) foo.add_comment( "target", "value" )
assert( foo[0].node_type == :comment ) assert( foo[0].node_type == :comment )
end end
def test_get_root def test_get_root
foo = Node.new( 'a' ) foo = Node.new( 'a' )
10.times { foo = foo.add_element('b') } 10.times { foo = foo.add_element('b') }
assert_equals( 'b', foo.name ) assert_equals( 'b', foo.name )
assert_equals( 'a', foo.root.name ) assert_equals( 'a', foo.root.name )
end end
def make_small_document def make_small_document
r = Node.new r = Node.new
a = r.add_element( "a" ) a = r.add_element( "a" )
a.add_element( 'b' ) a.add_element( 'b' )
a.add_element( 'c' ) a.add_element( 'c' )
r r
end end
=end =end
end end
end end

View file

@ -2,13 +2,13 @@ require_relative 'rexml_test_utils'
require 'rexml/parsers/lightparser' require 'rexml/parsers/lightparser'
module REXMLTests module REXMLTests
class LightParserTester < Test::Unit::TestCase class LightParserTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML include REXML
def test_parsing def test_parsing
f = File.new(fixture_path("documentation.xml")) f = File.new(fixture_path("documentation.xml"))
parser = REXML::Parsers::LightParser.new( f ) parser = REXML::Parsers::LightParser.new( f )
parser.parse parser.parse
end
end end
end end
end

View file

@ -6,126 +6,126 @@ require 'rexml/document'
require 'rexml/streamlistener' require 'rexml/streamlistener'
module REXMLTests module REXMLTests
class BaseTester < Test::Unit::TestCase class BaseTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
def test_empty def test_empty
return unless defined? @listener return unless defined? @listener
# Empty. # Empty.
t1 = %Q{<string></string>} t1 = %Q{<string></string>}
assert_equal( "", @listener.parse( t1 ), assert_equal( "", @listener.parse( t1 ),
"Empty" ) "Empty" )
end
def test_space
return unless defined? @listener
# Space.
t2 = %Q{<string> </string>}
assert_equal( " ", @listener.parse( t2 ),
"Space" )
end
def test_whitespace
return unless defined? @listener
# Whitespaces.
t3 = %Q{<string>RE\n \t \n \t XML</string>}
assert_equal( "RE\n \t \n \t XML", @listener.parse( t3 ),
"Whitespaces" )
end
def test_leading_trailing_whitespace
return unless defined? @listener
# Leading and trailing whitespaces.
t4 = %Q{<string> REXML </string>}
assert_equal( " REXML ", @listener.parse( t4 ),
"Leading and trailing whitespaces" )
end
def test_entity_reference
return unless defined? @listener
# Entity reference.
t5 = %Q{<string>&lt;&gt;&amp;lt;&amp;gt;</string>}
assert_equal( "<>&lt;&gt;", @listener.parse( t5 ),
"Entity reference" )
end
def test_character_reference
return unless defined? @listener
# Character reference.
t6 = %Q{<string>&#xd;</string>}
assert_equal( "\r", @listener.parse( t6 ),
"Character reference." )
end
def test_cr
return unless defined? @listener
# CR.
t7 = %Q{<string> \r\n \r \n </string>}
assert_equal( " \n \n \n ".unpack("C*").inspect,
@listener.parse( t7 ).unpack("C*").inspect, "CR" )
end
# 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 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
def test_accents def test_space
source = %[<?xml version="1.0" encoding="ISO-8859-1"?> return unless defined? @listener
# Space.
t2 = %Q{<string> </string>}
assert_equal( " ", @listener.parse( t2 ),
"Space" )
end
def test_whitespace
return unless defined? @listener
# Whitespaces.
t3 = %Q{<string>RE\n \t \n \t XML</string>}
assert_equal( "RE\n \t \n \t XML", @listener.parse( t3 ),
"Whitespaces" )
end
def test_leading_trailing_whitespace
return unless defined? @listener
# Leading and trailing whitespaces.
t4 = %Q{<string> REXML </string>}
assert_equal( " REXML ", @listener.parse( t4 ),
"Leading and trailing whitespaces" )
end
def test_entity_reference
return unless defined? @listener
# Entity reference.
t5 = %Q{<string>&lt;&gt;&amp;lt;&amp;gt;</string>}
assert_equal( "<>&lt;&gt;", @listener.parse( t5 ),
"Entity reference" )
end
def test_character_reference
return unless defined? @listener
# Character reference.
t6 = %Q{<string>&#xd;</string>}
assert_equal( "\r", @listener.parse( t6 ),
"Character reference." )
end
def test_cr
return unless defined? @listener
# CR.
t7 = %Q{<string> \r\n \r \n </string>}
assert_equal( " \n \n \n ".unpack("C*").inspect,
@listener.parse( t7 ).unpack("C*").inspect, "CR" )
end
# 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
def test_accents
source = %[<?xml version="1.0" encoding="ISO-8859-1"?>
<g> <g>
<f a="\xE9" /> <f a="\xE9" />
</g>] </g>]
doc = REXML::Document.new( source ) doc = REXML::Document.new( source )
a = doc.elements['/g/f'].attribute('a') a = doc.elements['/g/f'].attribute('a')
if a.value.respond_to? :force_encoding if a.value.respond_to? :force_encoding
a.value.force_encoding('binary') a.value.force_encoding('binary')
end end
assert_equal( "\xC3\xA9", a.value) assert_equal( "\xC3\xA9", a.value)
doc = REXML::Document.parse_stream( doc = REXML::Document.parse_stream(
File::new(fixture_path("stream_accents.xml")), File::new(fixture_path("stream_accents.xml")),
AccentListener::new AccentListener::new
) )
end
end
class MyREXMLListener
include REXML::StreamListener
def initialize
@text = nil
end
def parse( stringOrReadable )
@text = ""
REXML::Document.parse_stream( stringOrReadable, self )
@text
end
def text( text )
@text << text
end
end
class REXMLTester < BaseTester
def setup
@listener = MyREXMLListener.new
end
def test_character_reference_2
t6 = %Q{<string>&#xd;</string>}
assert_equal( t6.strip, REXML::Document.new(t6).to_s )
end
end end
end end
class MyREXMLListener
include REXML::StreamListener
def initialize
@text = nil
end
def parse( stringOrReadable )
@text = ""
REXML::Document.parse_stream( stringOrReadable, self )
@text
end
def text( text )
@text << text
end
end
class REXMLTester < BaseTester
def setup
@listener = MyREXMLListener.new
end
def test_character_reference_2
t6 = %Q{<string>&#xd;</string>}
assert_equal( t6.strip, REXML::Document.new(t6).to_s )
end
end
end

View file

@ -2,8 +2,8 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class OrderTester < Test::Unit::TestCase class OrderTester < Test::Unit::TestCase
DOC = <<END DOC = <<END
<paper> <paper>
<title>Remove this element and figs order differently</title> <title>Remove this element and figs order differently</title>
<figure src="fig1"/> <figure src="fig1"/>
@ -17,23 +17,23 @@ class OrderTester < Test::Unit::TestCase
</paper> </paper>
END END
def initialize n def initialize n
@doc = REXML::Document.new(DOC) @doc = REXML::Document.new(DOC)
@figs = REXML::XPath.match(@doc,'//figure') @figs = REXML::XPath.match(@doc,'//figure')
@names = @figs.collect {|f| f.attributes['src']} @names = @figs.collect {|f| f.attributes['src']}
super super
end end
def test_fig1 def test_fig1
assert_equal 'fig1', @figs[0].attributes['src'] assert_equal 'fig1', @figs[0].attributes['src']
end end
def test_fig2 def test_fig2
assert_equal 'fig2', @figs[1].attributes['src'] assert_equal 'fig2', @figs[1].attributes['src']
end end
def test_fig3 def test_fig3
assert_equal 'fig3', @figs[2].attributes['src'] assert_equal 'fig3', @figs[2].attributes['src']
end end
def test_fig4 def test_fig4
assert_equal 'fig4', @figs[3].attributes['src'] assert_equal 'fig4', @figs[3].attributes['src']
end
end end
end end
end

View file

@ -3,38 +3,38 @@ require_relative "rexml_test_utils"
require "rexml/document" require "rexml/document"
module REXMLTests module REXMLTests
class TestNamespace < Test::Unit::TestCase class TestNamespace < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML include REXML
def setup def setup
@xsa_source = <<-EOL @xsa_source = <<-EOL
<?xml version="1.0"?> <?xml version="1.0"?>
<?xsl stylesheet="blah.xsl"?> <?xsl stylesheet="blah.xsl"?>
<!-- The first line tests the XMLDecl, the second tests PI. <!-- The first line tests the XMLDecl, the second tests PI.
The next line tests DocType. This line tests comments. --> The next line tests DocType. This line tests comments. -->
<!DOCTYPE xsa PUBLIC <!DOCTYPE xsa PUBLIC
"-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML" "-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML"
"http://www.garshol.priv.no/download/xsa/xsa.dtd"> "http://www.garshol.priv.no/download/xsa/xsa.dtd">
<xsa> <xsa>
<vendor id="blah"> <vendor id="blah">
<name>Lars Marius Garshol</name> <name>Lars Marius Garshol</name>
<email>larsga@garshol.priv.no</email> <email>larsga@garshol.priv.no</email>
<url>http://www.stud.ifi.uio.no/~lmariusg/</url> <url>http://www.stud.ifi.uio.no/~lmariusg/</url>
</vendor> </vendor>
</xsa> </xsa>
EOL EOL
end end
def test_xml_namespace def test_xml_namespace
xml = <<-XML xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xml="http://www.w3.org/XML/1998/namespace" /> <root xmlns:xml="http://www.w3.org/XML/1998/namespace" />
XML XML
document = Document.new(xml) document = Document.new(xml)
assert_equal("http://www.w3.org/XML/1998/namespace", assert_equal("http://www.w3.org/XML/1998/namespace",
document.root.namespace("xml")) document.root.namespace("xml"))
end
end end
end end
end

View file

@ -6,10 +6,10 @@ rescue LoadError
end end
module REXMLTests module REXMLTests
class OrderTester < Test::Unit::TestCase class OrderTester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
TESTDOC = <<END TESTDOC = <<END
<a> <a>
<b/> <b/>
<x id='1'/> <x id='1'/>
@ -21,87 +21,87 @@ class OrderTester < Test::Unit::TestCase
</a> </a>
END END
def setup def setup
@doc = REXML::Document.new(TESTDOC) @doc = REXML::Document.new(TESTDOC)
@items = REXML::XPath.match(@doc,'//x') @items = REXML::XPath.match(@doc,'//x')
end end
def test_first_element def test_first_element
assert_equal '1', @items[0].attributes['id'] assert_equal '1', @items[0].attributes['id']
end end
def test_second_element def test_second_element
assert_equal '2', @items[1].attributes['id'] assert_equal '2', @items[1].attributes['id']
end end
def test_third_element def test_third_element
assert_equal '3', @items[2].attributes['id'] assert_equal '3', @items[2].attributes['id']
end end
def test_order def test_order
d = REXML::Document.new( "<a><x id='1'/><x id='2'/><x id='3'/> d = REXML::Document.new( "<a><x id='1'/><x id='2'/><x id='3'/>
<x id='4'/><x id='5'/></a>" ) <x id='4'/><x id='5'/></a>" )
items = REXML::XPath.match( d, '//x' ) items = REXML::XPath.match( d, '//x' )
assert_equal( %w{1 2 3 4 5}, items.collect{|e| e.attributes['id']} ) assert_equal( %w{1 2 3 4 5}, items.collect{|e| e.attributes['id']} )
d = REXML::Document.new( "<a> d = REXML::Document.new( "<a>
<x><z><y id='1'/><y id='2'/></z><y id='3'/></x> <x><z><y id='1'/><y id='2'/></z><y id='3'/></x>
<x><y id='4'/></x></a>" ) <x><y id='4'/></x></a>" )
items = REXML::XPath.match( d, '//y' ) items = REXML::XPath.match( d, '//y' )
assert_equal( %w{1 2 3 4}, items.collect{|e| e.attributes['id']} ) assert_equal( %w{1 2 3 4}, items.collect{|e| e.attributes['id']} )
end end
# Provided by Tom Talbott # Provided by Tom Talbott
def test_more_ordering def test_more_ordering
doc = REXML::Document.new(Zlib::GzipReader.open(fixture_path('LostineRiver.kml.gz'), encoding: 'utf-8')) doc = REXML::Document.new(Zlib::GzipReader.open(fixture_path('LostineRiver.kml.gz'), encoding: 'utf-8'))
actual = [ actual = [
"Head south from Phinney Ave N", "Head south from Phinney Ave N",
"Turn left at N 36th St", "Turn left at N 36th St",
"Turn right at Fremont Ave N", "Turn right at Fremont Ave N",
"Continue on 4th Ave N", "Continue on 4th Ave N",
"Turn left at Westlake Ave N", "Turn left at Westlake Ave N",
"Bear right at 9th Ave N", "Bear right at 9th Ave N",
"Turn left at Mercer St", "Turn left at Mercer St",
"Take the I-5 ramp", "Take the I-5 ramp",
"Take the I-5 S 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 exit #164 to Bellevue/Spokane/4th Ave S.",
"Take the I-90 E ramp to Bellevue/Spokane", "Take the I-90 E ramp to Bellevue/Spokane",
"Take exit #137 to Wanapum Dam/Richland", "Take exit #137 to Wanapum Dam/Richland",
"Bear right at WA-26", "Bear right at WA-26",
"Bear right and head toward WA-243", "Bear right and head toward WA-243",
"Continue on WA-243", "Continue on WA-243",
"Bear right at WA-24", "Bear right at WA-24",
"Continue on WA-240", "Continue on WA-240",
"Turn right at WA-240 E", "Turn right at WA-240 E",
"Take the I-182 W ramp to Yakima (I-82)/Pendleton", "Take the I-182 W ramp to Yakima (I-82)/Pendleton",
"Take the I-82 E ramp to Umatilla/Pendleton", "Take the I-82 E ramp to Umatilla/Pendleton",
"Take the I-84 E ramp to Pendleton", "Take the I-84 E ramp to Pendleton",
"Take the OR-82 exit #261 to La Grande/Elgin", "Take the OR-82 exit #261 to La Grande/Elgin",
"Turn right at Island Ave", "Turn right at Island Ave",
"Continue on W 1st St", "Continue on W 1st St",
"Turn left at N McAlister Rd", "Turn left at N McAlister Rd",
"Bear right at OR-82", "Bear right at OR-82",
"Continue on Wallowa Lake Hwy", "Continue on Wallowa Lake Hwy",
"Continue on OR-82", "Continue on OR-82",
"Continue on Ruckman Ave", "Continue on Ruckman Ave",
"Continue on OR-82", "Continue on OR-82",
"Continue on S 8th Ave", "Continue on S 8th Ave",
"Turn right at Albany St", "Turn right at Albany St",
"Continue on OR-82", "Continue on OR-82",
"Continue on Wallowa Lake Hwy", "Continue on Wallowa Lake Hwy",
"Continue on N Madison St", "Continue on N Madison St",
"Bear left at W 1st St", "Bear left at W 1st St",
"Continue on Wallowa Lake Hwy", "Continue on Wallowa Lake Hwy",
"Continue on Water St", "Continue on Water St",
"Bear right at Lostine River Rd", "Bear right at Lostine River Rd",
"Bear right and head toward Lostine River Rd", "Bear right and head toward Lostine River Rd",
"Turn right at Lostine River Rd", "Turn right at Lostine River Rd",
"Continue on NF-8210", "Continue on NF-8210",
"Turn right and head toward NF-8210", "Turn right and head toward NF-8210",
"Turn right at NF-8210", "Turn right at NF-8210",
"", "",
"Route" "Route"
] ]
count = 0 count = 0
REXML::XPath.each( doc, "//Placemark") { |element| REXML::XPath.each( doc, "//Placemark") { |element|
n = element.elements["name"].text.squeeze(" ") n = element.elements["name"].text.squeeze(" ")
assert_equal( actual[count], n ) unless n =~ /Arrive at/ assert_equal( actual[count], n ) unless n =~ /Arrive at/
count += 1 count += 1
} }
end if defined?(Zlib::GzipReader) end if defined?(Zlib::GzipReader)
end end
end end

View file

@ -3,38 +3,38 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
# daz - for report by Dan Kohn in: # daz - for report by Dan Kohn in:
# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/156328 # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/156328
class XPathTesterDd < Test::Unit::TestCase class XPathTesterDd < Test::Unit::TestCase
include REXML include REXML
def setup def setup
@@docDd = Document.new(<<-EOS, :ignore_whitespace_nodes => :all) @@docDd = Document.new(<<-EOS, :ignore_whitespace_nodes => :all)
<a> <a>
<b x='ab01A'> <b x='ab01A'>
<c y='abc01A'>Success</c> <c y='abc01A'>Success</c>
</b> </b>
<b x='ab02A' y='ab02B'> <b x='ab02A' y='ab02B'>
<c>abc02C</c> <c>abc02C</c>
</b> </b>
</a> </a>
EOS 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
end end
assert_equal( 'Success', arr.join )
end
def test_Dd_preceding_sibling_all def test_Dd_preceding_sibling_children
arr = [] arr = []
XPath.each(@@docDd, "//b[@x='ab02A']/preceding-sibling::*") do |cell| XPath.each(@@docDd, "//b[@x='ab02A']/preceding-sibling::b/child::*") do |cell|
arr << cell.to_s arr << cell.texts.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
end
assert_equal( "<b x='ab01A'><c y='abc01A'>Success</c></b>", arr.join )
end end
assert_equal( "<b x='ab01A'><c y='abc01A'>Success</c></b>", arr.join )
end end
end end
end

View file

@ -3,100 +3,100 @@ require "test/unit/testcase"
require 'rexml/parsers/pullparser' require 'rexml/parsers/pullparser'
module REXMLTests module REXMLTests
class PullParserTester < Test::Unit::TestCase class PullParserTester < Test::Unit::TestCase
include REXML include REXML
def test_basics def test_basics
source = '<?xml version="1.0"?> source = '<?xml version="1.0"?>
<!DOCTYPE blah> <!DOCTYPE blah>
<a>foo &lt;<b attribute="value">bar</b> nooo</a>' <a>foo &lt;<b attribute="value">bar</b> nooo</a>'
parser = REXML::Parsers::PullParser.new(source) parser = REXML::Parsers::PullParser.new(source)
res = { :text=>0 } res = { :text=>0 }
until parser.empty? until parser.empty?
results = parser.pull results = parser.pull
res[ :xmldecl ] = true if results.xmldecl? res[ :xmldecl ] = true if results.xmldecl?
res[ :doctype ] = true if results.doctype? res[ :doctype ] = true if results.doctype?
res[ :a ] = true if results.start_element? and results[0] == 'a' res[ :a ] = true if results.start_element? and results[0] == 'a'
if results.start_element? and results[0] == 'b' if results.start_element? and results[0] == 'b'
res[ :b ] = true res[ :b ] = true
assert_equal 'value', results[1]['attribute'] assert_equal 'value', results[1]['attribute']
end
res[ :text ] += 1 if results.text?
end 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 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 def test_bad_document
source = "<a><b></a>" source = "<a><b></a>"
parser = REXML::Parsers::PullParser.new(source) parser = REXML::Parsers::PullParser.new(source)
assert_raise(ParseException, "Parsing should have failed") { assert_raise(ParseException, "Parsing should have failed") {
parser.pull while parser.has_next? parser.pull while parser.has_next?
} }
end end
def test_entity_replacement def test_entity_replacement
source = '<!DOCTYPE foo [ source = '<!DOCTYPE foo [
<!ENTITY la "1234"> <!ENTITY la "1234">
<!ENTITY lala "--&la;--"> <!ENTITY lala "--&la;--">
<!ENTITY lalal "&la;&la;"> <!ENTITY lalal "&la;&la;">
]><a><la>&la;</la><lala>&lala;</lala></a>' ]><a><la>&la;</la><lala>&lala;</lala></a>'
pp = REXML::Parsers::PullParser.new( source ) pp = REXML::Parsers::PullParser.new( source )
el_name = '' el_name = ''
while pp.has_next? while pp.has_next?
event = pp.pull event = pp.pull
case event.event_type case event.event_type
when :start_element when :start_element
el_name = event[0] el_name = event[0]
when :text when :text
case el_name case el_name
when 'la' when 'la'
assert_equal('1234', event[1]) assert_equal('1234', event[1])
when 'lala' when 'lala'
assert_equal('--1234--', event[1]) assert_equal('--1234--', event[1])
end
end end
end end
end end
end
def test_peek_unshift def test_peek_unshift
source = "<a><b/></a>" source = "<a><b/></a>"
REXML::Parsers::PullParser.new(source) REXML::Parsers::PullParser.new(source)
# FINISH ME! # FINISH ME!
end
def test_inspect
xml = '<a id="1"><b id="2">Hey</b></a>'
parser = Parsers::PullParser.new( xml )
while parser.has_next?
pull_event = parser.pull
if pull_event.start_element?
peek = parser.peek()
peek.inspect
end
end end
end
def test_peek def test_inspect
xml = '<a id="1"><b id="2">Hey</b></a>' xml = '<a id="1"><b id="2">Hey</b></a>'
parser = Parsers::PullParser.new( xml ) parser = Parsers::PullParser.new( xml )
names = %w{ a b } while parser.has_next?
while parser.has_next? pull_event = parser.pull
pull_event = parser.pull if pull_event.start_element?
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() peek = parser.peek()
assert_equal( :start_element, peek.event_type ) peek.inspect
assert_equal( names[0], peek[0] )
end end
end end
end end
assert_equal( 0, names.length )
def test_peek
xml = '<a id="1"><b id="2">Hey</b></a>'
parser = Parsers::PullParser.new( xml )
names = %w{ a b }
while parser.has_next?
pull_event = parser.pull
if pull_event.start_element?
assert_equal( :start_element, pull_event.event_type )
assert_equal( names.shift, pull_event[0] )
if names[0] == 'b'
peek = parser.peek()
assert_equal( :start_element, peek.event_type )
assert_equal( names[0], peek[0] )
end
end
end
assert_equal( 0, names.length )
end
end end
end end
end

View file

@ -2,15 +2,15 @@ require_relative 'rexml_test_utils'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class TestIssuezillaParsing < Test::Unit::TestCase class TestIssuezillaParsing < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
def test_rexml def test_rexml
doc = REXML::Document.new(File.new(fixture_path("ofbiz-issues-full-177.xml"))) doc = REXML::Document.new(File.new(fixture_path("ofbiz-issues-full-177.xml")))
ctr = 1 ctr = 1
doc.root.each_element('//issue') do |issue| doc.root.each_element('//issue') do |issue|
assert_equal( ctr, issue.elements['issue_id'].text.to_i ) assert_equal( ctr, issue.elements['issue_id'].text.to_i )
ctr += 1 ctr += 1
end
end end
end end
end end
end

View file

@ -4,277 +4,277 @@ require 'rexml/parsers/sax2parser'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class SAX2Tester < Test::Unit::TestCase class SAX2Tester < Test::Unit::TestCase
include REXMLTestUtils include REXMLTestUtils
include REXML include REXML
def test_characters def test_characters
d = Document.new( "<A>@blah@</A>" ) d = Document.new( "<A>@blah@</A>" )
txt = d.root.text txt = d.root.text
p = Parsers::SAX2Parser.new "<A>@blah@</A>" p = Parsers::SAX2Parser.new "<A>@blah@</A>"
p.listen(:characters) {|x| assert_equal txt, x} p.listen(:characters) {|x| assert_equal txt, x}
p.listen(:characters, ["A"]) {|x| assert_equal txt,x} p.listen(:characters, ["A"]) {|x| assert_equal txt,x}
p.parse p.parse
end end
def test_entity_replacement def test_entity_replacement
source = '<!DOCTYPE foo [ source = '<!DOCTYPE foo [
<!ENTITY la "1234"> <!ENTITY la "1234">
<!ENTITY lala "--&la;--"> <!ENTITY lala "--&la;--">
<!ENTITY lalal "&la;&la;"> <!ENTITY lalal "&la;&la;">
]><a><la>&la;</la><lala>&lala;</lala></a>' ]><a><la>&la;</la><lala>&lala;</lala></a>'
sax = Parsers::SAX2Parser.new( source ) sax = Parsers::SAX2Parser.new( source )
results = [] results = []
sax.listen(:characters) {|x| results << x } sax.listen(:characters) {|x| results << x }
sax.parse sax.parse
assert_equal 2, results.size assert_equal 2, results.size
assert_equal '1234', results[0] assert_equal '1234', results[0]
assert_equal '--1234--', results[1] assert_equal '--1234--', results[1]
end end
def test_sax2 def test_sax2
f = File.new(fixture_path("documentation.xml")) f = File.new(fixture_path("documentation.xml"))
parser = Parsers::SAX2Parser.new( f ) parser = Parsers::SAX2Parser.new( f )
# Listen to all events on the following elements # Listen to all events on the following elements
count = 0 count = 0
blok = proc { |uri,localname,qname,attributes| blok = proc { |uri,localname,qname,attributes|
assert %w{ bugs todo }.include?(localname), 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}" "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 count += 1
} }
start_document = 0 start_document = 0
end_document = 0 end_document = 0
parser.listen( :start_document ) { start_document += 1 } parser.listen( :start_document ) { start_document += 1 }
parser.listen( :end_document ) { end_document += 1 } parser.listen( :end_document ) { end_document += 1 }
parser.listen( :start_element, %w{ changelog bugs todo }, &blok ) parser.listen( :start_element, %w{ changelog bugs todo }, &blok )
# Listen to all events on the following elements. Synonymous with # Listen to all events on the following elements. Synonymous with
# listen( :start_element, %w{ ... } ) # listen( :start_element, %w{ ... } )
parser.listen( %w{ changelog bugs todo }, &blok ) parser.listen( %w{ changelog bugs todo }, &blok )
# Listen for all start element events # Listen for all start element events
parser.listen( :start_element ) { |uri,localname,qname,attributes| parser.listen( :start_element ) { |uri,localname,qname,attributes|
} }
listener = MySAX2Listener.new listener = MySAX2Listener.new
# Listen for all events # Listen for all events
parser.listen( listener ) parser.listen( listener )
# Listen for all events on the given elements. Does not include children # Listen for all events on the given elements. Does not include children
# events. Regular expressions work as well! # events. Regular expressions work as well!
parser.listen( %w{ /change/ bugs todo }, listener ) parser.listen( %w{ /change/ bugs todo }, listener )
# Test the deafening method # Test the deafening method
blok = proc { |uri,localname,qname,attributes| blok = proc { |uri,localname,qname,attributes|
assert_fail "This listener should have been deafened!" assert_fail "This listener should have been deafened!"
} }
parser.listen( %w{ changelog }, &blok ) parser.listen( %w{ changelog }, &blok )
parser.deafen( &blok ) parser.deafen( &blok )
tc = 0 tc = 0
parser.listen( :characters, %w{version} ) {|text| parser.listen( :characters, %w{version} ) {|text|
assert(text=~/@ANT_VERSION@/, "version was '#{text}'") assert(text=~/@ANT_VERSION@/, "version was '#{text}'")
tc += 1 tc += 1
} }
begin begin
parser.parse parser.parse
rescue => exception rescue => exception
if exception.kind_of? Test::Unit::AssertionFailedError if exception.kind_of? Test::Unit::AssertionFailedError
raise exception raise exception
end
puts $!
puts exception.backtrace
end end
puts $! assert_equal 2, count
puts exception.backtrace assert_equal 1, tc
end assert_equal 1, start_document
assert_equal 2, count assert_equal 1, end_document
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
def initialize
@name = @pub_sys = @long_name = @uri = nil
end end
def doctype(name, pub_sys, long_name, uri)
@name = name
@pub_sys = pub_sys # used by test_simple_doctype_listener
@long_name = long_name # submitted by Jeff Barczewski
@uri = uri class SimpleDoctypeListener
include REXML::SAX2Listener
attr_reader :name, :pub_sys, :long_name, :uri
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
end
end end
end
# test simple non-entity doctype in sax listener # test simple non-entity doctype in sax listener
# submitted by Jeff Barczewski # submitted by Jeff Barczewski
def test_simple_doctype_listener def test_simple_doctype_listener
xml = <<-END xml = <<-END
<?xml version="1.0"?> <?xml version="1.0"?>
<!DOCTYPE greeting PUBLIC "Hello Greeting DTD" "http://foo/hello.dtd"> <!DOCTYPE greeting PUBLIC "Hello Greeting DTD" "http://foo/hello.dtd">
<greeting>Hello, world!</greeting> <greeting>Hello, world!</greeting>
END END
parser = Parsers::SAX2Parser.new(xml) parser = Parsers::SAX2Parser.new(xml)
dtl = SimpleDoctypeListener.new dtl = SimpleDoctypeListener.new
parser.listen(dtl) parser.listen(dtl)
tname = nil tname = nil
tpub_sys = nil tpub_sys = nil
tlong_name = nil tlong_name = nil
turi = nil turi = nil
parser.listen(:doctype) do |name, pub_sys, long_name, uri| parser.listen(:doctype) do |name, pub_sys, long_name, uri|
tname = name tname = name
tpub_sys = pub_sys tpub_sys = pub_sys
tlong_name = long_name tlong_name = long_name
turi = uri 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
# test doctype with missing name, should throw ParseException
# submitted by Jeff Barczewseki
def test_doctype_with_mising_name_throws_exception
xml = <<-END
<?xml version="1.0"?>
<!DOCTYPE >
<greeting>Hello, world!</greeting>
END
parser = Parsers::SAX2Parser.new(xml)
assert_raise(REXML::ParseException, 'doctype missing name did not throw ParseException') do
parser.parse
end
end
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
# Submitted by Kou
def test_begin_end_document
parser = Parsers::SAX2Parser.new("<a/>")
kl = KouListener.new
parser.listen(kl)
sd = false
ed = false
parser.listen(:start_document) { sd = true }
parser.listen(:end_document) { ed = true }
parser.parse
assert( sd, ':start_document block failed' )
assert( ed, ':end_document block failed' )
assert( kl.sdoc, ':start_document listener failed' )
assert( kl.edoc, ':end_document listener failed' )
end
# Submitted by Kou
def test_listen_before_start
# FIXME: the following comment should be a test for validity. (The xml declaration
# is invalid).
#parser = Parsers::SAX2Parser.new( "<?xml ?><?pi?><a><?pi?></a>")
parser = Parsers::SAX2Parser.new( "<?xml version='1.0'?><?pi?><a><?pi?></a>")
k1 = KouListener.new
parser.listen( k1 )
xmldecl = false
pi = 0
parser.listen( :xmldecl ) { xmldecl = true }
parser.listen( :processing_instruction ) { pi += 1 }
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
def test_socket
require 'socket'
server = TCPServer.new('127.0.0.1', 0)
socket = TCPSocket.new('127.0.0.1', server.addr[1])
ok = false
session = server.accept
session << '<foo>'
parser = REXML::Parsers::SAX2Parser.new(socket)
Fiber.new do
parser.listen(:start_element) do
ok = true
Fiber.yield
end end
parser.parse parser.parse
end.resume assert_equal 'greeting', tname, 'simple doctype block listener failed - incorrect name'
assert(ok) assert_equal 'PUBLIC', tpub_sys, 'simple doctype block listener failed - incorrect pub_sys'
end 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
def test_char_ref_sax2() # test doctype with missing name, should throw ParseException
parser = REXML::Parsers::SAX2Parser.new('<ABC>&#252;</ABC>') # submitted by Jeff Barczewseki
result = nil def test_doctype_with_mising_name_throws_exception
parser.listen(:characters) {|text| result = text.unpack('U*')} xml = <<-END
parser.parse() <?xml version="1.0"?>
assert_equal(1, result.size) <!DOCTYPE >
assert_equal(252, result[0]) <greeting>Hello, world!</greeting>
end END
parser = Parsers::SAX2Parser.new(xml)
assert_raise(REXML::ParseException, 'doctype missing name did not throw ParseException') do
parser.parse
end
end
def test_char_ref_dom() class KouListener
doc = REXML::Document.new('<ABC>&#252;</ABC>') include REXML::SAX2Listener
result = doc.root.text.unpack('U*') attr_accessor :sdoc, :edoc
assert_equal(1, result.size) attr_reader :selem, :decl, :pi
assert_equal(252, result[0]) def initialize
end @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
# Submitted by Kou
def test_begin_end_document
parser = Parsers::SAX2Parser.new("<a/>")
kl = KouListener.new
parser.listen(kl)
sd = false
ed = false
parser.listen(:start_document) { sd = true }
parser.listen(:end_document) { ed = true }
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 parser.parse
rescue assert( sd, ':start_document block failed' )
p parser.source.position assert( ed, ':end_document block failed' )
p parser.source.current_line assert( kl.sdoc, ':start_document listener failed' )
puts $!.backtrace.join("\n") assert( kl.edoc, ':end_document listener failed' )
flunk $!.message end
# Submitted by Kou
def test_listen_before_start
# FIXME: the following comment should be a test for validity. (The xml declaration
# is invalid).
#parser = Parsers::SAX2Parser.new( "<?xml ?><?pi?><a><?pi?></a>")
parser = Parsers::SAX2Parser.new( "<?xml version='1.0'?><?pi?><a><?pi?></a>")
k1 = KouListener.new
parser.listen( k1 )
xmldecl = false
pi = 0
parser.listen( :xmldecl ) { xmldecl = true }
parser.listen( :processing_instruction ) { pi += 1 }
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
def test_socket
require 'socket'
server = TCPServer.new('127.0.0.1', 0)
socket = TCPSocket.new('127.0.0.1', server.addr[1])
ok = false
session = server.accept
session << '<foo>'
parser = REXML::Parsers::SAX2Parser.new(socket)
Fiber.new do
parser.listen(:start_element) do
ok = true
Fiber.yield
end
parser.parse
end.resume
assert(ok)
end
def test_char_ref_sax2()
parser = REXML::Parsers::SAX2Parser.new('<ABC>&#252;</ABC>')
result = nil
parser.listen(:characters) {|text| result = text.unpack('U*')}
parser.parse()
assert_equal(1, result.size)
assert_equal(252, result[0])
end
def test_char_ref_dom()
doc = REXML::Document.new('<ABC>&#252;</ABC>')
result = doc.root.text.unpack('U*')
assert_equal(1, result.size)
assert_equal(252, result[0])
end
class Ticket68
include REXML::SAX2Listener
end
def test_ticket_68
parser = REXML::Parsers::SAX2Parser.new(File.new(fixture_path('ticket_68.xml')))
parser.listen( Ticket68.new )
begin
parser.parse
rescue
p parser.source.position
p parser.source.current_line
puts $!.backtrace.join("\n")
flunk $!.message
end
end end
end end
end
class MySAX2Listener class MySAX2Listener
include REXML::SAX2Listener include REXML::SAX2Listener
end end
end end

View file

@ -4,126 +4,126 @@ require 'rexml/streamlistener'
require 'stringio' require 'stringio'
module REXMLTests module REXMLTests
class MyListener class MyListener
include REXML::StreamListener include REXML::StreamListener
end
class StreamTester < Test::Unit::TestCase
# Submitted by Han Holl
def test_listener
data = %Q{<session1 user="han" password="rootWeiler" />\n<session2 user="han" password="rootWeiler" />}
b = RequestReader.new( data )
b = RequestReader.new( data )
end end
def test_ticket_49
source = StringIO.new( <<-EOL )
<!DOCTYPE foo [
<!ENTITY ent "replace">
]>
<a>&ent;</a>
EOL
REXML::Document.parse_stream(source, MyListener.new)
end
def test_ticket_10 class StreamTester < Test::Unit::TestCase
source = StringIO.new( <<-EOL ) # Submitted by Han Holl
<!DOCTYPE foo [ def test_listener
<!ENTITY ent "replace"> data = %Q{<session1 user="han" password="rootWeiler" />\n<session2 user="han" password="rootWeiler" />}
<!ATTLIST a
xmlns:human CDATA #FIXED "http://www.foo.com/human"> b = RequestReader.new( data )
<!ELEMENT bar (#PCDATA)> b = RequestReader.new( data )
<!NOTATION n1 PUBLIC "-//HM//NOTATION TEST1//EN" 'urn:x-henrikmartensson.org:test5'>
]>
<a/>
EOL
listener = MyListener.new
class << listener
attr_accessor :events
def entitydecl( content )
@events[ :entitydecl ] = true
end
def attlistdecl( element_name, attributes, raw_content )
@events[ :attlistdecl ] = true
end
def elementdecl( content )
@events[ :elementdecl ] = true
end
def notationdecl( content )
@events[ :notationdecl ] = true
end
end end
listener.events = {}
REXML::Document.parse_stream( source, listener ) def test_ticket_49
source = StringIO.new( <<-EOL )
assert( listener.events[:entitydecl] ) <!DOCTYPE foo [
assert( listener.events[:attlistdecl] ) <!ENTITY ent "replace">
assert( listener.events[:elementdecl] ) ]>
assert( listener.events[:notationdecl] ) <a>&ent;</a>
end EOL
REXML::Document.parse_stream(source, MyListener.new)
def test_entity
listener = MyListener.new
class << listener
attr_accessor :entities
def entity(content)
@entities << content
end
end end
listener.entities = []
source = StringIO.new(<<-XML) def test_ticket_10
source = StringIO.new( <<-EOL )
<!DOCTYPE foo [
<!ENTITY ent "replace">
<!ATTLIST a
xmlns:human CDATA #FIXED "http://www.foo.com/human">
<!ELEMENT bar (#PCDATA)>
<!NOTATION n1 PUBLIC "-//HM//NOTATION TEST1//EN" 'urn:x-henrikmartensson.org:test5'>
]>
<a/>
EOL
listener = MyListener.new
class << listener
attr_accessor :events
def entitydecl( content )
@events[ :entitydecl ] = true
end
def attlistdecl( element_name, attributes, raw_content )
@events[ :attlistdecl ] = true
end
def elementdecl( content )
@events[ :elementdecl ] = true
end
def notationdecl( content )
@events[ :notationdecl ] = true
end
end
listener.events = {}
REXML::Document.parse_stream( source, listener )
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
end
end
listener.entities = []
source = StringIO.new(<<-XML)
<!DOCTYPE root [ <!DOCTYPE root [
<!ENTITY % ISOLat2 <!ENTITY % ISOLat2
SYSTEM "http://www.xml.com/iso/isolat2-xml.entities" > SYSTEM "http://www.xml.com/iso/isolat2-xml.entities" >
%ISOLat2; %ISOLat2;
]> ]>
<root/> <root/>
XML XML
REXML::Document.parse_stream(source, listener) REXML::Document.parse_stream(source, listener)
assert_equal(["ISOLat2"], listener.entities) assert_equal(["ISOLat2"], listener.entities)
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
end end
end end
def tag_start(name, args)
if @doc
@stack.push(REXML::Element.new(name, @stack.last)) # For test_listener
else class RequestReader
@doc = REXML::Document.new("<#{name}/>") attr_reader :doc
@stack.push(@doc.root) def initialize(io)
@stack = []
@doc = nil
catch(:fini) do
REXML::Document.parse_stream(io, self)
raise IOError
end
end end
args.each do |attr,val| def tag_start(name, args)
@stack.last.add_attribute(attr, val) 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
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 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 end

View file

@ -1,21 +1,21 @@
require "rexml/text" require "rexml/text"
module REXMLTests module REXMLTests
class TextTester < Test::Unit::TestCase class TextTester < Test::Unit::TestCase
include REXML include REXML
def test_shift_operator_chain def test_shift_operator_chain
text = Text.new("original\r\n") text = Text.new("original\r\n")
text << "append1\r\n" << "append2\r\n" text << "append1\r\n" << "append2\r\n"
assert_equal("original\nappend1\nappend2\n", text.to_s) assert_equal("original\nappend1\nappend2\n", text.to_s)
end end
def test_shift_operator_cache def test_shift_operator_cache
text = Text.new("original\r\n") text = Text.new("original\r\n")
text << "append1\r\n" << "append2\r\n" text << "append1\r\n" << "append2\r\n"
assert_equal("original\nappend1\nappend2\n", text.to_s) assert_equal("original\nappend1\nappend2\n", text.to_s)
text << "append3\r\n" << "append4\r\n" text << "append3\r\n" << "append4\r\n"
assert_equal("original\nappend1\nappend2\nappend3\nappend4\n", text.to_s) assert_equal("original\nappend1\nappend2\nappend3\nappend4\n", text.to_s)
end
end end
end end
end

View file

@ -10,9 +10,9 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class Ticket80 < Test::Unit::TestCase class Ticket80 < Test::Unit::TestCase
@@xmlstr = '<?xml version="1.0"?> @@xmlstr = '<?xml version="1.0"?>
<root xmlns="urn:some-xml-ns" xmlns:other="urn:some-other-xml-ns"> <root xmlns="urn:some-xml-ns" xmlns:other="urn:some-other-xml-ns">
<l1-foo> <l1-foo>
<l2 value="foo-01"/> <l2 value="foo-01"/>
@ -28,29 +28,29 @@ class Ticket80 < Test::Unit::TestCase
</l1-bar> </l1-bar>
</root>' </root>'
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
def test_xpathNamespacedChildWildcard def test_xpathNamespacedChildWildcard
# tests the "prefix:*" node test syntax # tests the "prefix:*" node test syntax
out = Array.new out = Array.new
REXML::XPath.each( REXML::Document.new(@@xmlstr), REXML::XPath.each( REXML::Document.new(@@xmlstr),
'/ns:root/ns:*/ns:l2/@value', '/ns:root/ns:*/ns:l2/@value',
{ 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end { 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end
chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ] chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ]
assert_equal chk, out assert_equal chk, out
end end
#---------------------------------------------------------------------------- #----------------------------------------------------------------------------
def test_xpathNamespacedChildWildcardWorkaround def test_xpathNamespacedChildWildcardWorkaround
# tests a workaround for the "prefix:*" node test syntax # tests a workaround for the "prefix:*" node test syntax
out = Array.new out = Array.new
REXML::XPath.each( REXML::Document.new(@@xmlstr), REXML::XPath.each( REXML::Document.new(@@xmlstr),
'/ns:root/*[namespace-uri()="urn:some-xml-ns"]/ns:l2/@value', '/ns:root/*[namespace-uri()="urn:some-xml-ns"]/ns:l2/@value',
{ 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end { 'ns' => 'urn:some-xml-ns' } ) do |node| out.push node.value ; end
chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ] chk = [ 'foo-01', 'foo-02', 'foo-03', 'bar-01', 'bar-02' ]
assert_equal chk, out assert_equal chk, out
end end
end end
end end
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------

View file

@ -4,11 +4,11 @@ require "rexml/document"
require "rexml/validation/relaxng" require "rexml/validation/relaxng"
module REXMLTests module REXMLTests
class RNGValidation < Test::Unit::TestCase class RNGValidation < Test::Unit::TestCase
include REXML include REXML
def test_validate def test_validate
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -25,16 +25,16 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A><B><C X="x"><E/><E/></C><D/></B></A>} ) no_error( validator, %q{<A><B><C X="x"><E/><E/></C><D/></B></A>} )
error( validator, %q{<A><B><D/><C X="x"/></B></A>} ) error( validator, %q{<A><B><D/><C X="x"/></B></A>} )
end end
def test_sequence def test_sequence
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -46,18 +46,18 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B><C/><C/><D/></B></A>} ) error( validator, %q{<A><B><C/><C/><D/></B></A>} )
error( validator, %q{<A><B><D/><C/></B></A>} ) error( validator, %q{<A><B><D/><C/></B></A>} )
error( validator, %q{<A><C/><D/></A>} ) error( validator, %q{<A><C/><D/></A>} )
no_error( validator, %q{<A><B><C/><D/></B></A>} ) no_error( validator, %q{<A><B><C/><D/></B></A>} )
end end
def test_choice def test_choice
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -71,16 +71,16 @@ class RNGValidation < Test::Unit::TestCase
</choice> </choice>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B><C/><D/></B></A>} ) error( validator, %q{<A><B><C/><D/></B></A>} )
no_error( validator, %q{<A><B><D/></B></A>} ) no_error( validator, %q{<A><B><D/></B></A>} )
no_error( validator, %q{<A><B><C/></B></A>} ) no_error( validator, %q{<A><B><C/></B></A>} )
end end
def test_optional def test_optional
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -91,17 +91,17 @@ class RNGValidation < Test::Unit::TestCase
</optional> </optional>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B><C/></B></A>} ) no_error( validator, %q{<A><B><C/></B></A>} )
error( validator, %q{<A><B><D/></B></A>} ) error( validator, %q{<A><B><D/></B></A>} )
error( validator, %q{<A><B><C/><C/></B></A>} ) error( validator, %q{<A><B><C/><C/></B></A>} )
end end
def test_zero_or_more def test_zero_or_more
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -112,15 +112,15 @@ class RNGValidation < Test::Unit::TestCase
</zeroOrMore> </zeroOrMore>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B><C/></B></A>} ) no_error( validator, %q{<A><B><C/></B></A>} )
no_error( validator, %q{<A><B><C/><C/><C/></B></A>} ) no_error( validator, %q{<A><B><C/><C/><C/></B></A>} )
error( validator, %q{<A><B><D/></B></A>} ) error( validator, %q{<A><B><D/></B></A>} )
error( validator, %q{<A></A>} ) error( validator, %q{<A></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -134,17 +134,17 @@ class RNGValidation < Test::Unit::TestCase
</zeroOrMore> </zeroOrMore>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B><C/><D/></B></A>} ) no_error( validator, %q{<A><B><C/><D/></B></A>} )
no_error( validator, %q{<A><B><C/><D/><C/><D/></B></A>} ) no_error( validator, %q{<A><B><C/><D/><C/><D/></B></A>} )
error( validator, %q{<A><B><D/></B></A>} ) error( validator, %q{<A><B><D/></B></A>} )
end end
def test_one_or_more def test_one_or_more
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -155,34 +155,34 @@ class RNGValidation < Test::Unit::TestCase
</oneOrMore> </oneOrMore>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B><C/></B></A>} ) no_error( validator, %q{<A><B><C/></B></A>} )
no_error( validator, %q{<A><B><C/><C/><C/></B></A>} ) no_error( validator, %q{<A><B><C/><C/><C/></B></A>} )
error( validator, %q{<A><B><D/></B></A>} ) error( validator, %q{<A><B><D/></B></A>} )
error( validator, %q{<A></A>} ) error( validator, %q{<A></A>} )
end end
def test_attribute def test_attribute
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<attribute name="X"/> <attribute name="X"/>
<attribute name="Y"/> <attribute name="Y"/>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A/>} ) error( validator, %q{<A/>} )
error( validator, %q{<A X=""/>} ) error( validator, %q{<A X=""/>} )
no_error( validator, %q{<A X="1" Y="1"/>} ) no_error( validator, %q{<A X="1" Y="1"/>} )
end end
def test_choice_attributes def test_choice_attributes
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<choice> <choice>
@ -190,17 +190,17 @@ class RNGValidation < Test::Unit::TestCase
<attribute name="Y"/> <attribute name="Y"/>
</choice> </choice>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A X="1" Y="1"/>} ) error( validator, %q{<A X="1" Y="1"/>} )
error( validator, %q{<A/>} ) error( validator, %q{<A/>} )
no_error( validator, %q{<A X="1"/>}) no_error( validator, %q{<A X="1"/>})
no_error( validator, %q{<A Y="1"/>} ) no_error( validator, %q{<A Y="1"/>} )
end end
def test_choice_attribute_element def test_choice_attribute_element
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<choice> <choice>
@ -208,45 +208,45 @@ class RNGValidation < Test::Unit::TestCase
<element name="B"/> <element name="B"/>
</choice> </choice>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A X="1"><B/></A>} ) error( validator, %q{<A X="1"><B/></A>} )
error( validator, %q{<A/>} ) error( validator, %q{<A/>} )
no_error( validator, %q{<A X="1"/>}) no_error( validator, %q{<A X="1"/>})
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
end end
def test_empty def test_empty
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<empty/> <empty/>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A>Text</A>} ) error( validator, %q{<A>Text</A>} )
no_error( validator, %q{<A/>}) no_error( validator, %q{<A/>})
end end
def test_text_val def test_text_val
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<text/> <text/>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A>Text</A>} ) no_error( validator, %q{<A>Text</A>} )
error( validator, %q{<A/>}) error( validator, %q{<A/>})
end end
def test_choice_text def test_choice_text
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<choice> <choice>
@ -254,17 +254,17 @@ class RNGValidation < Test::Unit::TestCase
<text/> <text/>
</choice> </choice>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/>Text</A>} ) error( validator, %q{<A><B/>Text</A>} )
error( validator, %q{<A>Text<B/></A>} ) error( validator, %q{<A>Text<B/></A>} )
no_error( validator, %q{<A>Text</A>} ) no_error( validator, %q{<A>Text</A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
end end
def test_group def test_group
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<choice> <choice>
@ -275,15 +275,15 @@ class RNGValidation < Test::Unit::TestCase
</group> </group>
</choice> </choice>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/><C/></A>} ) error( validator, %q{<A><B/><C/></A>} )
error( validator, %q{<A><C/></A>} ) error( validator, %q{<A><C/></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><C/><D/></A>} ) no_error( validator, %q{<A><C/><D/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"/> <element name="B"/>
@ -292,33 +292,33 @@ class RNGValidation < Test::Unit::TestCase
<element name="D"/> <element name="D"/>
</group> </group>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/><C/></A>} ) error( validator, %q{<A><B/><C/></A>} )
error( validator, %q{<A><B/><D/></A>} ) error( validator, %q{<A><B/><D/></A>} )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B/><C/><D/></A>} ) no_error( validator, %q{<A><B/><C/><D/></A>} )
end end
def test_value def test_value
# Values as text nodes # Values as text nodes
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
<value>VaLuE</value> <value>VaLuE</value>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B>X</B></A>} ) error( validator, %q{<A><B>X</B></A>} )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B>VaLuE</B></A>} ) no_error( validator, %q{<A><B>VaLuE</B></A>} )
# Values as text nodes, via choice # Values as text nodes, via choice
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -328,32 +328,32 @@ class RNGValidation < Test::Unit::TestCase
</choice> </choice>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A><B>XYZ</B></A>} ) error( validator, %q{<A><B>XYZ</B></A>} )
no_error( validator, %q{<A><B>Option 1</B></A>} ) no_error( validator, %q{<A><B>Option 1</B></A>} )
no_error( validator, %q{<A><B>Option 2</B></A>} ) no_error( validator, %q{<A><B>Option 2</B></A>} )
# Attribute values # Attribute values
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<attribute name="B"> <attribute name="B">
<value>VaLuE</value> <value>VaLuE</value>
</attribute> </attribute>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A/>} ) error( validator, %q{<A/>} )
error( validator, %q{<A B=""/>} ) error( validator, %q{<A B=""/>} )
error( validator, %q{<A B="Lala"/>} ) error( validator, %q{<A B="Lala"/>} )
no_error( validator, %q{<A B="VaLuE"/>} ) no_error( validator, %q{<A B="VaLuE"/>} )
# Attribute values via choice # Attribute values via choice
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<attribute name="B"> <attribute name="B">
@ -363,17 +363,17 @@ class RNGValidation < Test::Unit::TestCase
</choice> </choice>
</attribute> </attribute>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A B=""/>} ) error( validator, %q{<A B=""/>} )
error( validator, %q{<A B="Value"/>} ) error( validator, %q{<A B="Value"/>} )
no_error( validator, %q{<A B="Option 1"></A>} ) no_error( validator, %q{<A B="Option 1"></A>} )
no_error( validator, %q{<A B="Option 2"/>} ) no_error( validator, %q{<A B="Option 2"/>} )
end end
def test_interleave def test_interleave
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -384,20 +384,20 @@ class RNGValidation < Test::Unit::TestCase
</interleave> </interleave>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B><C/></B></A>} ) error( validator, %q{<A><B><C/></B></A>} )
error( validator, %q{<A><B><C/><D/><C/></B></A>} ) error( validator, %q{<A><B><C/><D/><C/></B></A>} )
no_error( validator, %q{<A><B><C/><D/><E/></B></A>} ) no_error( validator, %q{<A><B><C/><D/><E/></B></A>} )
no_error( validator, %q{<A><B><E/><D/><C/></B></A>} ) no_error( validator, %q{<A><B><E/><D/><C/></B></A>} )
no_error( validator, %q{<A><B><D/><C/><E/></B></A>} ) no_error( validator, %q{<A><B><D/><C/><E/></B></A>} )
no_error( validator, %q{<A><B><E/><C/><D/></B></A>} ) no_error( validator, %q{<A><B><E/><C/><D/></B></A>} )
error( validator, %q{<A><B><E/><C/><D/><C/></B></A>} ) error( validator, %q{<A><B><E/><C/><D/><C/></B></A>} )
end end
def test_mixed def test_mixed
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<element name="A" xmlns="http://relaxng.org/ns/structure/1.0"> <element name="A" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="B"> <element name="B">
@ -406,15 +406,15 @@ class RNGValidation < Test::Unit::TestCase
</mixed> </mixed>
</element> </element>
</element> </element>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A><B>Text<D/></B></A>} ) no_error( validator, %q{<A><B>Text<D/></B></A>} )
no_error( validator, %q{<A><B><D/>Text</B></A>} ) no_error( validator, %q{<A><B><D/>Text</B></A>} )
end end
def test_ref_sequence def test_ref_sequence
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -430,15 +430,15 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A><B X=''/><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/><B X=''/></A>} )
error( validator, %q{<A><B X=''/></A>} ) error( validator, %q{<A><B X=''/></A>} )
end end
def test_ref_choice def test_ref_choice
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -454,15 +454,15 @@ class RNGValidation < Test::Unit::TestCase
<element name="C"/> <element name="C"/>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><D/></A>} ) error( validator, %q{<A><D/></A>} )
error( validator, %q{<A><B/><C/></A>} ) error( validator, %q{<A><B/><C/></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><C/></A>} ) no_error( validator, %q{<A><C/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -478,15 +478,15 @@ class RNGValidation < Test::Unit::TestCase
</choice> </choice>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><D/></A>} ) error( validator, %q{<A><D/></A>} )
error( validator, %q{<A><B/><C/></A>} ) error( validator, %q{<A><B/><C/></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><C/></A>} ) no_error( validator, %q{<A><C/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -503,18 +503,18 @@ class RNGValidation < Test::Unit::TestCase
<element name="C"/> <element name="C"/>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/><C/></A>} ) error( validator, %q{<A><B/><C/></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><C/></A>} ) no_error( validator, %q{<A><C/></A>} )
no_error( validator, %q{<A><D/></A>} ) no_error( validator, %q{<A><D/></A>} )
end end
def test_ref_zero_plus def test_ref_zero_plus
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -531,15 +531,15 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A/>} ) no_error( validator, %q{<A/>} )
no_error( validator, %q{<A><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/></A>} )
no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -556,18 +556,18 @@ class RNGValidation < Test::Unit::TestCase
</zeroOrMore> </zeroOrMore>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A/>} ) no_error( validator, %q{<A/>} )
no_error( validator, %q{<A><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/></A>} )
no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} )
end end
def test_ref_one_plus def test_ref_one_plus
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -584,15 +584,15 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A/>} ) error( validator, %q{<A/>} )
no_error( validator, %q{<A><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/></A>} )
no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -609,17 +609,17 @@ class RNGValidation < Test::Unit::TestCase
</oneOrMore> </oneOrMore>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A/>} ) error( validator, %q{<A/>} )
no_error( validator, %q{<A><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/></A>} )
no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} ) no_error( validator, %q{<A><B X=''/><B X=''/><B X=''/></A>} )
end end
def test_ref_interleave def test_ref_interleave
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -635,16 +635,16 @@ class RNGValidation < Test::Unit::TestCase
<element name="C"/> <element name="C"/>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A><C/></A>} ) error( validator, %q{<A><C/></A>} )
error( validator, %q{<A><C/><C/></A>} ) error( validator, %q{<A><C/><C/></A>} )
no_error( validator, %q{<A><B/><C/></A>} ) no_error( validator, %q{<A><B/><C/></A>} )
no_error( validator, %q{<A><C/><B/></A>} ) no_error( validator, %q{<A><C/><B/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -660,16 +660,16 @@ class RNGValidation < Test::Unit::TestCase
</interleave> </interleave>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A><C/></A>} ) error( validator, %q{<A><C/></A>} )
error( validator, %q{<A><C/><C/></A>} ) error( validator, %q{<A><C/><C/></A>} )
no_error( validator, %q{<A><B/><C/></A>} ) no_error( validator, %q{<A><B/><C/></A>} )
no_error( validator, %q{<A><C/><B/></A>} ) no_error( validator, %q{<A><C/><B/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -688,18 +688,18 @@ class RNGValidation < Test::Unit::TestCase
<element name="C"/> <element name="C"/>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A><B/></A>} ) error( validator, %q{<A><B/></A>} )
error( validator, %q{<A><C/></A>} ) error( validator, %q{<A><C/></A>} )
error( validator, %q{<A><C/><C/></A>} ) error( validator, %q{<A><C/><C/></A>} )
no_error( validator, %q{<A><B/><C/></A>} ) no_error( validator, %q{<A><B/><C/></A>} )
no_error( validator, %q{<A><C/><B/></A>} ) no_error( validator, %q{<A><C/><B/></A>} )
end end
def test_ref_recurse def test_ref_recurse
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -716,16 +716,16 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
error( validator, %q{<A></A>} ) error( validator, %q{<A></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
no_error( validator, %q{<A><B><B/></B></A>} ) no_error( validator, %q{<A><B><B/></B></A>} )
end end
def test_ref_optional def test_ref_optional
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -741,15 +741,15 @@ class RNGValidation < Test::Unit::TestCase
</element> </element>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A></A>} ) no_error( validator, %q{<A></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
error( validator, %q{<A><B/><B/></A>} ) error( validator, %q{<A><B/><B/></A>} )
error( validator, %q{<A><C/></A>} ) error( validator, %q{<A><C/></A>} )
rng = %q{ rng = %q{
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0"> <grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start> <start>
@ -765,28 +765,28 @@ class RNGValidation < Test::Unit::TestCase
</optional> </optional>
</define> </define>
</grammar> </grammar>
} }
validator = REXML::Validation::RelaxNG.new( rng ) validator = REXML::Validation::RelaxNG.new( rng )
no_error( validator, %q{<A></A>} ) no_error( validator, %q{<A></A>} )
no_error( validator, %q{<A><B/></A>} ) no_error( validator, %q{<A><B/></A>} )
error( validator, %q{<A><B/><B/></A>} ) error( validator, %q{<A><B/><B/></A>} )
error( validator, %q{<A><C/></A>} ) error( validator, %q{<A><C/></A>} )
end end
def error( validator, source ) def error( validator, source )
parser = REXML::Parsers::TreeParser.new( source ) parser = REXML::Parsers::TreeParser.new( source )
parser.add_listener( validator.reset ) parser.add_listener( validator.reset )
assert_raise( REXML::Validation::ValidationException, assert_raise( REXML::Validation::ValidationException,
"Expected a validation error" ) { parser.parse } "Expected a validation error" ) { parser.parse }
end end
def no_error( validator, source ) def no_error( validator, source )
parser = REXML::Parsers::TreeParser.new( source ) parser = REXML::Parsers::TreeParser.new( source )
parser.add_listener( validator.reset ) parser.add_listener( validator.reset )
assert_nothing_raised { parser.parse } assert_nothing_raised { parser.parse }
end
end end
end end
end

View file

@ -7,29 +7,29 @@ require "rexml/document"
require "test/unit" require "test/unit"
module REXMLTests module REXMLTests
class TestXmlDeclaration < Test::Unit::TestCase class TestXmlDeclaration < Test::Unit::TestCase
def setup def setup
xml = <<-'END_XML' xml = <<-'END_XML'
<?xml encoding= 'UTF-8' standalone='yes'?> <?xml encoding= 'UTF-8' standalone='yes'?>
<root> <root>
</root> </root>
END_XML END_XML
@doc = REXML::Document.new xml @doc = REXML::Document.new xml
@root = @doc.root @root = @doc.root
@xml_declaration = @doc.children[0] @xml_declaration = @doc.children[0]
end end
def test_is_first_child def test_is_first_child
assert_kind_of(REXML::XMLDecl, @xml_declaration) assert_kind_of(REXML::XMLDecl, @xml_declaration)
end end
def test_has_document_as_parent def test_has_document_as_parent
assert_kind_of(REXML::Document, @xml_declaration.parent) assert_kind_of(REXML::Document, @xml_declaration.parent)
end end
def test_has_sibling def test_has_sibling
assert_kind_of(REXML::XMLDecl, @root.previous_sibling.previous_sibling) assert_kind_of(REXML::XMLDecl, @root.previous_sibling.previous_sibling)
assert_kind_of(REXML::Element, @xml_declaration.next_sibling.next_sibling) assert_kind_of(REXML::Element, @xml_declaration.next_sibling.next_sibling)
end
end end
end end
end

View file

@ -2,28 +2,28 @@ require 'test/unit'
require 'rexml/document' require 'rexml/document'
module REXMLTests module REXMLTests
class TestXPathAttribute < Test::Unit::TestCase class TestXPathAttribute < Test::Unit::TestCase
def setup def setup
@xml = <<-XML @xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<root> <root>
<child name="one">child1</child> <child name="one">child1</child>
<child name="two">child2</child> <child name="two">child2</child>
<child name="three">child3</child> <child name="three">child3</child>
</root> </root>
XML XML
@document = REXML::Document.new(@xml) @document = REXML::Document.new(@xml)
end end
def test_elements def test_elements
root = @document.elements["root"] root = @document.elements["root"]
second_child = root.elements["child[@name='two']"] second_child = root.elements["child[@name='two']"]
assert_equal("child2", second_child.text) assert_equal("child2", second_child.text)
end end
def test_xpath_each def test_xpath_each
children = REXML::XPath.each(@document, "/root/child[@name='two']") children = REXML::XPath.each(@document, "/root/child[@name='two']")
assert_equal(["child2"], children.collect(&:text)) assert_equal(["child2"], children.collect(&:text))
end
end end
end end
end

View file

@ -2,38 +2,38 @@ require "test/unit/testcase"
require "rexml/document" require "rexml/document"
module REXMLTests module REXMLTests
class TestXPathAxisPredcedingSibling < Test::Unit::TestCase class TestXPathAxisPredcedingSibling < Test::Unit::TestCase
include REXML include REXML
SOURCE = <<-EOF SOURCE = <<-EOF
<a id='1'> <a id='1'>
<e id='2'> <e id='2'>
<f id='3'/> <f id='3'/>
<f id='4'/> <f id='4'/>
<f id='5'/> <f id='5'/>
<f id='6'/> <f id='6'/>
</e> </e>
</a> </a>
EOF EOF
def setup def setup
@@doc = Document.new(SOURCE) unless defined? @@doc @@doc = Document.new(SOURCE) unless defined? @@doc
end end
def test_preceding_sibling_axis def test_preceding_sibling_axis
context = XPath.first(@@doc,"/a/e/f[last()]") context = XPath.first(@@doc,"/a/e/f[last()]")
assert_equal "6", context.attributes["id"] assert_equal "6", context.attributes["id"]
prev = XPath.first(context, "preceding-sibling::f") prev = XPath.first(context, "preceding-sibling::f")
assert_equal "5", prev.attributes["id"] assert_equal "5", prev.attributes["id"]
prev = XPath.first(context, "preceding-sibling::f[1]") prev = XPath.first(context, "preceding-sibling::f[1]")
assert_equal "5", prev.attributes["id"] assert_equal "5", prev.attributes["id"]
prev = XPath.first(context, "preceding-sibling::f[2]") prev = XPath.first(context, "preceding-sibling::f[2]")
assert_equal "4", prev.attributes["id"] assert_equal "4", prev.attributes["id"]
prev = XPath.first(context, "preceding-sibling::f[3]") prev = XPath.first(context, "preceding-sibling::f[3]")
assert_equal "3", prev.attributes["id"] assert_equal "3", prev.attributes["id"]
end
end end
end end
end

File diff suppressed because it is too large Load diff

View file

@ -5,38 +5,38 @@ require_relative "../rexml_test_utils"
require "rexml/document" require "rexml/document"
module REXMLTests module REXMLTests
class TestXPathNode < Test::Unit::TestCase class TestXPathNode < Test::Unit::TestCase
def matches(xml, xpath) def matches(xml, xpath)
document = REXML::Document.new(xml) document = REXML::Document.new(xml)
REXML::XPath.each(document, xpath).collect(&:to_s) REXML::XPath.each(document, xpath).collect(&:to_s)
end end
class TestQName < self class TestQName < self
def test_ascii def test_ascii
xml = <<-XML xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<root> <root>
<ascii> <ascii>
<child>child</child> <child>child</child>
</ascii> </ascii>
</root> </root>
XML XML
assert_equal(["<child>child</child>"], assert_equal(["<child>child</child>"],
matches(xml, "/root/ascii/child")) matches(xml, "/root/ascii/child"))
end end
def test_non_ascii def test_non_ascii
xml = <<-XML xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<root> <root>
<non-àscii> <non-àscii>
<child>child</child> <child>child</child>
</non-àscii> </non-àscii>
</root> </root>
XML XML
assert_equal(["<child>child</child>"], assert_equal(["<child>child</child>"],
matches(xml, "/root/non-àscii/child")) matches(xml, "/root/non-àscii/child"))
end
end end
end end
end end
end

View file

@ -4,60 +4,60 @@ require "rexml/xpath"
require "rexml/parsers/xpathparser" require "rexml/parsers/xpathparser"
module REXMLTests module REXMLTests
class TestXPathPredicate < Test::Unit::TestCase class TestXPathPredicate < Test::Unit::TestCase
include REXML include REXML
SRC=<<-EOL SRC=<<-EOL
<article> <article>
<section role="subdivision" id="1"> <section role="subdivision" id="1">
<para>free flowing text.</para> <para>free flowing text.</para>
</section> </section>
<section role="division"> <section role="division">
<section role="subdivision" id="2"> <section role="subdivision" id="2">
<para>free flowing text.</para> <para>free flowing text.</para>
</section> </section>
<section role="division"> <section role="division">
<para>free flowing text.</para> <para>free flowing text.</para>
</section> </section>
</section> </section>
</article> </article>
EOL EOL
def setup def setup
@doc = REXML::Document.new( SRC ) @doc = REXML::Document.new( SRC )
@parser = REXML::Parsers::XPathParser.new @parser = REXML::Parsers::XPathParser.new
end end
def test_predicates_parent def test_predicates_parent
path = '//section[../self::section[@role="division"]]' path = '//section[../self::section[@role="division"]]'
m = do_path( path ) m = do_path( path )
assert_equal( 2, m.size ) assert_equal( 2, m.size )
assert_equal( "2", m[0].attributes["id"] ) assert_equal( "2", m[0].attributes["id"] )
assert_nil( m[1].attributes["id"] ) assert_nil( m[1].attributes["id"] )
end end
def test_predicates_single def test_predicates_single
path = '//section[@role="subdivision" and not(../self::section[@role="division"])]' path = '//section[@role="subdivision" and not(../self::section[@role="division"])]'
m = do_path( path ) m = do_path( path )
assert_equal( 1, m.size ) assert_equal( 1, m.size )
assert_equal( "1", m[0].attributes["id"] ) assert_equal( "1", m[0].attributes["id"] )
end end
def test_predicates_multi def test_predicates_multi
path = '//section[@role="subdivision"][not(../self::section[@role="division"])]' path = '//section[@role="subdivision"][not(../self::section[@role="division"])]'
m = do_path( path ) m = do_path( path )
assert_equal( 1, m.size ) assert_equal( 1, m.size )
assert_equal( "1", m[0].attributes["id"] ) assert_equal( "1", m[0].attributes["id"] )
end end
def do_path( path ) def do_path( path )
m = REXML::XPath.match( @doc, path ) m = REXML::XPath.match( @doc, path )
#puts path, @parser.parse( path ).inspect #puts path, @parser.parse( path ).inspect
return m return m
end end
def test_get_no_siblings_terminal_nodes def test_get_no_siblings_terminal_nodes
source = <<-XML source = <<-XML
<a> <a>
<b number='1' str='abc'>TEXT1</b> <b number='1' str='abc'>TEXT1</b>
<c number='1'/> <c number='1'/>
@ -68,15 +68,15 @@ class TestXPathPredicate < Test::Unit::TestCase
</c> </c>
</a> </a>
XML XML
doc = REXML::Document.new(source) doc = REXML::Document.new(source)
predicate = "count(child::node()|" + predicate = "count(child::node()|" +
"following-sibling::node()|" + "following-sibling::node()|" +
"preceding-sibling::node())=0" "preceding-sibling::node())=0"
m = REXML::XPath.match(doc, "/descendant-or-self::node()[#{predicate}]") m = REXML::XPath.match(doc, "/descendant-or-self::node()[#{predicate}]")
assert_equal( [REXML::Text.new("TEXT1"), assert_equal( [REXML::Text.new("TEXT1"),
REXML::Text.new("TEXT2"), REXML::Text.new("TEXT2"),
REXML::Comment.new("COMMENT")], REXML::Comment.new("COMMENT")],
m ) m )
end
end end
end end
end

View file

@ -4,71 +4,71 @@ require 'rexml/element'
require 'rexml/xpath' require 'rexml/xpath'
module REXMLTests module REXMLTests
class TestXPathText < Test::Unit::TestCase class TestXPathText < Test::Unit::TestCase
def setup def setup
@doc = REXML::Document.new @doc = REXML::Document.new
end end
def tear_down def tear_down
end end
def test_text_as_element def test_text_as_element
node1 = REXML::Element.new('a', @doc) node1 = REXML::Element.new('a', @doc)
node2 = REXML::Element.new('b', node1) node2 = REXML::Element.new('b', node1)
REXML::Text.new('test', false, node2) REXML::Text.new('test', false, node2)
assert_equal(1, @doc.elements.size, "doc owns 1 element node1") assert_equal(1, @doc.elements.size, "doc owns 1 element node1")
assert_same(node1, @doc.elements[1], "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_equal(1, node1.elements.size, "node1 owns 1 element node2")
assert_same(node2, node1.elements[1], "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") assert_equal(1, node2.size, "node2 owns 1 text element")
end end
def test_text_in_xpath_query def test_text_in_xpath_query
node1 = REXML::Element.new('a', @doc) node1 = REXML::Element.new('a', @doc)
node2 = REXML::Element.new('b', node1) node2 = REXML::Element.new('b', node1)
textnode = REXML::Text.new('test', false, node2) textnode = REXML::Text.new('test', false, node2)
textnode.parent = node2 # should be unnecessary textnode.parent = node2 # should be unnecessary
nodes = @doc.get_elements('//b') nodes = @doc.get_elements('//b')
assert_equal(1, nodes.size, "document has one element") assert_equal(1, nodes.size, "document has one element")
# why doesn't this query work right? # why doesn't this query work right?
nodes = REXML::XPath.match(@doc, '//text()') nodes = REXML::XPath.match(@doc, '//text()')
assert_equal(1, nodes.size, "//text() should yield one Text element") assert_equal(1, nodes.size, "//text() should yield one Text element")
assert_equal(REXML::Text, nodes[0].class) assert_equal(REXML::Text, nodes[0].class)
end end
def test_comment_in_xpath_query def test_comment_in_xpath_query
node1 = REXML::Element.new('a', @doc) node1 = REXML::Element.new('a', @doc)
node2 = REXML::Element.new('b', node1) node2 = REXML::Element.new('b', node1)
commentnode = REXML::Comment.new('test', node2) commentnode = REXML::Comment.new('test', node2)
nodes = REXML::XPath.match(@doc, '//comment()') nodes = REXML::XPath.match(@doc, '//comment()')
assert_equal(1, nodes.size, "//comment() should yield one Comment element") assert_equal(1, nodes.size, "//comment() should yield one Comment element")
assert_same commentnode, nodes[0] assert_same commentnode, nodes[0]
end end
def test_parentage def test_parentage
node1 = REXML::Element.new('a', @doc) node1 = REXML::Element.new('a', @doc)
assert_same(@doc, node1.parent, "node1 parent is document") assert_same(@doc, node1.parent, "node1 parent is document")
node2 = REXML::Element.new('b', node1) node2 = REXML::Element.new('b', node1)
assert_same(node1, node2.parent, "node2 parent is node1") assert_same(node1, node2.parent, "node2 parent is node1")
textnode = REXML::Text.new('test', false, node2) textnode = REXML::Text.new('test', false, node2)
# why isn't the text's parent node2? # why isn't the text's parent node2?
# Also look at Comment, etc. # Also look at Comment, etc.
assert_same(node2, textnode.parent) assert_same(node2, textnode.parent)
comment = REXML::Comment.new('Test comment', node2) comment = REXML::Comment.new('Test comment', node2)
assert_same(node2, comment.parent) assert_same(node2, comment.parent)
end end
def test_ancestors def test_ancestors
node1 = REXML::Element.new('a', @doc) node1 = REXML::Element.new('a', @doc)
node2 = REXML::Element.new('b', node1) node2 = REXML::Element.new('b', node1)
textnode = REXML::Text.new('test', false, node2) textnode = REXML::Text.new('test', false, node2)
#textnode.parent = node2 # should be unnecessary #textnode.parent = node2 # should be unnecessary
assert_same node2, textnode.parent assert_same node2, textnode.parent
nodes = @doc.get_elements('//b/ancestor::*') nodes = @doc.get_elements('//b/ancestor::*')
assert_equal(1, nodes.size, "<b> has one element ancestor") assert_equal(1, nodes.size, "<b> has one element ancestor")
nodes = @doc.get_elements('//b/ancestor::node()') nodes = @doc.get_elements('//b/ancestor::node()')
assert_equal(2, nodes.size, "<b> has two node ancestors") assert_equal(2, nodes.size, "<b> has two node ancestors")
assert nodes[1].kind_of?(REXML::Document) assert nodes[1].kind_of?(REXML::Document)
end
end end
end end
end