Skip to content

Commit fd5b686

Browse files
mroeschkepull[bot]
authored andcommitted
TST/CLN: Remove more seldom used fixtures (#56625)
* Remove conftest in indexing * Use less idx fixture in multi * Remove other seldom used fixtures * Revert "Use less idx fixture in multi" This reverts commit e4f81bb. * Remove more single use fixtures * Fix typos * Fix more typos * fix typo * pylint * Uncomment * add back parametrization * Simplify
1 parent 64e2711 commit fd5b686

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1193
-1719
lines changed

pandas/conftest.py

-10
Original file line numberDiff line numberDiff line change
@@ -1838,16 +1838,6 @@ def ip():
18381838
return InteractiveShell(config=c)
18391839

18401840

1841-
@pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
1842-
def spmatrix(request):
1843-
"""
1844-
Yields scipy sparse matrix classes.
1845-
"""
1846-
sparse = pytest.importorskip("scipy.sparse")
1847-
1848-
return getattr(sparse, request.param + "_matrix")
1849-
1850-
18511841
@pytest.fixture(
18521842
params=[
18531843
getattr(pd.offsets, o)

pandas/tests/arithmetic/test_numeric.py

+2-19
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,6 @@ def switch_numexpr_min_elements(request, monkeypatch):
3737
yield request.param
3838

3939

40-
@pytest.fixture(params=[Index, Series, tm.to_array])
41-
def box_pandas_1d_array(request):
42-
"""
43-
Fixture to test behavior for Index, Series and tm.to_array classes
44-
"""
45-
return request.param
46-
47-
4840
@pytest.fixture(
4941
params=[
5042
# TODO: add more dtypes here
@@ -62,17 +54,6 @@ def numeric_idx(request):
6254
return request.param
6355

6456

65-
@pytest.fixture(
66-
params=[Index, Series, tm.to_array, np.array, list], ids=lambda x: x.__name__
67-
)
68-
def box_1d_array(request):
69-
"""
70-
Fixture to test behavior for Index, Series, tm.to_array, numpy Array and list
71-
classes
72-
"""
73-
return request.param
74-
75-
7657
def adjust_negative_zero(zero, expected):
7758
"""
7859
Helper to adjust the expected result if we are dividing by -0.0
@@ -1499,6 +1480,8 @@ def test_dataframe_div_silenced():
14991480
"data, expected_data",
15001481
[([0, 1, 2], [0, 2, 4])],
15011482
)
1483+
@pytest.mark.parametrize("box_pandas_1d_array", [Index, Series, tm.to_array])
1484+
@pytest.mark.parametrize("box_1d_array", [Index, Series, tm.to_array, np.array, list])
15021485
def test_integer_array_add_list_like(
15031486
box_pandas_1d_array, box_1d_array, data, expected_data
15041487
):

pandas/tests/dtypes/test_inference.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -1977,9 +1977,12 @@ def test_nan_to_nat_conversions():
19771977

19781978

19791979
@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
1980+
@pytest.mark.parametrize("spmatrix", ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
19801981
def test_is_scipy_sparse(spmatrix):
1981-
pytest.importorskip("scipy")
1982-
assert is_scipy_sparse(spmatrix([[0, 1]]))
1982+
sparse = pytest.importorskip("scipy.sparse")
1983+
1984+
klass = getattr(sparse, spmatrix + "_matrix")
1985+
assert is_scipy_sparse(klass([[0, 1]]))
19831986
assert not is_scipy_sparse(np.array([1]))
19841987

19851988

pandas/tests/frame/indexing/test_indexing.py

+11-23
Original file line numberDiff line numberDiff line change
@@ -1662,25 +1662,6 @@ def orig(self):
16621662
orig = DataFrame({"cats": cats, "values": values}, index=idx)
16631663
return orig
16641664

1665-
@pytest.fixture
1666-
def exp_single_row(self):
1667-
# The expected values if we change a single row
1668-
cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
1669-
idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
1670-
values1 = [1, 1, 2, 1, 1, 1, 1]
1671-
exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1)
1672-
return exp_single_row
1673-
1674-
@pytest.fixture
1675-
def exp_multi_row(self):
1676-
# assign multiple rows (mixed values) (-> array) -> exp_multi_row
1677-
# changed multiple rows
1678-
cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
1679-
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
1680-
values2 = [1, 1, 2, 2, 1, 1, 1]
1681-
exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
1682-
return exp_multi_row
1683-
16841665
@pytest.fixture
16851666
def exp_parts_cats_col(self):
16861667
# changed part of the cats column
@@ -1702,7 +1683,7 @@ def exp_single_cats_value(self):
17021683
return exp_single_cats_value
17031684

17041685
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
1705-
def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer):
1686+
def test_loc_iloc_setitem_list_of_lists(self, orig, indexer):
17061687
# - assign multiple rows (mixed values) -> exp_multi_row
17071688
df = orig.copy()
17081689

@@ -1711,6 +1692,11 @@ def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer):
17111692
key = slice("j", "k")
17121693

17131694
indexer(df)[key, :] = [["b", 2], ["b", 2]]
1695+
1696+
cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
1697+
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
1698+
values2 = [1, 1, 2, 2, 1, 1, 1]
1699+
exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
17141700
tm.assert_frame_equal(df, exp_multi_row)
17151701

17161702
df = orig.copy()
@@ -1752,9 +1738,7 @@ def test_loc_iloc_setitem_mask_single_value_in_categories(
17521738
tm.assert_frame_equal(df, exp_single_cats_value)
17531739

17541740
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
1755-
def test_loc_iloc_setitem_full_row_non_categorical_rhs(
1756-
self, orig, exp_single_row, indexer
1757-
):
1741+
def test_loc_iloc_setitem_full_row_non_categorical_rhs(self, orig, indexer):
17581742
# - assign a complete row (mixed values) -> exp_single_row
17591743
df = orig.copy()
17601744

@@ -1764,6 +1748,10 @@ def test_loc_iloc_setitem_full_row_non_categorical_rhs(
17641748

17651749
# not categorical dtype, but "b" _is_ among the categories for df["cat"]
17661750
indexer(df)[key, :] = ["b", 2]
1751+
cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
1752+
idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
1753+
values1 = [1, 1, 2, 1, 1, 1, 1]
1754+
exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1)
17671755
tm.assert_frame_equal(df, exp_single_row)
17681756

17691757
# "c" is not among the categories for df["cat"]

pandas/tests/frame/methods/test_join.py

+9-21
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,6 @@
1717
from pandas.core.reshape.concat import concat
1818

1919

20-
@pytest.fixture
21-
def frame_with_period_index():
22-
return DataFrame(
23-
data=np.arange(20).reshape(4, 5),
24-
columns=list("abcde"),
25-
index=period_range(start="2000", freq="Y", periods=4),
26-
)
27-
28-
29-
@pytest.fixture
30-
def left():
31-
return DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
32-
33-
34-
@pytest.fixture
35-
def right():
36-
return DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
37-
38-
3920
@pytest.fixture
4021
def left_no_dup():
4122
return DataFrame(
@@ -112,7 +93,9 @@ def right_w_dups(right_no_dup):
11293
),
11394
],
11495
)
115-
def test_join(left, right, how, sort, expected):
96+
def test_join(how, sort, expected):
97+
left = DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
98+
right = DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
11699
result = left.join(right, how=how, sort=sort, validate="1:1")
117100
tm.assert_frame_equal(result, expected)
118101

@@ -347,7 +330,12 @@ def test_join_overlap(float_frame):
347330
tm.assert_frame_equal(joined, expected.loc[:, joined.columns])
348331

349332

350-
def test_join_period_index(frame_with_period_index):
333+
def test_join_period_index():
334+
frame_with_period_index = DataFrame(
335+
data=np.arange(20).reshape(4, 5),
336+
columns=list("abcde"),
337+
index=period_range(start="2000", freq="Y", periods=4),
338+
)
351339
other = frame_with_period_index.rename(columns=lambda key: f"{key}{key}")
352340

353341
joined_values = np.concatenate([frame_with_period_index.values] * 2, axis=1)

pandas/tests/frame/methods/test_nlargest.py

+13-23
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,6 @@
1212
from pandas.util.version import Version
1313

1414

15-
@pytest.fixture
16-
def df_duplicates():
17-
return pd.DataFrame(
18-
{"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},
19-
index=[0, 0, 1, 1, 1],
20-
)
21-
22-
23-
@pytest.fixture
24-
def df_strings():
25-
return pd.DataFrame(
26-
{
27-
"a": np.random.default_rng(2).permutation(10),
28-
"b": list(ascii_lowercase[:10]),
29-
"c": np.random.default_rng(2).permutation(10).astype("float64"),
30-
}
31-
)
32-
33-
3415
@pytest.fixture
3516
def df_main_dtypes():
3617
return pd.DataFrame(
@@ -81,9 +62,15 @@ class TestNLargestNSmallest:
8162
],
8263
)
8364
@pytest.mark.parametrize("n", range(1, 11))
84-
def test_nlargest_n(self, df_strings, nselect_method, n, order):
65+
def test_nlargest_n(self, nselect_method, n, order):
8566
# GH#10393
86-
df = df_strings
67+
df = pd.DataFrame(
68+
{
69+
"a": np.random.default_rng(2).permutation(10),
70+
"b": list(ascii_lowercase[:10]),
71+
"c": np.random.default_rng(2).permutation(10).astype("float64"),
72+
}
73+
)
8774
if "b" in order:
8875
error_msg = (
8976
f"Column 'b' has dtype (object|string), "
@@ -156,10 +143,13 @@ def test_nlargest_n_identical_values(self):
156143
[["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]],
157144
)
158145
@pytest.mark.parametrize("n", range(1, 6))
159-
def test_nlargest_n_duplicate_index(self, df_duplicates, n, order, request):
146+
def test_nlargest_n_duplicate_index(self, n, order, request):
160147
# GH#13412
161148

162-
df = df_duplicates
149+
df = pd.DataFrame(
150+
{"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},
151+
index=[0, 0, 1, 1, 1],
152+
)
163153
result = df.nsmallest(n, order)
164154
expected = df.sort_values(order).head(n)
165155
tm.assert_frame_equal(result, expected)

pandas/tests/frame/test_subclass.py

+10-13
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,6 @@
1515
)
1616

1717

18-
@pytest.fixture()
19-
def gpd_style_subclass_df():
20-
class SubclassedDataFrame(DataFrame):
21-
@property
22-
def _constructor(self):
23-
return SubclassedDataFrame
24-
25-
return SubclassedDataFrame({"a": [1, 2, 3]})
26-
27-
2818
class TestDataFrameSubclassing:
2919
def test_frame_subclassing_and_slicing(self):
3020
# Subclass frame and ensure it returns the right class on slicing it
@@ -710,14 +700,21 @@ def test_idxmax_preserves_subclass(self):
710700
result = df.idxmax()
711701
assert isinstance(result, tm.SubclassedSeries)
712702

713-
def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df):
703+
def test_convert_dtypes_preserves_subclass(self):
714704
# GH 43668
715705
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
716706
result = df.convert_dtypes()
717707
assert isinstance(result, tm.SubclassedDataFrame)
718708

719-
result = gpd_style_subclass_df.convert_dtypes()
720-
assert isinstance(result, type(gpd_style_subclass_df))
709+
def test_convert_dtypes_preserves_subclass_with_constructor(self):
710+
class SubclassedDataFrame(DataFrame):
711+
@property
712+
def _constructor(self):
713+
return SubclassedDataFrame
714+
715+
df = SubclassedDataFrame({"a": [1, 2, 3]})
716+
result = df.convert_dtypes()
717+
assert isinstance(result, SubclassedDataFrame)
721718

722719
def test_astype_preserves_subclass(self):
723720
# GH#40810

pandas/tests/frame/test_validate.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,6 @@
33
from pandas.core.frame import DataFrame
44

55

6-
@pytest.fixture
7-
def dataframe():
8-
return DataFrame({"a": [1, 2], "b": [3, 4]})
9-
10-
116
class TestDataFrameValidate:
127
"""Tests for error handling related to data types of method arguments."""
138

@@ -24,7 +19,8 @@ class TestDataFrameValidate:
2419
],
2520
)
2621
@pytest.mark.parametrize("inplace", [1, "True", [1, 2, 3], 5.0])
27-
def test_validate_bool_args(self, dataframe, func, inplace):
22+
def test_validate_bool_args(self, func, inplace):
23+
dataframe = DataFrame({"a": [1, 2], "b": [3, 4]})
2824
msg = 'For argument "inplace" expected type bool'
2925
kwargs = {"inplace": inplace}
3026

pandas/tests/generic/test_finalize.py

+1-8
Original file line numberDiff line numberDiff line change
@@ -386,18 +386,11 @@ def idfn(x):
386386
return str(x)
387387

388388

389-
@pytest.fixture(params=_all_methods, ids=lambda x: idfn(x[-1]))
390-
def ndframe_method(request):
391-
"""
392-
An NDFrame method returning an NDFrame.
393-
"""
394-
return request.param
395-
396-
397389
@pytest.mark.filterwarnings(
398390
"ignore:DataFrame.fillna with 'method' is deprecated:FutureWarning",
399391
"ignore:last is deprecated:FutureWarning",
400392
)
393+
@pytest.mark.parametrize("ndframe_method", _all_methods, ids=lambda x: idfn(x[-1]))
401394
def test_finalize_called(ndframe_method):
402395
cls, init_args, method = ndframe_method
403396
ndframe = cls(*init_args)

pandas/tests/generic/test_label_or_level_utils.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,6 @@ def df_ambig(df):
3434
return df
3535

3636

37-
@pytest.fixture
38-
def df_duplabels(df):
39-
"""DataFrame with level 'L1' and labels 'L2', 'L3', and 'L2'"""
40-
df = df.set_index(["L1"])
41-
df = pd.concat([df, df["L2"]], axis=1)
42-
43-
return df
44-
45-
4637
# Test is label/level reference
4738
# =============================
4839
def get_labels_levels(df_levels):
@@ -229,7 +220,9 @@ def test_get_label_or_level_values_df_ambig(df_ambig, axis):
229220
assert_label_values(df_ambig, ["L3"], axis=axis)
230221

231222

232-
def test_get_label_or_level_values_df_duplabels(df_duplabels, axis):
223+
def test_get_label_or_level_values_df_duplabels(df, axis):
224+
df = df.set_index(["L1"])
225+
df_duplabels = pd.concat([df, df["L2"]], axis=1)
233226
axis = df_duplabels._get_axis_number(axis)
234227
# Transpose frame if axis == 1
235228
if axis == 1:

0 commit comments

Comments
 (0)