# test/unit compatibility layer using minitest.
require 'minitest/unit'
require 'test/unit/assertions'
require 'test/unit/testcase'
require 'optparse'
module Test
module Unit
TEST_UNIT_IMPLEMENTATION = 'test/unit compatibility layer using minitest'
module RunCount
@@run_count = 0
def self.have_run?
@@run_count.nonzero?
end
def run(*)
@@run_count += 1
super
end
def run_once
return if have_run?
return if $! # don't run if there was an exception
yield
end
module_function :run_once
end
module Options
def initialize(*, &block)
@init_hook = block
@options = nil
super(&nil)
end
def option_parser
@option_parser ||= OptionParser.new
end
def process_args(args = [])
return @options if @options
orig_args = args.dup
options = {}
opts = option_parser
setup_options(opts, options)
opts.parse!(args)
orig_args -= args
args = @init_hook.call(args, options) if @init_hook
non_options(args, options)
@help = orig_args.map { |s| s =~ /[\s|&<>$()]/ ? s.inspect : s }.join " "
@options = options
if @options[:parallel]
@files = args
@args = orig_args
end
options
end
private
def setup_options(opts, options)
opts.separator 'minitest options:'
opts.version = MiniTest::Unit::VERSION
opts.on '-h', '--help', 'Display this help.' do
puts opts
exit
end
opts.on '-s', '--seed SEED', Integer, "Sets random seed" do |m|
options[:seed] = m
end
opts.on '-v', '--verbose', "Verbose. Show progress processing files." do
options[:verbose] = true
self.verbose = options[:verbose]
end
opts.on '-n', '--name PATTERN', "Filter test names on pattern." do |a|
options[:filter] = a
end
opts.on '--jobs-status [TYPE]', [:normal, :replace],
"Show status of jobs every file; Disabled when --jobs isn't specified." do |type|
options[:job_status] = type || :normal
end
opts.on '-j N', '--jobs N', "Allow run tests with N jobs at once" do |a|
if /^t/ =~ a
options[:testing] = true # For testing
options[:parallel] = a[1..-1].to_i
else
options[:parallel] = a.to_i
end
end
opts.on '--no-retry', "Don't retry running testcase when --jobs specified" do
options[:no_retry] = true
end
opts.on '--ruby VAL', "Path to ruby; It'll have used at -j option" do |a|
options[:ruby] = a.split(/ /).reject(&:empty?)
end
opts.on '-q', '--hide-skip', 'Hide skipped tests' do
options[:hide_skip] = true
end
end
def non_options(files, options)
begin
require "rbconfig"
rescue LoadError
warn "#{caller(1)[0]}: warning: Parallel running disabled because can't get path to ruby; run specify with --ruby argument"
options[:parallel] = nil
else
options[:ruby] ||= RbConfig.ruby
end
true
end
end
module GlobOption
include Options
@@testfile_prefix = "test"
def setup_options(parser, options)
super
parser.on '-b', '--basedir=DIR', 'Base directory of test suites.' do |dir|
options[:base_directory] = dir
end
parser.on '-x', '--exclude PATTERN', 'Exclude test files on pattern.' do |pattern|
(options[:reject] ||= []) << pattern
end
end
def non_options(files, options)
paths = [options.delete(:base_directory), nil].uniq
if reject = options.delete(:reject)
reject_pat = Regexp.union(reject.map {|r| /#{r}/ })
end
files.map! {|f|
f = f.tr(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
((paths if /\A\.\.?(?:\z|\/)/ !~ f) || [nil]).any? do |prefix|
if prefix
path = f.empty? ? prefix : "#{prefix}/#{f}"
else
next if f.empty?
path = f
end
if !(match = Dir["#{path}/**/#{@@testfile_prefix}_*.rb"]).empty?
if reject
match.reject! {|n|
n[(prefix.length+1)..-1] if prefix
reject_pat =~ n
}
end
break match
elsif !reject or reject_pat !~ f and File.exist? path
break path
end
end or
raise ArgumentError, "file not found: #{f}"
}
files.flatten!
super(files, options)
end
end
module LoadPathOption
include Options
def setup_options(parser, options)
super
parser.on '-Idirectory', 'Add library load path' do |dirs|
dirs.split(':').each { |d| $LOAD_PATH.unshift d }
end
end
end
module GCStressOption
def setup_options(parser, options)
super
parser.on '--[no-]gc-stress', 'Set GC.stress as true' do |flag|
options[:gc_stress] = flag
end
end
def non_options(files, options)
if options.delete(:gc_stress)
MiniTest::Unit::TestCase.class_eval do
oldrun = instance_method(:run)
define_method(:run) do |runner|
begin
gc_stress, GC.stress = GC.stress, true
oldrun.bind(self).call(runner)
ensure
GC.stress = gc_stress
end
end
end
end
super
end
end
module RequireFiles
def non_options(files, options)
return false if !super
result = false
files.each {|f|
d = File.dirname(path = File.expand_path(f))
unless $:.include? d
$: << d
end
begin
require path unless options[:parallel]
result = true
rescue LoadError
puts "#{f}: #{$!}"
end
}
result
end
end
class Runner < MiniTest::Unit
include Test::Unit::Options
include Test::Unit::GlobOption
include Test::Unit::LoadPathOption
include Test::Unit::GCStressOption
include Test::Unit::RunCount
class Worker
def self.launch(ruby,args=[])
io = IO.popen([*ruby,
"#{File.dirname(__FILE__)}/unit/parallel.rb",
*args], "rb+")
new(io, io.pid, :waiting)
end
def initialize(io, pid, status)
@io = io
@pid = pid
@status = status
@file = nil
@real_file = nil
@loadpath = []
@hooks = {}
end
def puts(*args)
@io.puts(*args)
end
def run(task,type)
@file = File.basename(task).gsub(/\.rb/,"")
@real_file = task
begin
puts "loadpath #{[Marshal.dump($:-@loadpath)].pack("m").gsub("\n","")}"
@loadpath = $:.dup
puts "run #{task} #{type}"
@status = :prepare
rescue Errno::EPIPE
died
rescue IOError
raise unless ["stream closed","closed stream"].include? $!.message
died
end
end
def hook(id,&block)
@hooks[id] ||= []
@hooks[id] << block
self
end
def read
res = (@status == :quit) ? @io.read : @io.gets
res && res.chomp
end
def close
@io.close
self
end
def died(*additional)
@status = :quit
@io.close
call_hook(:dead,*additional)
end
def to_s
if @file
"#{@pid}=#{@file}"
else
"#{@pid}:#{@status.to_s.ljust(7)}"
end
end
attr_reader :io, :pid
attr_accessor :status, :file, :real_file, :loadpath
private
def call_hook(id,*additional)
@hooks[id] ||= []
@hooks[id].each{|hook| hook[self,additional] }
self
end
end
class << self; undef autorun; end
@@stop_auto_run = false
def self.autorun
at_exit {
Test::Unit::RunCount.run_once {
exit(Test::Unit::Runner.new.run(ARGV) || true)
} unless @@stop_auto_run
} unless @@installed_at_exit
@@installed_at_exit = true
end
def after_worker_down(worker, e=nil, c=false)
return unless @options[:parallel]
return if @interrupt
if e
b = e.backtrace
warn "#{b.shift}: #{e.message} (#{e.class})"
STDERR.print b.map{|s| "\tfrom #{s}"}.join("\n")
end
@need_quit = true
warn ""
warn "Some worker was crashed. It seems ruby interpreter's bug"
warn "or, a bug of test/unit/parallel.rb. try again without -j"
warn "option."
warn ""
Loading ...