blob: f0ea964d942b8b3b3ba83155b0a8f2c48727aa08 [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
9def test_to_python():
10 m = Matrix(5, 5)
11
12 assert m[2, 3] == 0
13 m[2, 3] = 4
14 assert m[2, 3] == 4
15
16 m2 = np.array(m, copy=False)
17 assert m2.shape == (5, 5)
18 assert abs(m2).sum() == 4
19 assert m2[2, 3] == 4
20 m2[2, 3] = 5
21 assert m2[2, 3] == 5
22
23 cstats = ConstructorStats.get(Matrix)
24 assert cstats.alive() == 1
25 del m
26 assert cstats.alive() == 1
27 del m2 # holds an m reference
28 assert cstats.alive() == 0
29 assert cstats.values() == ["5x5 matrix"]
30 assert cstats.copy_constructions == 0
31 # assert cstats.move_constructions >= 0 # Don't invoke any
32 assert cstats.copy_assignments == 0
33 assert cstats.move_assignments == 0
34
35
36@pytest.requires_numpy
37def test_from_python():
38 with pytest.raises(RuntimeError) as excinfo:
39 Matrix(np.array([1, 2, 3])) # trying to assign a 1D array
40 assert str(excinfo.value) == "Incompatible buffer format!"
41
42 m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)
43 m4 = Matrix(m3)
44
45 for i in range(m4.rows()):
46 for j in range(m4.cols()):
47 assert m3[i, j] == m4[i, j]
48
49 cstats = ConstructorStats.get(Matrix)
50 assert cstats.alive() == 1
51 del m3, m4
52 assert cstats.alive() == 0
53 assert cstats.values() == ["2x3 matrix"]
54 assert cstats.copy_constructions == 0
55 # assert cstats.move_constructions >= 0 # Don't invoke any
56 assert cstats.copy_assignments == 0
57 assert cstats.move_assignments == 0