Eric Cope
Eric Cope

Reputation: 877

Printing to stdout and XML file using Python unittest-xml-reporting

I am using an extension of python's unittest, unittest-xml-reporting. It currently captures stdout and stores it in the xml output file. Awesome! But, I also want to echo it to the screen so I don't have to view that file every time I run my test suite. The two main functions involved are:

def _patch_standard_output(self):
    """Replace the stdout and stderr streams with string-based streams
    in order to capture the tests' output.
    """
    (self.old_stdout, self.old_stderr) = (sys.stdout, sys.stderr)
    (sys.stdout, sys.stderr) = (self.stdout, self.stderr) = \
        (StringIO(), StringIO())

def _restore_standard_output(self):
    "Restore the stdout and stderr streams."
    (sys.stdout, sys.stderr) = (self.old_stdout, self.old_stderr)

I tried removing the

(sys.stdout, sys.stderr) = (self.stdout, self.stderr) = (StringIO(), StringIO())

and replace it with

(self.stdout, self.stderr) = (StringIO(), StringIO())

but then it did not add it to the xml file. Any help is appreciated. I'll be glad to submit a pull request when I get it working too!

Upvotes: 4

Views: 2869

Answers (1)

Himanshu
Himanshu

Reputation: 2454

The current version does this http://pypi.python.org/pypi/unittest-xml-reporting/.

I tried it with the sample code here and the test output goes to xml and the stdout both https://github.com/danielfm/unittest-xml-reporting

Moreover the corresponding code apparently updated now :-

class _DelegateIO(object):
    """This class defines an object that captures whatever is written to
    a stream or file.
    """

    def __init__(self, delegate):
        self._captured = StringIO()
        self.delegate = delegate

    def write(self, text):
        self._captured.write(text)
        self.delegate.write(text)


def _patch_standard_output(self):
        """Replaces stdout and stderr streams with string-based streams
        in order to capture the tests' output.
        """
        sys.stdout = _DelegateIO(sys.stdout)
        sys.stderr = _DelegateIO(sys.stderr)

Upvotes: 2

Related Questions