1# frozen_string_literal: true
2require 'test/unit'
3
4module TestRipper; end
5class TestRipper::Generic < Test::Unit::TestCase
6  SRCDIR = File.expand_path("../../..", __FILE__)
7
8  %w[sample ext].each do |dir|
9    define_method("test_parse_files:#{dir}") do
10      assert_parse_files(dir)
11    end
12  end
13
14  %w[lib test].each do |dir|
15    define_method("test_parse_files:#{dir}") do
16      assert_parse_files(dir, "*.rb")
17    end
18    Dir["#{SRCDIR}/#{dir}/*/"].each do |dir|
19      dir = dir[(SRCDIR.length+1)..-2]
20      define_method("test_parse_files:#{dir}") do
21        assert_parse_files(dir)
22      end
23    end
24  end
25
26  def assert_parse_files(dir, pattern = "**/*.rb")
27    assert_separately(%W[--disable-gem -rripper - #{SRCDIR}/#{dir} #{pattern}],
28                      __FILE__, __LINE__, "#{<<-"begin;"}\n#{<<-'end;'}", timeout: Float::INFINITY)
29    pattern = "#{pattern}"
30    begin;
31      TEST_RATIO = ENV["TEST_RIPPER_RATIO"]&.tap {|s|break s.to_f} || 0.05 # testing all files needs too long time...
32      class Parser < Ripper
33        PARSER_EVENTS.each {|n| eval "def on_#{n}(*args) r = [:#{n}, *args]; r.inspect; Object.new end" }
34        SCANNER_EVENTS.each {|n| eval "def on_#{n}(*args) r = [:#{n}, *args]; r.inspect; Object.new end" }
35      end
36      dir = ARGV.shift
37      scripts = Dir.chdir(dir) {Dir[pattern]}
38      if (1...scripts.size).include?(num = scripts.size * TEST_RATIO)
39        scripts = scripts.sample(num)
40      end
41      scripts.sort!
42      for script in scripts
43        assert_nothing_raised {
44          parser = Parser.new(File.read("#{dir}/#{script}"), script)
45          parser.instance_eval "parse", "<#{script}>"
46        }
47      end
48    end;
49  end
50end
51