Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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
Python 在单元测试中,如何确定传递给自定义异常的参数?_Python_Unit Testing_Custom Exceptions - Fatal编程技术网

Python 在单元测试中,如何确定传递给自定义异常的参数?

Python 在单元测试中,如何确定传递给自定义异常的参数?,python,unit-testing,custom-exceptions,Python,Unit Testing,Custom Exceptions,单元测试在上面,我知道MissingInput测试类中有以下测试: def validate(self): """ Method of Input class to validate input and save it """ params = self.__params if 'dt' in params: self.__validateKey(escape(params['dt'][0])) else: raise Miss

单元测试在上面,我知道MissingInput测试类中有以下测试:

def validate(self):
    """ Method of Input class to validate input and save it """

    params = self.__params

    if 'dt' in params:
        self.__validateKey(escape(params['dt'][0]))
    else:
        raise MissingInputError(1101)

    if 'key' in params:
        self.__validateService(escape(params['key'][0]))
    else:
        raise MissingInputError(1102)

    # and so on ...
将正确检测是否引发MissingInputError异常

是否有任何方法可以在测试中确定调用异常时传递给异常的错误号,以便我可以确保针对该特定缺失输入而不是任何其他缺失输入引发错误

(附言:Python 2.4.3


提示:如果你一直坚持2.4到2.6,请使用。
在Python2.7和3.2中,将实现对unittest的一系列改进。unittest2是用于Python 2.4、2.5和2.6的新功能(和测试)的后端口。

您可以传递一个针对以下消息运行的正则表达式:

def testMissingKeyInput(self):
    """ Missing key should raise error """
    ip = controller.Input(MissingInput.missInputKey)
    self.assertRaises(errors.MissingInputError, ip.validate)

def testMissingDtInput(self):
    """ Missing dt should raise error """
    ip = controller.Input(MissingInput.missInputDt)
    self.assertRaises(errors.MissingInputError, ip.validate)

# and so on ...
这对你有意义吗?如果您正在生成MyError('foo')或MyError(101),测试将失败,因为它们与正则表达式'100'不匹配。幸运的是,此方法可以处理数字和任何可以转换为字符串的内容

有关assertRaisesRegexp的详细信息,请参阅

或者,如果您使用的是Python 2.6或更早版本,则assertRaisesRegexp不存在,您必须执行以下操作:

import unittest

class MyError(Exception):
    pass

def raiseError():
    raise MyError(100)

class TestStuff(unittest.TestCase):
    def testError(self):
        self.assertRaisesRegexp(MyError, '100', raiseError)

unittest.main()    
试试看:

除MyError外,信息:
self.failUnlessEqual(message.args,)
其他:
self.fail('未引发MyError')

参数可在
args
属性中找到:

try:
    <code>
except MyError, message:
    self.failUnlessEqual(message.args, <expected args>)
else:
    self.fail('MyError not raised')
我敢打赌也是这样

编辑:由于单元测试是通用代码,因此也可以在其中使用
args
参数:

>>> class CustomException(Exception):
...     pass
... 
>>> e = CustomException(42)
>>> e.args
(42,)

谢谢,肯。不幸的是,我得到了以下错误-AttributeError:“TestStuff”对象没有属性“assertRaisesRegexp”-我猜Python2.4.3不支持这一点。是的,2.4非常旧。在这种情况下,您可能只需要执行try/except块。我将更新我的答案。事实上,它只出现在Python 2.7或更高版本中。是的,但RedHat/CentOS更喜欢Python的那个版本,因此我坚持使用它。:)我想你的意思是,
self.failUnlessEqual(message.args[0])
。啊。。。你可以直接从2.7中获取unittest模块,但我怀疑这是否值得。关于message.args,您是对的;我更新了我的答案。谢谢。事实上,这正是我捕捉异常的方式。但不知何故,我有一种唠叨(非理性?)的感觉,一个尝试…除了块不应该在unittest中使用。哦,不,没有这样的约束。如果您使用的是Python2.7,我建议您使用Ken使用的
assertRaises()
方法,但在Python2.4中,一个
try except
方法是可行的。无论如何,
args
参数在使用这些解决方案的异常中可用。
>>> class CustomException(Exception):
...     pass
... 
>>> e = CustomException(42)
>>> e.args
(42,)
>>> import unittest
>>> class Test(unittest.TestCase):
...     def testA(self):
...         try:
...             raise CustomException(42)
...         except CustomException, e:
...             self.assertEquals(e.args[0], 42)
... 
>>>