4
class AppError(Exception): pass

class MissingInputError(AppError):

    em = {1101: "Date input is missing. Please verify.", \
          1102: "Key input is missing. Please verify.", \
          1103: "Stn input is missing. Please verify."}
          # and so on ...

...

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 ...

上面的单元测试,我知道MissingInput测试类中的测试如下:

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 ...

将正确检测是否引发了 MissingInputError 异常。

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

(PS:Python 2.4.3)。


提示:如果您坚持使用 2.4 到 2.6,请使用unittest2 库。在 Python 2.7 和 3.2 中,单元测试的一大堆改进将会到来。unittest2 是用于 Python 2.4、2.5 和 2.6 的新功能(和测试)的反向移植。

4

2 回答 2

3

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

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('foo') 或 MyError(101),测试将失败,因为它们与 '100' 的正则表达式不匹配。幸运的是,此方法适用于数字以及您可以转换为字符串的任何其他内容。

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

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

try:
    <code>
except MyError, message:
    self.failUnlessEqual(message.args, <expected args>)
else:
    self.fail('MyError not raised')
于 2011-06-01T19:09:39.303 回答
2

参数在args属性中找到:

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

我敢打赌它也适用于 Python 2.4

高温高压

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

>>> import unittest
>>> class Test(unittest.TestCase):
...     def testA(self):
...         try:
...             raise CustomException(42)
...         except CustomException, e:
...             self.assertEquals(e.args[0], 42)
... 
>>> 
于 2011-06-01T19:20:00.423 回答