当用numpy数组手动复制并没有失败时,为什么假设给出了一个伪造的例子?

2024-10-03 11:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写我的第一个超简单的numpy测试用例,但我想到的第一件事似乎遇到了障碍

所以我这样做了:

import numpy as np
from hypothesis import given
import hypothesis.strategies as hs
import hypothesis.extra.numpy as hxn
    
def tstind(a, i):
     i = max(i, 0)
     i = min(i, len(a)-1)
     return a[i]
     
@given(a=hxn.arrays(dtype=hxn.scalar_dtypes(),
       shape=hxn.array_shapes(max_dims=1)),
       i=hs.integers())
def test_tstind_typeconserve(a, i):
     assert tstind(a, i).dtype == a.dtype
     
test_tstind_typeconserve()

伪造的例子:

test_tstind_typeconserve(
    a=array([0.], dtype=float16), i=0,
)

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test_tstind_typeconserve
  File "/tmp/persistent/miniconda3/envs/hypo/lib/python3.7/site-packages/hypothesis/core.py", line 1169, in wrapped_test
    raise the_error_hypothesis_found
  File "<stdin>", line 5, in test_tstind_typeconserve
AssertionError

但是:

a=np.array([0.], dtype=np.float16)
i=0
assert tstind(a, i).dtype == a.dtype

(即正常,不失败)

顺便说一句,我希望它能找到这样一个奇怪的例子:

a=np.ma.masked_array([0.], mask=[1], dtype=np.float16)
a.dtype
dtype('float16')
a[0].dtype
dtype('float64')

Tags: intestimportnumpyasnplinearray
1条回答
网友
1楼 · 发布于 2024-10-03 11:15:59

假设显示Numpy数据类型有distinct byte orders。扩展您的测试

    got = tstind(a, i).dtype
    assert got == a.dtype, (a.dtype.byteorder, got.byteorder)

对我来说AssertionError: ('>', '=')失败。不幸的是,数组对象的repr不包括数据类型字节顺序,但我们现在看到了

(我把这篇报道称为issue 19059,不管它值多少钱)

相关问题 更多 >