test_buffers.py 2.4 KB

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