在 Python 中从单元测试输出数据 [英] Outputting data from unit test in Python

查看:35
本文介绍了在 Python 中从单元测试输出数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Python 中编写单元测试(使用 unittest 模块),是否可以从失败的测试中输出数据,以便我可以检查它以帮助推断导致错误的原因?

If I'm writing unit tests in Python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error?

我知道创建自定义消息的能力,它可以携带一些信息,但有时您可能会处理更复杂的数据,这些数据不能轻易表示为字符串.

I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.

例如,假设您有一个类 Foo,并且正在使用来自名为 testdata 的列表中的数据测试方法 bar:

For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:

class TestBar(unittest.TestCase):
    def runTest(self):
        for t1, t2 in testdata:
            f = Foo(t1)
            self.assertEqual(f.bar(t2), 2)

如果测试失败,我可能想输出 t1、t2 和/或 f,以了解为什么此特定数据会导致失败.通过输出,我的意思是在测试运行后,这些变量可以像任何其他变量一样被访问.

If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.

推荐答案

我们为此使用日志记录模块.

We use the logging module for this.

例如:

import logging
class SomeTest( unittest.TestCase ):
    def testSomething( self ):
        log= logging.getLogger( "SomeTest.testSomething" )
        log.debug( "this= %r", self.this )
        log.debug( "that= %r", self.that )
        # etc.
        self.assertEquals( 3.14, pi )

if __name__ == "__main__":
    logging.basicConfig( stream=sys.stderr )
    logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
    unittest.main()

这允许我们为我们知道失败的特定测试打开调试,并且我们需要额外的调试信息.

That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.

然而,我更喜欢的方法不是花大量时间在调试上,而是花时间编写更细粒度的测试来暴露问题.

My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.

这篇关于在 Python 中从单元测试输出数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆