diff -r 96e543ba96a4 Doc/library/test.rst --- a/Doc/library/test.rst Tue May 28 15:53:46 2013 +0300 +++ b/Doc/library/test.rst Tue May 28 16:00:25 2013 +0300 @@ -362,19 +362,34 @@ New optional arguments *filters* and *quiet*. -.. function:: captured_stdout() +.. function:: captured_stderr() + captured_stdout() - A context manager that runs the :keyword:`with` statement body using a - :class:`io.StringIO` object as sys.stdout. That object can be retrieved - using the ``as`` clause of the :keyword:`with` statement. + A context managers that temporarily replaces the + :data:`sys.stderr` / :data:`sys.stdout` stream with :class:`io.StringIO` object. Example use:: - with captured_stdout() as s: - print("hello") + with captured_stderr() as s: + print("hello", file=sys.stderr) assert s.getvalue() == "hello\n" +.. function:: captured_stdin() + + A context manager that temporarily replaces the :data:`sys.stdin` stream with + :class:`io.StringIO` object. + + Example use:: + + with captured_stdin() as s: + s.write('hello\n') + s.seek(0) + # call test code that consumes from stdin + captured = input() + self.assertEqual(captured, "hello") + + .. function:: temp_cwd(name='tempcwd', quiet=False, path=None) A context manager that temporarily changes the current working diff -r 96e543ba96a4 Lib/test/support.py --- a/Lib/test/support.py Tue May 28 15:53:46 2013 +0300 +++ b/Lib/test/support.py Tue May 28 16:00:25 2013 +0300 @@ -1181,14 +1181,29 @@ 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 to sys.stdin: + + with captured_stdin() as s: + s.write('hello\n') + s.seek(0) + # call test code that consumes from stdin + captured = input() + self.assertEqual(captured, "hello") + """ return captured_output("stdin") diff -r 96e543ba96a4 Lib/test/test_support.py --- a/Lib/test/test_support.py Tue May 28 15:53:46 2013 +0300 +++ b/Lib/test/test_support.py Tue May 28 16:00:25 2013 +0300 @@ -141,8 +141,11 @@ 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) + # call test code that consumes from stdin + captured = input() + self.assertEqual(captured, "hello") def test_gc_collect(self): support.gc_collect()