Skip to content

Commit 6c2631b

Browse files
authored
TST: arithmetic test parametrization/cleanup (#38673)
1 parent fa478d3 commit 6c2631b

File tree

6 files changed

+73
-86
lines changed

6 files changed

+73
-86
lines changed

pandas/core/arrays/datetimes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2077,15 +2077,15 @@ def objects_to_datetime64ns(
20772077
require_iso8601=require_iso8601,
20782078
)
20792079
result = result.reshape(data.shape, order=order)
2080-
except ValueError as e:
2080+
except ValueError as err:
20812081
try:
20822082
values, tz_parsed = conversion.datetime_to_datetime64(data.ravel("K"))
20832083
# If tzaware, these values represent unix timestamps, so we
20842084
# return them as i8 to distinguish from wall times
20852085
values = values.reshape(data.shape, order=order)
20862086
return values.view("i8"), tz_parsed
20872087
except (ValueError, TypeError):
2088-
raise e
2088+
raise err
20892089

20902090
if tz_parsed is not None:
20912091
# We can take a shortcut since the datetime64 numpy array

pandas/core/dtypes/cast.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ def maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]):
231231
# convert to datetime and change timezone
232232
i8values = result.astype("i8", copy=False)
233233
cls = dtype.construct_array_type()
234+
# equiv: DatetimeArray(i8values).tz_localize("UTC").tz_convert(dtype.tz)
234235
result = cls._simple_new(i8values, dtype=dtype)
235236
else:
236237
result = result.astype(dtype)

pandas/tests/arithmetic/test_period.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ def test_compare_zerodim(self, box_with_array):
4141
expected = tm.box_expected(expected, xbox)
4242
tm.assert_equal(result, expected)
4343

44-
@pytest.mark.parametrize("scalar", ["foo", Timestamp.now(), Timedelta(days=4)])
44+
@pytest.mark.parametrize(
45+
"scalar", ["foo", Timestamp.now(), Timedelta(days=4), 9, 9.5]
46+
)
4547
def test_compare_invalid_scalar(self, box_with_array, scalar):
4648
# comparison with scalar that cannot be interpreted as a Period
4749
pi = pd.period_range("2000", periods=4)

pandas/tests/arithmetic/test_timedelta64.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
Timedelta,
1717
TimedeltaIndex,
1818
Timestamp,
19+
offsets,
1920
timedelta_range,
2021
)
2122
import pandas._testing as tm
@@ -70,7 +71,12 @@ def test_compare_timedelta64_zerodim(self, box_with_array):
7071

7172
@pytest.mark.parametrize(
7273
"td_scalar",
73-
[timedelta(days=1), Timedelta(days=1), Timedelta(days=1).to_timedelta64()],
74+
[
75+
timedelta(days=1),
76+
Timedelta(days=1),
77+
Timedelta(days=1).to_timedelta64(),
78+
offsets.Hour(24),
79+
],
7480
)
7581
def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar):
7682
# regression test for GH#5963
@@ -84,7 +90,18 @@ def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar):
8490
expected = tm.box_expected(expected, xbox)
8591
tm.assert_equal(actual, expected)
8692

87-
@pytest.mark.parametrize("invalid", [345600000000000, "a"])
93+
@pytest.mark.parametrize(
94+
"invalid",
95+
[
96+
345600000000000,
97+
"a",
98+
Timestamp.now(),
99+
Timestamp.now("UTC"),
100+
Timestamp.now().to_datetime64(),
101+
Timestamp.now().to_pydatetime(),
102+
Timestamp.now().date(),
103+
],
104+
)
88105
def test_td64_comparisons_invalid(self, box_with_array, invalid):
89106
# GH#13624 for str
90107
box = box_with_array
@@ -261,7 +278,6 @@ def test_ufunc_coercions(self):
261278
tm.assert_index_equal(result, exp)
262279
assert result.freq == "H"
263280

264-
idx = TimedeltaIndex(["2H", "4H", "6H", "8H", "10H"], freq="2H", name="x")
265281
for result in [-idx, np.negative(idx)]:
266282
assert isinstance(result, TimedeltaIndex)
267283
exp = TimedeltaIndex(
@@ -413,10 +429,6 @@ def test_dti_tdi_numeric_ops(self):
413429
tdi = TimedeltaIndex(["1 days", pd.NaT, "2 days"], name="foo")
414430
dti = pd.date_range("20130101", periods=3, name="bar")
415431

416-
# TODO(wesm): unused?
417-
# td = Timedelta('1 days')
418-
# dt = Timestamp('20130101')
419-
420432
result = tdi - tdi
421433
expected = TimedeltaIndex(["0 days", pd.NaT, "0 days"], name="foo")
422434
tm.assert_index_equal(result, expected)
@@ -543,7 +555,6 @@ def test_tda_add_sub_index(self):
543555
expected = tdi - tdi
544556
tm.assert_index_equal(result, expected)
545557

546-
@pytest.mark.xfail(reason="GH38630", strict=False)
547558
def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture):
548559
# Result should be cast back to DatetimeArray
549560
box = box_with_array
@@ -555,10 +566,7 @@ def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture):
555566
obj = tm.box_expected(tdi, box)
556567
other = tm.box_expected(dti, box)
557568

558-
warn = None
559-
if box is not pd.DataFrame or tz_naive_fixture is None:
560-
warn = PerformanceWarning
561-
with tm.assert_produces_warning(warn):
569+
with tm.assert_produces_warning(PerformanceWarning):
562570
result = obj + other.astype(object)
563571
tm.assert_equal(result, other)
564572

pandas/tests/extension/base/setitem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def test_setitem_sequence_mismatched_length_raises(self, data, as_array):
4040
ser[slice(3)] = value
4141
self.assert_series_equal(ser, original)
4242

43-
def test_setitem_empty_indxer(self, data, box_in_series):
43+
def test_setitem_empty_indexer(self, data, box_in_series):
4444
if box_in_series:
4545
data = pd.Series(data)
4646
original = data.copy()

pandas/tests/series/test_arithmetic.py

Lines changed: 46 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def test_sub_datetimelike_align(self):
267267

268268
def test_alignment_doesnt_change_tz(self):
269269
# GH#33671
270-
dti = pd.date_range("2016-01-01", periods=10, tz="CET")
270+
dti = date_range("2016-01-01", periods=10, tz="CET")
271271
dti_utc = dti.tz_convert("UTC")
272272
ser = Series(10, index=dti)
273273
ser_utc = Series(10, index=dti_utc)
@@ -399,7 +399,7 @@ def test_ser_flex_cmp_return_dtypes_empty(self, opname):
399399
)
400400
def test_ser_cmp_result_names(self, names, op):
401401
# datetime64 dtype
402-
dti = pd.date_range("1949-06-07 03:00:00", freq="H", periods=5, name=names[0])
402+
dti = date_range("1949-06-07 03:00:00", freq="H", periods=5, name=names[0])
403403
ser = Series(dti).rename(names[1])
404404
result = op(ser, dti)
405405
assert result.name == names[2]
@@ -624,9 +624,13 @@ def test_ne(self):
624624
),
625625
],
626626
)
627-
def test_comp_ops_df_compat(self, left, right):
627+
def test_comp_ops_df_compat(self, left, right, frame_or_series):
628628
# GH 1134
629-
msg = "Can only compare identically-labeled Series objects"
629+
msg = f"Can only compare identically-labeled {frame_or_series.__name__} objects"
630+
if frame_or_series is not Series:
631+
left = left.to_frame()
632+
right = right.to_frame()
633+
630634
with pytest.raises(ValueError, match=msg):
631635
left == right
632636
with pytest.raises(ValueError, match=msg):
@@ -642,22 +646,6 @@ def test_comp_ops_df_compat(self, left, right):
642646
with pytest.raises(ValueError, match=msg):
643647
right < left
644648

645-
msg = "Can only compare identically-labeled DataFrame objects"
646-
with pytest.raises(ValueError, match=msg):
647-
left.to_frame() == right.to_frame()
648-
with pytest.raises(ValueError, match=msg):
649-
right.to_frame() == left.to_frame()
650-
651-
with pytest.raises(ValueError, match=msg):
652-
left.to_frame() != right.to_frame()
653-
with pytest.raises(ValueError, match=msg):
654-
right.to_frame() != left.to_frame()
655-
656-
with pytest.raises(ValueError, match=msg):
657-
left.to_frame() < right.to_frame()
658-
with pytest.raises(ValueError, match=msg):
659-
right.to_frame() < left.to_frame()
660-
661649
def test_compare_series_interval_keyword(self):
662650
# GH#25338
663651
s = Series(["IntervalA", "IntervalB", "IntervalC"])
@@ -724,7 +712,7 @@ def test_series_add_aware_naive_raises(self):
724712
def test_datetime_understood(self):
725713
# Ensures it doesn't fail to create the right series
726714
# reported in issue#16726
727-
series = Series(pd.date_range("2012-01-01", periods=3))
715+
series = Series(date_range("2012-01-01", periods=3))
728716
offset = pd.offsets.DateOffset(days=6)
729717
result = series - offset
730718
expected = Series(pd.to_datetime(["2011-12-26", "2011-12-27", "2011-12-28"]))
@@ -746,58 +734,46 @@ def test_align_date_objects_with_datetimeindex(self):
746734
tm.assert_series_equal(result2, expected)
747735

748736

749-
@pytest.mark.parametrize(
750-
"names",
751-
[
752-
("foo", None, None),
753-
("Egon", "Venkman", None),
754-
("NCC1701D", "NCC1701D", "NCC1701D"),
755-
],
756-
)
757-
@pytest.mark.parametrize("box", [list, tuple, np.array, pd.Index, pd.Series, pd.array])
758-
@pytest.mark.parametrize("flex", [True, False])
759-
def test_series_ops_name_retention(flex, box, names, all_binary_operators, request):
760-
# GH#33930 consistent name retention
761-
op = all_binary_operators
762-
763-
if op is ops.rfloordiv and box in [list, tuple] and not flex:
764-
mark = pytest.mark.xfail(
765-
reason="op fails because of inconsistent ndarray-wrapping GH#28759"
766-
)
767-
request.node.add_marker(mark)
768-
769-
left = Series(range(10), name=names[0])
770-
right = Series(range(10), name=names[1])
771-
772-
name = op.__name__.strip("_")
773-
is_logical = name in ["and", "rand", "xor", "rxor", "or", "ror"]
774-
is_rlogical = is_logical and name.startswith("r")
775-
776-
right = box(right)
777-
if flex:
778-
if is_logical:
779-
# Series doesn't have these as flex methods
737+
class TestNamePreservation:
738+
@pytest.mark.parametrize("box", [list, tuple, np.array, Index, Series, pd.array])
739+
@pytest.mark.parametrize("flex", [True, False])
740+
def test_series_ops_name_retention(self, flex, box, names, all_binary_operators):
741+
# GH#33930 consistent name renteiton
742+
op = all_binary_operators
743+
744+
if op is ops.rfloordiv and box in [list, tuple]:
745+
pytest.xfail("op fails because of inconsistent ndarray-wrapping GH#28759")
746+
747+
left = Series(range(10), name=names[0])
748+
right = Series(range(10), name=names[1])
749+
750+
name = op.__name__.strip("_")
751+
is_logical = name in ["and", "rand", "xor", "rxor", "or", "ror"]
752+
is_rlogical = is_logical and name.startswith("r")
753+
754+
right = box(right)
755+
if flex:
756+
if is_logical:
757+
# Series doesn't have these as flex methods
758+
return
759+
result = getattr(left, name)(right)
760+
else:
761+
# GH#37374 logical ops behaving as set ops deprecated
762+
warn = FutureWarning if is_rlogical and box is Index else None
763+
with tm.assert_produces_warning(warn, check_stacklevel=False):
764+
result = op(left, right)
765+
766+
if box is Index and is_rlogical:
767+
# Index treats these as set operators, so does not defer
768+
assert isinstance(result, Index)
780769
return
781-
result = getattr(left, name)(right)
782-
else:
783-
# GH#37374 logical ops behaving as set ops deprecated
784-
warn = FutureWarning if is_rlogical and box is Index else None
785-
with tm.assert_produces_warning(warn, check_stacklevel=False):
786-
result = op(left, right)
787-
788-
if box is pd.Index and is_rlogical:
789-
# Index treats these as set operators, so does not defer
790-
assert isinstance(result, pd.Index)
791-
return
792-
793-
assert isinstance(result, Series)
794-
if box in [pd.Index, pd.Series]:
795-
assert result.name == names[2]
796-
else:
797-
assert result.name == names[0]
798770

771+
assert isinstance(result, Series)
772+
if box in [Index, Series]:
773+
assert result.name == names[2]
774+
else:
775+
assert result.name == names[0]
799776

800-
class TestNamePreservation:
801777
def test_binop_maybe_preserve_name(self, datetime_series):
802778
# names match, preserve
803779
result = datetime_series * datetime_series

0 commit comments

Comments
 (0)