在Python中处理从断言到NumPy测试的异常
了解某人的代码并遇到以下情况: 有一个功能:在Python中处理从断言到NumPy测试的异常,python,unit-testing,numpy,exception,assert,Python,Unit Testing,Numpy,Exception,Assert,了解某人的代码并遇到以下情况: 有一个功能: def some_func(): print("Hello") assert(len(y)==len(p)) print("First assert") assert(p.all()<=0.99999) print("Second assert") return 1 在输出中,我们只需获得Hello而无异常消息: Hello 接下来,调用函数assert\
def some_func():
print("Hello")
assert(len(y)==len(p))
print("First assert")
assert(p.all()<=0.99999)
print("Second assert")
return 1
在输出中,我们只需获得Hello而无异常消息:
Hello
接下来,调用函数assert\u array\u less:
np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)
在输出中,我们首先得到Hello assert,然后是错误消息和AssertionError异常:
Hello
First assert
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-26-df1a32b4f5a0> in <module>()
9 np.testing.assert_raises(AssertionError, some_func, np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))
10
---> 11 np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)
<ipython-input-26-df1a32b4f5a0> in some_func(a, b)
3 assert(len(a)==len(b))
4 print("First assert")
----> 5 assert(a.all()<=0.99999)
6 print("Second assert")
7 return 1
AssertionError:
你好
第一断言
---------------------------------------------------------------------------
AssertionError回溯(上次最近的调用)
在()
9 np.testing.assert(断言错误,某些函数,np.asarray([1,2,3]),np.asarray([1,2,3,4,5]))
10
--->11 np.testing.assert\u array\u less(一些函数(np.asarray([1,2,3])、np.asarray([1,2,3])、np.inf)
在某些函数中(a,b)
3断言(len(a)=len(b))
4打印(“第一次断言”)
---->5 assert(a.all()根据您显示的错误消息,我猜您的
some_func
函数的实际定义是:
def some_func(a, b):
print("Hello")
assert(len(a)==len(b))
print("First assert")
assert(a.all()<=0.99999)
print("Second assert")
return 1
函数np.testing.assert\u依次调用
some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))
的第一行运行并打印some_func
Hello
- 接下来,
尝试断言some_func
和a
的长度相同。但是,b
的长度是3,a
的长度是5,因此断言失败。这会导致抛出b
。此时,AssertionError
的执行被终止,并且控件返回到some_func
assert\u
通过传递给它的第一个参数被告知需要一个assert\u-raises
。它看到一个AssertionError
确实被抛出了,所以从它的角度来看一切都很好。它处理AssertionError
(防止它创建一个错误消息,显示给用户),并且AssertionError
assert\u的执行正常结束
np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)
- 再次,运行并打印
的Hello
的第一行some_func
- 这一次,
,因此len(a)==len(b)==3
通过并正常继续执行assert
某些功能
- 接下来,第三行
运行并打印some_func
First assert
中的每个值都不是零,因此a
是a.all()
。布尔值True
的数值为True
。因此,1
a.all()
some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))
np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)