test_protocols.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import pytest
  2. import warnings
  3. import numpy as np
  4. @pytest.mark.filterwarnings("error")
  5. def test_getattr_warning():
  6. # issue gh-14735: make sure we clear only getattr errors, and let warnings
  7. # through
  8. class Wrapper:
  9. def __init__(self, array):
  10. self.array = array
  11. def __len__(self):
  12. return len(self.array)
  13. def __getitem__(self, item):
  14. return type(self)(self.array[item])
  15. def __getattr__(self, name):
  16. if name.startswith("__array_"):
  17. warnings.warn("object got converted", UserWarning, stacklevel=1)
  18. return getattr(self.array, name)
  19. def __repr__(self):
  20. return "<Wrapper({self.array})>".format(self=self)
  21. array = Wrapper(np.arange(10))
  22. with pytest.raises(UserWarning, match="object got converted"):
  23. np.asarray(array)
  24. def test_array_called():
  25. class Wrapper:
  26. val = '0' * 100
  27. def __array__(self, result=None):
  28. return np.array([self.val], dtype=object)
  29. wrapped = Wrapper()
  30. arr = np.array(wrapped, dtype=str)
  31. assert arr.dtype == 'U100'
  32. assert arr[0] == Wrapper.val