Testing & stdout

Miki Tebeka mikit at zoran.co.il
Tue Nov 4 10:51:09 CET 2003


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?

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