summaryrefslogtreecommitdiff
path: root/numpy/tests
diff options
context:
space:
mode:
authorEric Wieser <wieser.eric@gmail.com>2018-04-24 21:34:40 -0700
committerEric Wieser <wieser.eric@gmail.com>2018-05-26 01:21:02 -0700
commit8a8be508d2b2ce719de94209286293973c278b46 (patch)
tree234cbbbd5ab2ff15b5bf817556c45c15047df127 /numpy/tests
parent4ec8930f0b60d7fff059d0f005ed2a0efbf41fb7 (diff)
downloadnumpy-8a8be508d2b2ce719de94209286293973c278b46.tar.gz
BUG: Remove fragile use of __array_interface__ in ctypeslib.as_array
Everything behaves a lot better if we let the array constructor handle it, which will use the ctypes PEP3118 support. Bugs this fixes: * Stale state being attached to pointer objects (fixes gh-2671, closes gh-6214) * Weird failure modes on structured arrays (fixes-10978) * A regression in gh-10882 (fixes gh-10968)
Diffstat (limited to 'numpy/tests')
-rw-r--r--numpy/tests/test_ctypeslib.py48
1 files changed, 43 insertions, 5 deletions
diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py
index fd4336fad..75ce9c8ca 100644
--- a/numpy/tests/test_ctypeslib.py
+++ b/numpy/tests/test_ctypeslib.py
@@ -118,17 +118,55 @@ class TestNdpointer(object):
class TestAsArray(object):
def test_array(self):
from ctypes import c_int
- at = c_int * 2
- a = as_array(at(1, 2))
+
+ pair_t = c_int * 2
+ a = as_array(pair_t(1, 2))
assert_equal(a.shape, (2,))
assert_array_equal(a, np.array([1, 2]))
- a = as_array((at * 3)(at(1, 2), at(3, 4), at(5, 6)))
+ a = as_array((pair_t * 3)(pair_t(1, 2), pair_t(3, 4), pair_t(5, 6)))
assert_equal(a.shape, (3, 2))
assert_array_equal(a, np.array([[1, 2], [3, 4], [5, 6]]))
def test_pointer(self):
from ctypes import c_int, cast, POINTER
+
p = cast((c_int * 10)(*range(10)), POINTER(c_int))
- a = as_array(p, (10,))
+
+ a = as_array(p, shape=(10,))
assert_equal(a.shape, (10,))
- assert_array_equal(a, np.array(range(10)))
+ assert_array_equal(a, np.arange(10))
+
+ a = as_array(p, shape=(2, 5))
+ assert_equal(a.shape, (2, 5))
+ assert_array_equal(a, np.arange(10).reshape((2, 5)))
+
+ # shape argument is required
+ assert_raises(TypeError, as_array, p)
+
+ def test_struct_array_pointer(self):
+ from ctypes import c_int16, Structure, pointer
+
+ class Struct(Structure):
+ _fields_ = [('a', c_int16)]
+
+ Struct3 = 3 * Struct
+
+ c_array = (2 * Struct3)(
+ Struct3(Struct(a=1), Struct(a=2), Struct(a=3)),
+ Struct3(Struct(a=4), Struct(a=5), Struct(a=6))
+ )
+
+ expected = np.array([
+ [(1,), (2,), (3,)],
+ [(4,), (5,), (6,)],
+ ], dtype=[('a', np.int16)])
+
+ def check(x):
+ assert_equal(x.dtype, expected.dtype)
+ assert_equal(x, expected)
+
+ # all of these should be equivalent
+ check(as_array(c_array))
+ check(as_array(pointer(c_array), shape=()))
+ check(as_array(pointer(c_array[0]), shape=(2,)))
+ check(as_array(pointer(c_array[0][0]), shape=(2, 3)))