require 'test/unit'
require 'stringio'

class TestKillEnsure < Test::Unit::TestCase
  def test_kill_ensure_with_ruby
    output = run_and_kill("ruby kill_ensure.rb")
    assert(output.include?("Ensure was called"))
  end

  def test_kill_ensure_with_jruby
    output = run_and_kill("jruby kill_ensure.rb")
    assert(output.include?("Ensure was called"))
  end

  def run_and_kill(command)
    command_output = StringIO.new
    io = IO.popen(command)
    t = Thread.new do
      command_output << io.gets until io.eof?
    end
    sleep(0.1) while command_output.string.empty?
    Process.kill("HUP", io.pid)
    t.join    
    command_output.string
  ensure
    io.close
  end
end
