检查Python 2.7中是否正确引发了异常? [英] Check that an exception is correctly raised in Python 2.7?
问题描述
有人知道如何检查是否正确引发了异常吗?
Does anyone know how to check that an exception is raised correctly?
我需要可以在Python 2.7中运行的工具.下面的"assert"不是在Python unittest库中使用的正确方法:
I need something that works in Python 2.7. The below 'assert' is not quite correct method to use from the Python unittest library:
assert ( a_a0_getinst.add_port("iTCK", ISC.PortType_INPUT) ), "Can't add duplicate port"
我得到的错误是:
Traceback (most recent call last):
File "test_010_module.py", line 157, in runTest
a_a0_addinst = a_a0.add_instance( "A00", b_a0 )
File "/nfs/sc/disks/sc_dteg_2004/users/acheung1/dteg_tools-isc/python/t/ISC.py", line 475, in add_instance
return _ISC.SharedModule_add_instance(self, name, module)
RuntimeError: Can't add duplicate instance with instance name 'A00' to module 'A_A0'
推荐答案
如果只想确保它引发正确的异常类型,则可以使用:
If you just want to make sure it raises the correct type of exception, you can use:
self.assertRaises(RuntimeError, your_function, *args, **kwargs)
在unittest.TestCase类中.请参见 assertRaises的文档.
in a unittest.TestCase class. See the docs for assertRaises.
如果您还想检查它是否还具有正确的错误消息,则可以改用:
If you also want to check that it also has the correct error message, you can instead use:
self.assertRaisesRegexp(RuntimeError, "error message", your_function_call, *args, **kwargs)
在unittest.TestCase类中.这是 assertRaisesRegexp的文档.
in a unittest.TestCase class. Here are the docs for assertRaisesRegexp.
您也可以作为上下文管理器来执行这些操作,在这种情况下,您无需将参数分开:
You can also do these as context managers, in which case you don't need to separate the arguments out:
with self.assertRaises(RuntimeError):
your_function_call(arg1, arg2)
with self.assertRaisesRegexp(RuntimeError, "error message"):
your_function_call(arg1, arg2)
就像您提到的那样,这些都是针对python 2.7的.对于Python 3.x,assertRaises
的行为相同,但是正则表达式之一称为assertRegex
(没有p
).
Those are for Python 2.7, as you mentioned. For Python 3.x, assertRaises
behaves the same, but the regular expression one is called assertRegex
(no p
).
如注释中所指出,这仅在使用unittest风格的测试类时有效.如果您使用的是py.test,则它具有拥有您可以使用的类似方法.
As pointed out in the comments, this only works if you're using unittest-style test classes. If you're using py.test, it has its own similar methods you can use.
这篇关于检查Python 2.7中是否正确引发了异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!