Skip to content

(TST) Replacing Timestamp.now () in tests. #44501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Nov 20, 2021
Merged
10 changes: 10 additions & 0 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,16 @@ def timedelta64_dtype(request):
return request.param


@pytest.fixture
def fixed_now_ts():
"""
Fixture emits fixed Timestamp.now()
"""
return Timestamp(
year=2021, month=1, day=1, hour=12, minute=0, second=0, microsecond=0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per my previous suggestion, please make these not zero. e.g. 4, 13, 22

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I fixed it

)


@pytest.fixture(params=tm.FLOAT_NUMPY_DTYPES)
def float_numpy_dtype(request):
"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/arithmetic/test_datetime64.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array):
tz = tz_naive_fixture
box = box_with_array

ts = Timestamp.now(tz)
ts = Timestamp("2021-01-01", tz=tz)
ser = Series([ts, NaT])

obj = tm.box_expected(ser, box)
Expand Down
18 changes: 9 additions & 9 deletions pandas/tests/arithmetic/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ def test_operator_series_comparison_zerorank(self):
expected = 0.0 > Series([1, 2, 3])
tm.assert_series_equal(result, expected)

def test_df_numeric_cmp_dt64_raises(self, box_with_array):
def test_df_numeric_cmp_dt64_raises(self, box_with_array, fixed_now_ts):
# GH#8932, GH#22163
ts = pd.Timestamp.now()
ts = fixed_now_ts
obj = np.array(range(5))
obj = tm.box_expected(obj, box_with_array)

Expand Down Expand Up @@ -281,9 +281,9 @@ def test_add_sub_timedeltalike_invalid(self, numeric_idx, other, box_with_array)
@pytest.mark.parametrize(
"other",
[
pd.Timestamp.now().to_pydatetime(),
pd.Timestamp.now(tz="UTC").to_pydatetime(),
pd.Timestamp.now().to_datetime64(),
pd.Timestamp("2021-01-01").to_pydatetime(),
pd.Timestamp("2021-01-01", tz="UTC").to_pydatetime(),
pd.Timestamp("2021-01-01").to_datetime64(),
pd.NaT,
],
)
Expand Down Expand Up @@ -873,7 +873,7 @@ def test_add_frames(self, first, second, expected):
tm.assert_frame_equal(second + first, expected)

# TODO: This came from series.test.test_operators, needs cleanup
def test_series_frame_radd_bug(self):
def test_series_frame_radd_bug(self, fixed_now_ts):
# GH#353
vals = Series(tm.rands_array(5, 10))
result = "foo_" + vals
Expand All @@ -889,7 +889,7 @@ def test_series_frame_radd_bug(self):
ts.name = "ts"

# really raise this time
now = pd.Timestamp.now().to_pydatetime()
fix_now = fixed_now_ts.to_pydatetime()
msg = "|".join(
[
"unsupported operand type",
Expand All @@ -898,10 +898,10 @@ def test_series_frame_radd_bug(self):
]
)
with pytest.raises(TypeError, match=msg):
now + ts
fix_now + ts

with pytest.raises(TypeError, match=msg):
ts + now
ts + fix_now

# TODO: This came from series.test.test_operators, needs cleanup
def test_datetime64_with_index(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/arithmetic/test_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def test_sub_object(self):
with pytest.raises(TypeError, match=msg):
index - np.array([2, "foo"], dtype=object)

def test_rsub_object(self):
def test_rsub_object(self, fixed_now_ts):
# GH#19369
index = pd.Index([Decimal(1), Decimal(2)])
expected = pd.Index([Decimal(1), Decimal(0)])
Expand All @@ -331,7 +331,7 @@ def test_rsub_object(self):
"foo" - index

with pytest.raises(TypeError, match=msg):
np.array([True, Timestamp.now()]) - index
np.array([True, fixed_now_ts]) - index


class MyIndex(pd.Index):
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/arithmetic/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def test_compare_zerodim(self, box_with_array):
"scalar",
[
"foo",
Timestamp.now(),
Timestamp("2021-01-01"),
Timedelta(days=4),
9,
9.5,
Expand Down Expand Up @@ -693,9 +693,9 @@ def test_sub_n_gt_1_offsets(self, offset, kwd_name, n):
"other",
[
# datetime scalars
Timestamp.now(),
Timestamp.now().to_pydatetime(),
Timestamp.now().to_datetime64(),
Timestamp("2016-01-01"),
Timestamp("2016-01-01").to_pydatetime(),
Timestamp("2016-01-01").to_datetime64(),
# datetime-like arrays
pd.date_range("2016-01-01", periods=3, freq="H"),
pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"),
Expand Down
14 changes: 7 additions & 7 deletions pandas/tests/arithmetic/test_timedelta64.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar):
[
345600000000000,
"a",
Timestamp.now(),
Timestamp.now("UTC"),
Timestamp.now().to_datetime64(),
Timestamp.now().to_pydatetime(),
Timestamp.now().date(),
Timestamp("2021-01-01"),
Timestamp("2021-01-01").now("UTC"),
Timestamp("2021-01-01").now().to_datetime64(),
Timestamp("2021-01-01").now().to_pydatetime(),
Timestamp("2021-01-01").date(),
np.array(4), # zero-dim mismatched dtype
],
)
Expand Down Expand Up @@ -152,7 +152,7 @@ def test_td64arr_cmp_arraylike_invalid(self, other, box_with_array):

def test_td64arr_cmp_mixed_invalid(self):
rng = timedelta_range("1 days", periods=5)._data
other = np.array([0, 1, 2, rng[3], Timestamp.now()])
other = np.array([0, 1, 2, rng[3], Timestamp("2021-01-01")])

result = rng == other
expected = np.array([False, False, False, True, False])
Expand Down Expand Up @@ -2174,7 +2174,7 @@ def test_td64arr_pow_invalid(self, scalar_td, box_with_array):

def test_add_timestamp_to_timedelta():
# GH: 35897
timestamp = Timestamp.now()
timestamp = Timestamp("2021-01-01")
result = timestamp + timedelta_range("0s", "1s", periods=31)
expected = DatetimeIndex(
[
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ def test_to_numpy_na_value(dtype, nulls_fixture):
tm.assert_numpy_array_equal(result, expected)


def test_isin(dtype, request):
def test_isin(dtype, request, fixed_now_ts):
s = pd.Series(["a", "b", None], dtype=dtype)

result = s.isin(["a", "c"])
Expand All @@ -554,6 +554,6 @@ def test_isin(dtype, request):
expected = pd.Series([False, False, False])
tm.assert_series_equal(result, expected)

result = s.isin(["a", pd.Timestamp.now()])
result = s.isin(["a", fixed_now_ts])
expected = pd.Series([True, False, False])
tm.assert_series_equal(result, expected)
24 changes: 11 additions & 13 deletions pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -839,30 +839,29 @@ def test_int_properties(self, arr1d, propname):

tm.assert_numpy_array_equal(result, expected)

def test_take_fill_valid(self, arr1d):
def test_take_fill_valid(self, arr1d, fixed_now_ts):
arr = arr1d
dti = self.index_cls(arr1d)
dt_ind = Timestamp(2021, 1, 1, 12)
dt_ind_tz = dt_ind.tz_localize(dti.tz)

result = arr.take([-1, 1], allow_fill=True, fill_value=dt_ind_tz)
assert result[0] == dt_ind_tz
now = fixed_now_ts.tz_localize(dti.tz)
result = arr.take([-1, 1], allow_fill=True, fill_value=now)
assert result[0] == now

msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
with pytest.raises(TypeError, match=msg):
# fill_value Timedelta invalid
arr.take([-1, 1], allow_fill=True, fill_value=dt_ind_tz - dt_ind_tz)
arr.take([-1, 1], allow_fill=True, fill_value=now - now)

with pytest.raises(TypeError, match=msg):
# fill_value Period invalid
arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1"))

tz = None if dti.tz is not None else "US/Eastern"
dt_ind_tz = dt_ind.tz_localize(tz)
now = fixed_now_ts.tz_localize(tz)
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
# Timestamp with mismatched tz-awareness
arr.take([-1, 1], allow_fill=True, fill_value=dt_ind_tz)
arr.take([-1, 1], allow_fill=True, fill_value=now)

value = NaT.value
msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
Expand All @@ -878,7 +877,7 @@ def test_take_fill_valid(self, arr1d):
if arr.tz is not None:
# GH#37356
# Assuming here that arr1d fixture does not include Australia/Melbourne
value = dt_ind.tz_localize("Australia/Melbourne")
value = fixed_now_ts.tz_localize("Australia/Melbourne")
msg = "Timezones don't match. .* != 'Australia/Melbourne'"
with pytest.raises(ValueError, match=msg):
# require tz match, not just tzawareness match
Expand Down Expand Up @@ -1032,22 +1031,21 @@ def test_array_interface(self, timedelta_index):
expected = np.asarray(arr).astype(dtype)
tm.assert_numpy_array_equal(result, expected)

def test_take_fill_valid(self, timedelta_index):
def test_take_fill_valid(self, timedelta_index, fixed_now_ts):
tdi = timedelta_index
arr = TimedeltaArray(tdi)

td1 = pd.Timedelta(days=1)
result = arr.take([-1, 1], allow_fill=True, fill_value=td1)
assert result[0] == td1

dt_ind = Timestamp(2021, 1, 1, 12)
value = dt_ind
value = fixed_now_ts
msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got"
with pytest.raises(TypeError, match=msg):
# fill_value Timestamp invalid
arr.take([0, 1], allow_fill=True, fill_value=value)

value = dt_ind.to_period("D")
value = fixed_now_ts.to_period("D")
with pytest.raises(TypeError, match=msg):
# fill_value Period invalid
arr.take([0, 1], allow_fill=True, fill_value=value)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/arrays/test_datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,9 @@ def test_setitem_clears_freq(self):
@pytest.mark.parametrize(
"obj",
[
pd.Timestamp.now(),
pd.Timestamp.now().to_datetime64(),
pd.Timestamp.now().to_pydatetime(),
pd.Timestamp("2021-01-01"),
pd.Timestamp("2021-01-01").to_datetime64(),
pd.Timestamp("2021-01-01").to_pydatetime(),
],
)
def test_setitem_objects(self, obj):
Expand Down Expand Up @@ -329,7 +329,7 @@ def test_searchsorted_tzawareness_compat(self, index):
"invalid",
np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9,
np.arange(10).view("timedelta64[ns]") * 24 * 3600 * 10 ** 9,
pd.Timestamp.now().to_period("D"),
pd.Timestamp("2021-01-01").to_period("D"),
],
)
@pytest.mark.parametrize("index", [True, False])
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/arrays/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ def test_setitem_objects(self, obj):
np.int64(1),
1.0,
np.datetime64("NaT"),
pd.Timestamp.now(),
pd.Timestamp("2021-01-01"),
"invalid",
np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9,
(np.arange(10) * 24 * 3600 * 10 ** 9).view("datetime64[ns]"),
pd.Timestamp.now().to_period("D"),
pd.Timestamp("2021-01-01").to_period("D"),
],
)
@pytest.mark.parametrize("index", [True, False])
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/arrays/timedeltas/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,9 @@ def test_sum_2d_skipna_false(self):
"add",
[
Timedelta(0),
pd.Timestamp.now(),
pd.Timestamp.now("UTC"),
pd.Timestamp.now("Asia/Tokyo"),
pd.Timestamp("2021-01-01"),
pd.Timestamp("2021-01-01", tz="UTC"),
pd.Timestamp("2021-01-01", tz="Asia/Tokyo"),
],
)
def test_std(self, add):
Expand Down
5 changes: 2 additions & 3 deletions pandas/tests/dtypes/cast/test_construct_from_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from pandas import (
Categorical,
Timedelta,
Timestamp,
)
import pandas._testing as tm

Expand All @@ -25,9 +24,9 @@ def test_cast_1d_array_like_from_scalar_categorical():
tm.assert_categorical_equal(result, expected)


def test_cast_1d_array_like_from_timestamp():
def test_cast_1d_array_like_from_timestamp(fixed_now_ts):
# check we dont lose nanoseconds
ts = Timestamp.now() + Timedelta(1)
ts = fixed_now_ts + Timedelta(1)
res = construct_1d_arraylike_from_scalar(ts, 2, np.dtype("M8[ns]"))
assert res[0] == ts

Expand Down
16 changes: 8 additions & 8 deletions pandas/tests/dtypes/test_missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
import pandas._testing as tm
from pandas.core.api import Float64Index

now = pd.Timestamp.now()
utcnow = pd.Timestamp.now("UTC")
fix_now = pd.Timestamp("2021-01-01")
fix_utcnow = pd.Timestamp("2021-01-01", tz="UTC")


@pytest.mark.parametrize("notna_f", [notna, notnull])
Expand Down Expand Up @@ -467,12 +467,12 @@ def test_array_equivalent_different_dtype_but_equal():
# There are 3 variants for each of lvalue and rvalue. We include all
# three for the tz-naive `now` and exclude the datetim64 variant
# for utcnow because it drops tzinfo.
(now, utcnow),
(now.to_datetime64(), utcnow),
(now.to_pydatetime(), utcnow),
(now, utcnow),
(now.to_datetime64(), utcnow.to_pydatetime()),
(now.to_pydatetime(), utcnow.to_pydatetime()),
(fix_now, fix_utcnow),
(fix_now.to_datetime64(), fix_utcnow),
(fix_now.to_pydatetime(), fix_utcnow),
(fix_now, fix_utcnow),
(fix_now.to_datetime64(), fix_utcnow.to_pydatetime()),
(fix_now.to_pydatetime(), fix_utcnow.to_pydatetime()),
],
)
def test_array_equivalent_tzawareness(lvalue, rvalue):
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2888,8 +2888,8 @@ def test_from_timedelta_scalar_preserves_nanos(self, constructor):
obj = constructor(td, dtype="m8[ns]")
assert get1(obj) == td

def test_from_timestamp_scalar_preserves_nanos(self, constructor):
ts = Timestamp.now() + Timedelta(1)
def test_from_timestamp_scalar_preserves_nanos(self, constructor, fixed_now_ts):
ts = fixed_now_ts + Timedelta(1)

obj = constructor(ts, dtype="M8[ns]")
assert get1(obj) == ts
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/indexes/timedeltas/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def test_where_doesnt_retain_freq(self):
result = tdi.where(cond, tdi[::-1])
tm.assert_index_equal(result, expected)

def test_where_invalid_dtypes(self):
def test_where_invalid_dtypes(self, fixed_now_ts):
tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")

tail = tdi[2:].tolist()
Expand All @@ -161,17 +161,17 @@ def test_where_invalid_dtypes(self):
result = tdi.where(mask, i2.asi8)
tm.assert_index_equal(result, expected)

ts = i2 + Timestamp.now()
ts = i2 + fixed_now_ts
expected = Index([ts[0], ts[1]] + tail, dtype=object, name="idx")
result = tdi.where(mask, ts)
tm.assert_index_equal(result, expected)

per = (i2 + Timestamp.now()).to_period("D")
per = (i2 + fixed_now_ts).to_period("D")
expected = Index([per[0], per[1]] + tail, dtype=object, name="idx")
result = tdi.where(mask, per)
tm.assert_index_equal(result, expected)

ts = Timestamp.now()
ts = fixed_now_ts
expected = Index([ts, ts] + tail, dtype=object, name="idx")
result = tdi.where(mask, ts)
tm.assert_index_equal(result, expected)
Expand Down
Loading