kennethreitz / clint

Python Command-line Application Tools
http://pypi.python.org/pypi/clint/
ISC License
95 stars 19 forks source link

Problem when attempting to capture stdout in TestCase using "puts" #156

Open mmedal opened 8 years ago

mmedal commented 8 years ago

I've run into an problem where I cannot capture the stdout from a method that calls the clint.text.ui.puts method. I have written a contextmanager that looks like this:

@contextmanager
def captured_stdout():
    """Context manager to use when testing the output of CLI invoked methods."""
    new_out, new_err = StringIO(), StringIO()
    saved_out, saved_err = sys.stdout, sys.stderr
    try:
        sys.stdout, sys.stderr = new_out, new_err
        yield sys.stdout, sys.stderr
    finally:
        sys.stdout, sys.stderr = saved_out, saved_err

and I use it in a test like so:

def test_method_that_puts_something():
    with captured_stdout() as (out, err,):
        return_value = method_that_puts_something()
    std_out = out.getvalue().strip()
    assertEqual(std_out, 'something')

My test fails, claiming that std_out is a blank string. Strangely enough, when I edit the puts method to explicitly write to sys.std_out.write rather than the constant STDOUT, output is captured properly and my test passes. Also bizarre is an insertion of stream == sys.stdout.write on line 67 of core.py returns false.

Any help on this would be amazing.