#!/usr/bin/env ruby
#--
# Portions copyright 2004 by Jim Weirich (jim.weirichhouse.org).
# Portions copyright 2005 by Sam Ruby (rubys.intertwingly.net).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
require 'config/environment'
require 'builder'
require 'test/unit'
class Builder::XmlMarkup < Builder::XmlBase
def _escape(text, extra={})
result = text.
gsub(%r{&}, '&').
gsub(%r{<}, '<').
gsub(%r{>}, '>')
extra.each_pair {|key,value| result.gsub!(key, value)}
return result
end
# Insert the attributes (given in the hash).
def _insert_attributes(attrs, order=[])
return if attrs.nil?
q = {'"' => '"'}
order.each do |k|
v = attrs[k]
@target << %{ #{k}="#{_escape(v,q)}"} if v
end
attrs.each do |k, v|
@target << %{ #{k}="#{_escape(v,q)}"} unless order.member?(k)
end
end
end
class TestEscaping < Test::Unit::TestCase
def setup
@xml = Builder::XmlMarkup.new
end
def test_element_gt
@xml.title('2>1')
assert_equal '<title>2>1</title>', @xml.target!
end
def test_element_amp
@xml.title('AT&T')
assert_equal '<title>AT&T</title>', @xml.target!
end
def test_element_amp2
@xml.title('&')
assert_equal '<title>&</title>', @xml.target!
end
def test_attr_less
@xml.a(:title => '2>1')
assert_equal '<a title="2>1"/>', @xml.target!
end
def test_attr_amp
@xml.a(:title => 'AT&T')
assert_equal '<a title="AT&T"/>', @xml.target!
end
def test_attr_quot
@xml.a(:title => '"x"')
assert_equal '<a title=""x""/>', @xml.target!
end
end