summaryrefslogtreecommitdiff
path: root/test/irb/helper.rb
blob: acaf6277f3879da41a5c3986b5fadff9d75f84f4 (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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
require "test/unit"
require "pathname"
require "rubygems"

begin
  require_relative "../lib/helper"
  require_relative "../lib/envutil"
rescue LoadError # ruby/ruby defines helpers differently
end

begin
  require "pty"
rescue LoadError # some platforms don't support PTY
end

module IRB
  class InputMethod; end
end

module TestIRB
  RUBY_3_4 = Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3.4.0.dev")
  class TestCase < Test::Unit::TestCase
    class TestInputMethod < ::IRB::InputMethod
      attr_reader :list, :line_no

      def initialize(list = [])
        @line_no = 0
        @list = list
      end

      def gets
        @list[@line_no]&.tap {@line_no += 1}
      end

      def eof?
        @line_no >= @list.size
      end

      def encoding
        Encoding.default_external
      end

      def reset
        @line_no = 0
      end
    end

    def ruby_core?
      !Pathname(__dir__).join("../../", "irb.gemspec").exist?
    end

    def save_encodings
      @default_encoding = [Encoding.default_external, Encoding.default_internal]
      @stdio_encodings = [STDIN, STDOUT, STDERR].map {|io| [io.external_encoding, io.internal_encoding] }
    end

    def restore_encodings
      EnvUtil.suppress_warning do
        Encoding.default_external, Encoding.default_internal = *@default_encoding
        [STDIN, STDOUT, STDERR].zip(@stdio_encodings) do |io, encs|
          io.set_encoding(*encs)
        end
      end
    end

    def without_rdoc(&block)
      ::Kernel.send(:alias_method, :irb_original_require, :require)

      ::Kernel.define_method(:require) do |name|
        raise LoadError, "cannot load such file -- rdoc (test)" if name.match?("rdoc") || name.match?(/^rdoc\/.*/)
        ::Kernel.send(:irb_original_require, name)
      end

      yield
    ensure
      EnvUtil.suppress_warning {
        ::Kernel.send(:alias_method, :require, :irb_original_require)
        ::Kernel.undef_method :irb_original_require
      }
    end
  end

  class IntegrationTestCase < TestCase
    LIB = File.expand_path("../../lib", __dir__)
    TIMEOUT_SEC = 3

    def setup
      @envs = {}
      @tmpfiles = []

      unless defined?(PTY)
        omit "Integration tests require PTY."
      end

      if ruby_core?
        omit "This test works only under ruby/irb"
      end

      write_rc <<~RUBY
        IRB.conf[:USE_PAGER] = false
      RUBY
    end

    def teardown
      @tmpfiles.each do |tmpfile|
        File.unlink(tmpfile)
      end
    end

    def run_ruby_file(&block)
      cmd = [EnvUtil.rubybin, "-I", LIB, @ruby_file.to_path]
      tmp_dir = Dir.mktmpdir

      @commands = []
      lines = []

      yield

      # Test should not depend on user's irbrc file
      @envs["HOME"] ||= tmp_dir
      @envs["XDG_CONFIG_HOME"] ||= tmp_dir
      @envs["IRBRC"] = nil unless @envs.key?("IRBRC")

      envs_for_spawn = @envs.merge('TERM' => 'dumb', 'TEST_IRB_FORCE_INTERACTIVE' => 'true')

      PTY.spawn(envs_for_spawn, *cmd) do |read, write, pid|
        Timeout.timeout(TIMEOUT_SEC) do
          while line = safe_gets(read)
            lines << line

            # means the breakpoint is triggered
            if line.match?(/binding\.irb/)
              while command = @commands.shift
                write.puts(command)
              end
            end
          end
        end
      ensure
        read.close
        write.close
        kill_safely(pid)
      end

      lines.join
    rescue Timeout::Error
      message = <<~MSG
      Test timedout.

      #{'=' * 30} OUTPUT #{'=' * 30}
        #{lines.map { |l| "  #{l}" }.join}
      #{'=' * 27} END OF OUTPUT #{'=' * 27}
      MSG
      assert_block(message) { false }
    ensure
      FileUtils.remove_entry tmp_dir
    end

    # read.gets could raise exceptions on some platforms
    # https://github.com/ruby/ruby/blob/master/ext/pty/pty.c#L721-L728
    def safe_gets(read)
      read.gets
    rescue Errno::EIO
      nil
    end

    def kill_safely pid
      return if wait_pid pid, TIMEOUT_SEC

      Process.kill :TERM, pid
      return if wait_pid pid, 0.2

      Process.kill :KILL, pid
      Process.waitpid(pid)
    rescue Errno::EPERM, Errno::ESRCH
    end

    def wait_pid pid, sec
      total_sec = 0.0
      wait_sec = 0.001 # 1ms

      while total_sec < sec
        if Process.waitpid(pid, Process::WNOHANG) == pid
          return true
        end
        sleep wait_sec
        total_sec += wait_sec
        wait_sec *= 2
      end

      false
    rescue Errno::ECHILD
      true
    end

    def type(command)
      @commands << command
    end

    def write_ruby(program)
      @ruby_file = Tempfile.create(%w{irbtest- .rb})
      @tmpfiles << @ruby_file
      @ruby_file.write(program)
      @ruby_file.close
    end

    def write_rc(content)
      # Append irbrc content if a tempfile for it already exists
      if @irbrc
        @irbrc = File.open(@irbrc, "a")
      else
        @irbrc = Tempfile.new('irbrc')
        @tmpfiles << @irbrc
      end

      @irbrc.write(content)
      @irbrc.close
      @envs['IRBRC'] = @irbrc.path
    end
  end
end