test_utils.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from io import StringIO
  2. import pytest
  3. import numpy as np
  4. import numpy.lib._utils_impl as _utils_impl
  5. from numpy.testing import assert_raises_regex
  6. def test_assert_raises_regex_context_manager():
  7. with assert_raises_regex(ValueError, 'no deprecation warning'):
  8. raise ValueError('no deprecation warning')
  9. def test_info_method_heading():
  10. # info(class) should only print "Methods:" heading if methods exist
  11. class NoPublicMethods:
  12. pass
  13. class WithPublicMethods:
  14. def first_method():
  15. pass
  16. def _has_method_heading(cls):
  17. out = StringIO()
  18. np.info(cls, output=out)
  19. return 'Methods:' in out.getvalue()
  20. assert _has_method_heading(WithPublicMethods)
  21. assert not _has_method_heading(NoPublicMethods)
  22. def test_drop_metadata():
  23. def _compare_dtypes(dt1, dt2):
  24. return np.can_cast(dt1, dt2, casting='no')
  25. # structured dtype
  26. dt = np.dtype([('l1', [('l2', np.dtype('S8', metadata={'msg': 'toto'}))])],
  27. metadata={'msg': 'titi'})
  28. dt_m = _utils_impl.drop_metadata(dt)
  29. assert _compare_dtypes(dt, dt_m) is True
  30. assert dt_m.metadata is None
  31. assert dt_m['l1'].metadata is None
  32. assert dt_m['l1']['l2'].metadata is None
  33. # alignment
  34. dt = np.dtype([('x', '<f8'), ('y', '<i4')],
  35. align=True,
  36. metadata={'msg': 'toto'})
  37. dt_m = _utils_impl.drop_metadata(dt)
  38. assert _compare_dtypes(dt, dt_m) is True
  39. assert dt_m.metadata is None
  40. # subdtype
  41. dt = np.dtype('8f',
  42. metadata={'msg': 'toto'})
  43. dt_m = _utils_impl.drop_metadata(dt)
  44. assert _compare_dtypes(dt, dt_m) is True
  45. assert dt_m.metadata is None
  46. # scalar
  47. dt = np.dtype('uint32',
  48. metadata={'msg': 'toto'})
  49. dt_m = _utils_impl.drop_metadata(dt)
  50. assert _compare_dtypes(dt, dt_m) is True
  51. assert dt_m.metadata is None
  52. @pytest.mark.parametrize("dtype",
  53. [np.dtype("i,i,i,i")[["f1", "f3"]],
  54. np.dtype("f8"),
  55. np.dtype("10i")])
  56. def test_drop_metadata_identity_and_copy(dtype):
  57. # If there is no metadata, the identity is preserved:
  58. assert _utils_impl.drop_metadata(dtype) is dtype
  59. # If there is any, it is dropped (subforms are checked above)
  60. dtype = np.dtype(dtype, metadata={1: 2})
  61. assert _utils_impl.drop_metadata(dtype).metadata is None