Class: Baf::Testing::Process

Inherits:
Object
  • Object
show all
Defined in:
lib/baf/testing/process.rb

Constant Summary collapse

ExecutionFailure =
Class.new Error
TIMEOUT =
4
TMP_FILE_PREFIX =
'baf_test_'.freeze
WAIT_POLL_DELAY =
0.01

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, env_allow: [], timeout: TIMEOUT) ⇒ Process

Returns a new instance of Process.



16
17
18
19
20
21
22
# 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

Instance Attribute Details

#exit_statusObject (readonly)

Returns the value of attribute exit_status.



14
15
16
# File 'lib/baf/testing/process.rb', line 14

def exit_status
  @exit_status
end

#pidObject (readonly)

Returns the value of attribute pid.



14
15
16
# File 'lib/baf/testing/process.rb', line 14

def pid
  @pid
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



14
15
16
# File 'lib/baf/testing/process.rb', line 14

def timeout
  @timeout
end

Instance Method Details

#input(str) ⇒ Object



62
63
64
# File 'lib/baf/testing/process.rb', line 62

def input str
  @stdin.write str
end

#output(stream = nil) ⇒ Object



66
67
68
69
70
71
72
73
74
# 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?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/baf/testing/process.rb', line 58

def running?
  started? && !stopped?
end

#startObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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) ⇒ Object



49
50
51
52
53
54
55
56
# 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) ⇒ Object



39
40
41
42
43
44
45
46
47
# 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