#-- # _____ _ ___ _ # |_ _|__ __| |_ | __|_ _| |_ # | |/ -_|_-< _| | _|\ \ / _|_ # |_|\___/__/\__| |___/_\_\\__(_) # #++ require 'facet/string/margin' require 'facet/progressbar' require 'facet/filelist.rb' unless defined?( FileList ) module Reap # = Test Extraction # # This task scans every package script looking for sections of the form: # # =begin test # ... # =end # # With appropriate headers, it copies these sections to files in your # project's test/ dir, which then can be run using the Reap test task. # The exact directory layout of the files to be tested is reflected in # the test directory. You can then use Reap's test task to run the tests. # # Specific Settings: # # dir Specify the test directory. Default is 'test'. # files Specify files to extract. Default is 'lib/**/*.rb'. # class ExTest include TaskUtils attr_accessor :dir, :trunk, :files, :options def initialize( tst ) @dir = 'test' #@trunk = 'trunk' if File.directory?('trunk') @files = [ 'lib/**/*.rb' ] @options = {} super @files = [ @files ].flatten end # Extract tests. def extract if @trunk Dir.chdir( @trunk ) { extract_tests } else extract_tests end end alias_method :call, :extract private def extract_tests #test_libs = @libs.join(':') filelist = FileList.new filelist.include(*@files) if filelist.empty? tell "No script files found." return end #tell "Reap is scanning and copying embedded tests..." if @dir.strip.empty? tell "Test directory must be specified. Aborting." return # TODO use #abort or sepcial method to do a nice exit? end unless File.directory?( @dir ) tell "Test directory doesn't exist: #{File.expand_path( @dir )}" return end pbar = Console::ProgressBar.new( 'Extracting', filelist.size ) filelist.each { |file| pbar.inc testing = extract_from_file( file ) unless testing.strip.empty? complete_test = create( testing, file ) libpath = File.dirname( file ) testfile = "test_" + File.basename( file ) fp = File.join( dir, libpath, testfile ) unless File.directory?( File.dirname( fp ) ) FileUtils.mkdir_p( File.dirname(fp) ) end File.open( fp, "w" ) { |fw| fw << complete_test } end } pbar.finish end private def extract_from_file( file ) return nil if ! File.file?( file ) tests = ""; inside = false fstr = File.read( file ) fstr.split(/\n/).each do |l| if l =~ /^=begin[ ]*test/i tests << "\n" inside = true next elsif inside and l =~ /^=[ ]*end/ inside = false next end if inside tests << l << "\n" end end tests end def create( testing, file ) fp = file.split(/[\/]/) if fp[0] == 'lib' reqf = "require '#{fp[1..-1].join('/')}'" else reqf = '' end teststr = <<-HERE.margin `# _____ _ `# |_ _|__ ___| |_ `# | |/ _ \\/ __| __| `# | | __/\\__ \\ |_ `# |_|\\___||___/\\__| `# `# for #{file} `# `# Extracted #{Time.now} `# Unit Tools Reap Test Extractor `# ` `#{reqf} ` HERE teststr << testing << "\n" teststr end end end #module Reap