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

发布于 2024-11-10 15:51:08 字数 1618 浏览 4 评论 0原文

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 和 Python 一起使用。 2.6.

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

Unit testing the above, I know that the following tests in the MissingInput test class:

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

will correctly detect if a MissingInputError exception was raised.

Is there any way to determine in the test what error number was passed to the exception while calling it, so that I can be sure that the error is being raised for that particular missing input, and not for any other missing inputs?

(P.S: Python 2.4.3).


Tip: If you are stuck with 2.4 to 2.6, use the unittest2 library.
In Python 2.7 and 3.2 a whole bunch of improvements to unittest will arrive. unittest2 is a backport of the new features (and tests) to work with Python 2.4, 2.5 & 2.6.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

莫言歌 2024-11-17 15:51:08

您可以传递一个与消息相反的正则表达式:

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

You can pass a regular expression that runs against the message:

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

Does that make sense to you? If you were raising MyError('foo') or MyError(101), the test would fail because those wouldn't match the regular expression of '100'. Fortunately, this method will work against numbers and anything else that you can cast to a string.

See the unittest documentation for details on assertRaisesRegexp.

Alternatively, if you're on Python 2.6 or older, assertRaisesRegexp is not there and you'll have to do something like this:

try:
    <code>
except MyError, message:
    self.failUnlessEqual(message.args, <expected args>)
else:
    self.fail('MyError not raised')
冰火雁神 2024-11-17 15:51:08

这些参数可以在 args 属性中找到:

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

我敢打赌它可用于 Python 2.4 也是如此。

HTH

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

>>> import unittest
>>> class Test(unittest.TestCase):
...     def testA(self):
...         try:
...             raise CustomException(42)
...         except CustomException, e:
...             self.assertEquals(e.args[0], 42)
... 
>>> 

The parameters are found in the args attribute:

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

I'd bet it is available for Python 2.4 as well.

HTH

Edit: since unit tests is common code, you can use the args argument in it as well:

>>> import unittest
>>> class Test(unittest.TestCase):
...     def testA(self):
...         try:
...             raise CustomException(42)
...         except CustomException, e:
...             self.assertEquals(e.args[0], 42)
... 
>>> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文