Friday, April 01, 2011

Ruby Light #5

This is a remix of Ruby Light #1, done better (IMHO):

test/lib/redirect_io.rb
require 'stringio'

module RedirectIo
def setup
$stderr = @stderr = StringIO.new
$stdin = @stdin = StringIO.new
$stdout = @stdout = StringIO.new
super
end

def teardown
$stderr = STDERR
$stdin = STDIN
$stdout = STDOUT
super
end
end


test/unit/timestamp_logger_test.rb
require 'test_helper'
require 'lib/generic_test_helper.rb' # from Ruby Light #3
require 'lib/redirect_io'

class TimestampLoggerTest < Test::Unit::TestCase
include GenericTestHelper
include RedirectIo

LOG_LEVELS = [:error, :warn, :info, :debug]

def setup
super # RedirectIO.setup needs to run

@logger = TimestampLogger.new $stdout
@logger.level = Logger::DEBUG
end

def test_timestamps
LOG_LEVELS.each do |level|
@logger.send level, 'foo'
end

@stdout.string.split("\n").each do |line|
assert_match /^#{TIMESTAMP_MATCHER} /, line
end
end

def test_labels
LOG_LEVELS.each do |level|
@logger.send level, 'foo'
end

[:error, :warn].each do |level|
assert_match /^#{TIMESTAMP_MATCHER} \[#{level.to_s.upcase}\] /, @stdout.string
end
end

No comments: