Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #100158
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: manually build a unittest/doctest object. |
| Date | 2015-12-09 01:27 +1100 |
| Message-ID | <mailman.66.1449584833.12405.python-list@python.org> (permalink) |
| References | <CALyJZZXeRaFxxdDK6aNSZC4xyqn082kZCGtgYBQxnBqKU-_WEg@mail.gmail.com> <n466ip$bg7$1@ger.gmane.org> <CALyJZZVugpQ4FEo2xT9EYQvVrgwJWE503zqO7DwUOg_GGECUnA@mail.gmail.com> |
On Wed, Dec 9, 2015 at 1:04 AM, Vincent Davis <vincent@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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: manually build a unittest/doctest object. Chris Angelico <rosuav@gmail.com> - 2015-12-09 01:27 +1100
csiph-web