Skip to content

Instantly share code, notes, and snippets.

@masasakano
Last active November 5, 2019 19:30
Show Gist options
  • Select an option

  • Save masasakano/bec1858c7b2555106beccd93e9cb65b2 to your computer and use it in GitHub Desktop.

Select an option

Save masasakano/bec1858c7b2555106beccd93e9cb65b2 to your computer and use it in GitHub Desktop.
Suppress STDERR in the given block
# Suppress $stderr in the given block
#
# @author Masa Sakano, under Licence of CC BY-SA 4.0
#
# @example Simply suppressing $stderr (but not STDERR)
# suppress_stderr{ warn "Not displayed."; a=5 } #=> 5
#
# @example Backup-ping STDERR in a block, suppressing $stderr (and warn)
# suppress_stderr('/tmp/backup.log'){ warn "Not displayed."; a=5 } #=> 5
#
# @param backup_file [String] Filename to backup $stderr
# @return [Object] Returned value of the given block (yield)
# @yield [] Block to execute, in which $stderr is suppressed.
def suppress_stderr(backup_file='/dev/null')
stderr_orig = $stderr.dup # dup() is essential
$stderr.sync
$stderr = open(backup_file, 'w') # $stderr.reopen() does not work well.
begin
ret = yield
$stderr.sync
ensure
$stderr.close
end
return ret
ensure
$stderr = (stderr_orig || $stderr) # in case "ensured" before the first sentence is completed.
end
# Code snippet to easily suppress STDERR
#
def example_easy_suppress_stderr
warn_level = $VERBOSE
begin
$VERBOSE = nil # Suppress the warning in the following line(s).
warn "This is not printed" # warn does nothing when $VERBOSE.nil?
ensure
$VERBOSE = warn_level
end
end
########## Unit tests ##########
if $0 == __FILE__
require 'minitest/autorun'
require 'tempfile'
$stderr.sync=true
$stderr.puts "This is meant to be displayed."
suppress_stderr(){$stderr.puts "Not displayed."}
suppress_stderr(){warn "Not displayed."}
class TestUnitFoo < MiniTest::Test
def test_defs # $VERBOSE is set true in UnitTest
orig_io = $stderr.dup
assert_equal(5, suppress_stderr(){ 5}) # Return value test
assert_output('',"bar\n"){$stderr.print "bar\n"}
assert_output('',''){suppress_stderr(){$stderr.print "bar\n"}}
assert_output('',''){suppress_stderr(){warn "bar\n"}}
_, err = capture_io{warn "bar\n"}
assert_equal "bar\n", err
_, _ = capture_io{suppress_stderr(){STDERR.print "STDERR is meant not to be suppressed, or even captured by Unit-Test, like this.\n"}}
Tempfile.open(File.basename($0)+'tmp'){ |iotmp|
fname = iotmp.path # Test of Backup file
assert_output('',''){suppress_stderr(fname){$stderr.print "bar\n"}}
assert_equal "bar\n", IO.read(fname)
}
assert_raises(RangeError){suppress_stderr(){raise RangeError}} # Exception passed to the caller.
assert_equal orig_io.inspect, $stderr.inspect # All recovered; inspect is the only way to compare them.
assert_output('',''){example_easy_suppress_stderr}
end
end # class TestUnitFoo < MiniTest::Unit::TestCase
end # if $0 == __FILE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment