manually build a unittest/doctest object.

Chris Angelico rosuav at gmail.com
Tue Dec 8 09:27:10 EST 2015


On Wed, Dec 9, 2015 at 1:04 AM, Vincent Davis <vincent at vincentdavis.net> wrote:
> I also tried something like:
> assert exec("""print('hello word')""") == 'hello word'

I'm pretty sure exec() always returns None. If you want this to work,
you would need to capture sys.stdout into a string:

import io
import contextlib
output = io.StringIO()
with contextlib.redirect_stdout(output):
    exec("""print("Hello, world!")""")
assert output.getvalue() == "Hello, world!\n" # don't forget the \n

You could wrap this up into a function, if you like. Then your example
would work (modulo the \n):

def capture_output(code):
    """Execute 'code' and return its stdout"""
    output = io.StringIO()
    with contextlib.redirect_stdout(output):
        exec(code)
    return output.getvalue()

assert capture_output("""print('hello word')""") == 'hello word\n'
# no error

ChrisA



More information about the Python-list mailing list