![](/img/trans.png)
[英]In python 3.4.1, how can I assert an error in unittest like this?
[英]Using python unittest, how can I assert an error reported gave a certain message?
假设我有一个看起来像这样的方法:
def my_function(arg1, arg2):
if arg1:
raise RuntimeError('error message A')
else:
raise RuntimeError('error message B')
使用 python 的内置 unittets 库,有没有办法告诉 WHICH RuntimeError
被提出了? 我一直在做:
import unittest
from myfile import my_function
class MyTestCase(unittest.TestCase):
def test_my_function(self):
self.assertRaises(RuntimeError, my_function, arg1, arg2)
但这仅断言遇到了RuntimeError
。 我希望能够知道遇到了 WHICH RuntimeError
。 检查实际的错误消息是我认为可以完成的唯一方法,但我似乎找不到任何断言方法也尝试断言错误消息
在这种情况下,最好使用assertRaisesRegex 。
与
assertRaises()
类似,但也测试正则表达式匹配引发异常的字符串表示。 正则表达式可以是正则表达式 object 或包含适合re.search()
使用的正则表达式的字符串。
所以,你可以使用:
self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)
安装我的插件pytest-raisin 。 然后您可以使用匹配的异常实例进行断言:
with pytest.raises(RuntimeError("error message A")):
my_function(arg1, arg2)
您可以使用assertRaises
作为上下文管理器,并断言异常 object 的字符串值与预期的一样:
def my_function():
raise RuntimeError('hello')
class MyTestCase(unittest.TestCase):
def test_my_function(self):
with self.assertRaises(RuntimeError) as cm:
my_function()
self.assertEqual(str(cm.exception), 'hello')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.