Skip to content

Commit

Permalink
TST/CLN: Test parametrizations
Browse files Browse the repository at this point in the history
  • Loading branch information
mroeschke committed Jan 4, 2024
1 parent b2bca5e commit 1e99357
Show file tree
Hide file tree
Showing 22 changed files with 180 additions and 257 deletions.
24 changes: 12 additions & 12 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 @@ -1486,11 +1486,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 @@ -1512,6 +1511,7 @@ def test_dt64arr_add_sub_offset_array(
tm.assert_equal(res, expected)

# Same thing but boxing other
other = np.array(other)
other = tm.box_expected(other, box_with_array)
if box_with_array is pd.array and op is roperator.radd:
# We expect a NumpyExtensionArray, not ndarray[object] here
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],
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("other", [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
12 changes: 5 additions & 7 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")],
)
@pytest.mark.parametrize("method", ["argmax", "argmin"])
def test_empty_array(self, arr, 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
16 changes: 8 additions & 8 deletions pandas/tests/computation/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,16 +523,16 @@ 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):
expr = "+lhs"
expect = lhs
expect = DataFrame(lhs)

result = pd.eval(expr, engine=engine, parser=parser)
tm.assert_frame_equal(expect, result)
Expand All @@ -541,16 +541,16 @@ 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):
expr = "+lhs"
expect = lhs
expect = Series(lhs)

result = pd.eval(expr, engine=engine, parser=parser)
tm.assert_series_equal(expect, result)
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

0 comments on commit 1e99357

Please sign in to comment.