Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PythonUnitTest,我如何断言在给出特定消息时报告的错误?_Python_Python Unittest - Fatal编程技术网

使用PythonUnitTest,我如何断言在给出特定消息时报告的错误?

使用PythonUnitTest,我如何断言在给出特定消息时报告的错误?,python,python-unittest,Python,Python Unittest,假设我有一个如下的方法: def my_function(arg1, arg2): if arg1: raise RuntimeError('error message A') else: raise RuntimeError('error message B') 使用python的内置unittets库,是否有任何方法可以判断引发了哪个RuntimeError?我一直在做: import unittest from myfile import

假设我有一个如下的方法:

def my_function(arg1, arg2):
    if arg1:
        raise RuntimeError('error message A')
    else:
        raise RuntimeError('error message B')
使用python的内置unittets库,是否有任何方法可以判断引发了哪个
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
。检查实际的错误消息是我认为可以实现这一点的唯一方法,但我似乎找不到任何assert方法也尝试断言错误消息

unittest用户: 在这种情况下,最好使用

类似于
assertRaises()
,但也测试正则表达式是否与引发的异常的字符串表示形式匹配。正则表达式可以是正则表达式对象,也可以是包含适合
re.search()
使用的正则表达式的字符串

因此,您可以使用:

self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)
pytest用户: 安装我的插件。然后,您可以使用匹配的异常实例进行断言:


您可以使用
assertRaises
作为上下文管理器,并断言异常对象的字符串值符合预期:

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')

演示:

–1您的代码将无法工作,因为异常字符串上的断言无法访问。修正了。编辑后的代码可以正常工作。不过我接受了另一个答案,因为assertRaisesRegex语法非常复杂nicer@Rosey实际上,请记住,
assertRaisesRegex
方法仅在Python 3中可用,因此,如果您的项目需要支持Python 2,您必须使用这种更详细的方法解决。@blhsing不正确,它在Python2中可用,但称为
assertRaisesRegexp
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')