require "test/unit/testcase"
require 'rexml/sax2listener'
require 'rexml/sax2parser'

class SAX2Tester < Test::Unit::TestCase
	def test_characters
		d = REXML::Document.new( "<A>@blah@</A>" )
		txt = d.root.text
		p=REXML::SAX2Parser.new "<A>@blah@</A>"
		p.listen(:characters) {|x| assert_equal txt, x}
		p.listen(:characters, ["A"]) {|x| assert_equal txt,x}
		p.parse
	end
	def test_sax2
		f = File.new("documentation.xml")
		parser = REXML::SAX2Parser.new( f )
		# Listen to all events on the following elements
		count = 0
		blok = proc { |uri,localname,qname,attributes|
			assert %w{ changelog bugs todo }.include?(localname),
			"Mismatched name; we got '#{qname}'\nArgs were:\n\tURI: #{uri}\n\tLOCALNAME: #{localname}\n\tQNAME: #{qname}\n\tATTRIBUTES: #{attributes.inspect}\n\tSELF=#{blok}"
			count += 1
		}

		parser.listen( :start_element, %w{ changelog bugs todo }, &blok )
		# Listen to all events on the following elements.  Synonymous with
		# listen( :start_element, %w{ ... } )
		parser.listen( %w{ changelog bugs todo }, &blok )
		# Listen for all start element events
		parser.listen( :start_element ) { |uri,localname,qname,attributes|
		}
		listener = MySAX2Listener.new
		# Listen for all events
		parser.listen( listener )
		# Listen for all events on the given elements.  Does not include children
		# events.  Regular expressions work as well!
		parser.listen( %w{ /change/ bugs todo }, listener )
		# Test the deafening method
		blok = proc  { |uri,localname,qname,attributes|
			assert_fail "This listener should have been deafened!"
		}
		parser.listen( %w{ changelog }, &blok )
		parser.deafen( &blok )

		tc = 0
		parser.listen( :characters, %w{version} ) {|text|
			assert_not_nil(text=~/(\d\.?){2,3}/, "In looking for text")
			tc += 1
		}
		
		begin 
			parser.parse
		rescue Exception
			puts $!
		end
		assert_equal 3, count
		assert_equal 1, tc
	end
end

class MySAX2Listener
	include REXML::SAX2Listener
end
