[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

snippet - assert_stdout

Phlip

1/13/2008 8:08:00 AM

Rubies:

Ideally, when your developer tests call production code, it should not spew
output to your STDOUT stream. If it must emit strings, it should return
them to its caller. That way, your main() methods have the option to spew
the strings, and your tests can instead intercept the strings and
assert_match their contents.

Real life is often less than ideal. Your production code might couple with
legacy code. Or your production code might require some out-of-band spew,
such as a "syntax" or "usage" message.

Ruby makes this situation delightfully easy to test, by intercepting the
STDOUT itself. Some languages would force you to manipulate the raw STDOUT
file descriptor. Ruby simply permits you to replace your $stdout object
with one that implements .write.

So, without further ado, here's the assertion to trap and match your STDOUT
stream:

class BufferStdout
def write(stuff)
(@output ||= '') << stuff
end
def output; @output || '' end
end

def assert_stdout(matcher = nil, diagnostic = nil)
waz = $stdout
$stdout = BufferStdout.new
yield
assert_match matcher, $stdout.output, diagnostic if matcher
return $stdout.output # for if you need the whole string
ensure
$stdout = waz
end

def deny_stdout(unmatcher, diagnostic = nil, &block)
got = assert_stdout(nil, nil, &block)
assert_no_match unmatcher, got, diagnostic
end

With further ado, here's the assertion in action:

def test_help
assert_stdout /invalid.*argument.*
verbose.*=\>.*:false/mx do
assert_efficient_sql(:help){}
end
end

That test case demonstrates that another assertion, assert_efficient_sql,
will spew a helpful error to $stdout if you call it with an invalid
argument.

Modulo my typical life-issues, we will soon see more of that
assert_invalid_sql. But it only works with MySQL.

If you use it with another database adapter, it should not fail; it should
simply warn (spew) that it honestly cannot determine your SQL's efficiency.

To test that, we write a case which installs another adapter, then detects
that the warning only appears once:

assert_stdout /requires MySQL/, 'warn' do assert_efficient_sql end
deny_stdout /requires MySQL/, 'once' do assert_efficient_sql end

That shows deny_stdout in action, and the 'diagnostic' parameters.

--
Phlip
http://www.oreilly.com/catalog/9780...
^ assert_xpath