From c8197eb598b26e33531cb4bd029010920208d56f Mon Sep 17 00:00:00 2001 From: jimweirich Date: Thu, 1 Jun 2006 16:09:41 +0000 Subject: [PATCH] added rcov and unit tests git-svn-id: svn+ssh://rubyforge.org/var/svn/rake/trunk@564 5af023f1-ac1a-0410-98d6-829a145c37ef --- rake/.cvsignore | 1 + rake/CHANGES | 3 + rake/Rakefile | 17 +- rake/lib/rake.rb | 62 ++-- rake/test/capture_stdout.rb | 26 ++ rake/test/reqfile.rb | 3 + rake/test/reqfile2.rb | 3 + rake/test/reqfile3.rake | 3 + rake/test/test_application.rb | 400 ++++++++++++++++++++++++++ rake/test/test_earlytime.rb | 4 + rake/test/test_file_creation_task.rb | 6 + rake/test/test_filelist.rb | 26 +- rake/test/test_fileutils.rb | 49 +++- rake/test/test_namespace.rb | 20 +- rake/test/test_rake.rb | 13 + rake/test/test_rules.rb | 5 + rake/test/test_tasks.rb | 44 ++- rake/test/test_top_level_functions.rb | 79 +++++ 18 files changed, 711 insertions(+), 53 deletions(-) create mode 100644 rake/test/capture_stdout.rb create mode 100644 rake/test/reqfile.rb create mode 100644 rake/test/reqfile2.rb create mode 100644 rake/test/reqfile3.rake create mode 100644 rake/test/test_application.rb create mode 100644 rake/test/test_top_level_functions.rb diff --git a/rake/.cvsignore b/rake/.cvsignore index 6a29496ca..f7dc98bed 100644 --- a/rake/.cvsignore +++ b/rake/.cvsignore @@ -1,3 +1,4 @@ +coverage testdata html pkg diff --git a/rake/CHANGES b/rake/CHANGES index 2e730db85..7af9af394 100644 --- a/rake/CHANGES +++ b/rake/CHANGES @@ -6,6 +6,9 @@ Payton Quackenbush). * Better error handling on invalid command line arguments (from Payton Quackenbush). +* Added rcov task and updated unit testing for better code coverage. +* Fixed some bugs where the application object was going to the global + appliation instead of using its own data. == Version 0.7.1 diff --git a/rake/Rakefile b/rake/Rakefile index e6f38e516..541164992 100644 --- a/rake/Rakefile +++ b/rake/Rakefile @@ -23,6 +23,7 @@ CLOBBER.include('test/data/chains/play.*') CLOBBER.include('test/data/file_creation_task/build') CLOBBER.include('test/data/file_creation_task/src') CLOBBER.include('TAGS') +CLOBBER.include('coverage') def announce(msg='') STDERR.puts msg @@ -87,6 +88,18 @@ Rake::TestTask.new(:test_contribs) do |t| t.warning = true end +require 'rcov/rcovtask' + +Rcov::RcovTask.new do |t| + t.libs << "test" + t.rcov_opts = ['-xRakefile', '-xrakefile', '-xpublish.rf', '--text-report'] + t.test_files = FileList[ + 'test/test*.rb', + 'test/contrib/test*.rb' + ] + t.verbose = true +end + directory 'testdata' [:test_all, :test_units, :test_contribs, :test_functional].each do |t| task t => ['testdata'] @@ -244,12 +257,12 @@ load "publish.rf" if File.exist? "publish.rf" desc "Look for TODO and FIXME tags in the code" task :todo do - FileList['**/*.rb'].exclude('pkg').egrep /#.*(FIXME|TODO|TBD)/ + FileList['**/*.rb'].exclude('pkg').egrep(/#.*(FIXME|TODO|TBD)/) end desc "Look for Debugging print lines" task :dbg do - FileList['**/*.rb'].egrep /\bDBG|\bbreakpoint\b/ + FileList['**/*.rb'].egrep(/\bDBG|\bbreakpoint\b/) end desc "List all ruby files" diff --git a/rake/lib/rake.rb b/rake/lib/rake.rb index 418fdf3b2..9e33e28ba 100755 --- a/rake/lib/rake.rb +++ b/rake/lib/rake.rb @@ -395,7 +395,7 @@ def needed? # Timestamp for this task. Basic tasks return the current time for # their time stamp. Other tasks can be more sophisticated. def timestamp - @prerequisites.collect { |p| Rake::Task[p].timestamp }.max || Time.now + @prerequisites.collect { |p| application[p].timestamp }.max || Time.now end # Add a comment to the task. If a comment alread exists, separate @@ -419,12 +419,12 @@ def investigation result << "task needed: #{needed?}\n" result << "timestamp: #{timestamp}\n" result << "pre-requisites: \n" - prereqs = @prerequisites.collect {|name| Rake::Task[name]} + prereqs = @prerequisites.collect {|name| application[name]} prereqs.sort! {|a,b| a.timestamp <=> b.timestamp} prereqs.each do |p| result << "--#{p.name} (#{p.timestamp})\n" end - latest_prereq = @prerequisites.collect{|n| Rake::Task[n].timestamp}.max + latest_prereq = @prerequisites.collect{|n| application[n].timestamp}.max result << "latest-prerequisite time: #{latest_prereq}\n" result << "................................\n\n" return result @@ -513,7 +513,7 @@ def timestamp # Are there any prerequisites with a later time than the given # time stamp? def out_of_date?(stamp) - @prerequisites.any? { |n| Rake::Task[n].timestamp > stamp} + @prerequisites.any? { |n| application[n].timestamp > stamp} end # ---------------------------------------------------------------- @@ -555,7 +555,7 @@ def timestamp class MultiTask < Task def invoke_prerequisites threads = @prerequisites.collect { |p| - Thread.new(p) { |r| Task[r].invoke } + Thread.new(p) { |r| application[r].invoke } } threads.each { |t| t.join } end @@ -710,11 +710,7 @@ module FileUtils # end # def sh(*cmd, &block) - if Hash === cmd.last then - options = cmd.pop - else - options = {} - end + options = (Hash === cmd.last) ? cmd.pop : {} unless block_given? show_command = cmd.join(" ") show_command = show_command[0,42] + "..." if show_command.length > 45 @@ -736,11 +732,7 @@ def sh(*cmd, &block) # ruby %{-pe '$_.upcase!' 1 then sh(*([RUBY] + args + [options]), &block) else @@ -758,7 +750,7 @@ def safe_ln(*args) else begin ln(*args) - rescue StandardError, NotImplementedError + rescue StandardError, NotImplementedError => ex LN_SUPPORTED[0] = false cp(*args) end @@ -1125,7 +1117,7 @@ def calculate_exclude_regexp case pat when Regexp ignores << pat - when /[*.]/ + when /[*?]/ Dir[pat].each do |p| ignores << p end else ignores << Regexp.quote(pat) @@ -1141,8 +1133,6 @@ def calculate_exclude_regexp def resolve_add(fn) case fn - when Array - fn.each { |f| self.resolve_add(f) } when %r{[*?]} add_matching(fn) else @@ -1156,7 +1146,7 @@ def resolve_exclude case pat when Regexp reject! { |fn| fn =~ pat } - when /[*.]/ + when /[*?]/ reject_list = Dir[pat] reject! { |fn| reject_list.include?(fn) } else @@ -1427,7 +1417,6 @@ def define_task(task_class, args, &block) deps = [deps] unless deps.respond_to?(:to_ary) deps = deps.collect {|d| d.to_s } task = intern(task_class, task_name) - task.application = self task.add_comment(@last_comment) @last_comment = nil task.enhance(deps, &block) @@ -1602,9 +1591,9 @@ class Application include TaskManager # The original directory where rake was invoked. - attr_reader :original_dir + attr_reader :original_dir, :rakefile - RAKEFILES = ['rakefile', 'Rakefile', 'rakefile.rb', 'Rakefile.rb'] + DEFAULT_RAKEFILES = ['rakefile', 'Rakefile', 'rakefile.rb', 'Rakefile.rb'].freeze OPTIONS = [ ['--dry-run', '-n', GetoptLong::NO_ARGUMENT, @@ -1644,6 +1633,7 @@ class Application # Create a Rake::Application object. def initialize super + @rakefiles = DEFAULT_RAKEFILES.dup @rakefile = nil @pending_imports = [] @imported = [] @@ -1662,7 +1652,7 @@ def options # True if one of the files in RAKEFILES is in the current directory. # If a match is found, it is copied into @rakefile. def have_rakefile - RAKEFILES.each do |fn| + @rakefiles.each do |fn| if File.exist?(fn) || fn == '' @rakefile = fn return true @@ -1695,12 +1685,10 @@ def help # Display the tasks and dependencies. def display_tasks_and_comments - displayable_tasks = Rake::Task.tasks.select { |t| + displayable_tasks = tasks.select { |t| t.comment && t.name =~ options.show_task_pattern } - width = displayable_tasks.collect { |t| - t.name.length - }.max + width = displayable_tasks.collect { |t| t.name.length }.max displayable_tasks.each do |t| printf "rake %-#{width}s # %s\n", t.name, t.comment end @@ -1708,7 +1696,7 @@ def display_tasks_and_comments # Display the tasks and prerequisites def display_prerequisites - Rake::Task.tasks.each do |t| + tasks.each do |t| puts "rake #{t.name}" t.prerequisites.each { |pre| puts " #{pre}" } end @@ -1740,8 +1728,8 @@ def do_option(opt, value) when '--quiet' verbose(false) when '--rakefile' - RAKEFILES.clear - RAKEFILES << value + @rakefiles.clear + @rakefiles << value when '--rakelibdir' options.rakelib = value.split(':') when '--require' @@ -1774,8 +1762,6 @@ def do_option(opt, value) when '--classic-namespace' require 'rake/classic_namespace' options.classic_namespace = true - else - fail "Unknown option: #{opt}" end end @@ -1819,7 +1805,7 @@ def load_rakefile while ! have_rakefile Dir.chdir("..") if Dir.pwd == here || options.nosearch - fail "No Rakefile found (looking for: #{RAKEFILES.join(', ')})" + fail "No Rakefile found (looking for: #{@rakefiles.join(', ')})" end here = Dir.pwd end @@ -1833,7 +1819,7 @@ def load_rakefile end # Collect the list of tasks on the command line. If no tasks are - # give, return a list containing only the default task. + # given, return a list containing only the default task. # Environmental assignments are processed at this time as well. def collect_tasks tasks = [] @@ -1857,7 +1843,9 @@ def add_import(fn) def load_imports while fn = @pending_imports.shift next if @imported.member?(fn) - Rake::Task[fn].invoke if Rake::Task.task_defined?(fn) + if fn_task = lookup(fn) + fn_task.invoke + end ext = File.extname(fn) loader = @loaders[ext] || @default_loader loader.load(fn) @@ -1903,7 +1891,7 @@ def run elsif options.show_prereqs display_prerequisites else - tasks.each { |task_name| Rake::Task[task_name].invoke } + tasks.each { |task_name| self[task_name].invoke } end rescue SystemExit, GetoptLong::InvalidOption => ex # Exit silently diff --git a/rake/test/capture_stdout.rb b/rake/test/capture_stdout.rb new file mode 100644 index 000000000..8b664adca --- /dev/null +++ b/rake/test/capture_stdout.rb @@ -0,0 +1,26 @@ +#!/usr/bin/env ruby + +require 'stringio' + +# Mix-in for capturing standard output. +module CaptureStdout + def capture_stdout + s = StringIO.new + oldstdout = $stdout + $stdout = s + yield + s.string + ensure + $stdout = oldstdout + end + + def capture_stderr + s = StringIO.new + oldstderr = $stderr + $stderr = s + yield + s.string + ensure + $stderr = oldstderr + end +end diff --git a/rake/test/reqfile.rb b/rake/test/reqfile.rb new file mode 100644 index 000000000..5372544b6 --- /dev/null +++ b/rake/test/reqfile.rb @@ -0,0 +1,3 @@ +# For --require testing + +TESTING_REQUIRE << 1 diff --git a/rake/test/reqfile2.rb b/rake/test/reqfile2.rb new file mode 100644 index 000000000..65993907a --- /dev/null +++ b/rake/test/reqfile2.rb @@ -0,0 +1,3 @@ +# For --require testing + +TESTING_REQUIRE << 2 diff --git a/rake/test/reqfile3.rake b/rake/test/reqfile3.rake new file mode 100644 index 000000000..11fc16b2a --- /dev/null +++ b/rake/test/reqfile3.rake @@ -0,0 +1,3 @@ +# For --require testing + +TESTING_REQUIRE << 3 diff --git a/rake/test/test_application.rb b/rake/test/test_application.rb new file mode 100644 index 000000000..852f161f4 --- /dev/null +++ b/rake/test/test_application.rb @@ -0,0 +1,400 @@ +#!/usr/bin/env ruby + +require 'test/unit' +require 'rake' +require 'test/capture_stdout' +require 'flexmock' + +TESTING_REQUIRE = [ ] + +###################################################################### +class TestApplication < Test::Unit::TestCase + include CaptureStdout + include FlexMock::TestCase + + def setup + @app = Rake::Application.new + end + + def test_constant_warning + err = capture_stderr do @app.const_warning("Task") end + assert_match(/warning/i, err) + assert_match(/deprecated/i, err) + assert_match(/Task/i, err) + end + + def test_display_tasks + @app.options.show_task_pattern = // + @app.last_comment = "COMMENT" + @app.define_task(Rake::Task, "t") + out = capture_stdout do @app.display_tasks_and_comments end + assert_match(/^rake t/, out) + assert_match(/# COMMENT/, out) + end + + def test_finding_rakefile + assert @app.have_rakefile + assert_equal "rakefile", @app.rakefile.downcase + end + + def test_not_finding_rakefile + @app.instance_eval { @rakefiles = ['NEVER_FOUND'] } + assert ! @app.have_rakefile + assert_nil @app.rakefile + end + + def test_load_rakefile + original_dir = Dir.pwd + Dir.chdir("test/data/unittest") + @app.handle_options + @app.options.silent = true + @app.load_rakefile + assert_equal "rakefile", @app.rakefile.downcase + assert_match(%r(unittest$), Dir.pwd) + ensure + Dir.chdir(original_dir) + end + + def test_load_rakefile_from_subdir + original_dir = Dir.pwd + Dir.chdir("test/data/unittest/subdir") + @app.handle_options + @app.options.silent = true + @app.load_rakefile + assert_equal "rakefile", @app.rakefile.downcase + assert_match(%r(unittest$), Dir.pwd) + ensure + Dir.chdir(original_dir) + end + + def test_load_rakefile_not_found + original_dir = Dir.pwd + Dir.chdir("/") + @app.handle_options + @app.options.silent = true + ex = assert_raise(RuntimeError) do @app.load_rakefile end + assert_match(/no rakefile found/i, ex.message) + ensure + Dir.chdir(original_dir) + end + + def test_not_caring_about_finding_rakefile + @app.instance_eval { @rakefiles = [''] } + assert @app.have_rakefile + assert_equal '', @app.rakefile + end + + def test_loading_imports + mock = flexmock("loader") + mock.should_receive(:load).with("x.dummy").once + @app.add_loader("dummy", mock) + @app.add_import("x.dummy") + @app.load_imports + end + + def test_building_imported_files_on_demand + mock = flexmock("loader") + mock.should_receive(:load).with("x.dummy").once + mock.should_receive(:make_dummy).with_no_args.once + @app.intern(Rake::Task, "x.dummy").enhance do mock.make_dummy end + @app.add_loader("dummy", mock) + @app.add_import("x.dummy") + @app.load_imports + end + + def test_good_run + ran = false + @app.options.silent = true + @app.intern(Rake::Task, "default").enhance { ran = true } + @app.run + assert ran + end + + def test_display_task_run + ran = false + ARGV.clear + ARGV << '-f' << '-s' << '--tasks' + @app.last_comment = "COMMENT" + @app.define_task(Rake::Task, "default") + out = capture_stdout { @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 + ARGV.clear + ARGV << '-f' << '-s' << '--prereqs' + @app.last_comment = "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_stdout { @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 } + ARGV.clear + ARGV << '-f' << '-s' + assert_raise(SystemExit) { + err = capture_stderr { @app.run } + assert_match(/see full trace/, err) + } + ensure + ARGV.clear + end + + def test_bad_run_with_trace + @app.intern(Rake::Task, "default").enhance { fail } + ARGV.clear + ARGV << '-f' << '-s' << '-t' + assert_raise(SystemExit) { + err = capture_stderr { capture_stdout { @app.run } } + assert_no_match(/see full trace/, err) + } + ensure + ARGV.clear + end + + def test_run_with_bad_options + @app.intern(Rake::Task, "default").enhance { fail } + ARGV.clear + ARGV << '-f' << '-s' << '--xyzzy' + assert_raise(SystemExit) { + err = capture_stderr { capture_stdout { @app.run } } + } + ensure + ARGV.clear + end + +end + + +###################################################################### +class TestApplicationOptions < Test::Unit::TestCase + include CaptureStdout + + def setup + clear_argv + RakeFileUtils.verbose_flag = false + RakeFileUtils.nowrite_flag = false + end + + def teardown + clear_argv + RakeFileUtils.verbose_flag = false + RakeFileUtils.nowrite_flag = false + end + + def clear_argv + while ! ARGV.empty? + ARGV.pop + end + end + + def test_default_options + opts = command_line + assert_nil opts.show_task_pattern + assert_nil opts.dryrun + assert_nil opts.trace + assert_nil opts.nosearch + assert_nil opts.silent + assert_nil opts.show_prereqs + assert_nil opts.show_tasks + assert_nil opts.classic_namespace + assert_equal 'rakelib', opts.rakelib + assert ! RakeFileUtils.verbose_flag + assert ! RakeFileUtils.nowrite_flag + end + + def test_trace_option + flags('--trace', '-t') do |opts| + assert opts.trace + assert RakeFileUtils.verbose_flag + assert ! RakeFileUtils.nowrite_flag + end + end + + def test_dry_run + flags('--dry-run', '-n') do |opts| + assert opts.dryrun + assert opts.trace + assert RakeFileUtils.verbose_flag + assert RakeFileUtils.nowrite_flag + end + end + + def test_help + flags('--help', '-H') do |opts, output| + assert_match(/\Arake/, @out) + assert_match(/--help/, @out) + assert_equal :exit, @exit + end + end + + def test_usage + flags('--usage', '-h') do |opts, output| + assert_match(/\Arake/, @out) + assert_match(/\boptions\b/, @out) + assert_match(/\btargets\b/, @out) + assert_equal :exit, @exit + end + end + + def test_libdir + flags(['--libdir', 'xx'], ['-I', 'xx'], ['-Ixx']) do |opts| + $:.include?('xx') + end + ensure + $:.delete('xx') + end + + def test_nosearch + flags('--nosearch', '-N') do |opts| + assert opts.nosearch + end + end + + def test_show_prereqs + flags('--prereqs', '-P') do |opts| + assert opts.show_prereqs + end + end + + def test_quiet + flags('--quiet', '-q') do |opts| + assert ! RakeFileUtils.verbose_flag + assert ! opts.silent + end + end + + def test_silent + flags('--silent', '-s') do |opts| + assert ! RakeFileUtils.verbose_flag + assert opts.silent + 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 + flags(['--rakelibdir', 'A:B:C'], ['--rakelibdir=A:B:C'], ['-R', 'A:B:C'], ['-RA:B:C']) do |opts| + assert_equal ['A', 'B', 'C'], opts.rakelib + end + end + + def test_require + flags(['--require', 'test/reqfile'], '-rtest/reqfile2', '-rtest/reqfile3') do |opts| + end + assert TESTING_REQUIRE.include?(1) + assert TESTING_REQUIRE.include?(2) + assert TESTING_REQUIRE.include?(3) + assert_equal 3, TESTING_REQUIRE.size + end + + def test_missing_require + ex = assert_raises(LoadError) do + flags(['--require', 'test/missing']) do |opts| + end + end + assert_match(/no such file/, ex.message) + assert_match(/test\/missing/, ex.message) + end + + def test_tasks + flags('--tasks', '-T') do |opts| + assert opts.show_tasks + assert_equal(//.to_s, opts.show_task_pattern.to_s) + end + flags(['--tasks', 'xyz'], ['-Txyz']) do |opts| + assert opts.show_tasks + assert_equal(/xyz/, opts.show_task_pattern) + end + end + + def test_verbose + flags('--verbose', '-V') do |opts| + assert RakeFileUtils.verbose_flag + assert ! opts.silent + end + end + + def test_version + flags('--version', '-V') do |opts| + assert_match(/\bversion\b/, @out) + assert_match(/\b#{RAKEVERSION}\b/, @out) + assert_equal :exit, @exit + end + end + + def test_classic_namespace + flags(['--classic-namespace'], ['-C', '-T', '-P', '-n', '-s', '-t']) do |opts| + assert opts.classic_namespace + assert_equal opts.show_tasks, $show_tasks + assert_equal opts.show_prereqs, $show_prereqs + assert_equal opts.trace, $trace + assert_equal opts.dryrun, $dryrun + assert_equal opts.silent, $silent + end + end + + def test_bad_option + capture_stderr do + ex = assert_raise(GetoptLong::InvalidOption) { flags('--bad-option') } + assert_match(/unrecognized option/, ex.message) + assert_match(/--bad-option/, ex.message) + end + 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['TESTKEY'] = nil + command_line("a", "TESTKEY=12") + assert_equal ["a"], @tasks.sort + assert '12', ENV['TESTKEY'] + end + + private + + def flags(*sets) + sets.each do |set| + @out = capture_stdout { + @exit = catch(:system_exit) { opts = command_line(*set) } + } + yield(@app.options) + 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.handle_options + @tasks = @app.collect_tasks + @app.options + end +end + diff --git a/rake/test/test_earlytime.rb b/rake/test/test_earlytime.rb index 897fb2609..dc6e9648e 100644 --- a/rake/test/test_earlytime.rb +++ b/rake/test/test_earlytime.rb @@ -28,4 +28,8 @@ def test_original_time_compare_is_not_messed_up assert t1 == t1 assert t2 == t2 end + + def test_to_s + assert_equal "", Rake::EARLY.to_s + end end diff --git a/rake/test/test_file_creation_task.rb b/rake/test/test_file_creation_task.rb index 6a44cbcfd..1544e14d2 100644 --- a/rake/test/test_file_creation_task.rb +++ b/rake/test/test_file_creation_task.rb @@ -53,4 +53,10 @@ def test_no_retriggers_on_file_task 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 - 1000000 + end end diff --git a/rake/test/test_filelist.rb b/rake/test/test_filelist.rb index 76466b9c4..05b278493 100644 --- a/rake/test/test_filelist.rb +++ b/rake/test/test_filelist.rb @@ -2,9 +2,11 @@ require 'test/unit' require 'rake' +require 'test/capture_stdout' class TestFileList < Test::Unit::TestCase FileList = Rake::FileList + include CaptureStdout def setup create_test_data @@ -130,6 +132,13 @@ def test_exclude def test_exclude_return_on_create fl = FileList['testdata/*'].exclude(/.*\.c$/) + assert_equal ['testdata/existing'], fl + assert_equal FileList, fl.class + end + + def test_exclude_with_string_return_on_create + fl = FileList['testdata/*'].exclude('testdata/abc.c') + assert_equal ["testdata/existing", "testdata/x.c", "testdata/xyz.c"].sort, fl.sort assert_equal FileList, fl.class end @@ -242,7 +251,22 @@ def test_gsub f2.sort end - def test_egrep + def test_gsub! + create_test_data + f = FileList["testdata/*.c"] + f.gsub!(/a/, "A") + assert_equal ["testdAtA/Abc.c", "testdAtA/x.c", "testdAtA/xyz.c"].sort, + f.sort + end + + def test_egrep_with_output + files = FileList['test/test*.rb'] + the_line_number = __LINE__ + 1 + out = capture_stdout do files.egrep(/PUGH/) end + assert_match(/:#{the_line_number}:/, out) + end + + def test_egrep_with_block files = FileList['test/test*.rb'] found = false the_line_number = __LINE__ + 1 diff --git a/rake/test/test_fileutils.rb b/rake/test/test_fileutils.rb index b6623bd0f..d174228cd 100644 --- a/rake/test/test_fileutils.rb +++ b/rake/test/test_fileutils.rb @@ -14,6 +14,7 @@ def setup def teardown FileUtils.rm_rf("testdata") + FileUtils::LN_SUPPORTED[0] = true end def test_rm_one_file @@ -45,12 +46,49 @@ def test_ln assert_equal "TEST_LN\n", open("testdata/b") { |f| f.read } end + class BadLink + include RakeFileUtils + 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_raise(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){ + verbose(true) { assert_equal true, verbose } assert_equal false, verbose @@ -129,4 +167,13 @@ def test_ruby end end + def test_split_all + assert_equal ['a'], RakeFileUtils.split_all('a') + assert_equal ['..'], RakeFileUtils.split_all('..') + assert_equal ['/'], RakeFileUtils.split_all('/') + assert_equal ['a', 'b'], RakeFileUtils.split_all('a/b') + assert_equal ['/', 'a', 'b'], RakeFileUtils.split_all('/a/b') + assert_equal ['..', 'a', 'b'], RakeFileUtils.split_all('../a/b') + end + end diff --git a/rake/test/test_namespace.rb b/rake/test/test_namespace.rb index 856c6a7e2..821527015 100644 --- a/rake/test/test_namespace.rb +++ b/rake/test/test_namespace.rb @@ -6,19 +6,19 @@ require 'rake' class TestNameSpace < Test::Unit::TestCase + include FlexMock::TestCase + def test_namespace_creation - FlexMock.use("TaskManager") do |mgr| - ns = Rake::NameSpace.new(mgr, []) - assert_not_nil ns - end + mgr = flexmock("TaskManager") + ns = Rake::NameSpace.new(mgr, []) + assert_not_nil ns end def test_namespace_lookup - FlexMock.use("TaskManager") do |mgr| - mgr.should_receive(:lookup).with(:t, ["a"]). - and_return(nil).once - ns = Rake::NameSpace.new(mgr, ["a"]) - ns[:t] - end + mgr = flexmock("TaskManager") + mgr.should_receive(:lookup).with(:t, ["a"]). + and_return(nil).once + ns = Rake::NameSpace.new(mgr, ["a"]) + ns[:t] end end diff --git a/rake/test/test_rake.rb b/rake/test/test_rake.rb index e8e8ad8a0..b3f48e44e 100644 --- a/rake/test/test_rake.rb +++ b/rake/test/test_rake.rb @@ -17,5 +17,18 @@ def alldirs(fn) 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 Dir.pwd, Rake.original_dir + end end diff --git a/rake/test/test_rules.rb b/rake/test/test_rules.rb index 4db0add8f..8cf8e9abf 100644 --- a/rake/test/test_rules.rb +++ b/rake/test/test_rules.rb @@ -224,5 +224,10 @@ def test_recursive_overflow assert_match(/a\.z => testdata\/a.y/, ex.message) end + def test_bad_dependent + rule "a" => [ 1 ] do |t| puts t.name end + assert_raise(RuntimeError) do Task['a'].invoke end + end + end diff --git a/rake/test/test_tasks.rb b/rake/test/test_tasks.rb index 942981954..64e5cb847 100644 --- a/rake/test/test_tasks.rb +++ b/rake/test/test_tasks.rb @@ -4,9 +4,11 @@ require 'fileutils' require 'rake' require 'test/filecreation' +require 'test/capture_stdout' ###################################################################### class TestTask < Test::Unit::TestCase + include CaptureStdout include Rake def setup @@ -23,6 +25,7 @@ def test_create t.execute assert_equal t, arg assert_nil t.source + assert_equal [], t.sources end def test_invoke @@ -35,8 +38,29 @@ def test_invoke assert_equal ["t2", "t3", "t1"], runlist end - def intern(name) - Rake.application.define_task(Rake::Task,name) + def test_dry_run_prevents_actions + Rake.application.options.dryrun = true + runlist = [] + t1 = intern(:t1).enhance { |t| runlist << t.name; 3321 } + out = capture_stdout { t1.invoke } + assert_match(/execute .*t1/i, out) + assert_match(/dry run/i, out) + assert_no_match(/invoke/i, out) + assert_equal [], runlist + ensure + Rake.application.options.dryrun = false + end + + def test_tasks_can_be_traced + Rake.application.options.trace = true + t1 = intern(:t1) { |t| runlist << t.name; 3321 } + out = capture_stdout { + t1.invoke + } + assert_match(/invoke t1/i, out) + assert_match(/execute t1/i, out) + ensure + Rake.application.options.trace = false end def test_no_double_invoke @@ -102,5 +126,21 @@ def test_filelists_can_be_prerequisites assert_equal ["b", "c"], Task[:a].prerequisites end + def test_investigation_output + t1 = intern(:t1).enhance([:t2, :t3]) { |t| runlist << t.name; 3321 } + intern(:t2) + intern(:t3) + out = t1.investigation + assert_match(/class:\s*Rake::Task/, out) + assert_match(/needed:\s*true/, out) + assert_match(/pre-requisites:\s*--t2/, out) + end + + private + + def intern(name) + Rake.application.define_task(Rake::Task,name) + end + end diff --git a/rake/test/test_top_level_functions.rb b/rake/test/test_top_level_functions.rb new file mode 100644 index 000000000..25d5f7964 --- /dev/null +++ b/rake/test/test_top_level_functions.rb @@ -0,0 +1,79 @@ +#!/usr/bin/env ruby + +require 'test/unit' +require 'test/capture_stdout' +require 'rake' +require 'flexmock' + +class TestTopLevelFunctions < Test::Unit::TestCase + include FlexMock::TestCase + include CaptureStdout + + def setup + super + @app = Rake.application + Rake.application = flexmock("app") + end + + def teardown + Rake.application = @app + super + end + + def test_namespace + Rake.application.should_receive(:in_namespace).with("xyz", any).once + namespace "xyz" do end + end + + def test_import + Rake.application.should_receive(:add_import).with("x").once.ordered + Rake.application.should_receive(:add_import).with("y").once.ordered + Rake.application.should_receive(:add_import).with("z").once.ordered + import('x', 'y', 'z') + end + + def test_when_writing + out = capture_stdout do + when_writing("NOTWRITING") do + puts "WRITING" + end + end + assert_equal "WRITING\n", out + end + + def test_when_not_writing + RakeFileUtils.nowrite_flag = true + out = capture_stdout do + when_writing("NOTWRITING") do + puts "WRITING" + end + end + assert_equal "DRYRUN: NOTWRITING\n", out + ensure + RakeFileUtils.nowrite_flag = false + end + + def test_missing_constants_task + Rake.application.should_receive(:const_warning).with(:Task).once + Object.const_missing(:Task) + end + + def test_missing_constants_file_task + Rake.application.should_receive(:const_warning).with(:FileTask).once + Object.const_missing(:FileTask) + end + + def test_missing_constants_file_creation_task + Rake.application.should_receive(:const_warning).with(:FileCreationTask).once + Object.const_missing(:FileCreationTask) + end + + def test_missing_constants_rake_app + Rake.application.should_receive(:const_warning).with(:RakeApp).once + Object.const_missing(:RakeApp) + end + + def test_missing_other_constant + assert_raise(NameError) do Object.const_missing(:Xyz) end + end +end