且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查Python 2.7中是否正确引发了异常?

更新时间:2022-05-14 02:12:41

如果只想确保它引发正确的异常类型,则可以使用:

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.