Skip to content

TST: Use fixture instead of setup_method in tests/array/categorical #45988

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 2 commits into from
Feb 15, 2022
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
8 changes: 0 additions & 8 deletions pandas/tests/arrays/categorical/common.py

This file was deleted.

7 changes: 7 additions & 0 deletions pandas/tests/arrays/categorical/conftest.py
Original file line number Diff line number Diff line change
@@ -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)
19 changes: 9 additions & 10 deletions pandas/tests/arrays/categorical/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -427,21 +426,21 @@ 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
)
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
Expand All @@ -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]},
Expand Down Expand Up @@ -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
Expand Down
19 changes: 9 additions & 10 deletions pandas/tests/arrays/categorical/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 35 additions & 28 deletions pandas/tests/arrays/categorical/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
7 changes: 3 additions & 4 deletions pandas/tests/arrays/categorical/test_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
22 changes: 7 additions & 15 deletions pandas/tests/arrays/sparse/test_arithmetics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
1 change: 1 addition & 0 deletions pandas/tests/arrays/sparse/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/arrays/sparse/test_unary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand All @@ -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)