diff -r 09b88b5bebd0 Doc/library/test.rst --- a/Doc/library/test.rst Tue May 28 12:50:54 2013 +0300 +++ b/Doc/library/test.rst Tue May 28 14:42:18 2013 +0300 @@ -362,6 +362,34 @@ New optional arguments *filters* and *quiet*. +.. function:: captured_stderr() + + A context manager that runs the :keyword:`with` statement body using a + :class:`io.StringIO` object as sys.stderr. That object can be retrieved + using the ``as`` clause of the :keyword:`with` statement. + + Example use:: + + with captured_stderr() as s: + print("hello", file=sys.stderr) + assert s.getvalue() == "hello\n" + + +.. function:: captured_stdin() + + A context manager that runs the :keyword:`with` statement body using a + :class:`io.StringIO` object as sys.stdin. That object can be retrieved + using the ``as`` clause of the :keyword:`with` statement. + + Example use:: + + with support.captured_stdin() as s: + s.write('hello\n') + s.seek(0) + captured = input() + self.assertEqual(captured, "hello") + + .. function:: captured_stdout() A context manager that runs the :keyword:`with` statement body using a diff -r 09b88b5bebd0 Lib/test/support.py --- a/Lib/test/support.py Tue May 28 12:50:54 2013 +0300 +++ b/Lib/test/support.py Tue May 28 14:42:18 2013 +0300 @@ -1181,14 +1181,28 @@ with captured_stdout() as s: print("hello") - self.assertEqual(s.getvalue(), "hello") + self.assertEqual(s.getvalue(), "hello\n") """ return captured_output("stdout") def captured_stderr(): + """Capture the output of sys.stderr: + + with captured_stderr() as s: + print("hello", file=sys.stderr) + self.assertEqual(s.getvalue(), "hello\n") + """ return captured_output("stderr") def captured_stdin(): + """Capture the input of sys.stdin: + + with support.captured_stdin() as s: + s.write('hello\n') + s.seek(0) + captured = input() + self.assertEqual(captured, "hello") + """ return captured_output("stdin") diff -r 09b88b5bebd0 Lib/test/test_support.py --- a/Lib/test/test_support.py Tue May 28 12:50:54 2013 +0300 +++ b/Lib/test/test_support.py Tue May 28 14:42:18 2013 +0300 @@ -141,8 +141,10 @@ def test_captured_stdin(self): with support.captured_stdin() as s: - print("hello", file=sys.stdin) - self.assertEqual(s.getvalue(), "hello\n") + s.write('hello\n') + s.seek(0) + captured = input() + self.assertEqual(captured, "hello") def test_gc_collect(self): support.gc_collect()