Skip to content

Commit b365376

Browse files
authored
TST: Inline once used variables & parameterize (#45976)
* TST: Inline once used variables * Fix more tests
1 parent 332e70e commit b365376

File tree

10 files changed

+158
-143
lines changed

10 files changed

+158
-143
lines changed

pandas/tests/apply/test_str.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,11 @@ def test_apply_with_string_funcs(request, float_frame, func, args, kwds, how):
4545
tm.assert_series_equal(result, expected)
4646

4747

48-
def test_with_string_args(datetime_series):
49-
50-
for arg in ["sum", "mean", "min", "max", "std"]:
51-
result = datetime_series.apply(arg)
52-
expected = getattr(datetime_series, arg)()
53-
assert result == expected
48+
@pytest.mark.parametrize("arg", ["sum", "mean", "min", "max", "std"])
49+
def test_with_string_args(datetime_series, arg):
50+
result = datetime_series.apply(arg)
51+
expected = getattr(datetime_series, arg)()
52+
assert result == expected
5453

5554

5655
@pytest.mark.parametrize("op", ["mean", "median", "std", "var"])

pandas/tests/arithmetic/test_numeric.py

Lines changed: 88 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
from collections import abc
77
from decimal import Decimal
8-
from itertools import combinations
98
import operator
109
from typing import Any
1110

@@ -928,7 +927,6 @@ def test_datetime64_with_index(self):
928927
# TODO: taken from tests.frame.test_operators, needs cleanup
929928
def test_frame_operators(self, float_frame):
930929
frame = float_frame
931-
frame2 = pd.DataFrame(float_frame, columns=["D", "C", "B", "A"])
932930

933931
garbage = np.random.random(4)
934932
colSeries = Series(garbage, index=np.array(frame.columns))
@@ -952,23 +950,27 @@ def test_frame_operators(self, float_frame):
952950
else:
953951
assert np.isnan(origVal)
954952

953+
def test_frame_operators_col_align(self, float_frame):
954+
frame2 = pd.DataFrame(float_frame, columns=["D", "C", "B", "A"])
955955
added = frame2 + frame2
956956
expected = frame2 * 2
957957
tm.assert_frame_equal(added, expected)
958958

959+
def test_frame_operators_none_to_nan(self):
959960
df = pd.DataFrame({"a": ["a", None, "b"]})
960961
tm.assert_frame_equal(df + df, pd.DataFrame({"a": ["aa", np.nan, "bb"]}))
961962

963+
@pytest.mark.parametrize("dtype", ("float", "int64"))
964+
def test_frame_operators_empty_like(self, dtype):
962965
# Test for issue #10181
963-
for dtype in ("float", "int64"):
964-
frames = [
965-
pd.DataFrame(dtype=dtype),
966-
pd.DataFrame(columns=["A"], dtype=dtype),
967-
pd.DataFrame(index=[0], dtype=dtype),
968-
]
969-
for df in frames:
970-
assert (df + df).equals(df)
971-
tm.assert_frame_equal(df + df, df)
966+
frames = [
967+
pd.DataFrame(dtype=dtype),
968+
pd.DataFrame(columns=["A"], dtype=dtype),
969+
pd.DataFrame(index=[0], dtype=dtype),
970+
]
971+
for df in frames:
972+
assert (df + df).equals(df)
973+
tm.assert_frame_equal(df + df, df)
972974

973975
@pytest.mark.parametrize(
974976
"func",
@@ -1164,45 +1166,85 @@ def test_operators_reverse_object(self, op):
11641166
class TestNumericArithmeticUnsorted:
11651167
# Tests in this class have been moved from type-specific test modules
11661168
# but not yet sorted, parametrized, and de-duplicated
1167-
1168-
def check_binop(self, ops, scalars, idxs):
1169-
for op in ops:
1170-
for a, b in combinations(idxs, 2):
1171-
a = a._rename("foo")
1172-
b = b._rename("bar")
1173-
result = op(a, b)
1174-
expected = op(Int64Index(a), Int64Index(b))
1175-
tm.assert_index_equal(result, expected, exact="equiv")
1176-
for idx in idxs:
1177-
for scalar in scalars:
1178-
result = op(idx, scalar)
1179-
expected = op(Int64Index(idx), scalar)
1180-
tm.assert_index_equal(result, expected, exact="equiv")
1181-
1182-
def test_binops(self):
1183-
ops = [
1169+
@pytest.mark.parametrize(
1170+
"op",
1171+
[
11841172
operator.add,
11851173
operator.sub,
11861174
operator.mul,
11871175
operator.floordiv,
11881176
operator.truediv,
1189-
]
1190-
scalars = [-1, 1, 2]
1191-
idxs = [
1177+
],
1178+
)
1179+
@pytest.mark.parametrize(
1180+
"idx1",
1181+
[
11921182
RangeIndex(0, 10, 1),
11931183
RangeIndex(0, 20, 2),
11941184
RangeIndex(-10, 10, 2),
11951185
RangeIndex(5, -5, -1),
1196-
]
1197-
self.check_binop(ops, scalars, idxs)
1186+
],
1187+
)
1188+
@pytest.mark.parametrize(
1189+
"idx2",
1190+
[
1191+
RangeIndex(0, 10, 1),
1192+
RangeIndex(0, 20, 2),
1193+
RangeIndex(-10, 10, 2),
1194+
RangeIndex(5, -5, -1),
1195+
],
1196+
)
1197+
def test_binops_index(self, op, idx1, idx2):
1198+
idx1 = idx1._rename("foo")
1199+
idx2 = idx2._rename("bar")
1200+
result = op(idx1, idx2)
1201+
expected = op(Int64Index(idx1), Int64Index(idx2))
1202+
tm.assert_index_equal(result, expected, exact="equiv")
11981203

1199-
def test_binops_pow(self):
1204+
@pytest.mark.parametrize(
1205+
"op",
1206+
[
1207+
operator.add,
1208+
operator.sub,
1209+
operator.mul,
1210+
operator.floordiv,
1211+
operator.truediv,
1212+
],
1213+
)
1214+
@pytest.mark.parametrize(
1215+
"idx",
1216+
[
1217+
RangeIndex(0, 10, 1),
1218+
RangeIndex(0, 20, 2),
1219+
RangeIndex(-10, 10, 2),
1220+
RangeIndex(5, -5, -1),
1221+
],
1222+
)
1223+
@pytest.mark.parametrize("scalar", [-1, 1, 2])
1224+
def test_binops_index_scalar(self, op, idx, scalar):
1225+
result = op(idx, scalar)
1226+
expected = op(Int64Index(idx), scalar)
1227+
tm.assert_index_equal(result, expected, exact="equiv")
1228+
1229+
@pytest.mark.parametrize("idx1", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
1230+
@pytest.mark.parametrize("idx2", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
1231+
def test_binops_index_pow(self, idx1, idx2):
12001232
# numpy does not allow powers of negative integers so test separately
12011233
# https://github.com/numpy/numpy/pull/8127
1202-
ops = [pow]
1203-
scalars = [1, 2]
1204-
idxs = [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)]
1205-
self.check_binop(ops, scalars, idxs)
1234+
idx1 = idx1._rename("foo")
1235+
idx2 = idx2._rename("bar")
1236+
result = pow(idx1, idx2)
1237+
expected = pow(Int64Index(idx1), Int64Index(idx2))
1238+
tm.assert_index_equal(result, expected, exact="equiv")
1239+
1240+
@pytest.mark.parametrize("idx", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)])
1241+
@pytest.mark.parametrize("scalar", [1, 2])
1242+
def test_binops_index_scalar_pow(self, idx, scalar):
1243+
# numpy does not allow powers of negative integers so test separately
1244+
# https://github.com/numpy/numpy/pull/8127
1245+
result = pow(idx, scalar)
1246+
expected = pow(Int64Index(idx), scalar)
1247+
tm.assert_index_equal(result, expected, exact="equiv")
12061248

12071249
# TODO: divmod?
12081250
@pytest.mark.parametrize(
@@ -1273,8 +1315,9 @@ def test_numeric_compat2(self):
12731315
expected = Int64Index(idx._values) ** 2
12741316
tm.assert_index_equal(Index(result.values), expected, exact=True)
12751317

1276-
# __floordiv__
1277-
cases_exact = [
1318+
@pytest.mark.parametrize(
1319+
"idx, div, expected",
1320+
[
12781321
(RangeIndex(0, 1000, 2), 2, RangeIndex(0, 500, 1)),
12791322
(RangeIndex(-99, -201, -3), -3, RangeIndex(33, 67, 1)),
12801323
(
@@ -1291,9 +1334,11 @@ def test_numeric_compat2(self):
12911334
(RangeIndex(2, 4, 2), 3, RangeIndex(0, 1, 1)),
12921335
(RangeIndex(-5, -10, -6), 4, RangeIndex(-2, -1, 1)),
12931336
(RangeIndex(-100, -200, 3), 2, RangeIndex(0)),
1294-
]
1295-
for idx, div, expected in cases_exact:
1296-
tm.assert_index_equal(idx // div, expected, exact=True)
1337+
],
1338+
)
1339+
def test_numeric_compat2_floordiv(self, idx, div, expected):
1340+
# __floordiv__
1341+
tm.assert_index_equal(idx // div, expected, exact=True)
12971342

12981343
@pytest.mark.parametrize("dtype", [np.int64, np.float64])
12991344
@pytest.mark.parametrize("delta", [1, 0, -1])

pandas/tests/arithmetic/test_timedelta64.py

Lines changed: 47 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,26 @@ def test_comp_nat(self, dtype):
204204
tm.assert_numpy_array_equal(lhs < NaT, expected)
205205
tm.assert_numpy_array_equal(NaT > lhs, expected)
206206

207-
def test_comparisons_nat(self):
208-
tdidx1 = TimedeltaIndex(
207+
@pytest.mark.parametrize(
208+
"idx2",
209+
[
210+
TimedeltaIndex(
211+
["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"]
212+
),
213+
np.array(
214+
[
215+
np.timedelta64(2, "D"),
216+
np.timedelta64(2, "D"),
217+
np.timedelta64("nat"),
218+
np.timedelta64("nat"),
219+
np.timedelta64(1, "D") + np.timedelta64(2, "s"),
220+
np.timedelta64(5, "D") + np.timedelta64(3, "s"),
221+
]
222+
),
223+
],
224+
)
225+
def test_comparisons_nat(self, idx2):
226+
idx1 = TimedeltaIndex(
209227
[
210228
"1 day",
211229
NaT,
@@ -215,48 +233,30 @@ def test_comparisons_nat(self):
215233
"5 day 00:00:03",
216234
]
217235
)
218-
tdidx2 = TimedeltaIndex(
219-
["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"]
220-
)
221-
tdarr = np.array(
222-
[
223-
np.timedelta64(2, "D"),
224-
np.timedelta64(2, "D"),
225-
np.timedelta64("nat"),
226-
np.timedelta64("nat"),
227-
np.timedelta64(1, "D") + np.timedelta64(2, "s"),
228-
np.timedelta64(5, "D") + np.timedelta64(3, "s"),
229-
]
230-
)
231-
232-
cases = [(tdidx1, tdidx2), (tdidx1, tdarr)]
233-
234236
# Check pd.NaT is handles as the same as np.nan
235-
for idx1, idx2 in cases:
236-
237-
result = idx1 < idx2
238-
expected = np.array([True, False, False, False, True, False])
239-
tm.assert_numpy_array_equal(result, expected)
237+
result = idx1 < idx2
238+
expected = np.array([True, False, False, False, True, False])
239+
tm.assert_numpy_array_equal(result, expected)
240240

241-
result = idx2 > idx1
242-
expected = np.array([True, False, False, False, True, False])
243-
tm.assert_numpy_array_equal(result, expected)
241+
result = idx2 > idx1
242+
expected = np.array([True, False, False, False, True, False])
243+
tm.assert_numpy_array_equal(result, expected)
244244

245-
result = idx1 <= idx2
246-
expected = np.array([True, False, False, False, True, True])
247-
tm.assert_numpy_array_equal(result, expected)
245+
result = idx1 <= idx2
246+
expected = np.array([True, False, False, False, True, True])
247+
tm.assert_numpy_array_equal(result, expected)
248248

249-
result = idx2 >= idx1
250-
expected = np.array([True, False, False, False, True, True])
251-
tm.assert_numpy_array_equal(result, expected)
249+
result = idx2 >= idx1
250+
expected = np.array([True, False, False, False, True, True])
251+
tm.assert_numpy_array_equal(result, expected)
252252

253-
result = idx1 == idx2
254-
expected = np.array([False, False, False, False, False, True])
255-
tm.assert_numpy_array_equal(result, expected)
253+
result = idx1 == idx2
254+
expected = np.array([False, False, False, False, False, True])
255+
tm.assert_numpy_array_equal(result, expected)
256256

257-
result = idx1 != idx2
258-
expected = np.array([True, True, True, True, True, False])
259-
tm.assert_numpy_array_equal(result, expected)
257+
result = idx1 != idx2
258+
expected = np.array([True, True, True, True, True, False])
259+
tm.assert_numpy_array_equal(result, expected)
260260

261261
# TODO: better name
262262
def test_comparisons_coverage(self):
@@ -665,28 +665,21 @@ def test_tdi_ops_attributes(self):
665665
class TestAddSubNaTMasking:
666666
# TODO: parametrize over boxes
667667

668-
def test_tdarr_add_timestamp_nat_masking(self, box_with_array):
668+
@pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"])
669+
def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts):
669670
# GH#17991 checking for overflow-masking with NaT
670671
tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"])
671672
tdobj = tm.box_expected(tdinat, box_with_array)
672673

673-
tsneg = Timestamp("1950-01-01")
674-
ts_neg_variants = [
675-
tsneg,
676-
tsneg.to_pydatetime(),
677-
tsneg.to_datetime64().astype("datetime64[ns]"),
678-
tsneg.to_datetime64().astype("datetime64[D]"),
679-
]
680-
681-
tspos = Timestamp("1980-01-01")
682-
ts_pos_variants = [
683-
tspos,
684-
tspos.to_pydatetime(),
685-
tspos.to_datetime64().astype("datetime64[ns]"),
686-
tspos.to_datetime64().astype("datetime64[D]"),
674+
ts = Timestamp(str_ts)
675+
ts_variants = [
676+
ts,
677+
ts.to_pydatetime(),
678+
ts.to_datetime64().astype("datetime64[ns]"),
679+
ts.to_datetime64().astype("datetime64[D]"),
687680
]
688681

689-
for variant in ts_neg_variants + ts_pos_variants:
682+
for variant in ts_variants:
690683
res = tdobj + variant
691684
if box_with_array is DataFrame:
692685
assert res.iloc[1, 1] is NaT

pandas/tests/frame/test_query_eval.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,15 @@
1616
import pandas._testing as tm
1717
from pandas.core.computation.check import NUMEXPR_INSTALLED
1818

19-
PARSERS = "python", "pandas"
20-
ENGINES = "python", pytest.param("numexpr", marks=td.skip_if_no_ne)
2119

22-
23-
@pytest.fixture(params=PARSERS, ids=lambda x: x)
20+
@pytest.fixture(params=["python", "pandas"], ids=lambda x: x)
2421
def parser(request):
2522
return request.param
2623

2724

28-
@pytest.fixture(params=ENGINES, ids=lambda x: x)
25+
@pytest.fixture(
26+
params=["python", pytest.param("numexpr", marks=td.skip_if_no_ne)], ids=lambda x: x
27+
)
2928
def engine(request):
3029
return request.param
3130

pandas/tests/indexes/test_setops.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,6 @@
3232
UInt64Index,
3333
)
3434

35-
COMPATIBLE_INCONSISTENT_PAIRS = [
36-
(np.float64, np.int64),
37-
(np.float64, np.uint64),
38-
]
39-
4035

4136
def test_union_same_types(index):
4237
# Union with a non-unique, non-monotonic index raises error

pandas/tests/io/parser/test_parse_dates.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,6 @@
4545
# cause a deadlock instead, so we skip these instead of xfailing
4646
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
4747

48-
# constant
49-
_DEFAULT_DATETIME = datetime(1, 1, 1)
50-
5148

5249
@xfail_pyarrow
5350
def test_read_csv_with_custom_date_parser(all_parsers):
@@ -1723,7 +1720,7 @@ def test_hypothesis_delimited_date(
17231720
except_in_dateutil, expected = _helper_hypothesis_delimited_date(
17241721
du_parse,
17251722
date_string,
1726-
default=_DEFAULT_DATETIME,
1723+
default=datetime(1, 1, 1),
17271724
dayfirst=dayfirst,
17281725
yearfirst=False,
17291726
)

0 commit comments

Comments
 (0)