Testing & stdout

John Roth newsgroups at jhrothjr.com
Tue Nov 4 09:27:12 EST 2003


"Miki Tebeka" <mikit at zoran.co.il> wrote in message
news:6250403b.0311040151.32fd4754 at posting.google.com...
> Hello All,
>
> In my test suite I also test some function that output messages to stdout.
> Is there an easy way to temporary divert stdout to another location?

You can, I believe, replace the stdout object in the builtins directory
with one that does what you need it to do. Remember to restore it
when you're done. Python keeps the original value of stdout somewhere,
but that doesn't help if your application also replaces and restores it.

John Roth
>
> Currently I'm using:
>
> import sys
> from StringIO import StringIO
> from unittest import TestCase, main
>
> def with_io_divert(func):
>     '''Divert stdout'''
>     orig = sys.stdout
>     io = StringIO()
>     sys.stdout = io
>     try:
>         func(io)
>     finally:
>         sys.stdout = orig
>
> def io_clear(io):
>     '''Clear io'''
>     io.seek(0)
>     io.truncate()
>
> def io_value(io):
>     '''Value in io'''
>     return io.getvalue().strip()
>
> class SomeTest(TestCase):
>     def test_print(self):
>         def func(io):
>             msg = "Alice had a little lamb"
>             print msg
>             self.assertEqual(io_value(io), msg)
>
>         with_io_divert(func)
>
> if __name__ == "__main__":
>     main()
>
>
> This works fine if no one is caching stdout somewhere.
>
> TIA.
>
> Miki.






More information about the Python-list mailing list