gpt4 book ai didi

python - 如何在Python2.7的unittest中显示assertRaises()捕获的错误信息?

转载 作者:IT老高 更新时间:2023-10-28 21:39:00 25 4
gpt4 key购买 nike

为了确保来 self 的模块的错误消息提供信息,我想查看 assertRaises() 捕获的所有错误消息。今天我对每个 assertRaises() 都做,但由于测试代码中有很多,所以变得非常乏味。

如何打印所有 assertRaises() 的错误消息?我研究了 http://docs.python.org/library/unittest.html 上的文档没有弄清楚如何解决它。我可以以某种方式对 assertRaises() 方法进行修补吗?我不想更改测试代码中的所有 assertRaises() 行,因为我经常以标准方式使用测试代码。

我猜这个问题与 Python unittest: how do I test the argument in an Exceptions? 有关

这就是我今天的做法。例如:

#!/usr/bin/env python

def fail():
raise ValueError('Misspellled errrorr messageee')

以及测试代码:

#!/usr/bin/env python
import unittest
import failure

class TestFailureModule(unittest.TestCase):

def testFail(self):
self.assertRaises(ValueError, failure.fail)

if __name__ == '__main__':
unittest.main()

要检查错误消息,我只需将 assertRaises() 中的错误类型更改为例如 IOError。然后我可以看到错误信息:

 E
======================================================================
ERROR: testFail (__main__.TestFailureModule)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_failure.py", line 8, in testFail
self.assertRaises(IOError, failure.fail)
File "/usr/lib/python2.7/unittest/case.py", line 471, in assertRaises
callableObj(*args, **kwargs)
File "/home/jonas/Skrivbord/failure.py", line 4, in fail
raise ValueError('Misspellled errrorr messageee')
ValueError: Misspellled errrorr messageee

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

有什么建议吗?/乔纳斯

编辑:

在 Robert Rossney 的提示下,我设法解决了这个问题。它主要不是为了拼写错误,而是为了确保错误消息对模块的用户真正有意义。通过设置 SHOW_ERROR_MESSAGES = False 来实现 unittest 的正常功能(这是我大部分时间使用它的方式)。

我只是重写了 assertRaises() 方法,如下所示。它就像魅力一样!

SHOW_ERROR_MESSAGES = True

class NonexistantError(Exception):
pass

class ExtendedTestCase(unittest.TestCase):
def assertRaises(self, excClass, callableObj, *args, **kwargs):
if SHOW_ERROR_MESSAGES:
excClass = NonexistantError
try:
unittest.TestCase.assertRaises(self, excClass, callableObj, *args, **kwargs)
except:
print '\n ' + repr(sys.exc_info()[1])

结果输出的一小部分:

testNotIntegerInput (__main__.TestCheckRegisteraddress) ... 
TypeError('The registeraddress must be an integer. Given: 1.0',)

TypeError("The registeraddress must be an integer. Given: '1'",)

TypeError('The registeraddress must be an integer. Given: [1]',)

TypeError('The registeraddress must be an integer. Given: None',)
ok
testCorrectNumberOfBytes (__main__.TestCheckResponseNumberOfBytes) ... ok
testInconsistentLimits (__main__.TestCheckNumerical) ...
ValueError('The maxvalue must not be smaller than minvalue. Given: 45 and 47, respectively.',)

ValueError('The maxvalue must not be smaller than minvalue. Given: 45.0 and 47.0, respectively.',)
ok
testWrongValues (__main__.TestCheckRegisteraddress) ...
ValueError('The registeraddress is too small: -1, but minimum value is 0.',)

ValueError('The registeraddress is too large: 65536, but maximum value is 65535.',)
ok
testTooShortString (__main__.TestCheckResponseWriteData) ...
ValueError("The payload is too short: 2, but minimum value is 4. Given: '\\x00X'",)

ValueError("The payload is too short: 0, but minimum value is 4. Given: ''",)

ValueError("The writedata is too short: 1, but minimum value is 2. Given: 'X'",)

ValueError("The writedata is too short: 0, but minimum value is 2. Given: ''",)
ok
testKnownValues (__main__.TestCreateBitPattern) ... ok
testNotIntegerInput (__main__.TestCheckSlaveaddress) ...
TypeError('The slaveaddress must be an integer. Given: 1.0',)

TypeError("The slaveaddress must be an integer. Given: '1'",)

TypeError('The slaveaddress must be an integer. Given: [1]',)

TypeError('The slaveaddress must be an integer. Given: None',)
ok

最佳答案

我曾经更喜欢@Robert Rossney 上面给出的最出色的答案。现在,我更喜欢使用 assertRaises 作为上下文管理器(unittest2 中的一项新功能),如下所示:

with self.assertRaises(TypeError) as cm:
failure.fail()
self.assertEqual(
'The registeraddress must be an integer. Given: 1.0',
str(cm.exception)
)

关于python - 如何在Python2.7的unittest中显示assertRaises()捕获的错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8672754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com