The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

83 lines
2.4 KiB

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