From c1ba069737b23f717c1ea3e019ea6139c1b24816 Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Sun, 13 Feb 2022 21:56:54 -0800 Subject: [PATCH] TST: Use fixture instead of base class setup --- pandas/tests/arrays/categorical/common.py | 8 --- pandas/tests/arrays/categorical/conftest.py | 7 +++ pandas/tests/arrays/categorical/test_api.py | 19 +++--- .../tests/arrays/categorical/test_indexing.py | 19 +++--- .../arrays/categorical/test_operators.py | 63 ++++++++++--------- pandas/tests/arrays/categorical/test_repr.py | 7 +-- .../tests/arrays/sparse/test_arithmetics.py | 22 +++---- .../tests/arrays/sparse/test_constructors.py | 1 + pandas/tests/arrays/sparse/test_unary.py | 2 +- 9 files changed, 72 insertions(+), 76 deletions(-) delete mode 100644 pandas/tests/arrays/categorical/common.py diff --git a/pandas/tests/arrays/categorical/common.py b/pandas/tests/arrays/categorical/common.py deleted file mode 100644 index 86d80c5476195..0000000000000 --- a/pandas/tests/arrays/categorical/common.py +++ /dev/null @@ -1,8 +0,0 @@ -from pandas import Categorical - - -class TestCategorical: - def setup_method(self): - self.factor = Categorical( - ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True - ) diff --git a/pandas/tests/arrays/categorical/conftest.py b/pandas/tests/arrays/categorical/conftest.py index 640f5dfd63887..99c601274de80 100644 --- a/pandas/tests/arrays/categorical/conftest.py +++ b/pandas/tests/arrays/categorical/conftest.py @@ -1,7 +1,14 @@ import pytest +from pandas import Categorical + @pytest.fixture(params=[True, False]) def allow_fill(request): """Boolean 'allow_fill' parameter for Categorical.take""" return request.param + + +@pytest.fixture +def factor(): + return Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True) diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index bde75051389ca..87b1bb88aeac3 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -12,7 +12,6 @@ ) import pandas._testing as tm from pandas.core.arrays.categorical import recode_for_categories -from pandas.tests.arrays.categorical.common import TestCategorical class TestCategoricalAPI: @@ -427,13 +426,13 @@ def test_remove_unused_categories(self): assert out.tolist() == val.tolist() -class TestCategoricalAPIWithFactor(TestCategorical): - def test_describe(self): +class TestCategoricalAPIWithFactor: + def test_describe(self, factor): # string type - desc = self.factor.describe() - assert self.factor.ordered + desc = factor.describe() + assert factor.ordered exp_index = CategoricalIndex( - ["a", "b", "c"], name="categories", ordered=self.factor.ordered + ["a", "b", "c"], name="categories", ordered=factor.ordered ) expected = DataFrame( {"counts": [3, 2, 3], "freqs": [3 / 8.0, 2 / 8.0, 3 / 8.0]}, index=exp_index @@ -441,7 +440,7 @@ def test_describe(self): tm.assert_frame_equal(desc, expected) # check unused categories - cat = self.factor.copy() + cat = factor.copy() with tm.assert_produces_warning(FutureWarning): # issue #37643 inplace kwarg deprecated @@ -450,7 +449,7 @@ def test_describe(self): desc = cat.describe() exp_index = CategoricalIndex( - list("abcd"), ordered=self.factor.ordered, name="categories" + list("abcd"), ordered=factor.ordered, name="categories" ) expected = DataFrame( {"counts": [3, 2, 3, 0], "freqs": [3 / 8.0, 2 / 8.0, 3 / 8.0, 0]}, @@ -480,8 +479,8 @@ def test_describe(self): ) tm.assert_frame_equal(desc, expected) - def test_set_categories_inplace(self): - cat = self.factor.copy() + def test_set_categories_inplace(self, factor): + cat = factor.copy() with tm.assert_produces_warning(FutureWarning): # issue #37643 inplace kwarg deprecated diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 26366178050cc..73ac51c258a94 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -14,31 +14,30 @@ ) import pandas._testing as tm import pandas.core.common as com -from pandas.tests.arrays.categorical.common import TestCategorical -class TestCategoricalIndexingWithFactor(TestCategorical): - def test_getitem(self): - assert self.factor[0] == "a" - assert self.factor[-1] == "c" +class TestCategoricalIndexingWithFactor: + def test_getitem(self, factor): + assert factor[0] == "a" + assert factor[-1] == "c" - subf = self.factor[[0, 1, 2]] + subf = factor[[0, 1, 2]] tm.assert_numpy_array_equal(subf._codes, np.array([0, 1, 1], dtype=np.int8)) - subf = self.factor[np.asarray(self.factor) == "c"] + subf = factor[np.asarray(factor) == "c"] tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8)) - def test_setitem(self): + def test_setitem(self, factor): # int/positional - c = self.factor.copy() + c = factor.copy() c[0] = "b" assert c[0] == "b" c[-1] = "a" assert c[-1] == "a" # boolean - c = self.factor.copy() + c = factor.copy() indexer = np.zeros(len(c), dtype="bool") indexer[0] = True indexer[-1] = True diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 9f19e83e5b3d4..9642691b5c578 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -11,48 +11,47 @@ date_range, ) import pandas._testing as tm -from pandas.tests.arrays.categorical.common import TestCategorical -class TestCategoricalOpsWithFactor(TestCategorical): +class TestCategoricalOpsWithFactor: def test_categories_none_comparisons(self): factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True) - tm.assert_categorical_equal(factor, self.factor) + tm.assert_categorical_equal(factor, factor) - def test_comparisons(self): - result = self.factor[self.factor == "a"] - expected = self.factor[np.asarray(self.factor) == "a"] + def test_comparisons(self, factor): + result = factor[factor == "a"] + expected = factor[np.asarray(factor) == "a"] tm.assert_categorical_equal(result, expected) - result = self.factor[self.factor != "a"] - expected = self.factor[np.asarray(self.factor) != "a"] + result = factor[factor != "a"] + expected = factor[np.asarray(factor) != "a"] tm.assert_categorical_equal(result, expected) - result = self.factor[self.factor < "c"] - expected = self.factor[np.asarray(self.factor) < "c"] + result = factor[factor < "c"] + expected = factor[np.asarray(factor) < "c"] tm.assert_categorical_equal(result, expected) - result = self.factor[self.factor > "a"] - expected = self.factor[np.asarray(self.factor) > "a"] + result = factor[factor > "a"] + expected = factor[np.asarray(factor) > "a"] tm.assert_categorical_equal(result, expected) - result = self.factor[self.factor >= "b"] - expected = self.factor[np.asarray(self.factor) >= "b"] + result = factor[factor >= "b"] + expected = factor[np.asarray(factor) >= "b"] tm.assert_categorical_equal(result, expected) - result = self.factor[self.factor <= "b"] - expected = self.factor[np.asarray(self.factor) <= "b"] + result = factor[factor <= "b"] + expected = factor[np.asarray(factor) <= "b"] tm.assert_categorical_equal(result, expected) - n = len(self.factor) + n = len(factor) - other = self.factor[np.random.permutation(n)] - result = self.factor == other - expected = np.asarray(self.factor) == np.asarray(other) + other = factor[np.random.permutation(n)] + result = factor == other + expected = np.asarray(factor) == np.asarray(other) tm.assert_numpy_array_equal(result, expected) - result = self.factor == "d" - expected = np.zeros(len(self.factor), dtype=bool) + result = factor == "d" + expected = np.zeros(len(factor), dtype=bool) tm.assert_numpy_array_equal(result, expected) # comparisons with categoricals @@ -377,23 +376,31 @@ def test_numeric_like_ops(self): # mad technically works because it takes always the numeric data + def test_numeric_like_ops_series(self): # numpy ops s = Series(Categorical([1, 2, 3, 4])) with pytest.raises(TypeError, match="does not support reduction 'sum'"): np.sum(s) - # numeric ops on a Series - for op, str_rep in [ + @pytest.mark.parametrize( + "op, str_rep", + [ ("__add__", r"\+"), ("__sub__", "-"), ("__mul__", r"\*"), ("__truediv__", "/"), - ]: - msg = f"Series cannot perform the operation {str_rep}|unsupported operand" - with pytest.raises(TypeError, match=msg): - getattr(s, op)(2) + ], + ) + def test_numeric_like_ops_series_arith(self, op, str_rep): + # numeric ops on a Series + s = Series(Categorical([1, 2, 3, 4])) + msg = f"Series cannot perform the operation {str_rep}|unsupported operand" + with pytest.raises(TypeError, match=msg): + getattr(s, op)(2) + def test_numeric_like_ops_series_invalid(self): # invalid ufunc + s = Series(Categorical([1, 2, 3, 4])) msg = "Object with dtype category cannot perform the numpy op log" with pytest.raises(TypeError, match=msg): np.log(s) diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py index 578191c8f7603..3454c8bb90941 100644 --- a/pandas/tests/arrays/categorical/test_repr.py +++ b/pandas/tests/arrays/categorical/test_repr.py @@ -9,17 +9,16 @@ period_range, timedelta_range, ) -from pandas.tests.arrays.categorical.common import TestCategorical -class TestCategoricalReprWithFactor(TestCategorical): - def test_print(self): +class TestCategoricalReprWithFactor: + def test_print(self, factor): expected = [ "['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']", "Categories (3, object): ['a' < 'b' < 'c']", ] expected = "\n".join(expected) - actual = repr(self.factor) + actual = repr(factor) assert actual == expected diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index 8f975e942db93..35c183db7ad9b 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -500,23 +500,19 @@ def test_mismatched_length_cmp_op(cons): @pytest.mark.parametrize("op", ["add", "sub", "mul", "truediv", "floordiv", "pow"]) -def test_binary_operators(op): +@pytest.mark.parametrize("fill_value", [np.nan, 3]) +def test_binary_operators(op, fill_value): op = getattr(operator, op) data1 = np.random.randn(20) data2 = np.random.randn(20) - data1[::2] = np.nan - data2[::3] = np.nan + data1[::2] = fill_value + data2[::3] = fill_value - arr1 = SparseArray(data1) - arr2 = SparseArray(data2) + first = SparseArray(data1, fill_value=fill_value) + second = SparseArray(data2, fill_value=fill_value) - data1[::2] = 3 - data2[::3] = 3 - farr1 = SparseArray(data1, fill_value=3) - farr2 = SparseArray(data2, fill_value=3) - - def _check_op(op, first, second): + with np.errstate(all="ignore"): res = op(first, second) exp = SparseArray( op(first.to_dense(), second.to_dense()), fill_value=first.fill_value @@ -544,7 +540,3 @@ def _check_op(op, first, second): else: tm.assert_almost_equal(res4.fill_value, exp_fv) tm.assert_almost_equal(res4.to_dense(), exp) - - with np.errstate(all="ignore"): - for first_arr, second_arr in [(arr1, arr2), (farr1, farr2)]: - _check_op(op, first_arr, second_arr) diff --git a/pandas/tests/arrays/sparse/test_constructors.py b/pandas/tests/arrays/sparse/test_constructors.py index c1fcda4fcd121..e1d401f198533 100644 --- a/pandas/tests/arrays/sparse/test_constructors.py +++ b/pandas/tests/arrays/sparse/test_constructors.py @@ -71,6 +71,7 @@ def test_constructor_object_dtype(self): assert arr.dtype == SparseDtype(object, "A") assert arr.fill_value == "A" + def test_constructor_object_dtype_bool_fill(self): # GH#17574 data = [False, 0, 100.0, 0.0] arr = SparseArray(data, dtype=object, fill_value=False) diff --git a/pandas/tests/arrays/sparse/test_unary.py b/pandas/tests/arrays/sparse/test_unary.py index a99dbb10a1433..a34c3b0787753 100644 --- a/pandas/tests/arrays/sparse/test_unary.py +++ b/pandas/tests/arrays/sparse/test_unary.py @@ -60,7 +60,6 @@ def test_abs_operator(self): def test_invert_operator(self): arr = SparseArray([False, True, False, True], fill_value=False, dtype=np.bool8) - res = ~arr exp = SparseArray( np.invert([False, True, False, True]), fill_value=True, dtype=np.bool8 ) @@ -70,3 +69,4 @@ def test_invert_operator(self): arr = SparseArray([0, 1, 0, 2, 3, 0], fill_value=0, dtype=np.int32) res = ~arr exp = SparseArray([-1, -2, -1, -3, -4, -1], fill_value=-1, dtype=np.int32) + tm.assert_sp_array_equal(exp, res)