test_buffers.py revision 12037:d28054ac6ec9
1import pytest 2from pybind11_tests import Matrix, ConstructorStats 3 4pytestmark = pytest.requires_numpy 5 6with pytest.suppress(ImportError): 7 import numpy as np 8 9 10def test_from_python(): 11 with pytest.raises(RuntimeError) as excinfo: 12 Matrix(np.array([1, 2, 3])) # trying to assign a 1D array 13 assert str(excinfo.value) == "Incompatible buffer format!" 14 15 m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32) 16 m4 = Matrix(m3) 17 18 for i in range(m4.rows()): 19 for j in range(m4.cols()): 20 assert m3[i, j] == m4[i, j] 21 22 cstats = ConstructorStats.get(Matrix) 23 assert cstats.alive() == 1 24 del m3, m4 25 assert cstats.alive() == 0 26 assert cstats.values() == ["2x3 matrix"] 27 assert cstats.copy_constructions == 0 28 # assert cstats.move_constructions >= 0 # Don't invoke any 29 assert cstats.copy_assignments == 0 30 assert cstats.move_assignments == 0 31 32 33# PyPy: Memory leak in the "np.array(m, copy=False)" call 34# https://bitbucket.org/pypy/pypy/issues/2444 35@pytest.unsupported_on_pypy 36def test_to_python(): 37 m = Matrix(5, 5) 38 39 assert m[2, 3] == 0 40 m[2, 3] = 4 41 assert m[2, 3] == 4 42 43 m2 = np.array(m, copy=False) 44 assert m2.shape == (5, 5) 45 assert abs(m2).sum() == 4 46 assert m2[2, 3] == 4 47 m2[2, 3] = 5 48 assert m2[2, 3] == 5 49 50 cstats = ConstructorStats.get(Matrix) 51 assert cstats.alive() == 1 52 del m 53 pytest.gc_collect() 54 assert cstats.alive() == 1 55 del m2 # holds an m reference 56 pytest.gc_collect() 57 assert cstats.alive() == 0 58 assert cstats.values() == ["5x5 matrix"] 59 assert cstats.copy_constructions == 0 60 # assert cstats.move_constructions >= 0 # Don't invoke any 61 assert cstats.copy_assignments == 0 62 assert cstats.move_assignments == 0 63