Skip to content

Commit 102d19b

Browse files
committed
Add test for Timedelta hash invariance
1 parent c126eeb commit 102d19b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

pandas/tests/scalar/timedelta/test_arithmetic.py

+70
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,13 @@
66
timedelta,
77
)
88
import operator
9+
import sys
10+
from typing import Hashable
911

1012
import numpy as np
1113
import pytest
14+
from hypothesis import given
15+
from hypothesis.strategies import integers
1216

1317
from pandas.errors import OutOfBoundsTimedelta
1418

@@ -1143,6 +1147,72 @@ def test_compare_unknown_type(self, val):
11431147
with pytest.raises(TypeError, match=msg):
11441148
t < val
11451149

1150+
@given(integers(min_value=-sys.maxsize - 1, max_value=sys.maxsize))
1151+
def test_hash_invariant(value: int) -> None:
1152+
"""Reproducing GH#44504
1153+
1154+
See: https://github.com/pandas-dev/pandas/issues/44504
1155+
"""
1156+
1157+
# See: UnitChoices in pandas/_libs/tslibs/timedeltas.pyi
1158+
unit_choices = (
1159+
"W",
1160+
"w",
1161+
"D",
1162+
"d",
1163+
"days",
1164+
"day",
1165+
"hours",
1166+
"hour",
1167+
"hr",
1168+
"h",
1169+
"m",
1170+
"minute",
1171+
"min",
1172+
"minutes",
1173+
"t",
1174+
"s",
1175+
"seconds",
1176+
"sec",
1177+
"second",
1178+
"ms",
1179+
"milliseconds",
1180+
"millisecond",
1181+
"milli",
1182+
"millis",
1183+
"l",
1184+
"us",
1185+
"microseconds",
1186+
"microsecond",
1187+
"µs",
1188+
"micro",
1189+
"micros",
1190+
"u",
1191+
"ns",
1192+
"nanoseconds",
1193+
"nano",
1194+
"nanos",
1195+
"nanosecond",
1196+
"n",
1197+
)
1198+
1199+
def _hash_invariance_upheld(v1: Hashable, v2: Hashable) -> bool:
1200+
if v1 != v2:
1201+
return True
1202+
1203+
# See: https://docs.python.org/3/glossary.html#term-hashable
1204+
# Hashable objects which compare equal must have the same hash value.
1205+
return hash(v1) == hash(v2)
1206+
1207+
for unit in unit_choices:
1208+
pd_td = Timedelta(value, unit)
1209+
np_td = np.timedelta64(value)
1210+
1211+
try:
1212+
assert _hash_invariance_upheld(pd_td, np_td)
1213+
except AssertionError:
1214+
pytest.xfail("pd.Timedelta violates hash invariant (GH#44504).")
1215+
11461216

11471217
def test_ops_notimplemented():
11481218
class Other:

0 commit comments

Comments
 (0)