Opened 10 years ago

Last modified 10 years ago

#23930 closed New feature

Context manager for capturing output — at Version 1

Reported by: Wojtek Ruszczewski Owned by: nobody
Component: Testing framework Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Wojtek Ruszczewski)

I've recently something like this (for #23929, where the output is generated by a signal handler):

@contextmanager
def capture_stdout():
    """
    Captures the ``sys.stdout`` stream, making anything written to it
    available in the stream returned as the manager's context.

    For example:

        with capture_stdout() as out:
            # Print something.
        self.assertIn("something", out.getvalue())
    """
    old_stdout = sys.stdout
    sys.stdout = out = StringIO()
    try:
        yield out
    finally:
        sys.stdout = old_stdout

Would it be better to make it public, leave it buried for the test only or don't mind testing the output in such cases at all?

Change History (1)

comment:1 by Wojtek Ruszczewski, 10 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top