Python unittest - 如何将调试信息添加到 TestResult 对象?

标签 python unit-testing

我有一些运行大量测试的单元测试代码。以前,当运行每个测试时,一些信息会打印到标准输出。如果测试失败,此信息将极大地帮助调试。现在我想编写一个更复杂的程序来调用 unittest 并以编程方式捕获测试结果。 unittest 似乎提供了一个名为 TestResult 的对象,该对象旨在包含测试的输出。它有一个所有错误的列表,一个所有失败的列表,等等。我还想将我的调试输出添加到这个对象,以便我以后可以通过编程方式访问它。这可能吗?

编辑:这是一个例子:

import unittest2

class DemoTest(unittest2.TestCase):
    def test_one(self):
        print "'grimelsome' attribute of 'smoxy' was set to 'blimpy'"
        self.assertTrue(True)

    def test_two(self):
        print "'smithereen' attribute of 'brouhaha' was set to 'False'"
        self.assertTrue(True)

if __name__ == '__main__':
    suite = unittest2.TestLoader().loadTestsFromTestCase(DemoTest)
    result = unittest2.TextTestRunner(verbosity=2).run(suite)

    # this is what I'd like to be able to do:
    for fail in result.failures:
        print what_would_have_gone_to_stdout

最佳答案

您只需要使用 TextTestRunner 缓冲区选项:

import unittest2

class DemoTest(unittest2.TestCase):
    def test_one(self):
        print "'grimelsome' attribute of 'smoxy' was set to 'blimpy'"
        self.assertTrue(True)

    def test_two(self):
        print "'smithereen' attribute of 'brouhaha' was set to 'False'"
        self.assertTrue(False)

if __name__ == '__main__':
    suite = unittest2.TestLoader().loadTestsFromTestCase(DemoTest)
    result = unittest2.TextTestRunner(verbosity=2, buffer=True).run(suite)

在每次测试之前,runner 使用的 TextTestResult 将用它自己的流替换 sys.stderrsys.stdout,并且只如果测试失败则将内容发送到原始流,否则将其丢弃。

请注意,因为伪造的 sys.std* 流在每次测试后都会发生变化,如果您想对日志输出做同样的事情,则必须在 sys.std 之后添加日志处理程序。 sdt* 流已被替换,在每次测试之前或实现您自己的处理程序。

这是一个子类化 logging.StreamHandler 的示例:

import logging
import sys
import unittest2


class DemoTest(unittest2.TestCase):
    logger = logging.getLogger('DemoTest')

    def setUp(self):
        self.logger.debug("setting up stuff and logging it...")

    def teardown(self):
        self.logger.debug("You won't see me")
        print "me neither"

    def test_one(self):
        self.logger.debug("'grimelsome' attribute of 'smoxy' was set to 'blimpy'")
        self.assertTrue(True)

    def test_two(self):
        self.logger.debug("'smithereen' attribute of 'brouhaha' was set to 'False'")
        self.assertTrue(False)


class TestHandler(logging.StreamHandler):

    def __init__(self):
        logging.Handler.__init__(self)

    @property
    def stream(self):
        """Use which ever stream sys.stderr is referencing."""
        return sys.stderr


if __name__ == '__main__':
    formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
    logger_handler = TestHandler()
    logger_handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logger_handler)

    suite = unittest2.TestLoader().loadTestsFromTestCase(DemoTest)
    result = unittest2.TextTestRunner(
        verbosity=2, buffer=True, resultclass=TestResult
    ).run(suite)

关于Python unittest - 如何将调试信息添加到 TestResult 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14244463/

相关文章:

python - 带有 Python CGI 的 CSS 样式表

unit-testing - assert_called_once() 或 assert_called_xyz().... 等效?

python - Salt-Stack:执行与模式匹配的状态

python - 在不知道列表大小的情况下将列表的元素分配给变量?

c# - 单元测试 IHttpModule

c - 比较字符串的有效方法是什么?

c++ - 为一个类编写单元测试

unit-testing - Spock 单元测试断言日志调用并查看输出

python - Python 中错误的余弦值

python - 官方 Python 教程(第 9.10 章)中的示例错误?