#!/usr/bin/ruby -wIsrc

Dir.chdir ".." if Dir.pwd =~ /bin.?$/

require "test/unit/testcase"
require "test/unit/ui/console/testrunner"
require 'getoptlong'

Dir.entries('test').each do |file|
	require "test/#{file}" if file =~ /\.rb$/
end

runner = Test::Unit::UI::Console::TestRunner
suite = Test::Unit::TestSuite
level = Test::Unit::UI::NORMAL

opts = GetoptLong.new( 
  ['--verbose', '-v', GetoptLong::NO_ARGUMENT],
  ['--help', '-h', GetoptLong::NO_ARGUMENT],
  ['--list', '-l', GetoptLong::OPTIONAL_ARGUMENT],
  ['--gui', '-g', GetoptLong::NO_ARGUMENT]
)
opts.each { |opt, arg|
  case opt
  when '--help'
		puts "USAGE: #$0 [--verbose][--help|--list [<suite>]|[--gui] <suite> [<method>]|<method>]\n"+
		"  --list\tList the available test suites\n"+
		"    <suite>\tList the methods of a suite\n"+
		"  <suite>\tRun all of the tests in a suite\n"+
		"  <method>\tRun the given method"
		exit
  when '--list'
		if ARGV[0]
			suite = ARGV[0]
			ObjectSpace.each_object(Class){|ob|suite = ob if ob.to_s == suite}
			puts((suite.instance_methods - Object.methods).collect{|mn| "  "+mn})
		else
			ObjectSpace.each_object(Class){|ob| 
				puts ob.to_s if ob.ancestors.include? Test::Unit::TestCase and ob.to_s != 'RUNIT::TestCase'
			}
		end
		exit
  when '--verbose'
    level = Test::Unit::UI::VERBOSE
  when '--gui'
		ARGV.shift
		begin
			require 'test/unit/ui/fox/testrunner'
			runner = Test::Unit::UI::Fox::TestRunner
			suite = Test::Unit::TestSuite
		rescue Exception
			puts $!
			puts "You must have Test::Unit and FXRuby installed to run the GUI test runner.\n"
			puts "I'm continuing without the GUI."
		end
  end
}

puts "REXML version = #{REXML::Version}"

if ARGV.size > 0
	# Get the test Class object for the named test
	test = ARGV[0]
	ObjectSpace.each_object(Class) {|ob| test = ob if ob.to_s == test }

	# Are we running a single test, or a test suite?
	if ARGV.size == 2
		test = test.new(ARGV[1])
	else
		# They didn't supply a unit test name; look for methods
		if test.kind_of? String
			method = test
			ObjectSpace.each_object(Class) {|ob| 
				test = ob if ob.instance_methods(false).include? method 
			}
			test = test.new( method )
		else
			test = test.suite
		end
	end

	results = runner.run( test, level )
else
	suite = suite.new 'REXML'
	ObjectSpace.each_object(Class){|ob| 
		if ob.ancestors.include? Test::Unit::TestCase and ob.to_s != 'RUNIT::TestCase' and ob.to_s != 'Test::Unit::TestCase'
			suite << ob.suite 
		end
	}
	results = runner.run( suite, level )
end

exit 1 unless (results.failure_count == 0 and results.error_count == 0)
