class Baf::Testing::Process

Constants

ExecutionFailure
TIMEOUT
TMP_FILE_PREFIX
WAIT_POLL_DELAY

Attributes

exit_status[R]
pid[R]
timeout[R]

Public Class Methods

new(command, env_allow: [], timeout: TIMEOUT) click to toggle source
# File lib/baf/testing/process.rb, line 16
def initialize command, env_allow: [], timeout: TIMEOUT
  @command = command
  @env_allow = env_allow
  @timeout = timeout
  @stdout = Tempfile.new TMP_FILE_PREFIX
  @stderr = Tempfile.new TMP_FILE_PREFIX
end

Public Instance Methods

input(str) click to toggle source
# File lib/baf/testing/process.rb, line 62
def input str
  @stdin.write str
end
output(stream = nil) click to toggle source
# File lib/baf/testing/process.rb, line 66
def output stream = nil
  case stream
    when :output then [@stdout]
    when :error then [@stderr]
    else [@stdout, @stderr]
  end.inject '' do |memo, stream|
    memo + IO.read(stream.path)
  end
end
running?() click to toggle source
# File lib/baf/testing/process.rb, line 58
def running?
  started? && !stopped?
end
start() click to toggle source
# File lib/baf/testing/process.rb, line 24
def start
  reader, writer = IO.pipe

  @pid = spawn env,
    *@command,
    unsetenv_others: true,
    in: reader,
    out: @stdout,
    err: @stderr
  reader.close
  @stdin = writer
rescue Errno::ENOENT => e
  fail ExecutionFailure, e.message
end
stop(wait_timeout: 1) click to toggle source
# File lib/baf/testing/process.rb, line 49
def stop wait_timeout: 1
  ::Process.kill :TERM, @pid
  wait timeout: wait_timeout
  return if stopped?
  ::Process.kill :KILL, @pid
  ::Process.wait2 @pid
rescue Errno::ECHILD, Errno::ESRCH
end
wait(timeout: @timeout) { || ... } click to toggle source
# File lib/baf/testing/process.rb, line 39
def wait timeout: @timeout
  deadline = Time.now + timeout
  wait_poll
  until stopped? || Time.now >= deadline
    sleep WAIT_POLL_DELAY
    wait_poll
  end
  yield unless stopped? if block_given?
end

Private Instance Methods

env() click to toggle source
# File lib/baf/testing/process.rb, line 78
def env
  ENV.inject({}) do |acc, (k, v)|
    if env_allow? k then acc.merge k => v else acc end
  end.merge 'HOME' => File.realpath(?.)
end
env_allow?(var) click to toggle source
# File lib/baf/testing/process.rb, line 84
def env_allow? var
  @env_allow.any? do |e|
    case e
      when String then var == e
      when Regexp then var =~ e
    end
  end
end
started?() click to toggle source
# File lib/baf/testing/process.rb, line 93
def started?
  !!@pid
end
stopped?() click to toggle source
# File lib/baf/testing/process.rb, line 97
def stopped?
  !!@exit_status
end
wait_poll() click to toggle source
# File lib/baf/testing/process.rb, line 101
def wait_poll
  pid, status = ::Process.wait2 @pid, ::Process::WNOHANG
  @exit_status = status.exitstatus if pid
end