使用Python unittest-xml-reporting将内容打印到标准输出和XML文件

4
我正在使用Python的unittest扩展unittest-xml-reporting。它目前可以捕获stdout并将其存储在xml输出文件中。太棒了!但我也想要将其回显到屏幕上,这样每次运行测试套件时就不必查看该文件了。涉及到的两个主要函数是:
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)

我尝试移除了

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

将其替换为


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

但是它没有将其添加到XML文件中。任何帮助都将不胜感激。当我使其正常工作时,我很乐意提交一个pull request!
1个回答

2

当前版本可以通过http://pypi.python.org/pypi/unittest-xml-reporting/实现此功能。

我在这里尝试了示例代码,测试输出同时转换为XML和标准输出https://github.com/danielfm/unittest-xml-reporting

此外,相应的代码显然已经更新:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接