blob: 956839c1ca3dc4b07c7a37447fbe6dd398332f2c [file] [log] [blame]
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02001import pytest
2from pybind11_tests import Matrix, ConstructorStats
3
4with pytest.suppress(ImportError):
5 import numpy as np
6
7
8@pytest.requires_numpy
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02009def test_from_python():
10 with pytest.raises(RuntimeError) as excinfo:
11 Matrix(np.array([1, 2, 3])) # trying to assign a 1D array
12 assert str(excinfo.value) == "Incompatible buffer format!"
13
14 m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)
15 m4 = Matrix(m3)
16
17 for i in range(m4.rows()):
18 for j in range(m4.cols()):
19 assert m3[i, j] == m4[i, j]
20
21 cstats = ConstructorStats.get(Matrix)
22 assert cstats.alive() == 1
23 del m3, m4
24 assert cstats.alive() == 0
25 assert cstats.values() == ["2x3 matrix"]
26 assert cstats.copy_constructions == 0
27 # assert cstats.move_constructions >= 0 # Don't invoke any
28 assert cstats.copy_assignments == 0
29 assert cstats.move_assignments == 0
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +010030
31
32# PyPy: Memory leak in the "np.array(m, copy=False)" call
33# https://bitbucket.org/pypy/pypy/issues/2444
34@pytest.unsupported_on_pypy
35@pytest.requires_numpy
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