aboutsummaryrefslogtreecommitdiffstats
path: root/lib/test/unit.rb
blob: 646fd5e3caeb6128efb170a0116068c0f4364796 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# 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
    end

    def self.setup_argv(original_argv=::ARGV)
      minitest_argv = []
      files = []
      reject = []
      original_argv = original_argv.dup
      OptionParser.new do |parser|
        parser.default_argv = original_argv

        parser.on '-v', '--verbose' do |v|
          minitest_argv << '-v' if v
        end

        parser.on '-n', '--name TESTNAME' do |name|
          minitest_argv << '-n'
          minitest_argv << name
        end

        parser.on '-x', '--exclude PATTERN' do |pattern|
          reject << pattern
        end

        parser.on '-Idirectory' do |dirs|
          dirs.split(':').each { |d| $LOAD_PATH.unshift d }
        end
      end.parse!
      files = original_argv

      if block_given?
        files = yield files
      end

      files.map! {|f|
        f = f.tr(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
        if File.directory? f
          Dir["#{f}/**/test_*.rb"]
        elsif File.file? f
          f
        else
          raise ArgumentError, "file not found: #{f}"
        end
      }
      files.flatten!

      reject_pat = Regexp.union(reject.map {|r| /#{r}/ })
      files.reject! {|f| reject_pat =~ f }

      MiniTest::Unit._install_at_exit {
        next if RunCount.have_run?
        next if $! # don't run if there was an exception
        exit false unless run(minitest_argv)
      }

      files.each {|f|
        d = File.dirname(path = File.expand_path(f))
        unless $:.include? d
          $: << d
        end
        begin
          require path
        rescue LoadError
          puts "#{f}: #{$!}"
        end
      }

      minitest_argv
    end

    def self.run(args)
      exit_code = MiniTest::Unit.new.run(args)
      !exit_code || exit_code == 0
    end

    def self.start(argv=::ARGV, &block)
      run(setup_argv(argv, &block))
    end
  end
end

class MiniTest::Unit
  def self.new(*)
    super.extend(Test::Unit::RunCount)
  end

  def self._install_at_exit(&block)
    at_exit(&block) unless @@installed_at_exit
    @@installed_at_exit = true
  end
end