Skip to content

TST/CLN: Remove more seldom used fixtures #56625

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 17 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1838,16 +1838,6 @@ def ip():
return InteractiveShell(config=c)


@pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
def spmatrix(request):
"""
Yields scipy sparse matrix classes.
"""
sparse = pytest.importorskip("scipy.sparse")

return getattr(sparse, request.param + "_matrix")


@pytest.fixture(
params=[
getattr(pd.offsets, o)
Expand Down
21 changes: 2 additions & 19 deletions pandas/tests/arithmetic/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,6 @@ def switch_numexpr_min_elements(request, monkeypatch):
yield request.param


@pytest.fixture(params=[Index, Series, tm.to_array])
def box_pandas_1d_array(request):
"""
Fixture to test behavior for Index, Series and tm.to_array classes
"""
return request.param


@pytest.fixture(
params=[
# TODO: add more dtypes here
Expand All @@ -62,17 +54,6 @@ def numeric_idx(request):
return request.param


@pytest.fixture(
params=[Index, Series, tm.to_array, np.array, list], ids=lambda x: x.__name__
)
def box_1d_array(request):
"""
Fixture to test behavior for Index, Series, tm.to_array, numpy Array and list
classes
"""
return request.param


def adjust_negative_zero(zero, expected):
"""
Helper to adjust the expected result if we are dividing by -0.0
Expand Down Expand Up @@ -1499,6 +1480,8 @@ def test_dataframe_div_silenced():
"data, expected_data",
[([0, 1, 2], [0, 2, 4])],
)
@pytest.mark.parametrize("box_pandas_1d_array", [Index, Series, tm.to_array])
@pytest.mark.parametrize("box_1d_array", [Index, Series, tm.to_array, np.array, list])
def test_integer_array_add_list_like(
box_pandas_1d_array, box_1d_array, data, expected_data
):
Expand Down
7 changes: 5 additions & 2 deletions pandas/tests/dtypes/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -1977,9 +1977,12 @@ def test_nan_to_nat_conversions():


@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
@pytest.mark.parametrize("spmatrix", ["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
def test_is_scipy_sparse(spmatrix):
pytest.importorskip("scipy")
assert is_scipy_sparse(spmatrix([[0, 1]]))
sparse = pytest.importorskip("scipy.sparse")

klass = getattr(sparse, spmatrix + "_matrix")
assert is_scipy_sparse(klass([[0, 1]]))
assert not is_scipy_sparse(np.array([1]))


Expand Down
34 changes: 11 additions & 23 deletions pandas/tests/frame/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1662,25 +1662,6 @@ def orig(self):
orig = DataFrame({"cats": cats, "values": values}, index=idx)
return orig

@pytest.fixture
def exp_single_row(self):
# The expected values if we change a single row
cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
values1 = [1, 1, 2, 1, 1, 1, 1]
exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1)
return exp_single_row

@pytest.fixture
def exp_multi_row(self):
# assign multiple rows (mixed values) (-> array) -> exp_multi_row
# changed multiple rows
cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
values2 = [1, 1, 2, 2, 1, 1, 1]
exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
return exp_multi_row

@pytest.fixture
def exp_parts_cats_col(self):
# changed part of the cats column
Expand All @@ -1702,7 +1683,7 @@ def exp_single_cats_value(self):
return exp_single_cats_value

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

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

indexer(df)[key, :] = [["b", 2], ["b", 2]]

cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
values2 = [1, 1, 2, 2, 1, 1, 1]
exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
tm.assert_frame_equal(df, exp_multi_row)

df = orig.copy()
Expand Down Expand Up @@ -1752,9 +1738,7 @@ def test_loc_iloc_setitem_mask_single_value_in_categories(
tm.assert_frame_equal(df, exp_single_cats_value)

@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
def test_loc_iloc_setitem_full_row_non_categorical_rhs(
self, orig, exp_single_row, indexer
):
def test_loc_iloc_setitem_full_row_non_categorical_rhs(self, orig, indexer):
# - assign a complete row (mixed values) -> exp_single_row
df = orig.copy()

Expand All @@ -1764,6 +1748,10 @@ def test_loc_iloc_setitem_full_row_non_categorical_rhs(

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

# "c" is not among the categories for df["cat"]
Expand Down
30 changes: 9 additions & 21 deletions pandas/tests/frame/methods/test_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,6 @@
from pandas.core.reshape.concat import concat


@pytest.fixture
def frame_with_period_index():
return DataFrame(
data=np.arange(20).reshape(4, 5),
columns=list("abcde"),
index=period_range(start="2000", freq="Y", periods=4),
)


@pytest.fixture
def left():
return DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])


@pytest.fixture
def right():
return DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])


@pytest.fixture
def left_no_dup():
return DataFrame(
Expand Down Expand Up @@ -112,7 +93,9 @@ def right_w_dups(right_no_dup):
),
],
)
def test_join(left, right, how, sort, expected):
def test_join(how, sort, expected):
left = DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])
right = DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])
result = left.join(right, how=how, sort=sort, validate="1:1")
tm.assert_frame_equal(result, expected)

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


def test_join_period_index(frame_with_period_index):
def test_join_period_index():
frame_with_period_index = DataFrame(
data=np.arange(20).reshape(4, 5),
columns=list("abcde"),
index=period_range(start="2000", freq="Y", periods=4),
)
other = frame_with_period_index.rename(columns=lambda key: f"{key}{key}")

joined_values = np.concatenate([frame_with_period_index.values] * 2, axis=1)
Expand Down
36 changes: 13 additions & 23 deletions pandas/tests/frame/methods/test_nlargest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,6 @@
from pandas.util.version import Version


@pytest.fixture
def df_duplicates():
return pd.DataFrame(
{"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},
index=[0, 0, 1, 1, 1],
)


@pytest.fixture
def df_strings():
return pd.DataFrame(
{
"a": np.random.default_rng(2).permutation(10),
"b": list(ascii_lowercase[:10]),
"c": np.random.default_rng(2).permutation(10).astype("float64"),
}
)


@pytest.fixture
def df_main_dtypes():
return pd.DataFrame(
Expand Down Expand Up @@ -81,9 +62,15 @@ class TestNLargestNSmallest:
],
)
@pytest.mark.parametrize("n", range(1, 11))
def test_nlargest_n(self, df_strings, nselect_method, n, order):
def test_nlargest_n(self, nselect_method, n, order):
# GH#10393
df = df_strings
df = pd.DataFrame(
{
"a": np.random.default_rng(2).permutation(10),
"b": list(ascii_lowercase[:10]),
"c": np.random.default_rng(2).permutation(10).astype("float64"),
}
)
if "b" in order:
error_msg = (
f"Column 'b' has dtype (object|string), "
Expand Down Expand Up @@ -156,10 +143,13 @@ def test_nlargest_n_identical_values(self):
[["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]],
)
@pytest.mark.parametrize("n", range(1, 6))
def test_nlargest_n_duplicate_index(self, df_duplicates, n, order, request):
def test_nlargest_n_duplicate_index(self, n, order, request):
# GH#13412

df = df_duplicates
df = pd.DataFrame(
{"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},
index=[0, 0, 1, 1, 1],
)
result = df.nsmallest(n, order)
expected = df.sort_values(order).head(n)
tm.assert_frame_equal(result, expected)
Expand Down
23 changes: 10 additions & 13 deletions pandas/tests/frame/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,6 @@
)


@pytest.fixture()
def gpd_style_subclass_df():
class SubclassedDataFrame(DataFrame):
@property
def _constructor(self):
return SubclassedDataFrame

return SubclassedDataFrame({"a": [1, 2, 3]})


class TestDataFrameSubclassing:
def test_frame_subclassing_and_slicing(self):
# Subclass frame and ensure it returns the right class on slicing it
Expand Down Expand Up @@ -710,14 +700,21 @@ def test_idxmax_preserves_subclass(self):
result = df.idxmax()
assert isinstance(result, tm.SubclassedSeries)

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

result = gpd_style_subclass_df.convert_dtypes()
assert isinstance(result, type(gpd_style_subclass_df))
def test_convert_dtypes_preserves_subclass_with_constructor(self):
class SubclassedDataFrame(DataFrame):
@property
def _constructor(self):
return SubclassedDataFrame

df = SubclassedDataFrame({"a": [1, 2, 3]})
result = df.convert_dtypes()
assert isinstance(result, SubclassedDataFrame)

def test_astype_preserves_subclass(self):
# GH#40810
Expand Down
8 changes: 2 additions & 6 deletions pandas/tests/frame/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@
from pandas.core.frame import DataFrame


@pytest.fixture
def dataframe():
return DataFrame({"a": [1, 2], "b": [3, 4]})


class TestDataFrameValidate:
"""Tests for error handling related to data types of method arguments."""

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

Expand Down
9 changes: 1 addition & 8 deletions pandas/tests/generic/test_finalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,18 +386,11 @@ def idfn(x):
return str(x)


@pytest.fixture(params=_all_methods, ids=lambda x: idfn(x[-1]))
def ndframe_method(request):
"""
An NDFrame method returning an NDFrame.
"""
return request.param


@pytest.mark.filterwarnings(
"ignore:DataFrame.fillna with 'method' is deprecated:FutureWarning",
"ignore:last is deprecated:FutureWarning",
)
@pytest.mark.parametrize("ndframe_method", _all_methods, ids=lambda x: idfn(x[-1]))
def test_finalize_called(ndframe_method):
cls, init_args, method = ndframe_method
ndframe = cls(*init_args)
Expand Down
13 changes: 3 additions & 10 deletions pandas/tests/generic/test_label_or_level_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,6 @@ def df_ambig(df):
return df


@pytest.fixture
def df_duplabels(df):
"""DataFrame with level 'L1' and labels 'L2', 'L3', and 'L2'"""
df = df.set_index(["L1"])
df = pd.concat([df, df["L2"]], axis=1)

return df


# Test is label/level reference
# =============================
def get_labels_levels(df_levels):
Expand Down Expand Up @@ -229,7 +220,9 @@ def test_get_label_or_level_values_df_ambig(df_ambig, axis):
assert_label_values(df_ambig, ["L3"], axis=axis)


def test_get_label_or_level_values_df_duplabels(df_duplabels, axis):
def test_get_label_or_level_values_df_duplabels(df, axis):
df = df.set_index(["L1"])
df_duplabels = pd.concat([df, df["L2"]], axis=1)
axis = df_duplabels._get_axis_number(axis)
# Transpose frame if axis == 1
if axis == 1:
Expand Down
Loading