test_constructors.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import numpy as np
  2. import pytest
  3. from pandas.core.arrays import TimedeltaArray
  4. class TestTimedeltaArrayConstructor:
  5. def test_only_1dim_accepted(self):
  6. # GH#25282
  7. arr = np.array([0, 1, 2, 3], dtype="m8[h]").astype("m8[ns]")
  8. with pytest.raises(ValueError, match="Only 1-dimensional"):
  9. # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
  10. TimedeltaArray(arr.reshape(2, 2, 1))
  11. with pytest.raises(ValueError, match="Only 1-dimensional"):
  12. # 0-dim
  13. TimedeltaArray(arr[[0]].squeeze())
  14. def test_freq_validation(self):
  15. # ensure that the public constructor cannot create an invalid instance
  16. arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10**9
  17. msg = (
  18. "Inferred frequency None from passed values does not "
  19. "conform to passed frequency D"
  20. )
  21. with pytest.raises(ValueError, match=msg):
  22. TimedeltaArray(arr.view("timedelta64[ns]"), freq="D")
  23. def test_non_array_raises(self):
  24. with pytest.raises(ValueError, match="list"):
  25. TimedeltaArray([1, 2, 3])
  26. def test_other_type_raises(self):
  27. with pytest.raises(ValueError, match="dtype bool cannot be converted"):
  28. TimedeltaArray(np.array([1, 2, 3], dtype="bool"))
  29. def test_incorrect_dtype_raises(self):
  30. # TODO: why TypeError for 'category' but ValueError for i8?
  31. with pytest.raises(
  32. ValueError, match=r"category cannot be converted to timedelta64\[ns\]"
  33. ):
  34. TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
  35. with pytest.raises(
  36. ValueError, match=r"dtype int64 cannot be converted to timedelta64\[ns\]"
  37. ):
  38. TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("int64"))
  39. def test_copy(self):
  40. data = np.array([1, 2, 3], dtype="m8[ns]")
  41. arr = TimedeltaArray(data, copy=False)
  42. assert arr._ndarray is data
  43. arr = TimedeltaArray(data, copy=True)
  44. assert arr._ndarray is not data
  45. assert arr._ndarray.base is not data
  46. def test_from_sequence_dtype(self):
  47. msg = "dtype .*object.* cannot be converted to timedelta64"
  48. with pytest.raises(ValueError, match=msg):
  49. TimedeltaArray._from_sequence([], dtype=object)