问题
Does anyone know how to check that an exception is raised correctly?
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"
The error I get is:
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'
回答1:
If you just want to make sure it raises the correct type of exception, you can use:
self.assertRaises(RuntimeError, your_function, *args, **kwargs)
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)
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)
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
).
EDIT: 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.
来源:https://stackoverflow.com/questions/43814495/check-that-an-exception-is-correctly-raised-in-python-2-7