Module: Bosh::Exec
- Defined in:
- lib/common/exec.rb,
lib/common/exec/error.rb,
lib/common/exec/result.rb
Overview
Copyright © 2012 VMware, Inc.
Defined Under Namespace
Class Method Summary collapse
-
.included(base) ⇒ Object
Helper method to add sh as a class method when it is included.
-
.sh(command, options = {}) {|Bosh::Exec::Result| ... } ⇒ Bosh::Exec::Result
Execute commands in a way that forces you to deal with failures and helps you to simplify testing.
Class Method Details
.included(base) ⇒ Object
Helper method to add sh as a class method when it is included
83 84 85 |
# File 'lib/common/exec.rb', line 83 def self.included(base) base.extend(Bosh::Exec) end |
.sh(command, options = {}) {|Bosh::Exec::Result| ... } ⇒ Bosh::Exec::Result
Note:
As commands are executed using %x… you need to append 2>&1 to redirect stderr or it will be output to the stderr of the process invoking the sh method
Execute commands in a way that forces you to deal with failures and helps you to simplify testing. The module can be included which will add sh both as an instance and a class method.
A sample way to mock the execution of “ls /”:
it "should be possible to mock the result of a command execution" do
cmd = "ls /"
result = Bosh::Exec::Result.new(cmd, "bin etc var", "", 0)
Bosh::Exec.should_receive(:sh).with(cmd).and_return(result)
result = Bosh::Exec.sh(cmd)
result.success?.should be(true)
end
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 |
# File 'lib/common/exec.rb', line 52 def sh(command, ={}) opts = .dup # can only yield if we don't raise errors opts[:on_error] = :return if opts[:yield] == :on_false output = %x{#{command}} result = Result.new(command, output, $?.exitstatus) if result.failed? unless opts[:on_error] == :return raise Error.new(result.exit_status, command, output) end yield result if block_given? && opts[:yield] == :on_false else yield result if block_given? end result rescue Errno::ENOENT => e msg = "command not found: #{command}" raise Error.new(nil, command) unless opts[:on_error] == :return result = Result.new(command, msg, -1, true) yield result if block_given? && opts[:yield] == :on_false result end |