如果我在python中编写单元测试(使用unittest模块),是否可以从失败的测试中输出数据,所以我可以检查它以帮助推断导致错误的原因?我知道能够创建自定义消息,它可以携带一些信息,但有时您可能会处理更复杂的数据,这些数据不能轻易地表示为字符串。
例如,假设您有一个类Foo,并使用名为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,以查看此特定数据导致失败的原因。通过输出,我的意思是在运行测试之后,可以像任何其他变量一样访问变量。
答案 0 :(得分:67)
对于像我一样的人来到这里寻找一个简单快速的答案,这是非常晚的答案。
在Python 2.7中,您可以使用其他参数msg
向错误消息添加信息,如下所示:
self.assertEqual(f.bar(t2), 2, msg='{0}, {1}'.format(t1, t2))
官方文档here
答案 1 :(得分:66)
我们使用日志记录模块。
例如:
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()
这使我们可以打开我们知道失败的特定测试的调试,并且我们需要额外的调试信息。
然而,我首选的方法是不要花费大量时间进行调试,而是花费大量时间编写更精细的测试来揭露问题。
答案 2 :(得分:31)
您可以使用简单的打印语句或任何其他写入stdout的方式。您还可以在测试中的任何位置调用Python调试器。
如果您使用nose来运行测试(我推荐),它将收集每个测试的标准输出,并且仅在测试失败时显示给您,因此您不必使用测试通过时杂乱的输出。
nose还具有自动显示断言中提到的变量的开关,或者在失败的测试中调用调试器。例如-s
(--nocapture
)可以阻止stdout的捕获。
答案 3 :(得分:16)
我认为这不是你想要的,没有办法显示不会失败的变量值,但这可能会帮助你更接近按照你想要的方式输出结果。
您可以使用 TestRunner.run()返回的 TestResult object 进行结果分析和处理。特别是,TestResult.errors和TestResult.failures
关于TestResults对象:
http://docs.python.org/library/unittest.html#id3
有些代码可以指出正确的方向:
>>> import random
>>> import unittest
>>>
>>> class TestSequenceFunctions(unittest.TestCase):
... def setUp(self):
... self.seq = range(5)
... def testshuffle(self):
... # make sure the shuffled sequence does not lose any elements
... random.shuffle(self.seq)
... self.seq.sort()
... self.assertEqual(self.seq, range(10))
... def testchoice(self):
... element = random.choice(self.seq)
... error_test = 1/0
... self.assert_(element in self.seq)
... def testsample(self):
... self.assertRaises(ValueError, random.sample, self.seq, 20)
... for element in random.sample(self.seq, 5):
... self.assert_(element in self.seq)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)
testchoice (__main__.TestSequenceFunctions) ... ERROR
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... FAIL
======================================================================
ERROR: testchoice (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 11, in testchoice
ZeroDivisionError: integer division or modulo by zero
======================================================================
FAIL: testshuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 8, in testshuffle
AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
----------------------------------------------------------------------
Ran 3 tests in 0.031s
FAILED (failures=1, errors=1)
>>>
>>> testResult.errors
[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n File "<stdin>"
, line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')]
>>>
>>> testResult.failures
[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n File "<stdin>
", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')]
>>>
答案 4 :(得分:5)
我想我可能一直在思考这个问题。我提出的一种方法就是完成工作,只需要有一个全局变量,它可以累积诊断数据。
像这样:
log1 = dict()
class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
if f.bar(t2) != 2:
log1("TestBar.runTest") = (f, t1, t2)
self.fail("f.bar(t2) != 2")
感谢您的回复。他们给了我一些关于如何记录单元测试信息的替代方法。
答案 5 :(得分:5)
另一种选择 - 启动测试失败的调试器。
尝试使用Testoob运行测试(它将运行您的unittest套件而不进行更改),并且您可以使用'--debug'命令行开关在测试失败时打开调试器。
这是Windows上的终端会话:
C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
1 from unittest import TestCase
2 class MyTests(TestCase):
3 def test_foo(self):
4 x = 1
5 y = 2
6 -> self.assertEqual(x, y)
[EOF]
(Pdb)
答案 6 :(得分:5)
我使用的方法非常简单。我只是将其记录为警告,以便它实际显示出来。
import logging
class TestBar(unittest.TestCase):
def runTest(self):
#this line is important
logging.basicConfig()
log = logging.getLogger("LOG")
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
log.warning(t1)
答案 7 :(得分:2)
使用记录:
import unittest
import logging
import inspect
import os
logging_level = logging.INFO
try:
log_file = os.environ["LOG_FILE"]
except KeyError:
log_file = None
def logger(stack=None):
if not hasattr(logger, "initialized"):
logging.basicConfig(filename=log_file, level=logging_level)
logger.initialized = True
if not stack:
stack = inspect.stack()
name = stack[1][3]
try:
name = stack[1][0].f_locals["self"].__class__.__name__ + "." + name
except KeyError:
pass
return logging.getLogger(name)
def todo(msg):
logger(inspect.stack()).warning("TODO: {}".format(msg))
def get_pi():
logger().info("sorry, I know only three digits")
return 3.14
class Test(unittest.TestCase):
def testName(self):
todo("use a better get_pi")
pi = get_pi()
logger().info("pi = {}".format(pi))
todo("check more digits in pi")
self.assertAlmostEqual(pi, 3.14)
logger().debug("end of this test")
pass
用法:
# LOG_FILE=/tmp/log python3 -m unittest LoggerDemo
.
----------------------------------------------------------------------
Ran 1 test in 0.047s
OK
# cat /tmp/log
WARNING:Test.testName:TODO: use a better get_pi
INFO:get_pi:sorry, I know only three digits
INFO:Test.testName:pi = 3.14
WARNING:Test.testName:TODO: check more digits in pi
如果您未设置LOG_FILE
,则记录将转到stderr
。
答案 8 :(得分:2)
You can use logging
module for that.
So in the unit test code, use:
import logging as log
def test_foo(self):
log.debug("Some debug message.")
log.info("Some info message.")
log.warning("Some warning message.")
log.error("Some error message.")
By default warnings and errors are outputted to /dev/stderr
, so they should be visible on the console.
To customize logs (such as formatting), try the following sample:
# Set-up logger
if args.verbose or args.debug:
logging.basicConfig( stream=sys.stdout )
root = logging.getLogger()
root.setLevel(logging.INFO if args.verbose else logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO if args.verbose else logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
root.addHandler(ch)
else:
logging.basicConfig(stream=sys.stderr)
答案 9 :(得分:2)
在这些情况下,我要做的是在我的应用程序中添加一些log.debug()
消息。由于默认日志记录级别为WARNING
,因此这些消息不会在正常执行中显示。
然后,在unittest中我将日志记录级别更改为DEBUG
,以便在运行时显示此类消息。
import logging
log.debug("Some messages to be shown just when debugging or unittesting")
在单元测试中:
# Set log level
loglevel = logging.DEBUG
logging.basicConfig(level=loglevel)
查看完整示例:
这是daikiri.py
,这是一个以其名称和价格实现Daikiri的基本类。方法make_discount()
在应用给定折扣后返回特定daikiri的价格:
import logging
log = logging.getLogger(__name__)
class Daikiri(object):
def __init__(self, name, price):
self.name = name
self.price = price
def make_discount(self, percentage):
log.debug("Deducting discount...") # I want to see this message
return self.price * percentage
然后,我创建了一个单元测试test_daikiri.py
,用于检查其用法:
import unittest
import logging
from .daikiri import Daikiri
class TestDaikiri(unittest.TestCase):
def setUp(self):
# Changing log level to DEBUG
loglevel = logging.DEBUG
logging.basicConfig(level=loglevel)
self.mydaikiri = Daikiri("cuban", 25)
def test_drop_price(self):
new_price = self.mydaikiri.make_discount(0)
self.assertEqual(new_price, 0)
if __name__ == "__main__":
unittest.main()
因此,当我执行它时,我收到log.debug
条消息:
$ python -m test_daikiri
DEBUG:daikiri:Deducting discount...
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
答案 10 :(得分:1)
inspect.trace将在抛出异常后让您获取局部变量。然后,您可以使用类似下面的装饰器来包装单元测试,以便在验尸期间保存这些局部变量以进行检查。
import random
import unittest
import inspect
def store_result(f):
"""
Store the results of a test
On success, store the return value.
On failure, store the local variables where the exception was thrown.
"""
def wrapped(self):
if 'results' not in self.__dict__:
self.results = {}
# If a test throws an exception, store local variables in results:
try:
result = f(self)
except Exception as e:
self.results[f.__name__] = {'success':False, 'locals':inspect.trace()[-1][0].f_locals}
raise e
self.results[f.__name__] = {'success':True, 'result':result}
return result
return wrapped
def suite_results(suite):
"""
Get all the results from a test suite
"""
ans = {}
for test in suite:
if 'results' in test.__dict__:
ans.update(test.results)
return ans
# Example:
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
@store_result
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
return {1:2}
@store_result
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
return {7:2}
@store_result
def test_sample(self):
x = 799
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
return {1:99999}
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)
from pprint import pprint
pprint(suite_results(suite))
最后一行将打印测试成功的返回值和局部变量,在本例中为x,当它失败时:
{'test_choice': {'result': {7: 2}, 'success': True},
'test_sample': {'locals': {'self': <__main__.TestSequenceFunctions testMethod=test_sample>,
'x': 799},
'success': False},
'test_shuffle': {'result': {1: 2}, 'success': True}}
Hardetgøy: - )
答案 11 :(得分:1)
您也可以使用 --locals
选项:python3 -m unittest --locals
。
来自python3 -m unittest -h
:--locals Show local variables in tracebacks
答案 12 :(得分:0)
如何捕获断言失败产生的异常?在您的catch块中,您可以输出您想要的数据。然后,当你完成后,你可以重新抛出异常。测试运行器可能不知道差异。
免责声明:我没有尝试使用python的单元测试框架,但与其他单元测试框架一起使用。
答案 13 :(得分:-1)
扩展@ F.C.回答,这对我很有用:
class MyTest(unittest.TestCase):
def messenger(self, message):
try:
self.assertEqual(1, 2, msg=message)
except AssertionError as e:
print "\nMESSENGER OUTPUT: %s" % str(e),