Skip to content

TST/CLN: Test parametrizations #56737

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 4 commits into from
Jan 6, 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
25 changes: 12 additions & 13 deletions pandas/tests/arithmetic/test_datetime64.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,12 +182,12 @@ class TestDatetime64SeriesComparison:
@pytest.mark.parametrize(
"op, expected",
[
(operator.eq, Series([False, False, True])),
(operator.ne, Series([True, True, False])),
(operator.lt, Series([False, False, False])),
(operator.gt, Series([False, False, False])),
(operator.ge, Series([False, False, True])),
(operator.le, Series([False, False, True])),
(operator.eq, [False, False, True]),
(operator.ne, [True, True, False]),
(operator.lt, [False, False, False]),
(operator.gt, [False, False, False]),
(operator.ge, [False, False, True]),
(operator.le, [False, False, True]),
],
)
def test_nat_comparisons(
Expand All @@ -210,7 +210,7 @@ def test_nat_comparisons(

result = op(left, right)

tm.assert_series_equal(result, expected)
tm.assert_series_equal(result, Series(expected))

@pytest.mark.parametrize(
"data",
Expand Down Expand Up @@ -1485,11 +1485,10 @@ def test_dt64arr_add_sub_DateOffsets(
@pytest.mark.parametrize(
"other",
[
np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]),
np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()]),
np.array( # matching offsets
[pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)]
),
[pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
[pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()],
# matching offsets
[pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)],
],
)
@pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
Expand All @@ -1502,7 +1501,7 @@ def test_dt64arr_add_sub_offset_array(
tz = tz_naive_fixture
dti = date_range("2017-01-01", periods=2, tz=tz)
dtarr = tm.box_expected(dti, box_with_array)

other = np.array(other)
expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
expected = tm.box_expected(expected, box_with_array).astype(object)

Expand Down
18 changes: 10 additions & 8 deletions pandas/tests/arithmetic/test_timedelta64.py
Original file line number Diff line number Diff line change
Expand Up @@ -1960,19 +1960,20 @@ def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two):
two // tdser

@pytest.mark.parametrize(
"vector",
[np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
ids=lambda x: type(x).__name__,
"klass",
[np.array, Index, Series],
Copy link
Member

Choose a reason for hiding this comment

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

we have a fixture for this already no? Can't we just use that?

Copy link
Member Author

Choose a reason for hiding this comment

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

We don't have one yet like this; only ones that parametrize over pandas constructors. I do think we should have a "1D constructor" fixture in the future

ids=lambda x: x.__name__,
)
def test_td64arr_rmul_numeric_array(
self,
box_with_array,
vector,
klass,
any_real_numpy_dtype,
):
# GH#4521
# divide/multiply by integers

vector = klass([20, 30, 40])
tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
vector = vector.astype(any_real_numpy_dtype)

Expand All @@ -1990,16 +1991,17 @@ def test_td64arr_rmul_numeric_array(
tm.assert_equal(result, expected)

@pytest.mark.parametrize(
"vector",
[np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])],
ids=lambda x: type(x).__name__,
"klass",
[np.array, Index, Series],
ids=lambda x: x.__name__,
)
def test_td64arr_div_numeric_array(
self, box_with_array, vector, any_real_numpy_dtype
self, box_with_array, klass, any_real_numpy_dtype
):
# GH#4521
# divide/multiply by integers

vector = klass([20, 30, 40])
tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]")
vector = vector.astype(any_real_numpy_dtype)

Expand Down
8 changes: 3 additions & 5 deletions pandas/tests/arrays/categorical/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,10 @@ def test_setitem(self):

tm.assert_categorical_equal(c, expected)

@pytest.mark.parametrize(
"other",
[Categorical(["b", "a"]), Categorical(["b", "a"], categories=["b", "a"])],
)
def test_setitem_same_but_unordered(self, other):
@pytest.mark.parametrize("categories", [None, ["b", "a"]])
def test_setitem_same_but_unordered(self, categories):
# GH-24142
other = Categorical(["b", "a"], categories=categories)
target = Categorical(["a", "b"], categories=["a", "b"])
mask = np.array([True, False])
target[mask] = other[mask]
Expand Down
26 changes: 10 additions & 16 deletions pandas/tests/arrays/categorical/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,29 +307,23 @@ def test_comparisons(self, data, reverse, base):
with pytest.raises(TypeError, match=msg):
a < cat_rev

@pytest.mark.parametrize(
"ctor",
[
lambda *args, **kwargs: Categorical(*args, **kwargs),
lambda *args, **kwargs: Series(Categorical(*args, **kwargs)),
],
)
def test_unordered_different_order_equal(self, ctor):
@pytest.mark.parametrize("box", [lambda x: x, Series])
def test_unordered_different_order_equal(self, box):
# https://github.com/pandas-dev/pandas/issues/16014
c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
c1 = box(Categorical(["a", "b"], categories=["a", "b"], ordered=False))
c2 = box(Categorical(["a", "b"], categories=["b", "a"], ordered=False))
assert (c1 == c2).all()

c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
c2 = ctor(["b", "a"], categories=["b", "a"], ordered=False)
c1 = box(Categorical(["a", "b"], categories=["a", "b"], ordered=False))
c2 = box(Categorical(["b", "a"], categories=["b", "a"], ordered=False))
assert (c1 != c2).all()

c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
c2 = ctor(["b", "b"], categories=["b", "a"], ordered=False)
c1 = box(Categorical(["a", "a"], categories=["a", "b"], ordered=False))
c2 = box(Categorical(["b", "b"], categories=["b", "a"], ordered=False))
assert (c1 != c2).all()

c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
c1 = box(Categorical(["a", "a"], categories=["a", "b"], ordered=False))
c2 = box(Categorical(["a", "b"], categories=["b", "a"], ordered=False))
result = c1 == c2
tm.assert_numpy_array_equal(np.array(result), np.array([True, False]))

Expand Down
12 changes: 6 additions & 6 deletions pandas/tests/arrays/sparse/test_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,15 @@ def test_construct_from_string_raises():
@pytest.mark.parametrize(
"dtype, expected",
[
(SparseDtype(int), True),
(SparseDtype(float), True),
(SparseDtype(bool), True),
(SparseDtype(object), False),
(SparseDtype(str), False),
(int, True),
(float, True),
(bool, True),
(object, False),
(str, False),
],
)
def test_is_numeric(dtype, expected):
assert dtype._is_numeric is expected
assert SparseDtype(dtype)._is_numeric is expected


def test_str_uses_object():
Expand Down
14 changes: 6 additions & 8 deletions pandas/tests/arrays/sparse/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,13 @@ def test_sum(self):

@pytest.mark.parametrize(
"arr",
[np.array([0, 1, np.nan, 1]), np.array([0, 1, 1])],
[[0, 1, np.nan, 1], [0, 1, 1]],
)
@pytest.mark.parametrize("fill_value", [0, 1, np.nan])
@pytest.mark.parametrize("min_count, expected", [(3, 2), (4, np.nan)])
def test_sum_min_count(self, arr, fill_value, min_count, expected):
# GH#25777
sparray = SparseArray(arr, fill_value=fill_value)
sparray = SparseArray(np.array(arr), fill_value=fill_value)
result = sparray.sum(min_count=min_count)
if np.isnan(expected):
assert np.isnan(result)
Expand Down Expand Up @@ -296,11 +296,9 @@ def test_argmax_argmin(self, arr, argmax_expected, argmin_expected):
assert argmax_result == argmax_expected
assert argmin_result == argmin_expected

@pytest.mark.parametrize(
"arr,method",
[(SparseArray([]), "argmax"), (SparseArray([]), "argmin")],
)
def test_empty_array(self, arr, method):
@pytest.mark.parametrize("method", ["argmax", "argmin"])
def test_empty_array(self, method):
msg = f"attempt to get {method} of an empty sequence"
arr = SparseArray([])
with pytest.raises(ValueError, match=msg):
arr.argmax() if method == "argmax" else arr.argmin()
getattr(arr, method)()
9 changes: 5 additions & 4 deletions pandas/tests/base/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,22 +499,23 @@ def test_to_numpy_dataframe_na_value(data, dtype, na_value):


@pytest.mark.parametrize(
"data, expected",
"data, expected_data",
[
(
{"a": pd.array([1, 2, None])},
np.array([[1.0], [2.0], [np.nan]], dtype=float),
[[1.0], [2.0], [np.nan]],
),
(
{"a": [1, 2, 3], "b": [1, 2, 3]},
np.array([[1, 1], [2, 2], [3, 3]], dtype=float),
[[1, 1], [2, 2], [3, 3]],
),
],
)
def test_to_numpy_dataframe_single_block(data, expected):
def test_to_numpy_dataframe_single_block(data, expected_data):
# https://github.com/pandas-dev/pandas/issues/33820
df = pd.DataFrame(data)
result = df.to_numpy(dtype=float, na_value=np.nan)
expected = np.array(expected_data, dtype=float)
tm.assert_numpy_array_equal(result, expected)


Expand Down
14 changes: 8 additions & 6 deletions pandas/tests/computation/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,14 +522,15 @@ def test_series_negate(self, engine, parser):
"lhs",
[
# Float
DataFrame(np.random.default_rng(2).standard_normal((5, 2))),
np.random.default_rng(2).standard_normal((5, 2)),
# Int
DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))),
np.random.default_rng(2).integers(5, size=(5, 2)),
# bool doesn't work with numexpr but works elsewhere
DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5),
np.array([True, False, True, False, True], dtype=np.bool_),
],
)
def test_frame_pos(self, lhs, engine, parser):
lhs = DataFrame(lhs)
expr = "+lhs"
expect = lhs

Expand All @@ -540,14 +541,15 @@ def test_frame_pos(self, lhs, engine, parser):
"lhs",
[
# Float
Series(np.random.default_rng(2).standard_normal(5)),
np.random.default_rng(2).standard_normal(5),
# Int
Series(np.random.default_rng(2).integers(5, size=5)),
np.random.default_rng(2).integers(5, size=5),
# bool doesn't work with numexpr but works elsewhere
Series(np.random.default_rng(2).standard_normal(5) > 0.5),
np.array([True, False, True, False, True], dtype=np.bool_),
],
)
def test_series_pos(self, lhs, engine, parser):
lhs = Series(lhs)
expr = "+lhs"
expect = lhs

Expand Down
12 changes: 3 additions & 9 deletions pandas/tests/copy_view/index/test_datetimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,11 @@
)


@pytest.mark.parametrize(
"cons",
[
lambda x: DatetimeIndex(x),
lambda x: DatetimeIndex(DatetimeIndex(x)),
],
)
def test_datetimeindex(using_copy_on_write, cons):
@pytest.mark.parametrize("box", [lambda x: x, DatetimeIndex])
def test_datetimeindex(using_copy_on_write, box):
dt = date_range("2019-12-31", periods=3, freq="D")
ser = Series(dt)
idx = cons(ser)
idx = box(DatetimeIndex(ser))
expected = idx.copy(deep=True)
ser.iloc[0] = Timestamp("2020-12-31")
if using_copy_on_write:
Expand Down
12 changes: 3 additions & 9 deletions pandas/tests/copy_view/index/test_periodindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,11 @@
)


@pytest.mark.parametrize(
"cons",
[
lambda x: PeriodIndex(x),
lambda x: PeriodIndex(PeriodIndex(x)),
],
)
def test_periodindex(using_copy_on_write, cons):
@pytest.mark.parametrize("box", [lambda x: x, PeriodIndex])
def test_periodindex(using_copy_on_write, box):
dt = period_range("2019-12-31", periods=3, freq="D")
ser = Series(dt)
idx = cons(ser)
idx = box(PeriodIndex(ser))
expected = idx.copy(deep=True)
ser.iloc[0] = Period("2020-12-31")
if using_copy_on_write:
Expand Down
29 changes: 15 additions & 14 deletions pandas/tests/dtypes/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,15 +1078,15 @@ def test_integers(self):
@pytest.mark.parametrize(
"arr, skipna",
[
(np.array([1, 2, np.nan, np.nan, 3], dtype="O"), False),
(np.array([1, 2, np.nan, np.nan, 3], dtype="O"), True),
(np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), False),
(np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), True),
([1, 2, np.nan, np.nan, 3], False),
([1, 2, np.nan, np.nan, 3], True),
([1, 2, 3, np.int64(4), np.int32(5), np.nan], False),
([1, 2, 3, np.int64(4), np.int32(5), np.nan], True),
],
)
def test_integer_na(self, arr, skipna):
# GH 27392
result = lib.infer_dtype(arr, skipna=skipna)
result = lib.infer_dtype(np.array(arr, dtype="O"), skipna=skipna)
expected = "integer" if skipna else "integer-na"
assert result == expected

Expand Down Expand Up @@ -1287,13 +1287,13 @@ def test_infer_dtype_mixed_integer(self):
@pytest.mark.parametrize(
"arr",
[
np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]),
np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]),
np.array([datetime(2011, 1, 1), Timestamp("2011-01-02")]),
[Timestamp("2011-01-01"), Timestamp("2011-01-02")],
[datetime(2011, 1, 1), datetime(2012, 2, 1)],
[datetime(2011, 1, 1), Timestamp("2011-01-02")],
],
)
def test_infer_dtype_datetime(self, arr):
assert lib.infer_dtype(arr, skipna=True) == "datetime"
assert lib.infer_dtype(np.array(arr), skipna=True) == "datetime"

@pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
@pytest.mark.parametrize(
Expand Down Expand Up @@ -1902,14 +1902,15 @@ def test_is_scalar_numpy_array_scalars(self):
@pytest.mark.parametrize(
"zerodim",
[
np.array(1),
np.array("foobar"),
np.array(np.datetime64("2014-01-01")),
np.array(np.timedelta64(1, "h")),
np.array(np.datetime64("NaT")),
1,
"foobar",
np.datetime64("2014-01-01"),
np.timedelta64(1, "h"),
np.datetime64("NaT"),
],
)
def test_is_scalar_numpy_zerodim_arrays(self, zerodim):
zerodim = np.array(zerodim)
assert not is_scalar(zerodim)
assert is_scalar(lib.item_from_zerodim(zerodim))

Expand Down
12 changes: 6 additions & 6 deletions pandas/tests/frame/indexing/test_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ def test_get(self, float_frame):
)

@pytest.mark.parametrize(
"df",
"columns, index",
[
DataFrame(),
DataFrame(columns=list("AB")),
DataFrame(columns=list("AB"), index=range(3)),
[None, None],
[list("AB"), None],
[list("AB"), range(3)],
],
)
def test_get_none(self, df):
def test_get_none(self, columns, index):
# see gh-5652
assert df.get(None) is None
assert DataFrame(columns=columns, index=index).get(None) is None
Loading