test_buffers.py revision 12391:ceeca8b41e4b
1import struct
2import pytest
3from pybind11_tests import buffers as m
4from pybind11_tests import ConstructorStats
5
6pytestmark = pytest.requires_numpy
7
8with pytest.suppress(ImportError):
9    import numpy as np
10
11
12def test_from_python():
13    with pytest.raises(RuntimeError) as excinfo:
14        m.Matrix(np.array([1, 2, 3]))  # trying to assign a 1D array
15    assert str(excinfo.value) == "Incompatible buffer format!"
16
17    m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)
18    m4 = m.Matrix(m3)
19
20    for i in range(m4.rows()):
21        for j in range(m4.cols()):
22            assert m3[i, j] == m4[i, j]
23
24    cstats = ConstructorStats.get(m.Matrix)
25    assert cstats.alive() == 1
26    del m3, m4
27    assert cstats.alive() == 0
28    assert cstats.values() == ["2x3 matrix"]
29    assert cstats.copy_constructions == 0
30    # assert cstats.move_constructions >= 0  # Don't invoke any
31    assert cstats.copy_assignments == 0
32    assert cstats.move_assignments == 0
33
34
35# PyPy: Memory leak in the "np.array(m, copy=False)" call
36# https://bitbucket.org/pypy/pypy/issues/2444
37@pytest.unsupported_on_pypy
38def test_to_python():
39    mat = m.Matrix(5, 5)
40    assert memoryview(mat).shape == (5, 5)
41
42    assert mat[2, 3] == 0
43    mat[2, 3] = 4
44    assert mat[2, 3] == 4
45
46    mat2 = np.array(mat, copy=False)
47    assert mat2.shape == (5, 5)
48    assert abs(mat2).sum() == 4
49    assert mat2[2, 3] == 4
50    mat2[2, 3] = 5
51    assert mat2[2, 3] == 5
52
53    cstats = ConstructorStats.get(m.Matrix)
54    assert cstats.alive() == 1
55    del mat
56    pytest.gc_collect()
57    assert cstats.alive() == 1
58    del mat2  # holds a mat reference
59    pytest.gc_collect()
60    assert cstats.alive() == 0
61    assert cstats.values() == ["5x5 matrix"]
62    assert cstats.copy_constructions == 0
63    # assert cstats.move_constructions >= 0  # Don't invoke any
64    assert cstats.copy_assignments == 0
65    assert cstats.move_assignments == 0
66
67
68@pytest.unsupported_on_pypy
69def test_inherited_protocol():
70    """SquareMatrix is derived from Matrix and inherits the buffer protocol"""
71
72    matrix = m.SquareMatrix(5)
73    assert memoryview(matrix).shape == (5, 5)
74    assert np.asarray(matrix).shape == (5, 5)
75
76
77@pytest.unsupported_on_pypy
78def test_pointer_to_member_fn():
79    for cls in [m.Buffer, m.ConstBuffer, m.DerivedBuffer]:
80        buf = cls()
81        buf.value = 0x12345678
82        value = struct.unpack('i', bytearray(buf))[0]
83        assert value == 0x12345678
84