永发信息网

python:assert_raises() 怎么用啊,有哪些参数? 请说得详细些,先谢谢了!

答案:1  悬赏:70  手机版
解决时间 2021-12-22 21:09
  • 提问者网友:孤山下
  • 2021-12-22 02:12
python:assert_raises() 怎么用啊,有哪些参数? 请说得详细些,先谢谢了!
最佳答案
  • 五星知识达人网友:罪歌
  • 2022-01-10 04:21
刚才查了,它应该是nose测试框架中的一个测试用例的书写办法。如果没有文档,就看它的源代码。我刚刚下载了nose。


在1.0版本里找到这样一句话。
def raises(*exceptions):
    """Test must raise one of expected exceptions to pass.
    .....

    If you want to test many assertions about exceptions in a single test,
    you may want to use `assert_raises` instead.
    """
从含义上看,应该是确保一定要发生异常。而且要用在大量使用assert语言产生异常的条件下。


下面一段更说明问题。
def assert_raises(exception, callable, *args, **kw):
try:
callable(*args, **kw)
except exception, e:
return e
else:
if hasattr(exception, '__name__'):
name = exception.__name__
else:
name = ' or '.join([e.__name__ for e in exception])
assert False, '%s() did not raise %s' % (callable.__name__, name)

Usage:
def test_foo():
    e = assert_raises(EnvironmentError, open, '/tmp/notfound')
    assert e.errno == errno.ENOENT 还比如这样子。
import math

import py.test
py.test.raises(OverflowError, math.log, 0)
py.test.raises(ValueError, math.sqrt, -1)
py.test.raises(ZeroDivisionError, "1 / 0")

import nose.tools
nose.tools.assert_raises(OverflowError, math.log, 0)
nose.tools.assert_raises(ValueError, math.sqrt, -1)
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯