diff options
author | Jari Vetoniemi <jari.vetoniemi@indooratlas.com> | 2020-03-16 18:49:26 +0900 |
---|---|---|
committer | Jari Vetoniemi <jari.vetoniemi@indooratlas.com> | 2020-03-30 00:39:06 +0900 |
commit | fcbf63e62c627deae76c1b8cb8c0876c536ed811 (patch) | |
tree | 64cb17de3f41a2b6fef2368028fbd00349946994 /jni/ruby/test/rake |
Fresh start
Diffstat (limited to 'jni/ruby/test/rake')
53 files changed, 6975 insertions, 0 deletions
diff --git a/jni/ruby/test/rake/file_creation.rb b/jni/ruby/test/rake/file_creation.rb new file mode 100644 index 0000000..facc57a --- /dev/null +++ b/jni/ruby/test/rake/file_creation.rb @@ -0,0 +1,34 @@ +module FileCreation + OLDFILE = "old" + NEWFILE = "new" + + def create_timed_files(oldfile, *newfiles) + return if (File.exist?(oldfile) && + newfiles.all? { |newfile| + File.exist?(newfile) && File.stat(newfile).mtime > File.stat(oldfile).mtime + }) + now = Time.now + + create_file(oldfile, now - 60) + + newfiles.each do |newfile| + create_file(newfile, now) + end + end + + def create_dir(dirname) + FileUtils.mkdir_p(dirname) unless File.exist?(dirname) + File.stat(dirname).mtime + end + + def create_file(name, file_time=nil) + create_dir(File.dirname(name)) + FileUtils.touch(name) unless File.exist?(name) + File.utime(file_time, file_time, name) unless file_time.nil? + File.stat(name).mtime + end + + def delete_file(name) + File.delete(name) rescue nil + end +end diff --git a/jni/ruby/test/rake/helper.rb b/jni/ruby/test/rake/helper.rb new file mode 100644 index 0000000..ac1205a --- /dev/null +++ b/jni/ruby/test/rake/helper.rb @@ -0,0 +1,129 @@ +require 'rubygems' +$:.unshift File.expand_path('../../lib', __FILE__) + +begin + gem 'minitest', '~> 5' +rescue Gem::LoadError +end + +require 'minitest/autorun' +require 'rake' +require 'tmpdir' +require File.expand_path('../file_creation', __FILE__) + + +begin + require_relative 'support/ruby_runner' + require_relative 'support/rakefile_definitions' +rescue NoMethodError, LoadError + # ruby 1.8 + require 'test/support/ruby_runner' + require 'test/support/rakefile_definitions' +end + +class Rake::TestCase < Minitest::Test + include FileCreation + + include Rake::DSL + + class TaskManager + include Rake::TaskManager + end + + RUBY = defined?(EnvUtil) ? EnvUtil.rubybin : Gem.ruby + + def setup + ARGV.clear + + test_dir = File.basename File.dirname File.expand_path __FILE__ + + @rake_root = + if test_dir == 'test' + # rake repository + File.expand_path '../../', __FILE__ + else + # ruby repository + File.expand_path '../../../', __FILE__ + end + + @verbose = ENV['VERBOSE'] + + @rake_exec = File.join @rake_root, 'bin', 'rake' + @rake_lib = File.join @rake_root, 'lib' + @ruby_options = ["-I#{@rake_lib}", "-I."] + + @orig_pwd = Dir.pwd + @orig_appdata = ENV['APPDATA'] + @orig_home = ENV['HOME'] + @orig_homedrive = ENV['HOMEDRIVE'] + @orig_homepath = ENV['HOMEPATH'] + @orig_rake_columns = ENV['RAKE_COLUMNS'] + @orig_rake_system = ENV['RAKE_SYSTEM'] + @orig_rakeopt = ENV['RAKEOPT'] + @orig_userprofile = ENV['USERPROFILE'] + ENV.delete 'RAKE_COLUMNS' + ENV.delete 'RAKE_SYSTEM' + ENV.delete 'RAKEOPT' + + tmpdir = Dir.chdir Dir.tmpdir do Dir.pwd end + @tempdir = File.join tmpdir, "test_rake_#{$$}" + + FileUtils.mkdir_p @tempdir + + Dir.chdir @tempdir + + Rake.application = Rake::Application.new + Rake::TaskManager.record_task_metadata = true + RakeFileUtils.verbose_flag = false + end + + def teardown + Dir.chdir @orig_pwd + FileUtils.rm_rf @tempdir + + if @orig_appdata + ENV['APPDATA'] = @orig_appdata + else + ENV.delete 'APPDATA' + end + + ENV['HOME'] = @orig_home + ENV['HOMEDRIVE'] = @orig_homedrive + ENV['HOMEPATH'] = @orig_homepath + ENV['RAKE_COLUMNS'] = @orig_rake_columns + ENV['RAKE_SYSTEM'] = @orig_rake_system + ENV['RAKEOPT'] = @orig_rakeopt + ENV['USERPROFILE'] = @orig_userprofile + end + + def ignore_deprecations + Rake.application.options.ignore_deprecate = true + yield + ensure + Rake.application.options.ignore_deprecate = false + end + + def rake_system_dir + @system_dir = 'system' + + FileUtils.mkdir_p @system_dir + + open File.join(@system_dir, 'sys1.rake'), 'w' do |io| + io << <<-SYS +task "sys1" do + puts "SYS1" +end + SYS + end + + ENV['RAKE_SYSTEM'] = @system_dir + end + + def rakefile(contents) + open 'Rakefile', 'w' do |io| + io << contents + end + end + + include RakefileDefinitions +end diff --git a/jni/ruby/test/rake/support/rakefile_definitions.rb b/jni/ruby/test/rake/support/rakefile_definitions.rb new file mode 100644 index 0000000..a637c7e --- /dev/null +++ b/jni/ruby/test/rake/support/rakefile_definitions.rb @@ -0,0 +1,478 @@ +module RakefileDefinitions + include FileUtils + + def rakefile_access + rakefile <<-ACCESS +TOP_LEVEL_CONSTANT = 0 + +def a_top_level_function +end + +task :default => [:work, :obj, :const] + +task :work do + begin + a_top_level_function + puts "GOOD:M Top level methods can be called in tasks" + rescue NameError => ex + puts "BAD:M Top level methods can not be called in tasks" + end +end + +# TODO: remove `disabled_' when DeprecatedObjectDSL removed +task :obj +task :disabled_obj do + begin + Object.new.instance_eval { task :xyzzy } + puts "BAD:D Rake DSL are polluting objects" + rescue StandardError => ex + puts "GOOD:D Rake DSL are not polluting objects" + end +end + +task :const do + begin + TOP_LEVEL_CONSTANT + puts "GOOD:C Top level constants are available in tasks" + rescue StandardError => ex + puts "BAD:C Top level constants are NOT available in tasks" + end +end + ACCESS + end + + def rakefile_test_task + rakefile <<-RAKEFILE + require "rake/testtask" + + Rake::TestTask.new(:unit) do |t| + t.description = "custom test task description" + end + RAKEFILE + end + + def rakefile_chains + rakefile <<-DEFAULT +task :default => "play.app" + +file "play.scpt" => "base" do |t| + cp t.prerequisites.first, t.name +end + +rule ".app" => ".scpt" do |t| + cp t.source, t.name +end + +file 'base' do + touch 'base' +end + DEFAULT + end + + def rakefile_comments + rakefile <<-COMMENTS +# comment for t1 +task :t1 do +end + +# no comment or task because there's a blank line + +task :t2 do +end + +desc "override comment for t3" +# this is not the description +multitask :t3 do +end + +# this is not the description +desc "override comment for t4" +file :t4 do +end + COMMENTS + end + + def rakefile_default + rakefile <<-DEFAULT +if ENV['TESTTOPSCOPE'] + puts "TOPSCOPE" +end + +task :default do + puts "DEFAULT" +end + +task :other => [:default] do + puts "OTHER" +end + +task :task_scope do + if ENV['TESTTASKSCOPE'] + puts "TASKSCOPE" + end +end + DEFAULT + end + + def rakefile_dryrun + rakefile <<-DRYRUN +task :default => ["temp_main"] + +file "temp_main" => [:all_apps] do touch "temp_main" end + +task :all_apps => [:one, :two] +task :one => ["temp_one"] +task :two => ["temp_two"] + +file "temp_one" do |t| + touch "temp_one" +end +file "temp_two" do |t| + touch "temp_two" +end + +task :clean do + ["temp_one", "temp_two", "temp_main"].each do |file| + rm_f file + end +end + DRYRUN + + FileUtils.touch 'temp_main' + FileUtils.touch 'temp_two' + end + + def rakefile_extra + rakefile 'task :default' + + FileUtils.mkdir_p 'rakelib' + + open File.join('rakelib', 'extra.rake'), 'w' do |io| + io << <<-EXTRA_RAKE +# Added for testing + +namespace :extra do + desc "An Extra Task" + task :extra do + puts "Read all about it" + end +end + EXTRA_RAKE + end + end + + def rakefile_file_creation + rakefile <<-'FILE_CREATION' +N = 2 + +task :default => :run + +BUILD_DIR = 'build' +task :clean do + rm_rf 'build' + rm_rf 'src' +end + +task :run + +TARGET_DIR = 'build/copies' + +FileList['src/*'].each do |src| + directory TARGET_DIR + target = File.join TARGET_DIR, File.basename(src) + file target => [src, TARGET_DIR] do + cp src, target + end + task :run => target +end + +task :prep => :clean do + mkdir_p 'src' + N.times do |n| + touch "src/foo#{n}" + end +end + FILE_CREATION + end + + def rakefile_imports + rakefile <<-IMPORTS +require 'rake/loaders/makefile' + +task :default + +task :other do + puts "OTHER" +end + +file "dynamic_deps" do |t| + open(t.name, "w") do |f| f.puts "puts 'DYNAMIC'" end +end + +import "dynamic_deps" +import "static_deps" +import "static_deps" +import "deps.mf" +puts "FIRST" + IMPORTS + + open 'deps.mf', 'w' do |io| + io << <<-DEPS +default: other + DEPS + end + + open "static_deps", "w" do |f| + f.puts 'puts "STATIC"' + end + end + + def rakefile_regenerate_imports + rakefile <<-REGENERATE_IMPORTS +task :default + +task :regenerate do + open("deps", "w") do |f| + f << <<-CONTENT +file "deps" => :regenerate +puts "REGENERATED" + CONTENT + end +end + +import "deps" + REGENERATE_IMPORTS + + open "deps", "w" do |f| + f << <<-CONTENT +file "deps" => :regenerate +puts "INITIAL" + CONTENT + end + end + + def rakefile_multidesc + rakefile <<-MULTIDESC +task :b + +desc "A" +task :a + +desc "B" +task :b + +desc "A2" +task :a + +task :c + +desc "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +task :d + MULTIDESC + end + + def rakefile_namespace + rakefile <<-NAMESPACE +desc "copy" +task :copy do + puts "COPY" +end + +namespace "nest" do + desc "nest copy" + task :copy do + puts "NEST COPY" + end + task :xx => :copy +end + +anon_ns = namespace do + desc "anonymous copy task" + task :copy do + puts "ANON COPY" + end +end + +desc "Top level task to run the anonymous version of copy" +task :anon => anon_ns[:copy] + +namespace "very" do + namespace "nested" do + task "run" => "rake:copy" + end +end + +namespace "a" do + desc "Run task in the 'a' namespace" + task "run" do + puts "IN A" + end +end + +namespace "b" do + desc "Run task in the 'b' namespace" + task "run" => "a:run" do + puts "IN B" + end +end + +namespace "file1" do + file "xyz.rb" do + puts "XYZ1" + end +end + +namespace "file2" do + file "xyz.rb" do + puts "XYZ2" + end +end + +namespace "scopedep" do + task :prepare do + touch "scopedep.rb" + puts "PREPARE" + end + file "scopedep.rb" => [:prepare] do + puts "SCOPEDEP" + end +end + NAMESPACE + end + + def rakefile_nosearch + FileUtils.touch 'dummy' + end + + def rakefile_rakelib + FileUtils.mkdir_p 'rakelib' + + Dir.chdir 'rakelib' do + open 'test1.rb', 'w' do |io| + io << <<-TEST1 +task :default do + puts "TEST1" +end + TEST1 + end + + open 'test2.rake', 'w' do |io| + io << <<-TEST1 +task :default do + puts "TEST2" +end + TEST1 + end + end + end + + def rakefile_rbext + open 'rakefile.rb', 'w' do |io| + io << 'task :default do puts "OK" end' + end + end + + def rakefile_unittest + rakefile '# Empty Rakefile for Unit Test' + + readme = File.join 'subdir', 'README' + FileUtils.mkdir_p File.dirname readme + + FileUtils.touch readme + end + + def rakefile_verbose + rakefile <<-VERBOSE +task :standalone_verbose_true do + verbose true + sh "#{RUBY} -e '0'" +end + +task :standalone_verbose_false do + verbose false + sh "#{RUBY} -e '0'" +end + +task :inline_verbose_default do + sh "#{RUBY} -e '0'" +end + +task :inline_verbose_false do + sh "#{RUBY} -e '0'", :verbose => false +end + +task :inline_verbose_true do + sh "#{RUBY} -e '0'", :verbose => true +end + +task :block_verbose_true do + verbose(true) do + sh "#{RUBY} -e '0'" + end +end + +task :block_verbose_false do + verbose(false) do + sh "#{RUBY} -e '0'" + end +end + VERBOSE + end + + def rakefile_test_signal + rakefile <<-TEST_SIGNAL +require 'rake/testtask' + +Rake::TestTask.new(:a) do |t| + t.test_files = ['a_test.rb'] +end + +Rake::TestTask.new(:b) do |t| + t.test_files = ['b_test.rb'] +end + +task :test do + Rake::Task[:a].invoke + Rake::Task[:b].invoke +end + +task :default => :test + TEST_SIGNAL + open 'a_test.rb', 'w' do |io| + io << 'puts "ATEST"' << "\n" + io << '$stdout.flush' << "\n" + io << 'Process.kill("TERM", $$)' << "\n" + end + open 'b_test.rb', 'w' do |io| + io << 'puts "BTEST"' << "\n" + io << '$stdout.flush' << "\n" + end + end + + def rakefile_failing_test_task + rakefile <<-TEST_TASK +require 'rake/testtask' + +task :default => :test +Rake::TestTask.new(:test) do |t| + t.test_files = ['a_test.rb'] +end + TEST_TASK + open 'a_test.rb', 'w' do |io| + io << "require 'minitest/autorun'\n" + io << "class ExitTaskTest < Minitest::Test\n" + io << " def test_exit\n" + io << " assert false, 'this should fail'\n" + io << " end\n" + io << "end\n" + end + end + + def rakefile_stand_alone_filelist + open 'stand_alone_filelist.rb', 'w' do |io| + io << "require 'rake/file_list'\n" + io << "FL = Rake::FileList['*.rb']\n" + io << "puts FL\n" + end + end +end diff --git a/jni/ruby/test/rake/support/ruby_runner.rb b/jni/ruby/test/rake/support/ruby_runner.rb new file mode 100644 index 0000000..d51dd24 --- /dev/null +++ b/jni/ruby/test/rake/support/ruby_runner.rb @@ -0,0 +1,34 @@ +module RubyRunner + include FileUtils + + # Run a shell Ruby command with command line options (using the + # default test options). Output is captured in @out and @err + def ruby(*option_list) + run_ruby(@ruby_options + option_list) + end + + # Run a command line rake with the give rake options. Default + # command line ruby options are included. Output is captured in + # @out and @err + def rake(*rake_options) + run_ruby @ruby_options + [@rake_exec] + rake_options + end + + # Low level ruby command runner ... + def run_ruby(option_list) + puts "COMMAND: [#{RUBY} #{option_list.join ' '}]" if @verbose + + Open3.popen3(RUBY, *option_list) {|inn, out, err, wait| + inn.close + + @exit = wait ? wait.value : $? + @out = out.read + @err = err.read + } + + puts "OUTPUT: [#{@out}]" if @verbose + puts "ERROR: [#{@err}]" if @verbose + puts "EXIT: [#{@exit.inspect}]" if @verbose + puts "PWD: [#{Dir.pwd}]" if @verbose + end +end diff --git a/jni/ruby/test/rake/test_private_reader.rb b/jni/ruby/test/rake/test_private_reader.rb new file mode 100644 index 0000000..f86d424 --- /dev/null +++ b/jni/ruby/test/rake/test_private_reader.rb @@ -0,0 +1,42 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/private_reader' + +class TestPrivateAttrs < Rake::TestCase + + class Sample + include Rake::PrivateReader + + private_reader :reader, :a + + def initialize + @reader = :RVALUE + end + + def get_reader + reader + end + + end + + def setup + super + @sample = Sample.new + end + + def test_private_reader_is_private + assert_private do @sample.reader end + assert_private do @sample.a end + end + + def test_private_reader_returns_data + assert_equal :RVALUE, @sample.get_reader + end + + private + + def assert_private + ex = assert_raises(NoMethodError) do yield end + assert_match(/private/, ex.message) + end + +end diff --git a/jni/ruby/test/rake/test_rake.rb b/jni/ruby/test/rake/test_rake.rb new file mode 100644 index 0000000..b2a3928 --- /dev/null +++ b/jni/ruby/test/rake/test_rake.rb @@ -0,0 +1,40 @@ +require File.expand_path('../helper', __FILE__) + +class TestRake < Rake::TestCase + def test_each_dir_parent + assert_equal ['a'], alldirs('a') + assert_equal ['a/b', 'a'], alldirs('a/b') + assert_equal ['/a/b', '/a', '/'], alldirs('/a/b') + if File.dirname("c:/foo") == "c:" + # Under Unix + assert_equal ['c:/a/b', 'c:/a', 'c:'], alldirs('c:/a/b') + assert_equal ['c:a/b', 'c:a'], alldirs('c:a/b') + else + # Under Windows + assert_equal ['c:/a/b', 'c:/a', 'c:/'], alldirs('c:/a/b') + assert_equal ['c:a/b', 'c:a'], alldirs('c:a/b') + end + end + + def alldirs(fn) + result = [] + Rake.each_dir_parent(fn) { |d| result << d } + result + end + + def test_can_override_application + old_app = Rake.application + fake_app = Object.new + Rake.application = fake_app + + assert_equal fake_app, Rake.application + + ensure + Rake.application = old_app + end + + def test_original_dir_reports_current_dir + assert_equal @tempdir, Rake.original_dir + end + +end diff --git a/jni/ruby/test/rake/test_rake_application.rb b/jni/ruby/test/rake/test_rake_application.rb new file mode 100644 index 0000000..c010889 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_application.rb @@ -0,0 +1,643 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeApplication < Rake::TestCase + + def setup + super + + @app = Rake.application + @app.options.rakelib = [] + end + + def setup_command_line(*options) + ARGV.clear + options.each do |option| + ARGV << option + end + end + + def test_display_exception_details + obj = Object.new + obj.instance_eval("def #{__method__}; raise 'test'; end", "ruby") + begin + obj.__send__(__method__) + rescue => ex + end + + out, err = capture_io do + @app.display_error_message ex + end + + assert_empty out + + assert_match 'rake aborted!', err + assert_match __method__.to_s, err + end + + def test_display_exception_details_cause + skip 'Exception#cause not implemented' unless + Exception.method_defined? :cause + + begin + raise 'cause a' + rescue + begin + raise 'cause b' + rescue => ex + end + end + + out, err = capture_io do + @app.display_error_message ex + end + + assert_empty out + + assert_match 'cause a', err + assert_match 'cause b', err + end + + def test_display_exception_details_cause_loop + skip 'Exception#cause not implemented' unless + Exception.method_defined? :cause + + begin + begin + raise 'cause a' + rescue => a + begin + raise 'cause b' + rescue + raise a + end + end + rescue => ex + end + + out, err = capture_io do + @app.display_error_message ex + end + + assert_empty out + + assert_match 'cause a', err + assert_match 'cause b', err + end + + def test_display_tasks + @app.options.show_tasks = :tasks + @app.options.show_task_pattern = // + @app.last_description = "COMMENT" + @app.define_task(Rake::Task, "t") + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + assert_match(/^rake t/, out) + assert_match(/# COMMENT/, out) + end + + def test_display_tasks_with_long_comments + @app.terminal_columns = 80 + @app.options.show_tasks = :tasks + @app.options.show_task_pattern = // + numbers = "1234567890" * 8 + @app.last_description = numbers + @app.define_task(Rake::Task, "t") + + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + + assert_match(/^rake t/, out) + assert_match(/# #{numbers[0, 65]}\.\.\./, out) + end + + def test_display_tasks_with_task_name_wider_than_tty_display + @app.terminal_columns = 80 + @app.options.show_tasks = :tasks + @app.options.show_task_pattern = // + task_name = "task name" * 80 + @app.last_description = "something short" + @app.define_task(Rake::Task, task_name) + + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + + # Ensure the entire task name is output and we end up showing no description + assert_match(/rake #{task_name} # .../, out) + end + + def test_display_tasks_with_very_long_task_name_to_a_non_tty_shows_name_and_comment + @app.options.show_tasks = :tasks + @app.options.show_task_pattern = // + @app.tty_output = false + description = "something short" + task_name = "task name" * 80 + @app.last_description = "something short" + @app.define_task(Rake::Task, task_name) + + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + + # Ensure the entire task name is output and we end up showing no description + assert_match(/rake #{task_name} # #{description}/, out) + end + + def test_display_tasks_with_long_comments_to_a_non_tty_shows_entire_comment + @app.options.show_tasks = :tasks + @app.options.show_task_pattern = // + @app.tty_output = false + @app.last_description = "1234567890" * 8 + @app.define_task(Rake::Task, "t") + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + assert_match(/^rake t/, out) + assert_match(/# #{@app.last_description}/, out) + end + + def test_truncating_comments_to_a_non_tty + @app.terminal_columns = 80 + @app.options.show_tasks = :tasks + @app.options.show_task_pattern = // + @app.tty_output = false + numbers = "1234567890" * 8 + @app.last_description = numbers + @app.define_task(Rake::Task, "t") + + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + + assert_match(/^rake t/, out) + assert_match(/# #{numbers[0, 65]}\.\.\./, out) + end + + def test_describe_tasks + @app.options.show_tasks = :describe + @app.options.show_task_pattern = // + @app.last_description = "COMMENT" + @app.define_task(Rake::Task, "t") + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + assert_match(/^rake t$/, out) + assert_match(/^ {4}COMMENT$/, out) + end + + def test_show_lines + @app.options.show_tasks = :lines + @app.options.show_task_pattern = // + @app.last_description = "COMMENT" + @app.define_task(Rake::Task, "t") + @app['t'].locations << "HERE:1" + out, = capture_io do @app.instance_eval { display_tasks_and_comments } end + assert_match(/^rake t +[^:]+:\d+ *$/, out) + end + + def test_finding_rakefile + rakefile_default + + assert_match(/Rakefile/i, @app.instance_eval { have_rakefile }) + end + + def test_not_finding_rakefile + @app.instance_eval { @rakefiles = ['NEVER_FOUND'] } + assert(! @app.instance_eval do have_rakefile end) + assert_nil @app.rakefile + end + + def test_load_rakefile + rakefile_unittest + + @app.instance_eval do + handle_options + options.silent = true + load_rakefile + end + + assert_equal "rakefile", @app.rakefile.downcase + assert_equal @tempdir, Dir.pwd + end + + def test_load_rakefile_doesnt_print_rakefile_directory_from_same_dir + rakefile_unittest + + _, err = capture_io do + @app.instance_eval do + # pretend we started from the unittest dir + @original_dir = File.expand_path(".") + raw_load_rakefile + end + end + + assert_empty err + end + + def test_load_rakefile_from_subdir + rakefile_unittest + Dir.chdir 'subdir' + + @app.instance_eval do + handle_options + options.silent = true + load_rakefile + end + + assert_equal "rakefile", @app.rakefile.downcase + assert_equal @tempdir, Dir.pwd + end + + def test_load_rakefile_prints_rakefile_directory_from_subdir + rakefile_unittest + Dir.chdir 'subdir' + + app = Rake::Application.new + app.options.rakelib = [] + + _, err = capture_io do + app.instance_eval do + raw_load_rakefile + end + end + + assert_equal "(in #{@tempdir}\)\n", err + end + + def test_load_rakefile_doesnt_print_rakefile_directory_from_subdir_if_silent + rakefile_unittest + Dir.chdir 'subdir' + + _, err = capture_io do + @app.instance_eval do + handle_options + options.silent = true + raw_load_rakefile + end + end + + assert_empty err + end + + def test_load_rakefile_not_found + ARGV.clear + Dir.chdir @tempdir + ENV['RAKE_SYSTEM'] = 'not_exist' + + @app.instance_eval do + handle_options + options.silent = true + end + + + ex = assert_raises(RuntimeError) do + @app.instance_eval do + raw_load_rakefile + end + end + + assert_match(/no rakefile found/i, ex.message) + end + + def test_load_from_system_rakefile + rake_system_dir + + @app.instance_eval do + handle_options + options.silent = true + options.load_system = true + options.rakelib = [] + load_rakefile + end + + assert_equal @system_dir, @app.system_dir + assert_nil @app.rakefile + rescue SystemExit + flunk 'failed to load rakefile' + end + + def test_load_from_calculated_system_rakefile + rakefile_default + def @app.standard_system_dir + "__STD_SYS_DIR__" + end + + ENV['RAKE_SYSTEM'] = nil + + @app.instance_eval do + handle_options + options.silent = true + options.load_system = true + options.rakelib = [] + load_rakefile + end + + assert_equal "__STD_SYS_DIR__", @app.system_dir + rescue SystemExit + flunk 'failed to find system rakefile' + end + + def test_terminal_columns + old_rake_columns = ENV['RAKE_COLUMNS'] + + ENV['RAKE_COLUMNS'] = '42' + + app = Rake::Application.new + + assert_equal 42, app.terminal_columns + ensure + if old_rake_columns + ENV['RAKE_COLUMNS'].delete + else + ENV['RAKE_COLUMNS'] = old_rake_columns + end + end + + def test_windows + assert ! (@app.windows? && @app.unix?) + end + + def test_loading_imports + loader = util_loader + + @app.instance_eval do + add_loader("dummy", loader) + add_import("x.dummy") + load_imports + end + + # HACK no assertions + end + + def test_building_imported_files_on_demand + loader = util_loader + + @app.instance_eval do + intern(Rake::Task, "x.dummy").enhance do loader.make_dummy end + add_loader("dummy", loader) + add_import("x.dummy") + load_imports + end + + # HACK no assertions + end + + def test_handle_options_should_not_strip_options_from_argv + assert !@app.options.trace + + valid_option = '--trace' + setup_command_line(valid_option) + + @app.handle_options + + assert ARGV.include?(valid_option) + assert @app.options.trace + end + + def test_handle_options_trace_default_is_stderr + setup_command_line("--trace") + + @app.handle_options + + assert_equal STDERR, @app.options.trace_output + assert @app.options.trace + end + + def test_handle_options_trace_overrides_to_stdout + setup_command_line("--trace=stdout") + + @app.handle_options + + assert_equal STDOUT, @app.options.trace_output + assert @app.options.trace + end + + def test_handle_options_trace_does_not_eat_following_task_names + assert !@app.options.trace + + setup_command_line("--trace", "sometask") + + @app.handle_options + assert ARGV.include?("sometask") + assert @app.options.trace + end + + def test_good_run + ran = false + + ARGV << '--rakelib=""' + + @app.options.silent = true + + @app.instance_eval do + intern(Rake::Task, "default").enhance { ran = true } + end + + rakefile_default + + out, err = capture_io do + @app.run + end + + assert ran + assert_empty err + assert_equal "DEFAULT\n", out + end + + def test_display_task_run + ran = false + setup_command_line('-f', '-s', '--tasks', '--rakelib=""') + @app.last_description = "COMMENT" + @app.define_task(Rake::Task, "default") + out, = capture_io { @app.run } + assert @app.options.show_tasks + assert ! ran + assert_match(/rake default/, out) + assert_match(/# COMMENT/, out) + end + + def test_display_prereqs + ran = false + setup_command_line('-f', '-s', '--prereqs', '--rakelib=""') + @app.last_description = "COMMENT" + t = @app.define_task(Rake::Task, "default") + t.enhance([:a, :b]) + @app.define_task(Rake::Task, "a") + @app.define_task(Rake::Task, "b") + out, = capture_io { @app.run } + assert @app.options.show_prereqs + assert ! ran + assert_match(/rake a$/, out) + assert_match(/rake b$/, out) + assert_match(/rake default\n( *(a|b)\n){2}/m, out) + end + + def test_bad_run + @app.intern(Rake::Task, "default").enhance { fail } + setup_command_line('-f', '-s', '--rakelib=""') + _, err = capture_io { + assert_raises(SystemExit){ @app.run } + } + assert_match(/see full trace/i, err) + ensure + ARGV.clear + end + + def test_bad_run_with_trace + @app.intern(Rake::Task, "default").enhance { fail } + setup_command_line('-f', '-s', '-t') + _, err = capture_io { + assert_raises(SystemExit) { @app.run } + } + refute_match(/see full trace/i, err) + ensure + ARGV.clear + end + + def test_bad_run_with_backtrace + @app.intern(Rake::Task, "default").enhance { fail } + setup_command_line('-f', '-s', '--backtrace') + _, err = capture_io { + assert_raises(SystemExit) { + @app.run + } + } + refute_match(/see full trace/, err) + ensure + ARGV.clear + end + + CustomError = Class.new(RuntimeError) + + def test_bad_run_includes_exception_name + @app.intern(Rake::Task, "default").enhance { + raise CustomError, "intentional" + } + setup_command_line('-f', '-s') + _, err = capture_io { + assert_raises(SystemExit) { + @app.run + } + } + assert_match(/CustomError: intentional/, err) + end + + def test_rake_error_excludes_exception_name + @app.intern(Rake::Task, "default").enhance { + fail "intentional" + } + setup_command_line('-f', '-s') + _, err = capture_io { + assert_raises(SystemExit) { + @app.run + } + } + refute_match(/RuntimeError/, err) + assert_match(/intentional/, err) + end + + def cause_supported? + ex = StandardError.new + ex.respond_to?(:cause) + end + + def test_printing_original_exception_cause + custom_error = Class.new(StandardError) + @app.intern(Rake::Task, "default").enhance { + begin + raise custom_error, "Original Error" + rescue custom_error + raise custom_error, "Secondary Error" + end + } + setup_command_line('-f', '-s') + _ ,err = capture_io { + assert_raises(SystemExit) { + @app.run + } + } + if cause_supported? + assert_match(/Original Error/, err) + end + assert_match(/Secondary Error/, err) + ensure + ARGV.clear + end + + def test_run_with_bad_options + @app.intern(Rake::Task, "default").enhance { fail } + setup_command_line('-f', '-s', '--xyzzy') + assert_raises(SystemExit) { + capture_io { @app.run } + } + ensure + ARGV.clear + end + + def test_standard_exception_handling_invalid_option + out, err = capture_io do + e = assert_raises SystemExit do + @app.standard_exception_handling do + raise OptionParser::InvalidOption, 'blah' + end + end + + assert_equal 1, e.status + end + + assert_empty out + assert_equal "invalid option: blah\n", err + end + + def test_standard_exception_handling_other + out, err = capture_io do + e = assert_raises SystemExit do + @app.standard_exception_handling do + raise 'blah' + end + end + + assert_equal 1, e.status + end + + assert_empty out + assert_match "rake aborted!\n", err + assert_match "blah\n", err + end + + def test_standard_exception_handling_system_exit + out, err = capture_io do + e = assert_raises SystemExit do + @app.standard_exception_handling do + exit 0 + end + end + + assert_equal 0, e.status + end + + assert_empty out + assert_empty err + end + + def test_standard_exception_handling_system_exit_nonzero + out, err = capture_io do + e = assert_raises SystemExit do + @app.standard_exception_handling do + exit 5 + end + end + + assert_equal 5, e.status + end + + assert_empty out + assert_empty err + end + + def util_loader + loader = Object.new + + loader.instance_variable_set :@load_called, false + def loader.load arg + raise ArgumentError, arg unless arg == 'x.dummy' + @load_called = true + end + + loader.instance_variable_set :@make_dummy_called, false + def loader.make_dummy + @make_dummy_called = true + end + + loader + end + +end diff --git a/jni/ruby/test/rake/test_rake_application_options.rb b/jni/ruby/test/rake/test_rake_application_options.rb new file mode 100644 index 0000000..37adfac --- /dev/null +++ b/jni/ruby/test/rake/test_rake_application_options.rb @@ -0,0 +1,466 @@ +require File.expand_path('../helper', __FILE__) + +TESTING_REQUIRE = [] + +class TestRakeApplicationOptions < Rake::TestCase + + def setup + super + + clear_argv + Rake::FileUtilsExt.verbose_flag = false + Rake::FileUtilsExt.nowrite_flag = false + TESTING_REQUIRE.clear + end + + def teardown + clear_argv + Rake::FileUtilsExt.verbose_flag = false + Rake::FileUtilsExt.nowrite_flag = false + + super + end + + def clear_argv + ARGV.pop until ARGV.empty? + end + + def test_default_options + opts = command_line + assert_nil opts.backtrace + assert_nil opts.dryrun + assert_nil opts.ignore_system + assert_nil opts.load_system + assert_nil opts.always_multitask + assert_nil opts.nosearch + assert_equal ['rakelib'], opts.rakelib + assert_nil opts.show_prereqs + assert_nil opts.show_task_pattern + assert_nil opts.show_tasks + assert_nil opts.silent + assert_nil opts.trace + assert_nil opts.thread_pool_size + assert_equal ['rakelib'], opts.rakelib + assert ! Rake::FileUtilsExt.verbose_flag + assert ! Rake::FileUtilsExt.nowrite_flag + end + + def test_dry_run + flags('--dry-run', '-n') do |opts| + assert opts.dryrun + assert opts.trace + assert Rake::FileUtilsExt.verbose_flag + assert Rake::FileUtilsExt.nowrite_flag + end + end + + def test_describe + flags('--describe') do |opts| + assert_equal :describe, opts.show_tasks + assert_equal(//.to_s, opts.show_task_pattern.to_s) + end + end + + def test_describe_with_pattern + flags('--describe=X') do |opts| + assert_equal :describe, opts.show_tasks + assert_equal(/X/.to_s, opts.show_task_pattern.to_s) + end + end + + def test_execute + $xyzzy = 0 + flags('--execute=$xyzzy=1', '-e $xyzzy=1') do |opts| + assert_equal 1, $xyzzy + assert_equal :exit, @exit + $xyzzy = 0 + end + end + + def test_execute_and_continue + $xyzzy = 0 + flags('--execute-continue=$xyzzy=1', '-E $xyzzy=1') do |opts| + assert_equal 1, $xyzzy + refute_equal :exit, @exit + $xyzzy = 0 + end + end + + def test_execute_and_print + $xyzzy = 0 + out, = capture_io do + flags('--execute-print=$xyzzy="pugh"', '-p $xyzzy="pugh"') do |opts| + assert_equal 'pugh', $xyzzy + assert_equal :exit, @exit + $xyzzy = 0 + end + end + + assert_match(/^pugh$/, out) + end + + def test_help + out, = capture_io do + flags '--help', '-H', '-h' + end + + assert_match(/\Arake/, out) + assert_match(/\boptions\b/, out) + assert_match(/\btargets\b/, out) + assert_equal :exit, @exit + end + + def test_jobs + flags([]) do |opts| + assert_nil opts.thread_pool_size + end + flags(['--jobs', '0'], ['-j', '0']) do |opts| + assert_equal 0, opts.thread_pool_size + end + flags(['--jobs', '1'], ['-j', '1']) do |opts| + assert_equal 0, opts.thread_pool_size + end + flags(['--jobs', '4'], ['-j', '4']) do |opts| + assert_equal 3, opts.thread_pool_size + end + flags(['--jobs', 'asdas'], ['-j', 'asdas']) do |opts| + assert_equal Rake.suggested_thread_count-1, opts.thread_pool_size + end + flags('--jobs', '-j') do |opts| + assert opts.thread_pool_size > 1_000_000, "thread pool size should be huge (was #{opts.thread_pool_size})" + end + end + + def test_libdir + flags(['--libdir', 'xx'], ['-I', 'xx'], ['-Ixx']) do |opts| + $:.include?('xx') + end + ensure + $:.delete('xx') + end + + def test_multitask + flags('--multitask', '-m') do |opts| + assert_equal opts.always_multitask, true + end + end + + def test_rakefile + flags(['--rakefile', 'RF'], ['--rakefile=RF'], ['-f', 'RF'], ['-fRF']) do |opts| + assert_equal ['RF'], @app.instance_eval { @rakefiles } + end + end + + def test_rakelib + dirs = %w(A B C).join(File::PATH_SEPARATOR) + flags( + ['--rakelibdir', dirs], + ["--rakelibdir=#{dirs}"], + ['-R', dirs], + ["-R#{dirs}"]) do |opts| + assert_equal ['A', 'B', 'C'], opts.rakelib + end + end + + def test_require + $LOAD_PATH.unshift @tempdir + + open 'reqfile.rb', 'w' do |io| io << 'TESTING_REQUIRE << 1' end + open 'reqfile2.rb', 'w' do |io| io << 'TESTING_REQUIRE << 2' end + open 'reqfile3.rake', 'w' do |io| io << 'TESTING_REQUIRE << 3' end + + flags(['--require', 'reqfile'], '-rreqfile2', '-rreqfile3') + + assert_includes TESTING_REQUIRE, 1 + assert_includes TESTING_REQUIRE, 2 + assert_includes TESTING_REQUIRE, 3 + + assert_equal 3, TESTING_REQUIRE.size + ensure + $LOAD_PATH.delete @tempdir + end + + def test_missing_require + ex = assert_raises(LoadError) do + flags(['--require', 'test/missing']) do |opts| + end + end + assert_match(/such file/, ex.message) + assert_match(/test\/missing/, ex.message) + end + + def test_prereqs + flags('--prereqs', '-P') do |opts| + assert opts.show_prereqs + end + end + + def test_quiet + Rake::FileUtilsExt.verbose_flag = true + flags('--quiet', '-q') do |opts| + assert ! Rake::FileUtilsExt.verbose_flag, "verbose flag shoud be false" + assert ! opts.silent, "should not be silent" + end + end + + def test_no_search + flags('--nosearch', '--no-search', '-N') do |opts| + assert opts.nosearch + end + end + + def test_silent + Rake::FileUtilsExt.verbose_flag = true + flags('--silent', '-s') do |opts| + assert ! Rake::FileUtilsExt.verbose_flag, "verbose flag should be false" + assert opts.silent, "should be silent" + end + end + + def test_system + flags('--system', '-g') do |opts| + assert opts.load_system + end + end + + def test_no_system + flags('--no-system', '-G') do |opts| + assert opts.ignore_system + end + end + + def test_trace + flags('--trace', '-t') do |opts| + assert opts.trace, "should enable trace option" + assert opts.backtrace, "should enabled backtrace option" + assert_equal $stderr, opts.trace_output + assert Rake::FileUtilsExt.verbose_flag + assert ! Rake::FileUtilsExt.nowrite_flag + end + end + + def test_trace_with_stdout + flags('--trace=stdout', '-tstdout') do |opts| + assert opts.trace, "should enable trace option" + assert opts.backtrace, "should enabled backtrace option" + assert_equal $stdout, opts.trace_output + assert Rake::FileUtilsExt.verbose_flag + assert ! Rake::FileUtilsExt.nowrite_flag + end + end + + def test_trace_with_stderr + flags('--trace=stderr', '-tstderr') do |opts| + assert opts.trace, "should enable trace option" + assert opts.backtrace, "should enabled backtrace option" + assert_equal $stderr, opts.trace_output + assert Rake::FileUtilsExt.verbose_flag + assert ! Rake::FileUtilsExt.nowrite_flag + end + end + + def test_trace_with_error + ex = assert_raises(Rake::CommandLineOptionError) do + flags('--trace=xyzzy') do |opts| end + end + assert_match(/un(known|recognized).*\btrace\b.*xyzzy/i, ex.message) + end + + def test_trace_with_following_task_name + flags(['--trace', 'taskname'], ['-t', 'taskname']) do |opts| + assert opts.trace, "should enable trace option" + assert opts.backtrace, "should enabled backtrace option" + assert_equal $stderr, opts.trace_output + assert Rake::FileUtilsExt.verbose_flag + assert_equal ['taskname'], @app.top_level_tasks + end + end + + def test_backtrace + flags('--backtrace') do |opts| + assert opts.backtrace, "should enable backtrace option" + assert_equal $stderr, opts.trace_output + assert ! opts.trace, "should not enable trace option" + end + end + + def test_backtrace_with_stdout + flags('--backtrace=stdout') do |opts| + assert opts.backtrace, "should enable backtrace option" + assert_equal $stdout, opts.trace_output + assert ! opts.trace, "should not enable trace option" + end + end + + def test_backtrace_with_stderr + flags('--backtrace=stderr') do |opts| + assert opts.backtrace, "should enable backtrace option" + assert_equal $stderr, opts.trace_output + assert ! opts.trace, "should not enable trace option" + end + end + + def test_backtrace_with_error + ex = assert_raises(Rake::CommandLineOptionError) do + flags('--backtrace=xyzzy') do |opts| end + end + assert_match(/un(known|recognized).*\bbacktrace\b.*xyzzy/i, ex.message) + end + + def test_backtrace_with_following_task_name + flags(['--backtrace', 'taskname']) do |opts| + assert ! opts.trace, "should enable trace option" + assert opts.backtrace, "should enabled backtrace option" + assert_equal $stderr, opts.trace_output + assert_equal ['taskname'], @app.top_level_tasks + end + end + + def test_trace_rules + flags('--rules') do |opts| + assert opts.trace_rules + end + end + + def test_tasks + flags('--tasks', '-T') do |opts| + assert_equal :tasks, opts.show_tasks + assert_equal(//.to_s, opts.show_task_pattern.to_s) + assert_equal nil, opts.show_all_tasks + end + flags(['--tasks', 'xyz'], ['-Txyz']) do |opts| + assert_equal :tasks, opts.show_tasks + assert_equal(/xyz/.to_s, opts.show_task_pattern.to_s) + assert_equal nil, opts.show_all_tasks + end + flags(['--tasks', 'xyz', '--comments']) do |opts| + assert_equal :tasks, opts.show_tasks + assert_equal(/xyz/.to_s, opts.show_task_pattern.to_s) + assert_equal false, opts.show_all_tasks + end + end + + def test_where + flags('--where', '-W') do |opts| + assert_equal :lines, opts.show_tasks + assert_equal(//.to_s, opts.show_task_pattern.to_s) + assert_equal true, opts.show_all_tasks + end + flags(['--where', 'xyz'], ['-Wxyz']) do |opts| + assert_equal :lines, opts.show_tasks + assert_equal(/xyz/.to_s, opts.show_task_pattern.to_s) + assert_equal true, opts.show_all_tasks + end + flags(['--where', 'xyz', '--comments'], ['-Wxyz', '--comments']) do |opts| + assert_equal :lines, opts.show_tasks + assert_equal(/xyz/.to_s, opts.show_task_pattern.to_s) + assert_equal false, opts.show_all_tasks + end + end + + def test_no_deprecated_messages + flags('--no-deprecation-warnings', '-X') do |opts| + assert opts.ignore_deprecate + end + end + + def test_verbose + capture_io do + flags('--verbose', '-v') do |opts| + assert Rake::FileUtilsExt.verbose_flag, "verbose should be true" + assert ! opts.silent, "opts should not be silent" + end + end + end + + def test_version + out, _ = capture_io do + flags '--version', '-V' + end + + assert_match(/\bversion\b/, out) + assert_match(/\b#{RAKEVERSION}\b/, out) + assert_equal :exit, @exit + end + + def test_bad_option + _, err = capture_io do + ex = assert_raises(OptionParser::InvalidOption) do + flags('--bad-option') + end + + if ex.message =~ /^While/ # Ruby 1.9 error message + assert_match(/while parsing/i, ex.message) + else # Ruby 1.8 error message + assert_match(/(invalid|unrecognized) option/i, ex.message) + assert_match(/--bad-option/, ex.message) + end + end + + assert_equal '', err + end + + def test_task_collection + command_line("a", "b") + assert_equal ["a", "b"], @tasks.sort + end + + def test_default_task_collection + command_line() + assert_equal ["default"], @tasks + end + + def test_environment_definition + ENV.delete('TESTKEY') + command_line("TESTKEY=12") + assert_equal '12', ENV['TESTKEY'] + end + + def test_multiline_environment_definition + ENV.delete('TESTKEY') + command_line("TESTKEY=a\nb\n") + assert_equal "a\nb\n", ENV['TESTKEY'] + end + + def test_environment_and_tasks_together + ENV.delete('TESTKEY') + command_line("a", "b", "TESTKEY=12") + assert_equal ["a", "b"], @tasks.sort + assert_equal '12', ENV['TESTKEY'] + end + + def test_rake_explicit_task_library + Rake.add_rakelib 'app/task', 'other' + + libs = Rake.application.options.rakelib + + assert libs.include?("app/task") + assert libs.include?("other") + end + + private + + def flags(*sets) + sets.each do |set| + ARGV.clear + + @exit = catch(:system_exit) { command_line(*set) } + + yield(@app.options) if block_given? + end + end + + def command_line(*options) + options.each do |opt| ARGV << opt end + @app = Rake::Application.new + def @app.exit(*args) + throw :system_exit, :exit + end + @app.instance_eval do + args = handle_options + collect_command_line_tasks(args) + end + @tasks = @app.top_level_tasks + @app.options + end +end diff --git a/jni/ruby/test/rake/test_rake_backtrace.rb b/jni/ruby/test/rake/test_rake_backtrace.rb new file mode 100644 index 0000000..78eaa8d --- /dev/null +++ b/jni/ruby/test/rake/test_rake_backtrace.rb @@ -0,0 +1,119 @@ +require File.expand_path('../helper', __FILE__) +require 'open3' + +class TestBacktraceSuppression < Rake::TestCase + def test_bin_rake_suppressed + paths = ["something/bin/rake:12"] + + actual = Rake::Backtrace.collapse(paths) + + assert_equal [], actual + end + + def test_system_dir_suppressed + path = RbConfig::CONFIG['rubylibprefix'] + skip if path.nil? + path = File.expand_path path + + paths = [path + ":12"] + + actual = Rake::Backtrace.collapse(paths) + + assert_equal [], actual + end + + def test_near_system_dir_isnt_suppressed + path = RbConfig::CONFIG['rubylibprefix'] + skip if path.nil? + path = File.expand_path path + + paths = [" " + path + ":12"] + + actual = Rake::Backtrace.collapse(paths) + + assert_equal paths, actual + end +end + +class TestRakeBacktrace < Rake::TestCase + include RubyRunner + + def setup + super + + skip 'tmpdir is suppressed in backtrace' if + Rake::Backtrace::SUPPRESS_PATTERN =~ Dir.pwd + end + + def invoke(*args) + rake(*args) + @err + end + + def test_single_collapse + rakefile %q{ + task :foo do + raise "foooo!" + end + } + + lines = invoke("foo").split("\n") + + assert_equal "rake aborted!", lines[0] + assert_equal "foooo!", lines[1] + assert_something_matches %r!\A#{Regexp.quote Dir.pwd}/Rakefile:3!i, lines + assert_something_matches %r!\ATasks:!, lines + end + + def test_multi_collapse + rakefile %q{ + task :foo do + Rake.application.invoke_task(:bar) + end + task :bar do + raise "barrr!" + end + } + + lines = invoke("foo").split("\n") + + assert_equal "rake aborted!", lines[0] + assert_equal "barrr!", lines[1] + assert_something_matches %r!\A#{Regexp.quote Dir.pwd}/Rakefile:6!i, lines + assert_something_matches %r!\A#{Regexp.quote Dir.pwd}/Rakefile:3!i, lines + assert_something_matches %r!\ATasks:!, lines + end + + def test_suppress_option + rakefile %q{ + task :baz do + raise "bazzz!" + end + } + + lines = invoke("baz").split("\n") + assert_equal "rake aborted!", lines[0] + assert_equal "bazzz!", lines[1] + assert_something_matches %r!Rakefile!i, lines + + lines = invoke("--suppress-backtrace", ".ak.file", "baz").split("\n") + assert_equal "rake aborted!", lines[0] + assert_equal "bazzz!", lines[1] + refute_match %r!Rakefile!i, lines[2] + end + + private + + # Assert that the pattern matches at least one line in +lines+. + def assert_something_matches(pattern, lines) + lines.each do |ln| + if pattern =~ ln + assert_match pattern, ln + return + end + end + flunk "expected #{pattern.inspect} to match something in:\n" + + "#{lines.join("\n ")}" + end + +end diff --git a/jni/ruby/test/rake/test_rake_clean.rb b/jni/ruby/test/rake/test_rake_clean.rb new file mode 100644 index 0000000..0bce7bc --- /dev/null +++ b/jni/ruby/test/rake/test_rake_clean.rb @@ -0,0 +1,61 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/clean' + +class TestRakeClean < Rake::TestCase + def test_clean + load 'rake/clean.rb', true + + assert Rake::Task['clean'], "Should define clean" + assert Rake::Task['clobber'], "Should define clobber" + assert Rake::Task['clobber'].prerequisites.include?("clean"), + "Clobber should require clean" + end + + def test_cleanup + file_name = create_undeletable_file + + out, _ = capture_io do + Rake::Cleaner.cleanup(file_name, :verbose => false) + end + assert_match(/failed to remove/i, out) + + ensure + remove_undeletable_file + end + + def test_cleanup_ignores_missing_files + file_name = File.join(@tempdir, "missing_directory", "no_such_file") + + out, _ = capture_io do + Rake::Cleaner.cleanup(file_name, :verbose => false) + end + refute_match(/failed to remove/i, out) + end + + private + + def create_undeletable_file + dir_name = File.join(@tempdir, "deletedir") + file_name = File.join(dir_name, "deleteme") + FileUtils.mkdir(dir_name) + FileUtils.touch(file_name) + FileUtils.chmod(0, file_name) + FileUtils.chmod(0, dir_name) + begin + FileUtils.chmod(0644, file_name) + rescue + file_name + else + skip "Permission to delete files is different on thie system" + end + end + + def remove_undeletable_file + dir_name = File.join(@tempdir, "deletedir") + file_name = File.join(dir_name, "deleteme") + FileUtils.chmod(0777, dir_name) + FileUtils.chmod(0777, file_name) + Rake::Cleaner.cleanup(file_name, :verbose => false) + Rake::Cleaner.cleanup(dir_name, :verbose => false) + end +end diff --git a/jni/ruby/test/rake/test_rake_cpu_counter.rb b/jni/ruby/test/rake/test_rake_cpu_counter.rb new file mode 100644 index 0000000..87d0601 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_cpu_counter.rb @@ -0,0 +1,68 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeCpuCounter < Rake::TestCase + + def setup + super + + @cpu_counter = Rake::CpuCounter.new + end + + def test_count + num = @cpu_counter.count + skip 'cannot count CPU' if num == nil + assert_kind_of Numeric, num + assert_operator num, :>=, 1 + end + + def test_count_with_default_nil + def @cpu_counter.count; nil; end + assert_equal(8, @cpu_counter.count_with_default(8)) + assert_equal(4, @cpu_counter.count_with_default) + end + + def test_count_with_default_raise + def @cpu_counter.count; raise; end + assert_equal(8, @cpu_counter.count_with_default(8)) + assert_equal(4, @cpu_counter.count_with_default) + end + + class TestClassMethod < Rake::TestCase + def setup + super + + @klass = Class.new(Rake::CpuCounter) + end + + def test_count + @klass.class_eval do + def count; 8; end + end + assert_equal(8, @klass.count) + end + + def test_count_nil + counted = false + @klass.class_eval do + define_method(:count) do + counted = true + nil + end + end + assert_equal(4, @klass.count) + assert_equal(true, counted) + end + + def test_count_raise + counted = false + @klass.class_eval do + define_method(:count) do + counted = true + raise + end + end + assert_equal(4, @klass.count) + assert_equal(true, counted) + end + end +end diff --git a/jni/ruby/test/rake/test_rake_definitions.rb b/jni/ruby/test/rake/test_rake_definitions.rb new file mode 100644 index 0000000..ee474cb --- /dev/null +++ b/jni/ruby/test/rake/test_rake_definitions.rb @@ -0,0 +1,84 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' + +class TestRakeDefinitions < Rake::TestCase + include Rake + + EXISTINGFILE = "existing" + + def setup + super + + Task.clear + end + + def test_task + done = false + task :one => [:two] do done = true end + task :two + task :three => [:one, :two] + check_tasks(:one, :two, :three) + assert done, "Should be done" + end + + def test_file_task + done = false + file "one" => "two" do done = true end + file "two" + file "three" => ["one", "two"] + check_tasks("one", "two", "three") + assert done, "Should be done" + end + + def check_tasks(n1, n2, n3) + t = Task[n1] + assert Task === t, "Should be a Task" + assert_equal n1.to_s, t.name + assert_equal [n2.to_s], t.prerequisites.map { |n| n.to_s } + t.invoke + t2 = Task[n2] + assert_equal FileList[], t2.prerequisites + t3 = Task[n3] + assert_equal [n1.to_s, n2.to_s], t3.prerequisites.map { |n| n.to_s } + end + + def test_incremental_definitions + runs = [] + task :t1 => [:t2] do runs << "A"; 4321 end + task :t1 => [:t3] do runs << "B"; 1234 end + task :t1 => [:t3] + task :t2 + task :t3 + Task[:t1].invoke + assert_equal ["A", "B"], runs + assert_equal ["t2", "t3"], Task[:t1].prerequisites + end + + def test_missing_dependencies + task :x => ["missing"] + assert_raises(RuntimeError) { Task[:x].invoke } + end + + def test_falsey_dependencies + task :x => nil + assert_equal [], Task[:x].prerequisites + end + + def test_implicit_file_dependencies + runs = [] + create_existing_file + task :y => [EXISTINGFILE] do |t| runs << t.name end + Task[:y].invoke + assert_equal runs, ['y'] + end + + private # ---------------------------------------------------------- + + def create_existing_file + Dir.mkdir File.dirname(EXISTINGFILE) unless + File.exist?(File.dirname(EXISTINGFILE)) + open(EXISTINGFILE, "w") do |f| f.puts "HI" end unless + File.exist?(EXISTINGFILE) + end + +end diff --git a/jni/ruby/test/rake/test_rake_directory_task.rb b/jni/ruby/test/rake/test_rake_directory_task.rb new file mode 100644 index 0000000..0014d1c --- /dev/null +++ b/jni/ruby/test/rake/test_rake_directory_task.rb @@ -0,0 +1,76 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' +require 'pathname' + +class TestRakeDirectoryTask < Rake::TestCase + include Rake + + def test_directory + desc "DESC" + + directory "a/b/c" + + assert_equal FileCreationTask, Task["a"].class + assert_equal FileCreationTask, Task["a/b"].class + assert_equal FileCreationTask, Task["a/b/c"].class + + assert_nil Task["a"].comment + assert_nil Task["a/b"].comment + assert_equal "DESC", Task["a/b/c"].comment + + verbose(false) { + Task['a/b'].invoke + } + + assert File.exist?("a/b") + refute File.exist?("a/b/c") + end + + def test_directory_colon + directory "a:b" + + assert_equal FileCreationTask, Task['a:b'].class + end unless Rake::Win32.windows? + + if Rake::Win32.windows? + def test_directory_win32 + desc "WIN32 DESC" + directory 'c:/a/b/c' + assert_equal FileTask, Task['c:'].class + assert_equal FileCreationTask, Task['c:/a'].class + assert_equal FileCreationTask, Task['c:/a/b'].class + assert_equal FileCreationTask, Task['c:/a/b/c'].class + assert_nil Task['c:/'].comment + assert_equal "WIN32 DESC", Task['c:/a/b/c'].comment + assert_nil Task['c:/a/b'].comment + end + end + + def test_can_use_blocks + runlist = [] + + t1 = directory("a/b/c" => :t2) { |t| runlist << t.name } + task(:t2) { |t| runlist << t.name } + + verbose(false) { + t1.invoke + } + + assert_equal Task["a/b/c"], t1 + assert_equal FileCreationTask, Task["a/b/c"].class + assert_equal ["t2", "a/b/c"], runlist + assert File.directory?("a/b/c") + end + + def test_can_use_pathname + directory Pathname.new "a/b/c" + + assert_equal FileCreationTask, Task["a/b/c"].class + + verbose(false) { + Task['a/b/c'].invoke + } + + assert File.directory?("a/b/c") + end +end diff --git a/jni/ruby/test/rake/test_rake_dsl.rb b/jni/ruby/test/rake/test_rake_dsl.rb new file mode 100644 index 0000000..ad52f76 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_dsl.rb @@ -0,0 +1,40 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeDsl < Rake::TestCase + + def setup + super + Rake::Task.clear + end + + def test_namespace_command + namespace "n" do + task "t" + end + refute_nil Rake::Task["n:t"] + end + + def test_namespace_command_with_bad_name + ex = assert_raises(ArgumentError) do + namespace 1 do end + end + assert_match(/string/i, ex.message) + assert_match(/symbol/i, ex.message) + end + + def test_namespace_command_with_a_string_like_object + name = Object.new + def name.to_str + "bob" + end + namespace name do + task "t" + end + refute_nil Rake::Task["bob:t"] + end + + def test_no_commands_constant + assert ! defined?(Commands), "should not define Commands" + end + +end diff --git a/jni/ruby/test/rake/test_rake_early_time.rb b/jni/ruby/test/rake/test_rake_early_time.rb new file mode 100644 index 0000000..18c4dad --- /dev/null +++ b/jni/ruby/test/rake/test_rake_early_time.rb @@ -0,0 +1,31 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeEarlyTime < Rake::TestCase + def test_create + early = Rake::EarlyTime.instance + assert early <= Time.now + assert early < Time.now + assert early != Time.now + assert Time.now > early + assert Time.now >= early + assert Time.now != early + end + + def test_equality + early = Rake::EarlyTime.instance + assert_equal early, early, "two early times should be equal" + end + + def test_original_time_compare_is_not_messed_up + t1 = Time.mktime(1970, 1, 1, 0, 0, 0) + t2 = Time.now + assert t1 < t2 + assert t2 > t1 + assert t1 == t1 + assert t2 == t2 + end + + def test_to_s + assert_equal "<EARLY TIME>", Rake::EARLY.to_s + end +end diff --git a/jni/ruby/test/rake/test_rake_extension.rb b/jni/ruby/test/rake/test_rake_extension.rb new file mode 100644 index 0000000..18d55f1 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_extension.rb @@ -0,0 +1,59 @@ +require File.expand_path('../helper', __FILE__) +require 'stringio' + +class TestRakeExtension < Rake::TestCase + + module Redirect + def error_redirect + old_err = $stderr + result = StringIO.new + $stderr = result + yield + result + ensure + $stderr = old_err + end + end + + class Sample + extend Redirect + + def duplicate_method + :original + end + + OK_ERRS = error_redirect do + rake_extension("a") do + def ok_method + end + end + end + + + DUP_ERRS = error_redirect do + rake_extension("duplicate_method") do + def duplicate_method + :override + end + end + end + end + + def test_methods_actually_exist + sample = Sample.new + sample.ok_method + sample.duplicate_method + end + + def test_no_warning_when_defining_ok_method + assert_equal "", Sample::OK_ERRS.string + end + + def test_extension_complains_when_a_method_that_is_present + assert_match(/warning:/i, Sample::DUP_ERRS.string) + assert_match(/already exists/i, Sample::DUP_ERRS.string) + assert_match(/duplicate_method/i, Sample::DUP_ERRS.string) + assert_equal :original, Sample.new.duplicate_method + end + +end diff --git a/jni/ruby/test/rake/test_rake_file_creation_task.rb b/jni/ruby/test/rake/test_rake_file_creation_task.rb new file mode 100644 index 0000000..d8dcd96 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_file_creation_task.rb @@ -0,0 +1,56 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' + +###################################################################### +class TestRakeFileCreationTask < Rake::TestCase + include Rake + include Rake::DSL + + DUMMY_DIR = 'dummy_dir' + + def setup + super + + Task.clear + end + + def test_file_needed + create_dir DUMMY_DIR + fc_task = Task[DUMMY_DIR] + assert_equal DUMMY_DIR, fc_task.name + FileUtils.rm_rf fc_task.name + assert fc_task.needed?, "file should be needed" + FileUtils.mkdir fc_task.name + assert_equal nil, fc_task.prerequisites.map { |n| Task[n].timestamp }.max + assert ! fc_task.needed?, "file should not be needed" + end + + def test_directory + directory DUMMY_DIR + fc_task = Task[DUMMY_DIR] + assert_equal DUMMY_DIR, fc_task.name + assert FileCreationTask === fc_task + end + + def test_no_retriggers_on_filecreate_task + create_timed_files(OLDFILE, NEWFILE) + t1 = Rake.application.intern(FileCreationTask, OLDFILE).enhance([NEWFILE]) + t2 = Rake.application.intern(FileCreationTask, NEWFILE) + assert ! t2.needed?, "Should not need to build new file" + assert ! t1.needed?, "Should not need to rebuild old file because of new" + end + + def test_no_retriggers_on_file_task + create_timed_files(OLDFILE, NEWFILE) + t1 = Rake.application.intern(FileCreationTask, OLDFILE).enhance([NEWFILE]) + t2 = Rake.application.intern(FileCreationTask, NEWFILE) + assert ! t2.needed?, "Should not need to build new file" + assert ! t1.needed?, "Should not need to rebuild old file because of new" + end + + def test_very_early_timestamp + t1 = Rake.application.intern(FileCreationTask, OLDFILE) + assert t1.timestamp < Time.now + assert t1.timestamp < Time.now - 1_000_000 + end +end diff --git a/jni/ruby/test/rake/test_rake_file_list.rb b/jni/ruby/test/rake/test_rake_file_list.rb new file mode 100644 index 0000000..c1b4c92 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_file_list.rb @@ -0,0 +1,655 @@ +require File.expand_path('../helper', __FILE__) +require 'pathname' + +class TestRakeFileList < Rake::TestCase + FileList = Rake::FileList + + def setup + super + + FileUtils.mkdir "CVS" rescue nil + FileUtils.mkdir ".svn" rescue nil + @cdir = "cfiles" + FileUtils.mkdir @cdir rescue nil + FileUtils.touch ".dummy" + FileUtils.touch "x.bak" + FileUtils.touch "x~" + FileUtils.touch "core" + FileUtils.touch "x.c" + FileUtils.touch "xyz.c" + FileUtils.touch "abc.c" + FileUtils.touch "abc.h" + FileUtils.touch "abc.x" + FileUtils.touch "existing" + + open 'xyzzy.txt', 'w' do |io| + io.puts 'x' + io.puts 'XYZZY' + end + + end + + def test_delegating_methods_do_not_include_to_a_or_to_ary + assert ! FileList::DELEGATING_METHODS.include?("to_a"), "should not include to_a" + assert ! FileList::DELEGATING_METHODS.include?(:to_a), "should not include to_a" + assert ! FileList::DELEGATING_METHODS.include?("to_ary"), "should not include to_ary" + assert ! FileList::DELEGATING_METHODS.include?(:to_ary), "should not include to_ary" + end + + def test_create + fl = FileList.new + assert_equal 0, fl.size + end + + def test_create_with_args + fl = FileList.new("*.c", "x") + assert_equal ["abc.c", "x.c", "xyz.c", "x"].sort, + fl.sort + end + + def test_create_with_pathname + fl = FileList.new(Pathname.new("*.c")) + assert_equal ["abc.c", "x.c", "xyz.c"].sort, + fl.sort + end + + def test_create_with_block + fl = FileList.new { |f| f.include("x") } + assert_equal ["x"], fl.resolve + end + + def test_create_with_brackets + fl = FileList["*.c", "x"] + assert_equal ["abc.c", "x.c", "xyz.c", "x"].sort, + fl.sort + end + + def test_create_with_brackets_and_filelist + fl = FileList[FileList["*.c", "x"]] + assert_equal ["abc.c", "x.c", "xyz.c", "x"].sort, + fl.sort + end + + def test_include_with_another_array + fl = FileList.new.include(["x", "y", "z"]) + assert_equal ["x", "y", "z"].sort, fl.sort + end + + def test_include_with_another_filelist + fl = FileList.new.include(FileList["*.c", "x"]) + assert_equal ["abc.c", "x.c", "xyz.c", "x"].sort, + fl.sort + end + + def test_include_with_pathname + fl = FileList.new.include(Pathname.new("*.c")) + assert_equal ["abc.c", "x.c", "xyz.c"].sort, + fl.sort + end + + def test_append + fl = FileList.new + fl << "a.rb" << "b.rb" + assert_equal ['a.rb', 'b.rb'], fl + end + + def test_append_pathname + fl = FileList.new + fl << Pathname.new("a.rb") + assert_equal ['a.rb'], fl + end + + def test_add_many + fl = FileList.new + fl.include %w(a d c) + fl.include('x', 'y') + assert_equal ['a', 'd', 'c', 'x', 'y'], fl + assert_equal ['a', 'd', 'c', 'x', 'y'], fl.resolve + end + + def test_add_return + f = FileList.new + g = f << "x" + assert_equal f.object_id, g.object_id + h = f.include("y") + assert_equal f.object_id, h.object_id + end + + def test_match + fl = FileList.new + fl.include '*.c' + + assert_equal %w[abc.c x.c xyz.c], fl.sort + end + + def test_add_matching + fl = FileList.new + fl << "a.java" + fl.include '*.c' + + assert_equal %w[a.java abc.c x.c xyz.c], fl.sort + end + + def test_multiple_patterns + fl = FileList.new + fl.include('*.z', '*foo*') + + assert_equal [], fl + + fl.include('*.c', '*xist*') + assert_equal %w[x.c xyz.c abc.c existing].sort, fl.sort + end + + def test_square_bracket_pattern + fl = FileList.new + fl.include("abc.[ch]") + assert fl.size == 2 + assert fl.include?("abc.c") + assert fl.include?("abc.h") + end + + def test_curly_bracket_pattern + fl = FileList.new + fl.include("abc.{c,h}") + assert fl.size == 2 + assert fl.include?("abc.c") + assert fl.include?("abc.h") + end + + def test_reject + fl = FileList.new + fl.include %w(x.c abc.c xyz.c existing) + fl.reject! { |fn| fn =~ /^x/ } + assert_equal %w[abc.c existing], fl + end + + def test_exclude + fl = FileList['x.c', 'abc.c', 'xyz.c', 'existing'] + fl.each { |fn| touch fn, :verbose => false } + + x = fl.exclude(%r{^x.+\.}) + + assert_equal FileList, x.class + assert_equal %w(x.c abc.c existing), fl + assert_equal fl.object_id, x.object_id + + fl.exclude('*.c') + + assert_equal ['existing'], fl + + fl.exclude('existing') + + assert_equal [], fl + end + + def test_exclude_pathname + fl = FileList['x.c', 'abc.c', 'other'] + fl.each { |fn| touch fn, :verbose => false } + + fl.exclude(Pathname.new('*.c')) + + assert_equal ['other'], fl + end + + def test_excluding_via_block + fl = FileList['a.c', 'b.c', 'xyz.c'] + fl.exclude { |fn| fn.pathmap('%n') == 'xyz' } + assert fl.excluded_from_list?("xyz.c"), "Should exclude xyz.c" + assert_equal ['a.c', 'b.c'], fl + end + + def test_exclude_return_on_create + fl = FileList['*'].exclude(/.*\.[hcx]$/) + assert_equal %w[cfiles existing xyzzy.txt], fl.sort + assert_equal FileList, fl.class + end + + def test_exclude_with_string_return_on_create + fl = FileList['*'].exclude('abc.c') + assert_equal %w[abc.h abc.x cfiles existing x.c xyz.c xyzzy.txt], fl.sort + assert_equal FileList, fl.class + end + + def test_default_exclude + fl = FileList.new + fl.clear_exclude + fl.include("**/*~", "**/*.bak", "**/core") + assert fl.member?("core"), "Should include core" + assert fl.member?("x.bak"), "Should include .bak files" + end + + def test_unique + fl = FileList.new + fl << "x.c" << "a.c" << "b.rb" << "a.c" + assert_equal ['x.c', 'a.c', 'b.rb', 'a.c'], fl + fl.uniq! + assert_equal ['x.c', 'a.c', 'b.rb'], fl + end + + def test_to_string + fl = FileList.new + fl << "a.java" << "b.java" + assert_equal "a.java b.java", fl.to_s + assert_equal "a.java b.java", "#{fl}" + end + + def test_to_array + fl = FileList['a.java', 'b.java'] + assert_equal ['a.java', 'b.java'], fl.to_a + assert_equal Array, fl.to_a.class + assert_equal ['a.java', 'b.java'], fl.to_ary + assert_equal Array, fl.to_ary.class + end + + def test_to_s_pending + fl = FileList['abc.*'] + result = fl.to_s + assert_match(%r{abc\.c}, result) + assert_match(%r{abc\.h}, result) + assert_match(%r{abc\.x}, result) + assert_match(%r{(abc\..\b ?){2}}, result) + end + + def test_inspect_pending + fl = FileList['abc.*'] + result = fl.inspect + assert_match(%r{"abc\.c"}, result) + assert_match(%r{"abc\.h"}, result) + assert_match(%r{"abc\.x"}, result) + assert_match(%r|^\[("abc\..", ){2}"abc\.."\]$|, result) + end + + def test_sub + fl = FileList["*.c"] + f2 = fl.sub(/\.c$/, ".o") + assert_equal FileList, f2.class + assert_equal ["abc.o", "x.o", "xyz.o"].sort, + f2.sort + f3 = fl.gsub(/\.c$/, ".o") + assert_equal FileList, f3.class + assert_equal ["abc.o", "x.o", "xyz.o"].sort, + f3.sort + end + + def test_claim_to_be_a_kind_of_array + fl = FileList['*.c'] + assert fl.is_a?(Array) + assert fl.kind_of?(Array) + end + + def test_claim_to_be_a_kind_of_filelist + fl = FileList['*.c'] + assert fl.is_a?(FileList) + assert fl.kind_of?(FileList) + end + + def test_claim_to_be_a_filelist_instance + fl = FileList['*.c'] + assert fl.instance_of?(FileList) + end + + def test_dont_claim_to_be_an_array_instance + fl = FileList['*.c'] + assert ! fl.instance_of?(Array) + end + + def test_sub! + f = "x/a.c" + fl = FileList[f, "x/b.c"] + res = fl.sub!(/\.c$/, ".o") + assert_equal ["x/a.o", "x/b.o"].sort, fl.sort + assert_equal "x/a.c", f + assert_equal fl.object_id, res.object_id + end + + def test_sub_with_block + fl = FileList["src/org/onestepback/a.java", "src/org/onestepback/b.java"] +# The block version doesn't work the way I want it to ... +# f2 = fl.sub(%r{^src/(.*)\.java$}) { |x| "classes/" + $1 + ".class" } + f2 = fl.sub(%r{^src/(.*)\.java$}, "classes/\\1.class") + assert_equal [ + "classes/org/onestepback/a.class", + "classes/org/onestepback/b.class" + ].sort, + f2.sort + end + + def test_string_ext + assert_equal "one.net", "one.two".ext("net") + assert_equal "one.net", "one.two".ext(".net") + assert_equal "one.net", "one".ext("net") + assert_equal "one.net", "one".ext(".net") + assert_equal "one.two.net", "one.two.c".ext(".net") + assert_equal "one/two.net", "one/two.c".ext(".net") + assert_equal "one.x/two.net", "one.x/two.c".ext(".net") + assert_equal "one.x/two.net", "one.x/two".ext(".net") + assert_equal ".onerc.net", ".onerc.dot".ext("net") + assert_equal ".onerc.net", ".onerc".ext("net") + assert_equal ".a/.onerc.net", ".a/.onerc".ext("net") + assert_equal "one", "one.two".ext('') + assert_equal "one", "one.two".ext + assert_equal ".one", ".one.two".ext + assert_equal ".one", ".one".ext + assert_equal ".", ".".ext("c") + assert_equal "..", "..".ext("c") + # These only need to work in windows + if Rake::Win32.windows? + assert_equal "one.x\\two.net", "one.x\\two.c".ext(".net") + assert_equal "one.x\\two.net", "one.x\\two".ext(".net") + end + end + + def test_filelist_ext + assert_equal FileList['one.c', '.one.c'], + FileList['one.net', '.one'].ext('c') + end + + def test_gsub + fl = FileList["*.c"] + f2 = fl.gsub(/a/, "A") + assert_equal ["Abc.c", "x.c", "xyz.c"].sort, + f2.sort + end + + def test_gsub! + f = FileList["*.c"] + f.gsub!(/a/, "A") + assert_equal ["Abc.c", "x.c", "xyz.c"].sort, + f.sort + end + + def test_egrep_returns_0_if_no_matches + files = FileList['test/lib/*_test.rb'].exclude("test/lib/filelist_test.rb") + assert_equal 0, files.egrep(/XYZZY/) { } + end + + def test_egrep_with_output + files = FileList['*.txt'] + + out, = capture_io do + files.egrep(/XYZZY/) + end + + assert_equal "xyzzy.txt:2:XYZZY\n", out + end + + def test_egrep_with_block + files = FileList['*.txt'] + found = nil + + files.egrep(/XYZZY/) do |fn, ln, line| + found = [fn, ln, line] + end + + assert_equal ["xyzzy.txt", 2, "XYZZY\n"], found + end + + def test_egrep_with_error + files = FileList['*.txt'] + + _, err = capture_io do + files.egrep(/XYZZY/) do |fn, ln, line | + raise "_EGREP_FAILURE_" + end + end + + assert_equal "Error while processing 'xyzzy.txt': _EGREP_FAILURE_\n", err + end + + def test_existing + fl = FileList['abc.c', 'notthere.c'] + assert_equal ["abc.c"], fl.existing + assert fl.existing.is_a?(FileList) + end + + def test_existing! + fl = FileList['abc.c', 'notthere.c'] + result = fl.existing! + assert_equal ["abc.c"], fl + assert_equal fl.object_id, result.object_id + end + + def test_ignore_special + f = FileList['*'] + assert ! f.include?("CVS"), "Should not contain CVS" + assert ! f.include?(".svn"), "Should not contain .svn" + assert ! f.include?(".dummy"), "Should not contain dot files" + assert ! f.include?("x.bak"), "Should not contain .bak files" + assert ! f.include?("x~"), "Should not contain ~ files" + assert ! f.include?("core"), "Should not contain core files" + end + + def test_clear_ignore_patterns + f = FileList['*', '.svn'] + f.clear_exclude + assert f.include?("abc.c") + assert f.include?("xyz.c") + assert f.include?("CVS") + assert f.include?(".svn") + assert f.include?("x.bak") + assert f.include?("x~") + end + + def test_exclude_with_alternate_file_seps + fl = FileList.new + assert fl.excluded_from_list?("x/CVS/y") + assert fl.excluded_from_list?("x\\CVS\\y") + assert fl.excluded_from_list?("x/.svn/y") + assert fl.excluded_from_list?("x\\.svn\\y") + assert fl.excluded_from_list?("x/core") + assert fl.excluded_from_list?("x\\core") + end + + def test_add_default_exclude_list + fl = FileList.new + fl.exclude(/~\d+$/) + assert fl.excluded_from_list?("x/CVS/y") + assert fl.excluded_from_list?("x\\CVS\\y") + assert fl.excluded_from_list?("x/.svn/y") + assert fl.excluded_from_list?("x\\.svn\\y") + assert fl.excluded_from_list?("x/core") + assert fl.excluded_from_list?("x\\core") + assert fl.excluded_from_list?("x/abc~1") + end + + def test_basic_array_functions + f = FileList['b', 'c', 'a'] + assert_equal 'b', f.first + assert_equal 'b', f[0] + assert_equal 'a', f.last + assert_equal 'a', f[2] + assert_equal 'a', f[-1] + assert_equal ['a', 'b', 'c'], f.sort + f.sort! + assert_equal ['a', 'b', 'c'], f + end + + def test_flatten + assert_equal ['a', 'x.c', 'xyz.c', 'abc.c'].sort, + ['a', FileList['*.c']].flatten.sort + end + + def test_clone_and_dup + a = FileList['a', 'b', 'c'] + c = a.clone + d = a.dup + a << 'd' + assert_equal ['a', 'b', 'c', 'd'], a + assert_equal ['a', 'b', 'c'], c + assert_equal ['a', 'b', 'c'], d + end + + def test_dup_and_clone_replicate_taint + a = FileList['a', 'b', 'c'] + a.taint + c = a.clone + d = a.dup + assert c.tainted?, "Clone should be tainted" + assert d.tainted?, "Dup should be tainted" + end + + def test_duped_items_will_thaw + a = FileList['a', 'b', 'c'] + a.freeze + d = a.dup + d << 'more' + assert_equal ['a', 'b', 'c', 'more'], d + end + + def test_cloned_items_stay_frozen + a = FileList['a', 'b', 'c'] + a.freeze + c = a.clone + assert_raises(TypeError, RuntimeError) do + c << 'more' + end + end + + def test_array_comparisons + fl = FileList['b', 'b'] + a = ['b', 'a'] + b = ['b', 'b'] + c = ['b', 'c'] + assert_equal(1, fl <=> a) + assert_equal(0, fl <=> b) + assert_equal(-1, fl <=> c) + assert_equal(-1, a <=> fl) + assert_equal(0, b <=> fl) + assert_equal(1, c <=> fl) + end + + def test_array_equality + a = FileList['a', 'b'] + b = ['a', 'b'] + assert a == b + assert b == a +# assert a.eql?(b) +# assert b.eql?(a) + assert ! a.equal?(b) + assert ! b.equal?(a) + end + + def test_enumeration_methods + a = FileList['a', 'b'] + b = a.map { |it| it.upcase } + assert_equal ['A', 'B'], b + assert_equal FileList, b.class + + b = a.map { |it| it.upcase } + assert_equal ['A', 'B'], b + assert_equal FileList, b.class + + b = a.sort + assert_equal ['a', 'b'], b + assert_equal FileList, b.class + + b = a.sort_by { |it| it } + assert_equal ['a', 'b'], b + assert_equal FileList, b.class + + b = a.select { |it| it == 'b' } + assert_equal ['b'], b + assert_equal FileList, b.class + + b = a.select { |it| it.size == 1 } + assert_equal ['a', 'b'], b + assert_equal FileList, b.class + + b = a.reject { |it| it == 'b' } + assert_equal ['a'], b + assert_equal FileList, b.class + + b = a.grep(/./) + assert_equal ['a', 'b'], b + assert_equal FileList, b.class + + b = a.partition { |it| it == 'b' } + assert_equal [['b'], ['a']], b + assert_equal Array, b.class + assert_equal FileList, b[0].class + assert_equal FileList, b[1].class + + b = a.zip(['x', 'y']).to_a + assert_equal [['a', 'x'], ['b', 'y']], b + assert_equal Array, b.class + assert_equal Array, b[0].class + assert_equal Array, b[1].class + end + + def test_array_operators + a = ['a', 'b'] + b = ['c', 'd'] + f = FileList['x', 'y'] + g = FileList['w', 'z'] + + r = f + g + assert_equal ['x', 'y', 'w', 'z'], r + assert_equal FileList, r.class + + r = a + g + assert_equal ['a', 'b', 'w', 'z'], r + assert_equal Array, r.class + + r = f + b + assert_equal ['x', 'y', 'c', 'd'], r + assert_equal FileList, r.class + + r = FileList['w', 'x', 'y', 'z'] - f + assert_equal ['w', 'z'], r + assert_equal FileList, r.class + + r = FileList['w', 'x', 'y', 'z'] & f + assert_equal ['x', 'y'], r + assert_equal FileList, r.class + + r = f * 2 + assert_equal ['x', 'y', 'x', 'y'], r + assert_equal FileList, r.class + + r = f * ',' + assert_equal 'x,y', r + assert_equal String, r.class + + r = f | ['a', 'x'] + assert_equal ['a', 'x', 'y'].sort, r.sort + assert_equal FileList, r.class + end + + def test_other_array_returning_methods + f = FileList['a', nil, 'b'] + r = f.compact + assert_equal ['a', 'b'], r + assert_equal FileList, r.class + + f = FileList['a', 'b'] + r = f.concat(['x', 'y']) + assert_equal ['a', 'b', 'x', 'y'], r + assert_equal FileList, r.class + + f = FileList['a', ['b', 'c'], FileList['d', 'e']] + r = f.flatten + assert_equal ['a', 'b', 'c', 'd', 'e'], r + assert_equal FileList, r.class + + f = FileList['a', 'b', 'a'] + r = f.uniq + assert_equal ['a', 'b'], r + assert_equal FileList, r.class + + f = FileList['a', 'b', 'c', 'd'] + r = f.values_at(1, 3) + assert_equal ['b', 'd'], r + assert_equal FileList, r.class + end + + def test_file_utils_can_use_filelists + cfiles = FileList['*.c'] + + cp cfiles, @cdir, :verbose => false + + assert File.exist?(File.join(@cdir, 'abc.c')) + assert File.exist?(File.join(@cdir, 'xyz.c')) + assert File.exist?(File.join(@cdir, 'x.c')) + end + +end diff --git a/jni/ruby/test/rake/test_rake_file_list_path_map.rb b/jni/ruby/test/rake/test_rake_file_list_path_map.rb new file mode 100644 index 0000000..5935dc2 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_file_list_path_map.rb @@ -0,0 +1,8 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeFileListPathMap < Rake::TestCase + def test_file_list_supports_pathmap + assert_equal ['a', 'b'], FileList['dir/a.rb', 'dir/b.rb'].pathmap("%n") + end +end + diff --git a/jni/ruby/test/rake/test_rake_file_task.rb b/jni/ruby/test/rake/test_rake_file_task.rb new file mode 100644 index 0000000..a249511 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_file_task.rb @@ -0,0 +1,197 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' +require 'pathname' + +class TestRakeFileTask < Rake::TestCase + include Rake + + def setup + super + + Task.clear + @runs = Array.new + FileUtils.rm_f NEWFILE + FileUtils.rm_f OLDFILE + end + + def test_file_need + name = "dummy" + file name + + ftask = Task[name] + + assert_equal name.to_s, ftask.name + File.delete(ftask.name) rescue nil + + assert ftask.needed?, "file should be needed" + assert_equal Rake::LATE, ftask.timestamp + + open(ftask.name, "w") { |f| f.puts "HI" } + + assert_equal nil, ftask.prerequisites.map { |n| Task[n].timestamp }.max + assert ! ftask.needed?, "file should not be needed" + ensure + File.delete(ftask.name) rescue nil + end + + def test_file_times_new_depends_on_old + create_timed_files(OLDFILE, NEWFILE) + + t1 = Rake.application.intern(FileTask, NEWFILE).enhance([OLDFILE]) + t2 = Rake.application.intern(FileTask, OLDFILE) + assert ! t2.needed?, "Should not need to build old file" + assert ! t1.needed?, "Should not need to rebuild new file because of old" + end + + def test_file_times_new_depend_on_regular_task_timestamps + load_phony + + name = "dummy" + task name + + create_timed_files(NEWFILE) + + t1 = Rake.application.intern(FileTask, NEWFILE).enhance([name]) + + assert t1.needed?, "depending on non-file task uses Time.now" + + task(name => :phony) + + assert t1.needed?, "unless the non-file task has a timestamp" + end + + def test_file_times_old_depends_on_new + create_timed_files(OLDFILE, NEWFILE) + + t1 = Rake.application.intern(FileTask, OLDFILE).enhance([NEWFILE]) + t2 = Rake.application.intern(FileTask, NEWFILE) + assert ! t2.needed?, "Should not need to build new file" + preq_stamp = t1.prerequisites.map { |t| Task[t].timestamp }.max + assert_equal t2.timestamp, preq_stamp + assert t1.timestamp < preq_stamp, "T1 should be older" + assert t1.needed?, "Should need to rebuild old file because of new" + end + + def test_file_depends_on_task_depend_on_file + create_timed_files(OLDFILE, NEWFILE) + + file NEWFILE => [:obj] do |t| @runs << t.name end + task :obj => [OLDFILE] do |t| @runs << t.name end + file OLDFILE do |t| @runs << t.name end + + Task[:obj].invoke + Task[NEWFILE].invoke + assert @runs.include?(NEWFILE) + end + + def test_existing_file_depends_on_non_existing_file + create_file(OLDFILE) + delete_file(NEWFILE) + file NEWFILE do |t| @runs << t.name end + file OLDFILE => NEWFILE do |t| @runs << t.name end + + Task[OLDFILE].invoke + + assert_equal [NEWFILE, OLDFILE], @runs + end + + def test_needed_eh_build_all + create_file 'a' + + file 'a' + + a_task = Task['a'] + + refute a_task.needed? + + Rake.application.options.build_all = true + + assert a_task.needed? + ensure + delete_file 'a' + end + + def test_needed_eh_dependency + create_file 'a', Time.now + create_file 'b', Time.now - 60 + + create_file 'c', Time.now + create_file 'd', Time.now - 60 + + file 'b' => 'a' + + b_task = Task['b'] + + assert b_task.needed? + + file 'c' => 'd' + + c_task = Task['c'] + + refute c_task.needed? + ensure + delete_file 'old' + delete_file 'new' + end + + def test_needed_eh_exists + name = "dummy" + file name + + ftask = Task[name] + + assert ftask.needed? + + create_file name + + refute ftask.needed? + ensure + delete_file name + end + + def test_source_is_first_prerequisite + t = file :f => ["preqA", "preqB"] + assert_equal "preqA", t.source + end + + def test_sources_is_all_prerequisites + t = file :f => ["preqA", "preqB"] + assert_equal ["preqA", "preqB"], t.sources + end + + def test_task_can_be_pathname + name = "dummy" + file Pathname.new name + + ftask = Task[name] + + assert_equal name.to_s, ftask.name + end + + def test_prerequisite_can_be_pathname + t = file :f => Pathname.new("preq") + assert_equal "preq", t.source + end + + # I have currently disabled this test. I'm not convinced that + # deleting the file target on failure is always the proper thing to + # do. I'm willing to hear input on this topic. + def ztest_file_deletes_on_failure + task :obj + file NEWFILE => [:obj] do |t| + FileUtils.touch NEWFILE + fail "Ooops" + end + assert Task[NEWFILE] + begin + Task[NEWFILE].invoke + rescue Exception + end + assert(! File.exist?(NEWFILE), "NEWFILE should be deleted") + end + + def load_phony + load File.join(@rake_lib, "rake/phony.rb") + end + +end diff --git a/jni/ruby/test/rake/test_rake_file_utils.rb b/jni/ruby/test/rake/test_rake_file_utils.rb new file mode 100644 index 0000000..37d33dc --- /dev/null +++ b/jni/ruby/test/rake/test_rake_file_utils.rb @@ -0,0 +1,309 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' +require 'stringio' + +class TestRakeFileUtils < Rake::TestCase + + def teardown + FileUtils::LN_SUPPORTED[0] = true + RakeFileUtils.verbose_flag = Rake::FileUtilsExt::DEFAULT + + super + end + + def test_rm_one_file + create_file("a") + FileUtils.rm_rf "a" + refute File.exist?("a") + end + + def test_rm_two_files + create_file("a") + create_file("b") + FileUtils.rm_rf ["a", "b"] + refute File.exist?("a") + refute File.exist?("b") + end + + def test_rm_filelist + list = Rake::FileList.new << "a" << "b" + list.each { |fn| create_file(fn) } + FileUtils.rm_r list + refute File.exist?("a") + refute File.exist?("b") + end + + def test_ln + open("a", "w") { |f| f.puts "TEST_LN" } + + Rake::FileUtilsExt.safe_ln("a", "b", :verbose => false) + + assert_equal "TEST_LN\n", File.read('b') + end + + class BadLink + include Rake::FileUtilsExt + attr_reader :cp_args + + def initialize(klass) + @failure_class = klass + end + + def cp(*args) + @cp_args = args + end + + def ln(*args) + fail @failure_class, "ln not supported" + end + + public :safe_ln + end + + def test_safe_ln_failover_to_cp_on_standard_error + FileUtils::LN_SUPPORTED[0] = true + c = BadLink.new(StandardError) + c.safe_ln "a", "b" + assert_equal ['a', 'b'], c.cp_args + c.safe_ln "x", "y" + assert_equal ['x', 'y'], c.cp_args + end + + def test_safe_ln_failover_to_cp_on_not_implemented_error + FileUtils::LN_SUPPORTED[0] = true + c = BadLink.new(NotImplementedError) + c.safe_ln "a", "b" + assert_equal ['a', 'b'], c.cp_args + end + + def test_safe_ln_fails_on_script_error + FileUtils::LN_SUPPORTED[0] = true + c = BadLink.new(ScriptError) + assert_raises(ScriptError) do c.safe_ln "a", "b" end + end + + def test_verbose + verbose true + assert_equal true, verbose + verbose false + assert_equal false, verbose + verbose(true) { + assert_equal true, verbose + } + assert_equal false, verbose + end + + def test_nowrite + nowrite true + assert_equal true, nowrite + nowrite false + assert_equal false, nowrite + nowrite(true) { + assert_equal true, nowrite + } + assert_equal false, nowrite + end + + def test_file_utils_methods_are_available_at_top_level + create_file("a") + + capture_io do + rm_rf "a" + end + + refute File.exist?("a") + end + + def test_fileutils_methods_dont_leak + obj = Object.new + assert_raises(NoMethodError) { obj.copy } # from FileUtils + assert_raises(NoMethodError) { obj.ruby "-v" } # from RubyFileUtils + end + + def test_sh + shellcommand + + verbose(false) { sh %{#{Rake::TestCase::RUBY} shellcommand.rb} } + assert true, "should not fail" + end + + def test_sh_with_a_single_string_argument + check_expansion + + ENV['RAKE_TEST_SH'] = 'someval' + verbose(false) { + sh %{#{RUBY} check_expansion.rb #{env_var} someval} + } + end + + def test_sh_with_multiple_arguments + check_no_expansion + ENV['RAKE_TEST_SH'] = 'someval' + + verbose(false) { + sh RUBY, 'check_no_expansion.rb', env_var, 'someval' + } + end + + def test_sh_failure + shellcommand + + assert_raises(RuntimeError) { + verbose(false) { sh %{#{RUBY} shellcommand.rb 1} } + } + end + + def test_sh_special_handling + shellcommand + + count = 0 + verbose(false) { + sh(%{#{RUBY} shellcommand.rb}) do |ok, res| + assert(ok) + assert_equal 0, res.exitstatus + count += 1 + end + sh(%{#{RUBY} shellcommand.rb 1}) do |ok, res| + assert(!ok) + assert_equal 1, res.exitstatus + count += 1 + end + } + assert_equal 2, count, "Block count should be 2" + end + + def test_sh_noop + shellcommand + + verbose(false) { sh %{shellcommand.rb 1}, :noop=>true } + assert true, "should not fail" + end + + def test_sh_bad_option + shellcommand + + ex = assert_raises(ArgumentError) { + verbose(false) { sh %{shellcommand.rb}, :bad_option=>true } + } + assert_match(/bad_option/, ex.message) + end + + def test_sh_verbose + shellcommand + + _, err = capture_io do + verbose(true) { + sh %{shellcommand.rb}, :noop=>true + } + end + + assert_equal "shellcommand.rb\n", err + end + + def test_sh_verbose_false + shellcommand + + _, err = capture_io do + verbose(false) { + sh %{shellcommand.rb}, :noop=>true + } + end + + assert_equal '', err + end + + def test_sh_verbose_flag_nil + shellcommand + + RakeFileUtils.verbose_flag = nil + + assert_silent do + sh %{shellcommand.rb}, :noop=>true + end + end + + def test_ruby_with_a_single_string_argument + check_expansion + + ENV['RAKE_TEST_SH'] = 'someval' + + verbose(false) { + replace_ruby { + ruby %{check_expansion.rb #{env_var} someval} + } + } + end + + def test_ruby_with_multiple_arguments + check_no_expansion + + ENV['RAKE_TEST_SH'] = 'someval' + verbose(false) { + replace_ruby { + ruby 'check_no_expansion.rb', env_var, 'someval' + } + } + end + + def test_split_all + assert_equal ['a'], Rake::FileUtilsExt.split_all('a') + assert_equal ['..'], Rake::FileUtilsExt.split_all('..') + assert_equal ['/'], Rake::FileUtilsExt.split_all('/') + assert_equal ['a', 'b'], Rake::FileUtilsExt.split_all('a/b') + assert_equal ['/', 'a', 'b'], Rake::FileUtilsExt.split_all('/a/b') + assert_equal ['..', 'a', 'b'], Rake::FileUtilsExt.split_all('../a/b') + end + + def command(name, text) + open name, 'w', 0750 do |io| + io << text + end + end + + def check_no_expansion + command 'check_no_expansion.rb', <<-CHECK_EXPANSION +if ARGV[0] != ARGV[1] + exit 0 +else + exit 1 +end + CHECK_EXPANSION + end + + def check_expansion + command 'check_expansion.rb', <<-CHECK_EXPANSION +if ARGV[0] != ARGV[1] + exit 1 +else + exit 0 +end + CHECK_EXPANSION + end + + def replace_ruby + ruby = FileUtils::RUBY + FileUtils.send :remove_const, :RUBY + FileUtils.const_set :RUBY, RUBY + yield + ensure + FileUtils.send :remove_const, :RUBY + FileUtils.const_set:RUBY, ruby + end + + def shellcommand + command 'shellcommand.rb', <<-SHELLCOMMAND +#!/usr/bin/env ruby + +exit((ARGV[0] || "0").to_i) + SHELLCOMMAND + end + + def env_var + windows? ? '%RAKE_TEST_SH%' : '$RAKE_TEST_SH' + end + + def windows? + ! File::ALT_SEPARATOR.nil? + end + +end diff --git a/jni/ruby/test/rake/test_rake_ftp_file.rb b/jni/ruby/test/rake/test_rake_ftp_file.rb new file mode 100644 index 0000000..5749b8a --- /dev/null +++ b/jni/ruby/test/rake/test_rake_ftp_file.rb @@ -0,0 +1,74 @@ +require File.expand_path('../helper', __FILE__) +require 'date' +require 'time' +require 'rake/contrib/ftptools' + +class FakeDate + def self.today + Date.new(2003, 10, 3) + end + + def self.now + Time.local(2003, 10, 3, 12, 00, 00) + end +end + +class TestRakeFtpFile < Rake::TestCase + + def setup + super + + Rake::FtpFile.class_eval { + @date_class = FakeDate + @time_class = FakeDate + } + end + + def test_general + file = Rake::FtpFile.new( + "here", + "-rw-r--r-- 1 a279376 develop 121770 Mar 6 14:50 wiki.pl") + assert_equal "wiki.pl", file.name + assert_equal "here/wiki.pl", file.path + assert_equal "a279376", file.owner + assert_equal "develop", file.group + assert_equal 0644, file.mode + assert_equal 121_770, file.size + assert_equal Time.mktime(2003, 3, 6, 14, 50, 0, 0), file.time + assert ! file.directory? + assert ! file.symlink? + end + + def test_far_date + file = Rake::FtpFile.new( + ".", + "drwxr-xr-x 3 a279376 develop 4096 Nov 26 2001 vss") + assert_equal Time.mktime(2001, 11, 26, 0, 0, 0, 0), file.time + end + + def test_close_date + file = Rake::FtpFile.new( + ".", + "drwxr-xr-x 3 a279376 develop 4096 Nov 26 15:35 vss") + assert_equal Time.mktime(2002, 11, 26, 15, 35, 0, 0), file.time + end + + def test_directory + file = Rake::FtpFile.new( + ".", + "drwxrwxr-x 9 a279376 develop 4096 Mar 13 14:32 working") + assert file.directory? + assert !file.symlink? + end + + def test_symlink + file = Rake::FtpFile.new( + ".", + "lrwxrwxrwx 1 a279376 develop 64 Mar 26 2002 " + + "xtrac -> /home/a279376/working/ics/development/java/" + + "com/fmr/fwp/ics/xtrac") + assert_equal 'xtrac', file.name + assert file.symlink? + assert !file.directory? + end +end diff --git a/jni/ruby/test/rake/test_rake_functional.rb b/jni/ruby/test/rake/test_rake_functional.rb new file mode 100644 index 0000000..bf7ba92 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_functional.rb @@ -0,0 +1,482 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' +require 'open3' + +class TestRakeFunctional < Rake::TestCase + include RubyRunner + + def setup + super + + if @verbose + puts + puts + puts '-' * 80 + puts @__name__ + puts '-' * 80 + end + end + + def test_rake_default + rakefile_default + + rake + + assert_match(/^DEFAULT$/, @out) + end + + def test_rake_error_on_bad_task + rakefile_default + + rake '-t', 'xyz' + + assert_match(/rake aborted/, @err) + end + + def test_env_available_at_top_scope + rakefile_default + + rake "TESTTOPSCOPE=1" + + assert_match(/^TOPSCOPE$/, @out) + end + + def test_env_available_at_task_scope + rakefile_default + + rake 'TESTTASKSCOPE=1', 'task_scope' + + assert_match(/^TASKSCOPE$/, @out) + end + + def test_multi_desc + ENV['RAKE_COLUMNS'] = '80' + rakefile_multidesc + + rake "-T" + + assert_match %r{^rake a *# A / A2 *$}, @out + assert_match %r{^rake b *# B *$}, @out + refute_match %r{^rake c}, @out + assert_match %r{^rake d *# x{65}\.\.\.$}, @out + end + + def test_long_description + rakefile_multidesc + + rake "--describe" + + assert_match %r{^rake a\n *A\n *A2 *$}m, @out + assert_match %r{^rake b\n *B *$}m, @out + assert_match %r{^rake d\n *x{80}}m, @out + refute_match %r{^rake c\n}m, @out + end + + def test_proper_namespace_access + rakefile_access + + rake + + refute_match %r{^BAD:}, @out + end + + def test_rbext + rakefile_rbext + + rake "-N" + + assert_match %r{^OK$}, @out + end + + def test_system + rake_system_dir + + rake '-g', "sys1" + + assert_match %r{^SYS1}, @out + end + + def test_system_excludes_rakelib_files_too + rake_system_dir + + rake '-g', "sys1", '-T', 'extra' + + refute_match %r{extra:extra}, @out + end + + def test_by_default_rakelib_files_are_included + rake_system_dir + rakefile_extra + + rake '-T', 'extra', '--trace' + + assert_match %r{extra:extra}, @out + end + + def test_implicit_system + rake_system_dir + Dir.chdir @tempdir + + rake "sys1", "--trace" + + assert_match %r{^SYS1}, @out + end + + def test_no_system + rake_system_dir + rakefile_extra + + rake '-G', "sys1" + + assert_match %r{^Don't know how to build task}, @err # emacs wart: ' + end + + def test_nosearch_with_rakefile_uses_local_rakefile + rakefile_default + + rake "--nosearch" + + assert_match %r{^DEFAULT}, @out + end + + def test_nosearch_without_rakefile_finds_system + rakefile_nosearch + rake_system_dir + + rake "--nosearch", "sys1" + + assert_match %r{^SYS1}, @out + end + + def test_nosearch_without_rakefile_and_no_system_fails + rakefile_nosearch + ENV['RAKE_SYSTEM'] = 'not_exist' + + rake "--nosearch" + + assert_match %r{^No Rakefile found}, @err + end + + def test_invalid_command_line_options + rakefile_default + + rake "--bad-options" + + assert_match %r{invalid +option}i, @err + end + + def test_inline_verbose_default_should_show_command + rakefile_verbose + + rake "inline_verbose_default" + + assert_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_inline_verbose_true_should_show_command + rakefile_verbose + + rake "inline_verbose_true" + + assert_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_inline_verbose_false_should_not_show_command + rakefile_verbose + + rake "inline_verbose_false" + + refute_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_block_verbose_false_should_not_show_command + rakefile_verbose + + rake "block_verbose_false" + + refute_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_block_verbose_true_should_show_command + rakefile_verbose + + rake "block_verbose_true" + + assert_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_standalone_verbose_true_should_show_command + rakefile_verbose + + rake "standalone_verbose_true" + + assert_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_standalone_verbose_false_should_not_show_command + rakefile_verbose + + rake "standalone_verbose_false" + + refute_match(/#{Regexp.quote(RUBY)} -e/, @err) + end + + def test_dry_run + rakefile_default + + rake "-n", "other" + + assert_match %r{Execute \(dry run\) default}, @err + assert_match %r{Execute \(dry run\) other}, @err + refute_match %r{DEFAULT}, @out + refute_match %r{OTHER}, @out + end + + # Test for the trace/dry_run bug found by Brian Chandler + def test_dry_run_bug + rakefile_dryrun + + rake + + FileUtils.rm_f 'temp_one' + + rake "--dry-run" + + refute_match(/No such file/, @out) + end + + # Test for the trace/dry_run bug found by Brian Chandler + def test_trace_bug + rakefile_dryrun + + rake + + FileUtils.rm_f 'temp_one' + + rake "--trace" + + refute_match(/No such file/, @out) + end + + def test_imports + rakefile_imports + + rake + + assert File.exist?(File.join(@tempdir, 'dynamic_deps')), + "'dynamic_deps' file should exist" + assert_match(/^FIRST$\s+^DYNAMIC$\s+^STATIC$\s+^OTHER$/, @out) + end + + def test_regenerate_imports + rakefile_regenerate_imports + + rake + + assert_match(/^INITIAL\s+^REGENERATED$/, @out) + end + + def test_rules_chaining_to_file_task + rakefile_chains + + rake + + assert File.exist?(File.join(@tempdir, 'play.app')), + "'play.app' file should exist" + end + + def test_file_creation_task + rakefile_file_creation + + rake "prep" + rake "run" + rake "run" + + assert(@err !~ /^cp src/, "Should not recopy data") + end + + def test_dash_f_with_no_arg_foils_rakefile_lookup + rakefile_rakelib + + rake '-I', 'rakelib', '-rtest1', '-f' + + assert_match(/^TEST1$/, @out) + end + + def test_dot_rake_files_can_be_loaded_with_dash_r + rakefile_rakelib + + rake '-I', 'rakelib', '-rtest2', '-f' + + assert_empty @err + assert_match(/^TEST2$/, @out) + end + + def test_can_invoke_task_in_toplevel_namespace + rakefile_namespace + + rake "copy" + + assert_match(/^COPY$/, @out) + end + + def test_can_invoke_task_in_nested_namespace + rakefile_namespace + + rake "nest:copy" + + assert_match(/^NEST COPY$/, @out) + end + + def test_tasks_can_reference_task_in_same_namespace + rakefile_namespace + + rake "nest:xx" + + assert_match(/^NEST COPY$/m, @out) + end + + def test_tasks_can_reference_task_in_other_namespaces + rakefile_namespace + + rake "b:run" + + assert_match(/^IN A\nIN B$/m, @out) + end + + def test_anonymous_tasks_can_be_invoked_indirectly + rakefile_namespace + + rake "anon" + + assert_match(/^ANON COPY$/m, @out) + end + + def test_rake_namespace_refers_to_toplevel + rakefile_namespace + + rake "very:nested:run" + + assert_match(/^COPY$/m, @out) + end + + def test_file_task_are_not_scoped_by_namespaces + rakefile_namespace + + rake "xyz.rb" + + assert_match(/^XYZ1\nXYZ2$/m, @out) + end + + def test_file_task_dependencies_scoped_by_namespaces + rakefile_namespace + + rake "scopedep.rb" + + assert_match(/^PREPARE\nSCOPEDEP$/m, @out) + end + + def test_test_task_descriptions + rakefile_test_task + + rake "-T" + + assert_match(/custom test task description/, @out) + end + + def test_comment_before_task_acts_like_desc + rakefile_comments + + rake "-T" + + refute_match(/comment for t1/, @out) + end + + def test_comment_separated_from_task_by_blank_line_is_not_picked_up + rakefile_comments + + rake "-T" + + refute_match("t2", @out) + end + + def test_comment_after_desc_is_ignored + rakefile_comments + + rake "-T" + + assert_match("override comment for t3", @out) + end + + def test_comment_before_desc_is_ignored + rakefile_comments + + rake "-T" + + assert_match("override comment for t4", @out) + end + + def test_correct_number_of_tasks_reported + rakefile_comments + + rake "-T" + + assert_equal(2, @out.split(/\n/).grep(/t\d/).size) + end + + def test_file_list_is_requirable_separately + ruby '-rrake/file_list', '-e', 'puts Rake::FileList["a"].size' + assert_equal "1\n", @out + end + + def can_detect_signals? + system RUBY, '-e', 'Process.kill "TERM", $$' + status = $? + if @verbose + puts " SIG status = #{$?.inspect}" + puts " SIG status.respond_to?(:signaled?) = " + + "#{$?.respond_to?(:signaled?).inspect}" + puts " SIG status.signaled? = #{status.signaled?}" if + status.respond_to?(:signaled?) + end + status.respond_to?(:signaled?) && status.signaled? + end + + def test_signal_propagation_in_tests + if can_detect_signals? + rakefile_test_signal + rake + assert_match(/ATEST/, @out) + refute_match(/BTEST/, @out) + else + skip "Signal detect seems broken on this system" + end + end + + def test_failing_test_sets_exit_status + skip if uncertain_exit_status? + rakefile_failing_test_task + rake + assert @exit.exitstatus > 0, "should be non-zero" + end + + def test_stand_alone_filelist + rakefile_stand_alone_filelist + + run_ruby @ruby_options + ["stand_alone_filelist.rb"] + + assert_match(/^stand_alone_filelist\.rb$/, @out) + assert_equal 0, @exit.exitstatus unless uncertain_exit_status? + end + + private + + # We are unable to accurately verify that Rake returns a proper + # error exit status using popen3 in Ruby 1.8.7 and JRuby. This + # predicate function can be used to skip tests or assertions as + # needed. + def uncertain_exit_status? + RUBY_VERSION < "1.9" || defined?(JRUBY_VERSION) + end + +end diff --git a/jni/ruby/test/rake/test_rake_invocation_chain.rb b/jni/ruby/test/rake/test_rake_invocation_chain.rb new file mode 100644 index 0000000..0176339 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_invocation_chain.rb @@ -0,0 +1,64 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeInvocationChain < Rake::TestCase + include Rake + + def setup + super + + @empty = InvocationChain.empty + + @first_member = "A" + @second_member = "B" + @one = @empty.append(@first_member) + @two = @one.append(@second_member) + end + + def test_conj_on_invocation_chains + list = InvocationChain.empty.conj("B").conj("A") + assert_equal InvocationChain.make("A", "B"), list + assert_equal InvocationChain, list.class + end + + def test_make_on_invocation_chains + assert_equal @empty, InvocationChain.make() + assert_equal @one, InvocationChain.make(@first_member) + assert_equal @two, InvocationChain.make(@second_member, @first_member) + end + + def test_append_with_one_argument + chain = @empty.append("A") + + assert_equal 'TOP => A', chain.to_s # HACK + end + + def test_append_one_circular + ex = assert_raises RuntimeError do + @one.append(@first_member) + end + assert_match(/circular +dependency/i, ex.message) + assert_match(/A.*=>.*A/, ex.message) + end + + def test_append_two_circular + ex = assert_raises RuntimeError do + @two.append(@first_member) + end + assert_match(/A.*=>.*B.*=>.*A/, ex.message) + end + + def test_member_eh_one + assert @one.member?(@first_member) + end + + def test_member_eh_two + assert @two.member?(@first_member) + assert @two.member?(@second_member) + end + + def test_to_s_empty + assert_equal "TOP", @empty.to_s + assert_equal "TOP => A", @one.to_s + end + +end diff --git a/jni/ruby/test/rake/test_rake_late_time.rb b/jni/ruby/test/rake/test_rake_late_time.rb new file mode 100644 index 0000000..4b910a7 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_late_time.rb @@ -0,0 +1,18 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeLateTime < Rake::TestCase + def test_late_time_comparisons + late = Rake::LATE + assert_equal late, late + assert late >= Time.now + assert late > Time.now + assert late != Time.now + assert Time.now < late + assert Time.now <= late + assert Time.now != late + end + + def test_to_s + assert_equal '<LATE TIME>', Rake::LATE.to_s + end +end diff --git a/jni/ruby/test/rake/test_rake_linked_list.rb b/jni/ruby/test/rake/test_rake_linked_list.rb new file mode 100644 index 0000000..10957fb --- /dev/null +++ b/jni/ruby/test/rake/test_rake_linked_list.rb @@ -0,0 +1,84 @@ +require File.expand_path('../helper', __FILE__) + +class TestLinkedList < Rake::TestCase + include Rake + + def test_empty_list + empty = LinkedList::EMPTY + assert empty.empty?, "should be empty" + end + + def test_list_with_one_item + list = LinkedList.make(:one) + assert ! list.empty?, "should not be empty" + assert_equal :one, list.head + assert_equal LinkedList::EMPTY, list.tail + end + + def test_make_with_no_arguments + empty = LinkedList.make() + assert_equal LinkedList::EMPTY, empty + end + + def test_make_with_one_argument + list = LinkedList.make(:one) + assert ! list.empty? + assert_equal :one, list.head + assert_equal LinkedList::EMPTY, list.tail + end + + def test_make_with_two_arguments + list = LinkedList.make(:one, :two) + assert ! list.empty? + assert_equal :one, list.head + assert_equal :two, list.tail.head + assert_equal LinkedList::EMPTY, list.tail.tail + end + + def test_list_with_several_items + list = LinkedList.make(:one, :two, :three) + + assert ! list.empty?, "should not be empty" + assert_equal :one, list.head + assert_equal :two, list.tail.head + assert_equal :three, list.tail.tail.head + assert_equal LinkedList::EMPTY, list.tail.tail.tail + end + + def test_lists_are_structurally_equivalent + list = LinkedList.make(1, 2, 3) + same = LinkedList.make(1, 2, 3) + diff = LinkedList.make(1, 2, 4) + short = LinkedList.make(1, 2) + + assert_equal list, same + refute_equal list, diff + refute_equal list, short + refute_equal short, list + end + + def test_converstion_to_string + list = LinkedList.make(:one, :two, :three) + assert_equal "LL(one, two, three)", list.to_s + assert_equal "LL()", LinkedList.make().to_s + end + + def test_converstion_with_inspect + list = LinkedList.make(:one, :two, :three) + assert_equal "LL(:one, :two, :three)", list.inspect + assert_equal "LL()", LinkedList.make().inspect + end + + def test_lists_are_enumerable + list = LinkedList.make(1, 2, 3) + new_list = list.map { |item| item + 10 } + expected = [11, 12, 13] + assert_equal expected, new_list + end + + def test_conjunction + list = LinkedList.make.conj("C").conj("B").conj("A") + assert_equal LinkedList.make("A", "B", "C"), list + end + +end diff --git a/jni/ruby/test/rake/test_rake_makefile_loader.rb b/jni/ruby/test/rake/test_rake_makefile_loader.rb new file mode 100644 index 0000000..9e9265a --- /dev/null +++ b/jni/ruby/test/rake/test_rake_makefile_loader.rb @@ -0,0 +1,46 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/loaders/makefile' + +class TestRakeMakefileLoader < Rake::TestCase + include Rake + + def test_parse + Dir.chdir @tempdir + + open 'sample.mf', 'w' do |io| + io << <<-'SAMPLE_MF' +# Comments +a: a1 a2 a3 a4 +b: b1 b2 b3 \ + b4 b5 b6\ +# Mid: Comment +b7 + + a : a5 a6 a7 +c: c1 +d: d1 d2 \ + +e f : e1 f1 + +g\ 0: g1 g\ 2 g\ 3 g4 + SAMPLE_MF + end + + Task.clear + loader = Rake::MakefileLoader.new + loader.load 'sample.mf' + %w(a b c d).each do |t| + assert Task.task_defined?(t), "#{t} should be a defined task" + end + assert_equal %w(a1 a2 a3 a4 a5 a6 a7).sort, Task['a'].prerequisites.sort + assert_equal %w(b1 b2 b3 b4 b5 b6 b7).sort, Task['b'].prerequisites.sort + assert_equal %w(c1).sort, Task['c'].prerequisites.sort + assert_equal %w(d1 d2).sort, Task['d'].prerequisites.sort + assert_equal %w(e1 f1).sort, Task['e'].prerequisites.sort + assert_equal %w(e1 f1).sort, Task['f'].prerequisites.sort + assert_equal( + ["g1", "g 2", "g 3", "g4"].sort, + Task['g 0'].prerequisites.sort) + assert_equal 7, Task.tasks.size + end +end diff --git a/jni/ruby/test/rake/test_rake_multi_task.rb b/jni/ruby/test/rake/test_rake_multi_task.rb new file mode 100644 index 0000000..9f8fed6 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_multi_task.rb @@ -0,0 +1,64 @@ +require File.expand_path('../helper', __FILE__) +require 'thread' + +class TestRakeMultiTask < Rake::TestCase + include Rake + include Rake::DSL + + def setup + super + + Task.clear + @runs = Array.new + @mutex = Mutex.new + end + + def teardown + Rake.application.thread_pool.join + + super + end + + def add_run(obj) + @mutex.synchronize do + @runs << obj + end + end + + def test_running_multitasks + task :a do 3.times do |i| add_run("A#{i}"); sleep 0.01; end end + task :b do 3.times do |i| add_run("B#{i}"); sleep 0.01; end end + multitask :both => [:a, :b] + Task[:both].invoke + assert_equal 6, @runs.size + assert @runs.index("A0") < @runs.index("A1") + assert @runs.index("A1") < @runs.index("A2") + assert @runs.index("B0") < @runs.index("B1") + assert @runs.index("B1") < @runs.index("B2") + end + + def test_all_multitasks_wait_on_slow_prerequisites + task :slow do 3.times do |i| add_run("S#{i}"); sleep 0.05 end end + task :a => [:slow] do 3.times do |i| add_run("A#{i}"); sleep 0.01 end end + task :b => [:slow] do 3.times do |i| add_run("B#{i}"); sleep 0.01 end end + multitask :both => [:a, :b] + Task[:both].invoke + assert_equal 9, @runs.size + assert @runs.index("S0") < @runs.index("S1") + assert @runs.index("S1") < @runs.index("S2") + assert @runs.index("S2") < @runs.index("A0") + assert @runs.index("S2") < @runs.index("B0") + assert @runs.index("A0") < @runs.index("A1") + assert @runs.index("A1") < @runs.index("A2") + assert @runs.index("B0") < @runs.index("B1") + assert @runs.index("B1") < @runs.index("B2") + end + + def test_multitasks_with_parameters + task :a, [:arg] do |t, args| add_run(args[:arg]) end + multitask :b, [:arg] => [:a] do |t, args| add_run(args[:arg] + 'mt') end + Task[:b].invoke "b" + assert @runs[0] == "b" + assert @runs[1] == "bmt" + end +end diff --git a/jni/ruby/test/rake/test_rake_name_space.rb b/jni/ruby/test/rake/test_rake_name_space.rb new file mode 100644 index 0000000..d35e70e --- /dev/null +++ b/jni/ruby/test/rake/test_rake_name_space.rb @@ -0,0 +1,57 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeNameSpace < Rake::TestCase + + class TM + include Rake::TaskManager + end + + def test_namespace_creation + mgr = TM.new + ns = Rake::NameSpace.new(mgr, []) + refute_nil ns + end + + def test_namespace_lookup + mgr = TM.new + ns = mgr.in_namespace("n") do + mgr.define_task(Rake::Task, "t") + end + + refute_nil ns["t"] + assert_equal mgr["n:t"], ns["t"] + end + + def test_namespace_reports_tasks_it_owns + mgr = TM.new + nns = nil + ns = mgr.in_namespace("n") do + mgr.define_task(Rake::Task, :x) + mgr.define_task(Rake::Task, :y) + nns = mgr.in_namespace("nn") do + mgr.define_task(Rake::Task, :z) + end + end + mgr.in_namespace("m") do + mgr.define_task(Rake::Task, :x) + end + + assert_equal ["n:nn:z", "n:x", "n:y"], + ns.tasks.map { |tsk| tsk.name } + assert_equal ["n:nn:z"], nns.tasks.map { |t| t.name } + end + + def test_scope + mgr = TM.new + + scope = Rake::LinkedList.new 'b' + scope = scope.conj 'a' + + ns = Rake::NameSpace.new mgr, scope + + assert_equal scope, ns.scope + + refute_same scope, ns.scope + end + +end diff --git a/jni/ruby/test/rake/test_rake_package_task.rb b/jni/ruby/test/rake/test_rake_package_task.rb new file mode 100644 index 0000000..87cb57c --- /dev/null +++ b/jni/ruby/test/rake/test_rake_package_task.rb @@ -0,0 +1,79 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/packagetask' + +class TestRakePackageTask < Rake::TestCase + + def test_initialize + touch 'install.rb' + touch 'a.c' + touch 'b.c' + mkdir 'CVS' + touch 'a.rb~' + + pkg = Rake::PackageTask.new("pkgr", "1.2.3") { |p| + p.package_files << "install.rb" + p.package_files.include '*.c' + p.package_files.exclude(/\bCVS\b/) + p.package_files.exclude(/~$/) + p.package_dir = 'pkg' + p.need_tar = true + p.need_tar_gz = true + p.need_tar_bz2 = true + p.need_zip = true + } + + assert_equal "pkg", pkg.package_dir + + assert_includes pkg.package_files, 'a.c' + + assert_equal 'pkgr', pkg.name + assert_equal '1.2.3', pkg.version + assert Rake::Task[:package] + assert Rake::Task['pkg/pkgr-1.2.3.tgz'] + assert Rake::Task['pkg/pkgr-1.2.3.tar.gz'] + assert Rake::Task['pkg/pkgr-1.2.3.tar.bz2'] + assert Rake::Task['pkg/pkgr-1.2.3.zip'] + assert Rake::Task['pkg/pkgr-1.2.3'] + assert Rake::Task[:clobber_package] + assert Rake::Task[:repackage] + end + + def test_initialize_no_version + e = assert_raises RuntimeError do + Rake::PackageTask.new 'pkgr' + end + + assert_equal 'Version required (or :noversion)', e.message + end + + def test_initialize_noversion + pkg = Rake::PackageTask.new 'pkgr', :noversion + + assert_equal 'pkg', pkg.package_dir + assert_equal 'pkgr', pkg.name + assert_equal nil, pkg.version + end + + def test_clone + pkg = Rake::PackageTask.new("x", :noversion) + p2 = pkg.clone + pkg.package_files << "y" + p2.package_files << "x" + assert_equal ["y"], pkg.package_files + assert_equal ["x"], p2.package_files + end + + def test_package_name + pkg = Rake::PackageTask.new 'a', '1' + + assert_equal 'a-1', pkg.package_name + end + + def test_package_name_noversion + pkg = Rake::PackageTask.new 'a', :noversion + + assert_equal 'a', pkg.package_name + end + +end + diff --git a/jni/ruby/test/rake/test_rake_path_map.rb b/jni/ruby/test/rake/test_rake_path_map.rb new file mode 100644 index 0000000..038ba1f --- /dev/null +++ b/jni/ruby/test/rake/test_rake_path_map.rb @@ -0,0 +1,168 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakePathMap < Rake::TestCase + + def test_returns_self_with_no_args + assert_equal "abc.rb", "abc.rb".pathmap + end + + def test_s_returns_file_separator + sep = File::ALT_SEPARATOR || File::SEPARATOR + assert_equal sep, "abc.rb".pathmap("%s") + assert_equal sep, "".pathmap("%s") + assert_equal "a#{sep}b", "a/b".pathmap("%d%s%f") + end + + def test_f_returns_basename + assert_equal "abc.rb", "abc.rb".pathmap("%f") + assert_equal "abc.rb", "this/is/a/dir/abc.rb".pathmap("%f") + assert_equal "abc.rb", "/this/is/a/dir/abc.rb".pathmap("%f") + end + + def test_n_returns_basename_without_extension + assert_equal "abc", "abc.rb".pathmap("%n") + assert_equal "abc", "abc".pathmap("%n") + assert_equal "abc", "this/is/a/dir/abc.rb".pathmap("%n") + assert_equal "abc", "/this/is/a/dir/abc.rb".pathmap("%n") + assert_equal "abc", "/this/is/a/dir/abc".pathmap("%n") + end + + def test_d_returns_dirname + assert_equal ".", "abc.rb".pathmap("%d") + assert_equal "/", "/abc".pathmap("%d") + assert_equal "this/is/a/dir", "this/is/a/dir/abc.rb".pathmap("%d") + assert_equal "/this/is/a/dir", "/this/is/a/dir/abc.rb".pathmap("%d") + end + + def test_9d_returns_partial_dirname + assert_equal "this/is", "this/is/a/dir/abc.rb".pathmap("%2d") + assert_equal "this", "this/is/a/dir/abc.rb".pathmap("%1d") + assert_equal ".", "this/is/a/dir/abc.rb".pathmap("%0d") + assert_equal "dir", "this/is/a/dir/abc.rb".pathmap("%-1d") + assert_equal "a/dir", "this/is/a/dir/abc.rb".pathmap("%-2d") + assert_equal "this/is/a/dir", "this/is/a/dir/abc.rb".pathmap("%100d") + assert_equal "this/is/a/dir", "this/is/a/dir/abc.rb".pathmap("%-100d") + end + + def test_x_returns_extension + assert_equal "", "abc".pathmap("%x") + assert_equal ".rb", "abc.rb".pathmap("%x") + assert_equal ".rb", "abc.xyz.rb".pathmap("%x") + assert_equal "", ".depends".pathmap("%x") + assert_equal "", "dir/.depends".pathmap("%x") + end + + def test_x_returns_everything_but_extension + assert_equal "abc", "abc".pathmap("%X") + assert_equal "abc", "abc.rb".pathmap("%X") + assert_equal "abc.xyz", "abc.xyz.rb".pathmap("%X") + assert_equal "ab.xyz", "ab.xyz.rb".pathmap("%X") + assert_equal "a.xyz", "a.xyz.rb".pathmap("%X") + assert_equal "abc", "abc.rb".pathmap("%X") + assert_equal "ab", "ab.rb".pathmap("%X") + assert_equal "a", "a.rb".pathmap("%X") + assert_equal ".depends", ".depends".pathmap("%X") + assert_equal "a/dir/.depends", "a/dir/.depends".pathmap("%X") + assert_equal "/.depends", "/.depends".pathmap("%X") + end + + def test_p_returns_entire_pathname + assert_equal "abc.rb", "abc.rb".pathmap("%p") + assert_equal "this/is/a/dir/abc.rb", "this/is/a/dir/abc.rb".pathmap("%p") + assert_equal "/this/is/a/dir/abc.rb", "/this/is/a/dir/abc.rb".pathmap("%p") + end + + def test_dash_returns_empty_string + assert_equal "", "abc.rb".pathmap("%-") + assert_equal "abc.rb", "abc.rb".pathmap("%X%-%x") + end + + def test_percent_percent_returns_percent + assert_equal "a%b", "".pathmap("a%%b") + end + + def test_undefined_percent_causes_error + assert_raises(ArgumentError) { + "dir/abc.rb".pathmap("%z") + } + end + + def test_pattern_returns_substitutions + assert_equal "bin/org/osb", + "src/org/osb/Xyz.java".pathmap("%{src,bin}d") + end + + def test_pattern_can_use_backreferences + assert_equal "dir/hi/is", "dir/this/is".pathmap("%{t(hi)s,\\1}p") + end + + def test_pattern_with_star_replacement_string_uses_block + assert_equal "src/ORG/osb", + "src/org/osb/Xyz.java".pathmap("%{/org,*}d") { |d| d.upcase } + assert_equal "Xyz.java", + "src/org/osb/Xyz.java".pathmap("%{.*,*}f") { |f| f.capitalize } + end + + def test_pattern_with_no_replacement_nor_block_substitutes_empty_string + assert_equal "bc.rb", "abc.rb".pathmap("%{a}f") + end + + def test_pattern_works_with_certain_valid_operators + assert_equal "dir/xbc.rb", "dir/abc.rb".pathmap("%{a,x}p") + assert_equal "d1r", "dir/abc.rb".pathmap("%{i,1}d") + assert_equal "xbc.rb", "dir/abc.rb".pathmap("%{a,x}f") + assert_equal ".Rb", "dir/abc.rb".pathmap("%{r,R}x") + assert_equal "xbc", "dir/abc.rb".pathmap("%{a,x}n") + end + + def test_multiple_patterns + assert_equal "this/is/b/directory/abc.rb", + "this/is/a/dir/abc.rb".pathmap("%{a,b;dir,\\0ectory}p") + end + + def test_partial_directory_selection_works_with_patterns + assert_equal "this/is/a/long", + "this/is/a/really/long/path/ok.rb".pathmap("%{/really/,/}5d") + end + + def test_pattern_with_invalid_operator + ex = assert_raises(ArgumentError) do + "abc.xyz".pathmap("%{src,bin}z") + end + assert_match(/unknown.*pathmap.*spec.*z/i, ex.message) + end + + def test_works_with_windows_separators + if File::ALT_SEPARATOR + assert_equal "abc", 'dir\abc.rb'.pathmap("%n") + assert_equal 'this\is\a\dir', + 'this\is\a\dir\abc.rb'.pathmap("%d") + end + end + + def test_complex_patterns + sep = "".pathmap("%s") + assert_equal( + "dir/abc.rb", + "dir/abc.rb".pathmap("%d/%n%x")) + assert_equal( + "./abc.rb", + "abc.rb".pathmap("%d/%n%x")) + assert_equal( + "Your file extension is '.rb'", + "dir/abc.rb".pathmap("Your file extension is '%x'")) + assert_equal( + "bin/org/onstepback/proj/A.class", + "src/org/onstepback/proj/A.java".pathmap("%{src,bin}d/%n.class")) + assert_equal( + "src_work/bin/org/onstepback/proj/A.class", + "src_work/src/org/onstepback/proj/A.java". + pathmap('%{\bsrc\b,bin}X.class')) + assert_equal( + ".depends.bak", + ".depends".pathmap("%X.bak")) + assert_equal( + "d#{sep}a/b/c#{sep}file.txt", + "a/b/c/d/file.txt".pathmap("%-1d%s%3d%s%f")) + end +end diff --git a/jni/ruby/test/rake/test_rake_path_map_explode.rb b/jni/ruby/test/rake/test_rake_path_map_explode.rb new file mode 100644 index 0000000..a79235e --- /dev/null +++ b/jni/ruby/test/rake/test_rake_path_map_explode.rb @@ -0,0 +1,34 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakePathMapExplode < Rake::TestCase + def setup + super + + String.class_eval { public :pathmap_explode } + end + + def teardown + String.class_eval { protected :pathmap_explode } + + super + end + + def test_explode + assert_equal ['a'], 'a'.pathmap_explode + assert_equal ['a', 'b'], 'a/b'.pathmap_explode + assert_equal ['a', 'b', 'c'], 'a/b/c'.pathmap_explode + assert_equal ['/', 'a'], '/a'.pathmap_explode + assert_equal ['/', 'a', 'b'], '/a/b'.pathmap_explode + assert_equal ['/', 'a', 'b', 'c'], '/a/b/c'.pathmap_explode + + if File::ALT_SEPARATOR + assert_equal ['c:.', 'a'], 'c:a'.pathmap_explode + assert_equal ['c:.', 'a', 'b'], 'c:a/b'.pathmap_explode + assert_equal ['c:.', 'a', 'b', 'c'], 'c:a/b/c'.pathmap_explode + assert_equal ['c:/', 'a'], 'c:/a'.pathmap_explode + assert_equal ['c:/', 'a', 'b'], 'c:/a/b'.pathmap_explode + assert_equal ['c:/', 'a', 'b', 'c'], 'c:/a/b/c'.pathmap_explode + end + end +end + diff --git a/jni/ruby/test/rake/test_rake_path_map_partial.rb b/jni/ruby/test/rake/test_rake_path_map_partial.rb new file mode 100644 index 0000000..566e681 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_path_map_partial.rb @@ -0,0 +1,18 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakePathMapPartial < Rake::TestCase + def test_pathmap_partial + @path = "1/2/file" + def @path.call(n) + pathmap_partial(n) + end + assert_equal("1", @path.call(1)) + assert_equal("1/2", @path.call(2)) + assert_equal("1/2", @path.call(3)) + assert_equal(".", @path.call(0)) + assert_equal("2", @path.call(-1)) + assert_equal("1/2", @path.call(-2)) + assert_equal("1/2", @path.call(-3)) + end +end + diff --git a/jni/ruby/test/rake/test_rake_pathname_extensions.rb b/jni/ruby/test/rake/test_rake_pathname_extensions.rb new file mode 100644 index 0000000..7da702d --- /dev/null +++ b/jni/ruby/test/rake/test_rake_pathname_extensions.rb @@ -0,0 +1,15 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/ext/pathname' + +class TestRakePathnameExtensions < Rake::TestCase + def test_ext_works_on_pathnames + pathname = Pathname.new("abc.foo") + assert_equal Pathname.new("abc.bar"), pathname.ext("bar") + end + + def test_path_map_works_on_pathnames + pathname = Pathname.new("this/is/a/dir/abc.rb") + assert_equal Pathname.new("abc.rb"), pathname.pathmap("%f") + assert_equal Pathname.new("this/is/a/dir"), pathname.pathmap("%d") + end +end diff --git a/jni/ruby/test/rake/test_rake_pseudo_status.rb b/jni/ruby/test/rake/test_rake_pseudo_status.rb new file mode 100644 index 0000000..51b3fef --- /dev/null +++ b/jni/ruby/test/rake/test_rake_pseudo_status.rb @@ -0,0 +1,21 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakePseudoStatus < Rake::TestCase + def test_with_zero_exit_status + s = Rake::PseudoStatus.new + assert_equal 0, s.exitstatus + assert_equal 0, s.to_i + assert_equal 0, s >> 8 + refute s.stopped? + assert s.exited? + end + + def test_with_99_exit_status + s = Rake::PseudoStatus.new(99) + assert_equal 99, s.exitstatus + assert_equal 25344, s.to_i + assert_equal 99, s >> 8 + refute s.stopped? + assert s.exited? + end +end diff --git a/jni/ruby/test/rake/test_rake_rake_test_loader.rb b/jni/ruby/test/rake/test_rake_rake_test_loader.rb new file mode 100644 index 0000000..0485c4c --- /dev/null +++ b/jni/ruby/test/rake/test_rake_rake_test_loader.rb @@ -0,0 +1,20 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeRakeTestLoader < Rake::TestCase + + def test_pattern + orig_loaded_features = $:.dup + FileUtils.touch 'foo.rb' + FileUtils.touch 'test_a.rb' + FileUtils.touch 'test_b.rb' + + ARGV.replace %w[foo.rb test_*.rb -v] + + load File.join(@rake_lib, 'rake/rake_test_loader.rb') + + assert_equal %w[-v], ARGV + ensure + $:.replace orig_loaded_features + end + +end diff --git a/jni/ruby/test/rake/test_rake_reduce_compat.rb b/jni/ruby/test/rake/test_rake_reduce_compat.rb new file mode 100644 index 0000000..d295266 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_reduce_compat.rb @@ -0,0 +1,26 @@ +require File.expand_path('../helper', __FILE__) +require 'open3' + +class TestRakeReduceCompat < Rake::TestCase + include RubyRunner + + def invoke_normal(task_name) + rake task_name.to_s + @out + end + + def test_no_deprecated_dsl + rakefile %q{ + task :check_task do + Module.new { p defined?(task) } + end + + task :check_file do + Module.new { p defined?(file) } + end + } + + assert_equal "nil", invoke_normal(:check_task).chomp + assert_equal "nil", invoke_normal(:check_file).chomp + end +end diff --git a/jni/ruby/test/rake/test_rake_require.rb b/jni/ruby/test/rake/test_rake_require.rb new file mode 100644 index 0000000..d229edb --- /dev/null +++ b/jni/ruby/test/rake/test_rake_require.rb @@ -0,0 +1,40 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeRequire < Rake::TestCase + + def test_can_load_rake_library + rakefile_rakelib + app = Rake::Application.new + + assert app.instance_eval { + rake_require("test2", ['rakelib'], []) + } + end + + def test_wont_reload_rake_library + rakefile_rakelib + app = Rake::Application.new + + paths = ['rakelib'] + loaded_files = [] + app.rake_require("test2", paths, loaded_files) + + assert ! app.instance_eval { + rake_require("test2", paths, loaded_files) + } + end + + def test_throws_error_if_library_not_found + rakefile_rakelib + + app = Rake::Application.new + ex = assert_raises(LoadError) { + assert app.instance_eval { + rake_require("testx", ['rakelib'], []) + } + } + assert_match(/(can *not|can't)\s+find/i, ex.message) + assert_match(/testx/, ex.message) + end +end + diff --git a/jni/ruby/test/rake/test_rake_rules.rb b/jni/ruby/test/rake/test_rake_rules.rb new file mode 100644 index 0000000..ece75e5 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_rules.rb @@ -0,0 +1,388 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' + +class TestRakeRules < Rake::TestCase + include Rake + + SRCFILE = "abc.c" + SRCFILE2 = "xyz.c" + FTNFILE = "abc.f" + OBJFILE = "abc.o" + FOOFILE = "foo" + DOTFOOFILE = ".foo" + + def setup + super + + Task.clear + @runs = [] + end + + def test_multiple_rules1 + create_file(FTNFILE) + delete_file(SRCFILE) + delete_file(OBJFILE) + rule(/\.o$/ => ['.c']) do @runs << :C end + rule(/\.o$/ => ['.f']) do @runs << :F end + t = Task[OBJFILE] + t.invoke + Task[OBJFILE].invoke + assert_equal [:F], @runs + end + + def test_multiple_rules2 + create_file(FTNFILE) + delete_file(SRCFILE) + delete_file(OBJFILE) + rule(/\.o$/ => ['.f']) do @runs << :F end + rule(/\.o$/ => ['.c']) do @runs << :C end + Task[OBJFILE].invoke + assert_equal [:F], @runs + end + + def test_create_with_source + create_file(SRCFILE) + rule(/\.o$/ => ['.c']) do |t| + @runs << t.name + assert_equal OBJFILE, t.name + assert_equal SRCFILE, t.source + end + Task[OBJFILE].invoke + assert_equal [OBJFILE], @runs + end + + def test_single_dependent + create_file(SRCFILE) + rule(/\.o$/ => '.c') do |t| + @runs << t.name + end + Task[OBJFILE].invoke + assert_equal [OBJFILE], @runs + end + + def test_rule_can_be_created_by_string + create_file(SRCFILE) + rule '.o' => ['.c'] do |t| + @runs << t.name + end + Task[OBJFILE].invoke + assert_equal [OBJFILE], @runs + end + + def test_rule_prereqs_can_be_created_by_string + create_file(SRCFILE) + rule '.o' => '.c' do |t| + @runs << t.name + end + Task[OBJFILE].invoke + assert_equal [OBJFILE], @runs + end + + def test_plain_strings_as_dependents_refer_to_files + create_file(SRCFILE) + rule '.o' => SRCFILE do |t| + @runs << t.name + end + Task[OBJFILE].invoke + assert_equal [OBJFILE], @runs + end + + def test_file_names_beginning_with_dot_can_be_tricked_into_referring_to_file + verbose(false) do + create_file('.foo') + rule '.o' => "./.foo" do |t| + @runs << t.name + end + Task[OBJFILE].invoke + assert_equal [OBJFILE], @runs + end + end + + def test_file_names_beginning_with_dot_can_be_wrapped_in_lambda + verbose(false) do + + create_file(".foo") + rule '.o' => lambda { ".foo" } do |t| + @runs << "#{t.name} - #{t.source}" + end + Task[OBJFILE].invoke + assert_equal ["#{OBJFILE} - .foo"], @runs + end + end + + def test_file_names_containing_percent_can_be_wrapped_in_lambda + verbose(false) do + create_file("foo%x") + rule '.o' => lambda { "foo%x" } do |t| + @runs << "#{t.name} - #{t.source}" + end + Task[OBJFILE].invoke + assert_equal ["#{OBJFILE} - foo%x"], @runs + end + end + + def test_non_extension_rule_name_refers_to_file + verbose(false) do + create_file("abc.c") + rule "abc" => '.c' do |t| + @runs << t.name + end + Task["abc"].invoke + assert_equal ["abc"], @runs + end + end + + def test_pathmap_automatically_applies_to_name + verbose(false) do + create_file("zzabc.c") + rule ".o" => 'zz%{x,a}n.c' do |t| + @runs << "#{t.name} - #{t.source}" + end + Task["xbc.o"].invoke + assert_equal ["xbc.o - zzabc.c"], @runs + end + end + + def test_plain_strings_are_just_filenames + verbose(false) do + create_file("plainname") + rule ".o" => 'plainname' do |t| + @runs << "#{t.name} - #{t.source}" + end + Task["xbc.o"].invoke + assert_equal ["xbc.o - plainname"], @runs + end + end + + def test_rule_runs_when_explicit_task_has_no_actions + create_file(SRCFILE) + create_file(SRCFILE2) + delete_file(OBJFILE) + rule '.o' => '.c' do |t| + @runs << t.source + end + file OBJFILE => [SRCFILE2] + Task[OBJFILE].invoke + assert_equal [SRCFILE], @runs + end + + def test_close_matches_on_name_do_not_trigger_rule + create_file("x.c") + rule '.o' => ['.c'] do |t| + @runs << t.name + end + assert_raises(RuntimeError) { Task['x.obj'].invoke } + assert_raises(RuntimeError) { Task['x.xyo'].invoke } + end + + def test_rule_rebuilds_obj_when_source_is_newer + create_timed_files(OBJFILE, SRCFILE) + rule(/\.o$/ => ['.c']) do + @runs << :RULE + end + Task[OBJFILE].invoke + assert_equal [:RULE], @runs + end + + def test_rule_with_two_sources_runs_if_both_sources_are_present + create_timed_files(OBJFILE, SRCFILE, SRCFILE2) + rule OBJFILE => [lambda { SRCFILE }, lambda { SRCFILE2 }] do + @runs << :RULE + end + Task[OBJFILE].invoke + assert_equal [:RULE], @runs + end + + def test_rule_with_two_sources_but_one_missing_does_not_run + create_timed_files(OBJFILE, SRCFILE) + delete_file(SRCFILE2) + rule OBJFILE => [lambda { SRCFILE }, lambda { SRCFILE2 }] do + @runs << :RULE + end + Task[OBJFILE].invoke + assert_equal [], @runs + end + + def test_rule_with_two_sources_builds_both_sources + task 'x.aa' + task 'x.bb' + rule '.a' => '.aa' do + @runs << "A" + end + rule '.b' => '.bb' do + @runs << "B" + end + rule ".c" => ['.a', '.b'] do + @runs << "C" + end + Task["x.c"].invoke + assert_equal ["A", "B", "C"], @runs.sort + end + + def test_second_rule_runs_when_first_rule_doesnt + create_timed_files(OBJFILE, SRCFILE) + delete_file(SRCFILE2) + rule OBJFILE => [lambda { SRCFILE }, lambda { SRCFILE2 }] do + @runs << :RULE1 + end + rule OBJFILE => [lambda { SRCFILE }] do + @runs << :RULE2 + end + Task[OBJFILE].invoke + assert_equal [:RULE2], @runs + end + + def test_second_rule_doest_run_if_first_triggers + create_timed_files(OBJFILE, SRCFILE, SRCFILE2) + rule OBJFILE => [lambda { SRCFILE }, lambda { SRCFILE2 }] do + @runs << :RULE1 + end + rule OBJFILE => [lambda { SRCFILE }] do + @runs << :RULE2 + end + Task[OBJFILE].invoke + assert_equal [:RULE1], @runs + end + + def test_second_rule_doest_run_if_first_triggers_with_reversed_rules + create_timed_files(OBJFILE, SRCFILE, SRCFILE2) + rule OBJFILE => [lambda { SRCFILE }] do + @runs << :RULE1 + end + rule OBJFILE => [lambda { SRCFILE }, lambda { SRCFILE2 }] do + @runs << :RULE2 + end + Task[OBJFILE].invoke + assert_equal [:RULE1], @runs + end + + def test_rule_with_proc_dependent_will_trigger + mkdir_p("src/jw") + create_file("src/jw/X.java") + rule %r(classes/.*\.class) => [ + proc { |fn| fn.pathmap("%{classes,src}d/%n.java") } + ] do |task| + assert_equal task.name, 'classes/jw/X.class' + assert_equal task.source, 'src/jw/X.java' + @runs << :RULE + end + Task['classes/jw/X.class'].invoke + assert_equal [:RULE], @runs + ensure + rm_r("src", :verbose=>false) rescue nil + end + + def test_proc_returning_lists_are_flattened_into_prereqs + ran = false + mkdir_p("flatten") + create_file("flatten/a.txt") + task 'flatten/b.data' do |t| + ran = true + touch t.name, :verbose => false + end + rule '.html' => + proc { |fn| + [ + fn.ext("txt"), + "flatten/b.data" + ] + } do |task| + end + Task['flatten/a.html'].invoke + assert ran, "Should have triggered flattened dependency" + ensure + rm_r("flatten", :verbose=>false) rescue nil + end + + def test_recursive_rules_will_work_as_long_as_they_terminate + actions = [] + create_file("abc.xml") + rule '.y' => '.xml' do actions << 'y' end + rule '.c' => '.y' do actions << 'c'end + rule '.o' => '.c' do actions << 'o'end + rule '.exe' => '.o' do actions << 'exe'end + Task["abc.exe"].invoke + assert_equal ['y', 'c', 'o', 'exe'], actions + end + + def test_recursive_rules_that_dont_terminate_will_overflow + create_file("a.a") + prev = 'a' + ('b'..'z').each do |letter| + rule ".#{letter}" => ".#{prev}" do |t| puts "#{t.name}" end + prev = letter + end + ex = assert_raises(Rake::RuleRecursionOverflowError) { + Task["a.z"].invoke + } + assert_match(/a\.z => a.y/, ex.message) + end + + def test_rules_with_bad_dependents_will_fail + rule "a" => [1] do |t| puts t.name end + assert_raises(RuntimeError) do Task['a'].invoke end + end + + def test_string_rule_with_args + delete_file(OBJFILE) + create_file(SRCFILE) + rule '.o', [:a] => SRCFILE do |t, args| + assert_equal 'arg', args.a + end + Task[OBJFILE].invoke('arg') + end + + def test_regex_rule_with_args + delete_file(OBJFILE) + create_file(SRCFILE) + rule(/.o$/, [:a] => SRCFILE) do |t, args| + assert_equal 'arg', args.a + end + Task[OBJFILE].invoke('arg') + end + + def test_string_rule_with_args_and_lambda_prereq + delete_file(OBJFILE) + create_file(SRCFILE) + rule '.o', [:a] => [lambda{SRCFILE}]do |t, args| + assert_equal 'arg', args.a + end + Task[OBJFILE].invoke('arg') + end + + def test_regex_rule_with_args_and_lambda_prereq + delete_file(OBJFILE) + create_file(SRCFILE) + rule(/.o$/, [:a] => [lambda{SRCFILE}]) do |t, args| + assert_equal 'arg', args.a + end + Task[OBJFILE].invoke('arg') + end + + def test_rule_with_method_prereq + create_file(".foo") + obj = Object.new + def obj.find_prereq + ".foo" + end + rule '.o' => obj.method(:find_prereq) do |t| + @runs << "#{t.name} - #{t.source}" + end + Task[OBJFILE].invoke + assert_equal ["#{OBJFILE} - .foo"], @runs + end + + def test_rule_with_one_arg_method_prereq + create_file(SRCFILE) + obj = Object.new + def obj.find_prereq(task_name) + task_name.ext(".c") + end + rule '.o' => obj.method(:find_prereq) do |t| + @runs << "#{t.name} - #{t.source}" + end + Task[OBJFILE].invoke + assert_equal ["#{OBJFILE} - abc.c"], @runs + end + +end diff --git a/jni/ruby/test/rake/test_rake_scope.rb b/jni/ruby/test/rake/test_rake_scope.rb new file mode 100644 index 0000000..ef06618 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_scope.rb @@ -0,0 +1,44 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeScope < Rake::TestCase + include Rake + + def test_path_against_empty_scope + scope = Scope.make + assert_equal scope, Scope::EMPTY + assert_equal scope.path, "" + end + + def test_path_against_one_element + scope = Scope.make(:one) + assert_equal "one", scope.path + end + + def test_path_against_two_elements + scope = Scope.make(:inner, :outer) + assert_equal "outer:inner", scope.path + end + + def test_path_with_task_name + scope = Scope.make(:inner, :outer) + assert_equal "outer:inner:task", scope.path_with_task_name("task") + end + + def test_path_with_task_name_against_empty_scope + scope = Scope.make + assert_equal "task", scope.path_with_task_name("task") + end + + def test_conj_against_two_elements + scope = Scope.make.conj("B").conj("A") + assert_equal Scope.make("A", "B"), scope + end + + def test_trim + scope = Scope.make("A", "B") + assert_equal scope, scope.trim(0) + assert_equal scope.tail, scope.trim(1) + assert_equal scope.tail.tail, scope.trim(2) + assert_equal scope.tail.tail, scope.trim(3) + end +end diff --git a/jni/ruby/test/rake/test_rake_task.rb b/jni/ruby/test/rake/test_rake_task.rb new file mode 100644 index 0000000..d7f14ef --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task.rb @@ -0,0 +1,393 @@ +require File.expand_path('../helper', __FILE__) +require 'fileutils' + +class TestRakeTask < Rake::TestCase + include Rake + + def setup + super + + Task.clear + Rake::TaskManager.record_task_metadata = true + end + + def teardown + Rake::TaskManager.record_task_metadata = false + Rake.application.thread_pool.join + + super + end + + def test_create + arg = nil + t = task(:name) { |task| arg = task; 1234 } + assert_equal "name", t.name + assert_equal [], t.prerequisites + assert t.needed? + t.execute(0) + assert_equal t, arg + assert_nil t.source + assert_equal [], t.sources + assert_equal 1, t.locations.size + assert_match(/#{Regexp.quote(__FILE__)}/, t.locations.first) + end + + def test_inspect + t = task(:foo => [:bar, :baz]) + assert_equal "<Rake::Task foo => [bar, baz]>", t.inspect + end + + def test_invoke + runlist = [] + t1 = task(:t1 => [:t2, :t3]) { |t| runlist << t.name; 3321 } + task(:t2) { |t| runlist << t.name } + task(:t3) { |t| runlist << t.name } + assert_equal ["t2", "t3"], t1.prerequisites + t1.invoke + assert_equal ["t2", "t3", "t1"], runlist + end + + def test_invoke_with_circular_dependencies + runlist = [] + t1 = task(:t1 => [:t2]) { |t| runlist << t.name; 3321 } + t2 = task(:t2 => [:t1]) { |t| runlist << t.name } + assert_equal ["t2"], t1.prerequisites + assert_equal ["t1"], t2.prerequisites + ex = assert_raises RuntimeError do + t1.invoke + end + assert_match(/circular dependency/i, ex.message) + assert_match(/t1 => t2 => t1/, ex.message) + end + + def test_dry_run_prevents_actions + Rake.application.options.dryrun = true + runlist = [] + t1 = task(:t1) { |t| runlist << t.name; 3321 } + _, err = capture_io { t1.invoke } + assert_match(/execute .*t1/i, err) + assert_match(/dry run/i, err) + refute_match(/invoke/i, err) + assert_equal [], runlist + ensure + Rake.application.options.dryrun = false + end + + def test_tasks_can_be_traced + Rake.application.options.trace = true + t1 = task(:t1) + _, err = capture_io { + t1.invoke + } + assert_match(/invoke t1/i, err) + assert_match(/execute t1/i, err) + ensure + Rake.application.options.trace = false + end + + def test_no_double_invoke + runlist = [] + t1 = task(:t1 => [:t2, :t3]) { |t| runlist << t.name; 3321 } + task(:t2 => [:t3]) { |t| runlist << t.name } + task(:t3) { |t| runlist << t.name } + t1.invoke + assert_equal ["t3", "t2", "t1"], runlist + end + + def test_can_double_invoke_with_reenable + runlist = [] + t1 = task(:t1) { |t| runlist << t.name } + t1.invoke + t1.reenable + t1.invoke + assert_equal ["t1", "t1"], runlist + end + + def test_clear + desc "a task" + t = task("t" => "a") { } + t.clear + assert t.prerequisites.empty?, "prerequisites should be empty" + assert t.actions.empty?, "actions should be empty" + assert_nil t.comment, "comments should be empty" + end + + def test_clear_prerequisites + t = task("t" => ["a", "b"]) + assert_equal ['a', 'b'], t.prerequisites + t.clear_prerequisites + assert_equal [], t.prerequisites + end + + def test_clear_actions + t = task("t") { } + t.clear_actions + assert t.actions.empty?, "actions should be empty" + end + + def test_clear_comments + desc "the original foo" + task :foo => [:x] do + # Dummy action + end + + task(:foo).clear_comments + + desc "a slightly different foo" + task :foo + + assert_equal "a slightly different foo", task(:foo).comment + assert_equal ["x"], task(:foo).prerequisites + assert_equal 1, task(:foo).actions.size + end + + def test_find + task :tfind + assert_equal "tfind", Task[:tfind].name + ex = assert_raises(RuntimeError) { Task[:leaves] } + assert_equal "Don't know how to build task 'leaves'", ex.message + end + + def test_defined + assert ! Task.task_defined?(:a) + task :a + assert Task.task_defined?(:a) + end + + def test_multi_invocations + runs = [] + p = proc do |t| runs << t.name end + task({ :t1 => [:t2, :t3] }, &p) + task({ :t2 => [:t3] }, &p) + task(:t3, &p) + Task[:t1].invoke + assert_equal ["t1", "t2", "t3"], runs.sort + end + + def test_task_list + task :t2 + task :t1 => [:t2] + assert_equal ["t1", "t2"], Task.tasks.map { |t| t.name } + end + + def test_task_gives_name_on_to_s + task :abc + assert_equal "abc", Task[:abc].to_s + end + + def test_symbols_can_be_prerequisites + task :a => :b + assert_equal ["b"], Task[:a].prerequisites + end + + def test_strings_can_be_prerequisites + task :a => "b" + assert_equal ["b"], Task[:a].prerequisites + end + + def test_arrays_can_be_prerequisites + task :a => ["b", "c"] + assert_equal ["b", "c"], Task[:a].prerequisites + end + + def test_filelists_can_be_prerequisites + task :a => FileList.new.include("b", "c") + assert_equal ["b", "c"], Task[:a].prerequisites + end + + def test_prerequiste_tasks_returns_tasks_not_strings + a = task :a => ["b", "c"] + b = task :b + c = task :c + assert_equal [b, c], a.prerequisite_tasks + end + + def test_prerequiste_tasks_fails_if_prerequisites_are_undefined + a = task :a => ["b", "c"] + task :b + assert_raises(RuntimeError) do + a.prerequisite_tasks + end + end + + def test_prerequiste_tasks_honors_namespaces + a = b = nil + namespace "X" do + a = task :a => ["b", "c"] + b = task :b + end + c = task :c + + assert_equal [b, c], a.prerequisite_tasks + end + + def test_all_prerequisite_tasks_includes_all_prerequisites + a = task :a => "b" + b = task :b => ["c", "d"] + c = task :c => "e" + d = task :d + e = task :e + + assert_equal [b, c, d, e], a.all_prerequisite_tasks.sort_by { |t| t.name } + end + + def test_all_prerequisite_tasks_does_not_include_duplicates + a = task :a => ["b", "c"] + b = task :b => "c" + c = task :c + + assert_equal [b, c], a.all_prerequisite_tasks.sort_by { |t| t.name } + end + + def test_all_prerequisite_tasks_includes_self_on_cyclic_dependencies + a = task :a => "b" + b = task :b => "a" + + assert_equal [a, b], a.all_prerequisite_tasks.sort_by { |t| t.name } + end + + def test_timestamp_returns_now_if_all_prereqs_have_no_times + a = task :a => ["b", "c"] + task :b + task :c + + assert_in_delta Time.now, a.timestamp, 0.1, 'computer too slow?' + end + + def test_timestamp_returns_latest_prereq_timestamp + a = task :a => ["b", "c"] + b = task :b + c = task :c + + now = Time.now + def b.timestamp() Time.now + 10 end + def c.timestamp() Time.now + 5 end + + assert_in_delta now, a.timestamp, 0.1, 'computer too slow?' + end + + def test_always_multitask + mx = Mutex.new + result = [] + + t_a = task(:a) do |t| + sleep 0.2 + mx.synchronize { result << t.name } + end + + t_b = task(:b) do |t| + mx.synchronize { result << t.name } + end + + t_c = task(:c => [:a, :b]) do |t| + mx.synchronize { result << t.name } + end + + t_c.invoke + + # task should always run in order + assert_equal ['a', 'b', 'c'], result + + [t_a, t_b, t_c].each { |t| t.reenable } + result.clear + + Rake.application.options.always_multitask = true + t_c.invoke + + # with multitask, task 'b' should grab the mutex first + assert_equal ['b', 'a', 'c'], result + end + + def test_investigation_output + t1 = task(:t1 => [:t2, :t3]) { |t| runlist << t.name; 3321 } + task(:t2) + task(:t3) + out = t1.investigation + assert_match(/class:\s*Rake::Task/, out) + assert_match(/needed:\s*true/, out) + assert_match(/pre-requisites:\s*--t[23]/, out) + end + + # NOTE: Rail-ties uses comment=. + def test_comment_setting + t = task(:t, :name, :rev) + t.comment = "A Comment" + assert_equal "A Comment", t.comment + end + + def test_comments_with_sentences + desc "Comment 1. Comment 2." + t = task(:t, :name, :rev) + assert_equal "Comment 1", t.comment + end + + def test_comments_with_tabbed_sentences + desc "Comment 1.\tComment 2." + t = task(:t, :name, :rev) + assert_equal "Comment 1", t.comment + end + + def test_comments_with_decimal_points + desc "Revision 1.2.3." + t = task(:t, :name, :rev) + assert_equal "Revision 1.2.3", t.comment + end + + def test_comments_do_not_set + t = task(:t, :name, :rev) + assert_equal nil, t.comment + end + + def test_comments_is_nil + t = task(:t, :name, :rev) + t.comment = nil + assert_equal nil, t.comment + end + + def test_extended_comments + desc %{ + This is a comment. + + And this is the extended comment. + name -- Name of task to execute. + rev -- Software revision to use. + } + t = task(:t, :name, :rev) + assert_equal "[name,rev]", t.arg_description + assert_equal "This is a comment", t.comment + assert_match(/^\s*name -- Name/, t.full_comment) + assert_match(/^\s*rev -- Software/, t.full_comment) + assert_match(/\A\s*This is a comment\.$/, t.full_comment) + end + + def test_multiple_comments + desc "line one" + t = task(:t) + desc "line two" + task(:t) + assert_equal "line one / line two", t.comment + end + + def test_duplicate_comments + desc "line one" + t = task(:t) + desc "line one" + task(:t) + assert_equal "line one", t.comment + end + + def test_interspersed_duplicate_comments + desc "line one" + t = task(:t) + desc "line two" + task(:t) + desc "line one" + task(:t) + assert_equal "line one / line two", t.comment + end + + def test_source_is_first_prerequisite + t = task :t => ["preqA", "preqB"] + assert_equal "preqA", t.source + end +end diff --git a/jni/ruby/test/rake/test_rake_task_argument_parsing.rb b/jni/ruby/test/rake/test_rake_task_argument_parsing.rb new file mode 100644 index 0000000..3cb5d9c --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task_argument_parsing.rb @@ -0,0 +1,119 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeTaskArgumentParsing < Rake::TestCase + def setup + super + + @app = Rake::Application.new + end + + def test_name_only + name, args = @app.parse_task_string("name") + assert_equal "name", name + assert_equal [], args + end + + def test_empty_args + name, args = @app.parse_task_string("name[]") + assert_equal "name", name + assert_equal [], args + end + + def test_one_argument + name, args = @app.parse_task_string("name[one]") + assert_equal "name", name + assert_equal ["one"], args + end + + def test_two_arguments + name, args = @app.parse_task_string("name[one,two]") + assert_equal "name", name + assert_equal ["one", "two"], args + end + + def test_can_handle_spaces_between_args + name, args = @app.parse_task_string("name[one, two,\tthree , \tfour]") + assert_equal "name", name + assert_equal ["one", "two", "three", "four"], args + end + + def test_keeps_embedded_spaces + name, args = @app.parse_task_string("name[a one ana, two]") + assert_equal "name", name + assert_equal ["a one ana", "two"], args + end + + def test_can_handle_commas_in_args + name, args = @app.parse_task_string("name[one, two, three_a\\, three_b, four]") + assert_equal "name", name + assert_equal ["one", "two", "three_a, three_b", "four"], args + end + + def test_treat_blank_arg_as_empty_string + name, args = @app.parse_task_string("name[one,]") + assert_equal "name", name + assert_equal ["one", ""], args + + name, args = @app.parse_task_string("name[one,,two]") + assert_equal "name", name + assert_equal ["one", "", "two"], args + end + + def test_terminal_width_using_env + app = Rake::Application.new + app.terminal_columns = 1234 + + assert_equal 1234, app.terminal_width + end + + def test_terminal_width_using_stty + def @app.unix?() true end + def @app.dynamic_width_stty() 1235 end + def @app.dynamic_width_tput() 0 end + + assert_equal 1235, @app.terminal_width + end + + def test_terminal_width_using_tput + def @app.unix?() true end + def @app.dynamic_width_stty() 0 end + def @app.dynamic_width_tput() 1236 end + + assert_equal 1236, @app.terminal_width + end + + def test_terminal_width_using_hardcoded_80 + def @app.unix?() false end + + assert_equal 80, @app.terminal_width + end + + def test_terminal_width_with_failure + def @app.unix?() raise end + + assert_equal 80, @app.terminal_width + end + + def test_no_rakeopt + ARGV << '--trace' + app = Rake::Application.new + app.init + assert !app.options.silent + end + + def test_rakeopt_with_blank_options + ARGV << '--trace' + app = Rake::Application.new + app.init + assert !app.options.silent + end + + def test_rakeopt_with_silent_options + ENV['RAKEOPT'] = '-s' + app = Rake::Application.new + + app.init + + assert app.options.silent + end +end diff --git a/jni/ruby/test/rake/test_rake_task_arguments.rb b/jni/ruby/test/rake/test_rake_task_arguments.rb new file mode 100644 index 0000000..369ecf6 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task_arguments.rb @@ -0,0 +1,127 @@ +require File.expand_path('../helper', __FILE__) + +###################################################################### +class TestRakeTaskArguments < Rake::TestCase + def teardown + ENV.delete('rev') + ENV.delete('VER') + + super + end + + def test_empty_arg_list_is_empty + ta = Rake::TaskArguments.new([], []) + assert_equal({}, ta.to_hash) + end + + def test_multiple_values_in_args + ta = Rake::TaskArguments.new([:a, :b, :c], [:one, :two, :three]) + assert_equal({:a => :one, :b => :two, :c => :three}, ta.to_hash) + end + + def test_has_key + ta = Rake::TaskArguments.new([:a], [:one]) + assert(ta.has_key?(:a)) + refute(ta.has_key?(:b)) + end + + def test_to_s + ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3]) + assert_equal ta.to_hash.inspect, ta.to_s + assert_equal ta.to_hash.inspect, ta.inspect + end + + def test_enumerable_behavior + ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3]) + assert_equal [10, 20, 30], ta.map { |k, v| v * 10 }.sort + end + + def test_named_args + ta = Rake::TaskArguments.new(["aa", "bb"], [1, 2]) + assert_equal 1, ta.aa + assert_equal 1, ta[:aa] + assert_equal 1, ta["aa"] + assert_equal 2, ta.bb + assert_nil ta.cc + end + + def test_args_knows_its_names + ta = Rake::TaskArguments.new(["aa", "bb"], [1, 2]) + assert_equal ["aa", "bb"], ta.names + end + + def test_extra_names_are_nil + ta = Rake::TaskArguments.new(["aa", "bb", "cc"], [1, 2]) + assert_nil ta.cc + end + + def test_args_do_not_reference_env_values + ta = Rake::TaskArguments.new(["aa"], [1]) + ENV['rev'] = "1.2" + ENV['VER'] = "2.3" + assert_nil ta.rev + assert_nil ta.ver + end + + def test_creating_new_argument_scopes + parent = Rake::TaskArguments.new(['p'], [1]) + child = parent.new_scope(['c', 'p']) + assert_equal({:p=>1}, child.to_hash) + assert_equal 1, child.p + assert_equal 1, child["p"] + assert_equal 1, child[:p] + assert_nil child.c + end + + def test_child_hides_parent_arg_names + parent = Rake::TaskArguments.new(['aa'], [1]) + child = Rake::TaskArguments.new(['aa'], [2], parent) + assert_equal 2, child.aa + end + + def test_default_arguments_values_can_be_merged + ta = Rake::TaskArguments.new(["aa", "bb"], [nil, "original_val"]) + ta.with_defaults({ :aa => 'default_val' }) + assert_equal 'default_val', ta[:aa] + assert_equal 'original_val', ta[:bb] + end + + def test_default_arguments_that_dont_match_names_are_ignored + ta = Rake::TaskArguments.new(["aa", "bb"], [nil, "original_val"]) + ta.with_defaults({ "cc" => "default_val" }) + assert_nil ta[:cc] + end + + def test_all_and_extra_arguments_without_named_arguments + app = Rake::Application.new + _, args = app.parse_task_string("task[1,two,more]") + ta = Rake::TaskArguments.new([], args) + assert_equal [], ta.names + assert_equal ['1', 'two', 'more'], ta.to_a + assert_equal ['1', 'two', 'more'], ta.extras + end + + def test_all_and_extra_arguments_with_named_arguments + app = Rake::Application.new + _, args = app.parse_task_string("task[1,two,more,still more]") + ta = Rake::TaskArguments.new([:first, :second], args) + assert_equal [:first, :second], ta.names + assert_equal "1", ta[:first] + assert_equal "two", ta[:second] + assert_equal ['1', 'two', 'more', 'still more'], ta.to_a + assert_equal ['more', 'still more'], ta.extras + end + + def test_extra_args_with_less_than_named_arguments + app = Rake::Application.new + _, args = app.parse_task_string("task[1,two]") + ta = Rake::TaskArguments.new([:first, :second, :third], args) + assert_equal [:first, :second, :third], ta.names + assert_equal "1", ta[:first] + assert_equal "two", ta[:second] + assert_equal nil, ta[:third] + assert_equal ['1', 'two'], ta.to_a + assert_equal [], ta.extras + end + +end diff --git a/jni/ruby/test/rake/test_rake_task_lib.rb b/jni/ruby/test/rake/test_rake_task_lib.rb new file mode 100644 index 0000000..9f3f7e9 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task_lib.rb @@ -0,0 +1,9 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/tasklib' + +class TestRakeTaskLib < Rake::TestCase + def test_paste + tl = Rake::TaskLib.new + assert_equal :ab, tl.paste(:a, :b) + end +end diff --git a/jni/ruby/test/rake/test_rake_task_manager.rb b/jni/ruby/test/rake/test_rake_task_manager.rb new file mode 100644 index 0000000..c2730b6 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task_manager.rb @@ -0,0 +1,178 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeTaskManager < Rake::TestCase + + def setup + super + + @tm = Rake::TestCase::TaskManager.new + end + + def test_create_task_manager + refute_nil @tm + assert_equal [], @tm.tasks + end + + def test_define_task + t = @tm.define_task(Rake::Task, :t) + assert_equal "t", t.name + assert_equal @tm, t.application + end + + def test_index + e = assert_raises RuntimeError do + @tm['bad'] + end + + assert_equal "Don't know how to build task 'bad'", e.message + end + + def test_name_lookup + t = @tm.define_task(Rake::Task, :t) + assert_equal t, @tm[:t] + end + + def test_namespace_task_create + @tm.in_namespace("x") do + t = @tm.define_task(Rake::Task, :t) + assert_equal "x:t", t.name + end + assert_equal ["x:t"], @tm.tasks.map { |t| t.name } + end + + def test_define_namespaced_task + t = @tm.define_task(Rake::Task, 'n:a:m:e:t') + assert_equal Rake::Scope.make("e", "m", "a", "n"), t.scope + assert_equal "n:a:m:e:t", t.name + assert_equal @tm, t.application + end + + def test_define_namespace_in_namespace + t = nil + @tm.in_namespace("n") do + t = @tm.define_task(Rake::Task, 'a:m:e:t') + end + assert_equal Rake::Scope.make("e", "m", "a", "n"), t.scope + assert_equal "n:a:m:e:t", t.name + assert_equal @tm, t.application + end + + def test_anonymous_namespace + anon_ns = @tm.in_namespace(nil) do + t = @tm.define_task(Rake::Task, :t) + assert_equal "_anon_1:t", t.name + end + task = anon_ns[:t] + assert_equal "_anon_1:t", task.name + end + + def test_create_filetask_in_namespace + @tm.in_namespace("x") do + t = @tm.define_task(Rake::FileTask, "fn") + assert_equal "fn", t.name + end + + assert_equal ["fn"], @tm.tasks.map { |t| t.name } + end + + def test_namespace_yields_same_namespace_as_returned + yielded_namespace = nil + returned_namespace = @tm.in_namespace("x") do |ns| + yielded_namespace = ns + end + assert_equal returned_namespace, yielded_namespace + end + + def test_name_lookup_with_implicit_file_tasks + FileUtils.touch 'README.rdoc' + + t = @tm["README.rdoc"] + + assert_equal "README.rdoc", t.name + assert Rake::FileTask === t + end + + def test_name_lookup_with_nonexistent_task + assert_raises(RuntimeError) { + @tm["DOES NOT EXIST"] + } + end + + def test_name_lookup_in_multiple_scopes + aa = nil + bb = nil + xx = @tm.define_task(Rake::Task, :xx) + top_z = @tm.define_task(Rake::Task, :z) + @tm.in_namespace("a") do + aa = @tm.define_task(Rake::Task, :aa) + mid_z = @tm.define_task(Rake::Task, :z) + ns_d = @tm.define_task(Rake::Task, "n:t") + @tm.in_namespace("b") do + bb = @tm.define_task(Rake::Task, :bb) + bot_z = @tm.define_task(Rake::Task, :z) + + assert_equal Rake::Scope.make("b", "a"), @tm.current_scope + + assert_equal bb, @tm["a:b:bb"] + assert_equal aa, @tm["a:aa"] + assert_equal xx, @tm["xx"] + assert_equal bot_z, @tm["z"] + assert_equal mid_z, @tm["^z"] + assert_equal top_z, @tm["^^z"] + assert_equal top_z, @tm["^^^z"] # Over the top + assert_equal top_z, @tm["rake:z"] + end + + assert_equal Rake::Scope.make("a"), @tm.current_scope + + assert_equal bb, @tm["a:b:bb"] + assert_equal aa, @tm["a:aa"] + assert_equal xx, @tm["xx"] + assert_equal bb, @tm["b:bb"] + assert_equal aa, @tm["aa"] + assert_equal mid_z, @tm["z"] + assert_equal top_z, @tm["^z"] + assert_equal top_z, @tm["^^z"] # Over the top + assert_equal top_z, @tm["rake:z"] + assert_equal ns_d, @tm["n:t"] + assert_equal ns_d, @tm["a:n:t"] + end + + assert_equal Rake::Scope.make, @tm.current_scope + + assert_equal Rake::Scope.make, xx.scope + assert_equal Rake::Scope.make('a'), aa.scope + assert_equal Rake::Scope.make('b', 'a'), bb.scope + end + + def test_lookup_with_explicit_scopes + t1, t2, t3, s = (0...4).map { nil } + t1 = @tm.define_task(Rake::Task, :t) + @tm.in_namespace("a") do + t2 = @tm.define_task(Rake::Task, :t) + s = @tm.define_task(Rake::Task, :s) + @tm.in_namespace("b") do + t3 = @tm.define_task(Rake::Task, :t) + end + end + assert_equal t1, @tm[:t, Rake::Scope.make] + assert_equal t2, @tm[:t, Rake::Scope.make("a")] + assert_equal t3, @tm[:t, Rake::Scope.make("b", "a")] + assert_equal s, @tm[:s, Rake::Scope.make("b", "a")] + assert_equal s, @tm[:s, Rake::Scope.make("a")] + end + + def test_correctly_scoped_prerequisites_are_invoked + values = [] + @tm = Rake::Application.new + @tm.define_task(Rake::Task, :z) do values << "top z" end + @tm.in_namespace("a") do + @tm.define_task(Rake::Task, :z) do values << "next z" end + @tm.define_task(Rake::Task, :x => :z) + end + + @tm["a:x"].invoke + assert_equal ["next z"], values + end + +end diff --git a/jni/ruby/test/rake/test_rake_task_manager_argument_resolution.rb b/jni/ruby/test/rake/test_rake_task_manager_argument_resolution.rb new file mode 100644 index 0000000..43fa2ac --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task_manager_argument_resolution.rb @@ -0,0 +1,19 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeTaskManagerArgumentResolution < Rake::TestCase + + def test_good_arg_patterns + assert_equal [:t, [], []], task(:t) + assert_equal [:t, [], [:x]], task(:t => :x) + assert_equal [:t, [], [:x, :y]], task(:t => [:x, :y]) + + assert_equal [:t, [:a, :b], []], task(:t, [:a, :b]) + assert_equal [:t, [:a, :b], [:x]], task(:t, [:a, :b] => :x) + assert_equal [:t, [:a, :b], [:x, :y]], task(:t, [:a, :b] => [:x, :y]) + end + + def task(*args) + tm = Rake::TestCase::TaskManager.new + tm.resolve_args(args) + end +end diff --git a/jni/ruby/test/rake/test_rake_task_with_arguments.rb b/jni/ruby/test/rake/test_rake_task_with_arguments.rb new file mode 100644 index 0000000..8646fc0 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_task_with_arguments.rb @@ -0,0 +1,172 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeTaskWithArguments < Rake::TestCase + include Rake + + def setup + super + + Task.clear + Rake::TaskManager.record_task_metadata = true + end + + def teardown + Rake::TaskManager.record_task_metadata = false + Rake.application.thread_pool.join + + super + end + + def test_no_args_given + t = task :t + assert_equal [], t.arg_names + end + + def test_args_given + t = task :t, :a, :b + assert_equal [:a, :b], t.arg_names + end + + def test_name_and_needs + t = task(:t => [:pre]) + assert_equal "t", t.name + assert_equal [], t.arg_names + assert_equal ["pre"], t.prerequisites + end + + def test_name_args_and_prereqs + t = task(:t, [:x, :y] => [:pre]) + assert_equal "t", t.name + assert_equal [:x, :y], t.arg_names + assert_equal ["pre"], t.prerequisites + end + + def test_arg_list_is_empty_if_no_args_given + t = task(:t) { |tt, args| assert_equal({}, args.to_hash) } + t.invoke(1, 2, 3) + end + + def test_tasks_can_access_arguments_as_hash + t = task :t, :a, :b, :c do |tt, args| + assert_equal({:a => 1, :b => 2, :c => 3}, args.to_hash) + assert_equal 1, args[:a] + assert_equal 2, args[:b] + assert_equal 3, args[:c] + assert_equal 1, args.a + assert_equal 2, args.b + assert_equal 3, args.c + end + t.invoke(1, 2, 3) + end + + def test_actions_of_various_arity_are_ok_with_args + notes = [] + t = task(:t, :x) do + notes << :a + end + t.enhance do | | + notes << :b + end + t.enhance do |task| + notes << :c + assert_kind_of Task, task + end + t.enhance do |t2, args| + notes << :d + assert_equal t, t2 + assert_equal({:x => 1}, args.to_hash) + end + t.invoke(1) + assert_equal [:a, :b, :c, :d], notes + end + + def test_arguments_are_passed_to_block + t = task(:t, :a, :b) { |tt, args| + assert_equal({ :a => 1, :b => 2 }, args.to_hash) + } + t.invoke(1, 2) + end + + def test_extra_parameters_are_ignored + t = task(:t, :a) { |tt, args| + assert_equal 1, args.a + assert_nil args.b + } + t.invoke(1, 2) + end + + def test_arguments_are_passed_to_all_blocks + counter = 0 + t = task :t, :a + task :t do |tt, args| + assert_equal 1, args.a + counter += 1 + end + task :t do |tt, args| + assert_equal 1, args.a + counter += 1 + end + t.invoke(1) + assert_equal 2, counter + end + + def test_block_with_no_parameters_is_ok + t = task(:t) { } + t.invoke(1, 2) + end + + def test_name_with_args + desc "T" + t = task(:tt, :a, :b) + assert_equal "tt", t.name + assert_equal "T", t.comment + assert_equal "[a,b]", t.arg_description + assert_equal "tt[a,b]", t.name_with_args + assert_equal [:a, :b], t.arg_names + end + + def test_named_args_are_passed_to_prereqs + value = nil + task(:pre, :rev) { |t, args| value = args.rev } + t = task(:t, [:name, :rev] => [:pre]) + t.invoke("bill", "1.2") + assert_equal "1.2", value + end + + def test_args_not_passed_if_no_prereq_names_on_task + task(:pre) { |t, args| + assert_equal({}, args.to_hash) + assert_equal "bill", args.name + } + t = task(:t, [:name, :rev] => [:pre]) + t.invoke("bill", "1.2") + end + + def test_args_not_passed_if_no_prereq_names_on_multitask + task(:pre) { |t, args| + assert_equal({}, args.to_hash) + assert_equal "bill", args.name + } + t = multitask(:t, [:name, :rev] => [:pre]) + t.invoke("bill", "1.2") + end + + def test_args_not_passed_if_no_arg_names + task(:pre, :rev) { |t, args| + assert_equal({}, args.to_hash) + } + t = task(:t => [:pre]) + t.invoke("bill", "1.2") + end + + def test_values_at + t = task(:pre, [:a, :b, :c]) { |task, args| + a, b, c = args.values_at(:a, :b, :c) + assert_equal %w[1 2 3], [a, b, c] + } + + t.invoke(*%w[1 2 3]) + + # HACK no assertions + end +end diff --git a/jni/ruby/test/rake/test_rake_test_task.rb b/jni/ruby/test/rake/test_rake_test_task.rb new file mode 100644 index 0000000..5c4be79 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_test_task.rb @@ -0,0 +1,146 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/testtask' + +class TestRakeTestTask < Rake::TestCase + include Rake + + def test_initialize + tt = Rake::TestTask.new do |t| end + refute_nil tt + assert_equal :test, tt.name + assert_equal ['lib'], tt.libs + assert_equal 'test/test*.rb', tt.pattern + assert_equal false, tt.verbose + assert Task.task_defined?(:test) + end + + def test_initialize_override + tt = Rake::TestTask.new(:example) do |t| + t.description = "Run example tests" + t.libs = ['src', 'ext'] + t.pattern = 'test/tc_*.rb' + t.verbose = true + end + refute_nil tt + assert_equal "Run example tests", tt.description + assert_equal :example, tt.name + assert_equal ['src', 'ext'], tt.libs + assert_equal 'test/tc_*.rb', tt.pattern + assert_equal true, tt.verbose + assert Task.task_defined?(:example) + end + + def test_file_list_env_test + ENV['TEST'] = 'testfile.rb' + tt = Rake::TestTask.new do |t| + t.pattern = '*' + end + + assert_equal ["testfile.rb"], tt.file_list.to_a + ensure + ENV.delete 'TEST' + end + + def test_libs_equals + test_task = Rake::TestTask.new do |t| + t.libs << ["A", "B"] + end + + path = %w[lib A B].join File::PATH_SEPARATOR + + assert_equal "-I\"#{path}\"", test_task.ruby_opts_string + end + + def test_libs_equals_empty + test_task = Rake::TestTask.new do |t| + t.libs = [] + end + + assert_equal '', test_task.ruby_opts_string + end + + def test_pattern_equals + tt = Rake::TestTask.new do |t| + t.pattern = '*.rb' + end + assert_equal ['*.rb'], tt.file_list.to_a + end + + def test_pattern_equals_test_files_equals + tt = Rake::TestTask.new do |t| + t.test_files = FileList['a.rb', 'b.rb'] + t.pattern = '*.rb' + end + assert_equal ['a.rb', 'b.rb', '*.rb'], tt.file_list.to_a + end + + def test_run_code_direct + test_task = Rake::TestTask.new do |t| + t.loader = :direct + end + + assert_equal '-e "ARGV.each{|f| require f}"', test_task.run_code + end + + def test_run_code_rake + spec = Gem::Specification.new 'rake', 0 + spec.loaded_from = File.join Gem::Specification.dirs.last, 'rake-0.gemspec' + rake, Gem.loaded_specs['rake'] = Gem.loaded_specs['rake'], spec + + test_task = Rake::TestTask.new do |t| + t.loader = :rake + end + + assert_match(/\A-I".*?" ".*?"\Z/, test_task.run_code) + ensure + Gem.loaded_specs['rake'] = rake + end + + def test_run_code_rake_default_gem + skip 'this ruby does not have default gems' unless + Gem::Specification.method_defined? :default_specifications_dir + + default_spec = Gem::Specification.new 'rake', 0 + default_spec.loaded_from = File.join Gem::Specification.default_specifications_dir, 'rake-0.gemspec' + begin + rake, Gem.loaded_specs['rake'] = Gem.loaded_specs['rake'], default_spec + + test_task = Rake::TestTask.new do |t| + t.loader = :rake + end + + assert_match(/\A(-I".*?" *)* ".*?"\Z/, test_task.run_code) + ensure + Gem.loaded_specs['rake'] = rake + end + end + + def test_run_code_testrb_ruby_1_8_2 + test_task = Rake::TestTask.new do |t| + t.loader = :testrb + end + + def test_task.ruby_version() '1.8.2' end + + assert_match(/^-S testrb +".*"$/, test_task.run_code) + end + + def test_run_code_testrb_ruby_1_8_6 + test_task = Rake::TestTask.new do |t| + t.loader = :testrb + end + + def test_task.ruby_version() '1.8.6' end + + assert_match(/^-S testrb +$/, test_task.run_code) + end + + def test_test_files_equals + tt = Rake::TestTask.new do |t| + t.test_files = FileList['a.rb', 'b.rb'] + end + + assert_equal ["a.rb", 'b.rb'], tt.file_list.to_a + end + +end diff --git a/jni/ruby/test/rake/test_rake_thread_pool.rb b/jni/ruby/test/rake/test_rake_thread_pool.rb new file mode 100644 index 0000000..35a1fe9 --- /dev/null +++ b/jni/ruby/test/rake/test_rake_thread_pool.rb @@ -0,0 +1,145 @@ +require File.expand_path('../helper', __FILE__) +require 'rake/thread_pool' + +class TestRakeTestThreadPool < Rake::TestCase + include Rake + + def test_pool_executes_in_current_thread_for_zero_threads + pool = ThreadPool.new(0) + f = pool.future { Thread.current } + pool.join + assert_equal Thread.current, f.value + end + + def test_pool_executes_in_other_thread_for_pool_of_size_one + pool = ThreadPool.new(1) + f = pool.future { Thread.current } + pool.join + refute_equal Thread.current, f.value + end + + def test_pool_executes_in_two_other_threads_for_pool_of_size_two + pool = ThreadPool.new(2) + threads = 2.times.map { + pool.future { + sleep 0.1 + Thread.current + } + }.each { |f| + f.value + } + + refute_equal threads[0], threads[1] + refute_equal Thread.current, threads[0] + refute_equal Thread.current, threads[1] + ensure + pool.join + end + + def test_pool_creates_the_correct_number_of_threads + pool = ThreadPool.new(2) + threads = Set.new + t_mutex = Mutex.new + 10.times.each do + pool.future do + sleep 0.02 + t_mutex.synchronize { threads << Thread.current } + end + end + pool.join + assert_equal 2, threads.count + end + + def test_pool_future_does_not_duplicate_arguments + pool = ThreadPool.new(2) + obj = Object.new + captured = nil + pool.future(obj) { |var| captured = var } + pool.join + assert_equal obj, captured + end + + def test_pool_join_empties_queue + pool = ThreadPool.new(2) + repeat = 25 + repeat.times { + pool.future do + repeat.times { + pool.future do + repeat.times { + pool.future do end + } + end + } + end + } + + pool.join + assert_equal( + true, + pool.__send__(:__queue__).empty?, + "queue should be empty") + end + + CustomError = Class.new(StandardError) + + # test that throwing an exception way down in the blocks propagates + # to the top + def test_exceptions + pool = ThreadPool.new(10) + + deep_exception_block = lambda do |count| + raise CustomError if count < 1 + pool.future(count - 1, &deep_exception_block).value + end + + assert_raises(CustomError) do + pool.future(2, &deep_exception_block).value + end + ensure + pool.join + end + + def test_pool_prevents_deadlock + pool = ThreadPool.new(5) + + common_dependency_a = pool.future { sleep 0.2 } + futures_a = 10.times.map { + pool.future { + common_dependency_a.value + sleep(rand() * 0.01) + } + } + + common_dependency_b = pool.future { futures_a.each { |f| f.value } } + futures_b = 10.times.map { + pool.future { + common_dependency_b.value + sleep(rand() * 0.01) + } + } + + futures_b.each { |f| f.value } + pool.join + end + + def test_pool_reports_correct_results + pool = ThreadPool.new(7) + + a = 18 + b = 5 + c = 3 + + result = a.times.map do + pool.future do + b.times.map do + pool.future { sleep rand * 0.001; c } + end.reduce(0) { |m, f| m + f.value } + end + end.reduce(0) { |m, f| m + f.value } + + assert_equal a * b * c, result + pool.join + end + +end diff --git a/jni/ruby/test/rake/test_rake_top_level_functions.rb b/jni/ruby/test/rake/test_rake_top_level_functions.rb new file mode 100644 index 0000000..fee702d --- /dev/null +++ b/jni/ruby/test/rake/test_rake_top_level_functions.rb @@ -0,0 +1,71 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeTopLevelFunctions < Rake::TestCase + + def setup + super + + @app = Object.new + + def @app.called + @called + end + + def @app.method_missing(*a, &b) + @called ||= [] + @called << [a, b] + nil + end + + Rake.application = @app + end + + def test_namespace + block = proc do end + + namespace("xyz", &block) + + expected = [ + [[:in_namespace, 'xyz'], block] + ] + + assert_equal expected, @app.called + end + + def test_import + import('x', 'y', 'z') + + expected = [ + [[:add_import, 'x'], nil], + [[:add_import, 'y'], nil], + [[:add_import, 'z'], nil], + ] + + assert_equal expected, @app.called + end + + def test_when_writing + out, = capture_io do + when_writing("NOTWRITING") do + puts "WRITING" + end + end + assert_equal "WRITING\n", out + end + + def test_when_not_writing + Rake::FileUtilsExt.nowrite_flag = true + _, err = capture_io do + when_writing("NOTWRITING") do + puts "WRITING" + end + end + assert_equal "DRYRUN: NOTWRITING\n", err + ensure + Rake::FileUtilsExt.nowrite_flag = false + end + + def test_missing_other_constant + assert_raises(NameError) do Object.const_missing(:Xyz) end + end +end diff --git a/jni/ruby/test/rake/test_rake_win32.rb b/jni/ruby/test/rake/test_rake_win32.rb new file mode 100644 index 0000000..fc2746a --- /dev/null +++ b/jni/ruby/test/rake/test_rake_win32.rb @@ -0,0 +1,72 @@ +require File.expand_path('../helper', __FILE__) + +class TestRakeWin32 < Rake::TestCase + + Win32 = Rake::Win32 + + def test_win32_system_dir_uses_home_if_defined + ENV['HOME'] = 'C:\\HP' + + assert_equal "C:/HP/Rake", Win32.win32_system_dir + end + + def test_win32_system_dir_uses_homedrive_homepath_when_no_home_defined + ENV['HOME'] = nil + ENV['HOMEDRIVE'] = 'C:' + ENV['HOMEPATH'] = '\\HP' + + assert_equal "C:/HP/Rake", Win32.win32_system_dir + end + + def test_win32_system_dir_uses_appdata_when_no_home_or_home_combo + ENV['APPDATA'] = "C:\\Documents and Settings\\HP\\Application Data" + ENV['HOME'] = nil + ENV['HOMEDRIVE'] = nil + ENV['HOMEPATH'] = nil + + assert_equal "C:/Documents and Settings/HP/Application Data/Rake", + Win32.win32_system_dir + end + + def test_win32_system_dir_fallback_to_userprofile_otherwise + ENV['HOME'] = nil + ENV['HOMEDRIVE'] = nil + ENV['HOMEPATH'] = nil + ENV['APPDATA'] = nil + ENV['USERPROFILE'] = "C:\\Documents and Settings\\HP" + + assert_equal "C:/Documents and Settings/HP/Rake", Win32.win32_system_dir + end + + def test_win32_system_dir_nil_of_no_env_vars + ENV['APPDATA'] = nil + ENV['HOME'] = nil + ENV['HOMEDRIVE'] = nil + ENV['HOMEPATH'] = nil + ENV['RAKE_SYSTEM'] = nil + ENV['USERPROFILE'] = nil + + assert_raises(Rake::Win32::Win32HomeError) do + Win32.win32_system_dir + end + end + + def test_win32_backtrace_with_different_case + ex = nil + begin + raise 'test exception' + rescue => ex + end + + ex.set_backtrace ['abc', 'rakefile'] + + rake = Rake::Application.new + rake.options.trace = true + rake.instance_variable_set(:@rakefile, 'Rakefile') + + _, err = capture_io { rake.display_error_message(ex) } + + assert_match(/rakefile/, err) + end + +end diff --git a/jni/ruby/test/rake/test_thread_history_display.rb b/jni/ruby/test/rake/test_thread_history_display.rb new file mode 100644 index 0000000..bb5879c --- /dev/null +++ b/jni/ruby/test/rake/test_thread_history_display.rb @@ -0,0 +1,101 @@ +require File.expand_path('../helper', __FILE__) + +require 'rake/thread_history_display' + +class TestThreadHistoryDisplay < Rake::TestCase + def setup + super + @time = 1_000_000 + @stats = [] + @display = Rake::ThreadHistoryDisplay.new(@stats) + end + + def test_banner + out, _ = capture_io do + @display.show + end + assert_match(/Job History/i, out) + end + + def test_item_queued + @stats << event(:item_queued, :item_id => 123) + out, _ = capture_io do + @display.show + end + assert_match(/^ *1000000 +A +item_queued +item_id:1$/, out) + end + + def test_item_dequeued + @stats << event(:item_dequeued, :item_id => 123) + out, _ = capture_io do + @display.show + end + assert_match(/^ *1000000 +A +item_dequeued +item_id:1$/, out) + end + + def test_multiple_items + @stats << event(:item_queued, :item_id => 123) + @stats << event(:item_queued, :item_id => 124) + out, _ = capture_io do + @display.show + end + assert_match(/^ *1000000 +A +item_queued +item_id:1$/, out) + assert_match(/^ *1000001 +A +item_queued +item_id:2$/, out) + end + + def test_waiting + @stats << event(:waiting, :item_id => 123) + out, _ = capture_io do + @display.show + end + assert_match(/^ *1000000 +A +waiting +item_id:1$/, out) + end + + def test_continue + @stats << event(:continue, :item_id => 123) + out, _ = capture_io do + @display.show + end + assert_match(/^ *1000000 +A +continue +item_id:1$/, out) + end + + def test_thread_deleted + @stats << event( + :thread_deleted, + :deleted_thread => 123_456, + :thread_count => 12) + out, _ = capture_io do + @display.show + end + assert_match( + /^ *1000000 +A +thread_deleted( +deleted_thread:B| +thread_count:12){2}$/, + out) + end + + def test_thread_created + @stats << event( + :thread_created, + :new_thread => 123_456, + :thread_count => 13) + out, _ = capture_io do + @display.show + end + assert_match( + /^ *1000000 +A +thread_created( +new_thread:B| +thread_count:13){2}$/, + out) + end + + private + + def event(type, data = {}) + result = { + :event => type, + :time => @time / 1_000_000.0, + :data => data, + :thread => Thread.current.object_id + } + @time += 1 + result + end + +end diff --git a/jni/ruby/test/rake/test_trace_output.rb b/jni/ruby/test/rake/test_trace_output.rb new file mode 100644 index 0000000..f9aead9 --- /dev/null +++ b/jni/ruby/test/rake/test_trace_output.rb @@ -0,0 +1,52 @@ +require File.expand_path('../helper', __FILE__) +require 'stringio' + +class TestTraceOutput < Rake::TestCase + include Rake::TraceOutput + + class PrintSpy + attr_reader :result, :calls + + def initialize + @result = "" + @calls = 0 + end + + def print(string) + @result << string + @calls += 1 + end + end + + def test_trace_issues_single_io_for_args_with_empty_args + spy = PrintSpy.new + trace_on(spy) + assert_equal "\n", spy.result + assert_equal 1, spy.calls + end + + def test_trace_issues_single_io_for_args_multiple_strings + spy = PrintSpy.new + trace_on(spy, "HI\n", "LO") + assert_equal "HI\nLO\n", spy.result + assert_equal 1, spy.calls + end + + def test_trace_handles_nil_objects + spy = PrintSpy.new + trace_on(spy, "HI\n", nil, "LO") + assert_equal "HI\nLO\n", spy.result + assert_equal 1, spy.calls + end + + def test_trace_issues_single_io_for_args_multiple_strings_and_alternate_sep + old_sep = $\ + $\ = "\r" + spy = PrintSpy.new + trace_on(spy, "HI\r", "LO") + assert_equal "HI\rLO\r", spy.result + assert_equal 1, spy.calls + ensure + $\ = old_sep + end +end |