Skip to content

TST: Use fixtures instead of setup_method for index tests #28865

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 3 commits into from
Oct 11, 2019
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
720 changes: 339 additions & 381 deletions pandas/tests/indexes/common.py

Large diffs are not rendered by default.

43 changes: 22 additions & 21 deletions pandas/tests/indexes/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,29 @@
from pandas.core.indexes.api import Index, MultiIndex
import pandas.util.testing as tm

indices_list = [
tm.makeUnicodeIndex(100),
tm.makeStringIndex(100),
tm.makeDateIndex(100),
tm.makePeriodIndex(100),
tm.makeTimedeltaIndex(100),
tm.makeIntIndex(100),
tm.makeUIntIndex(100),
tm.makeRangeIndex(100),
tm.makeFloatIndex(100),
Index([True, False]),
tm.makeCategoricalIndex(100),
tm.makeIntervalIndex(100),
Index([]),
MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])),
Index([0, 0, 1, 1, 2, 2]),
]


@pytest.fixture(params=indices_list, ids=lambda x: type(x).__name__)
indices_dict = {
"unicode": tm.makeUnicodeIndex(100),
"string": tm.makeStringIndex(100),
"datetime": tm.makeDateIndex(100),
"period": tm.makePeriodIndex(100),
"timedelta": tm.makeTimedeltaIndex(100),
"int": tm.makeIntIndex(100),
"uint": tm.makeUIntIndex(100),
"range": tm.makeRangeIndex(100),
"float": tm.makeFloatIndex(100),
"bool": Index([True, False]),
"categorical": tm.makeCategoricalIndex(100),
"interval": tm.makeIntervalIndex(100),
"empty": Index([]),
"tuples": MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])),
"repeats": Index([0, 0, 1, 1, 2, 2]),
}


@pytest.fixture(params=indices_dict.keys())
def indices(request):
Copy link
Member

Choose a reason for hiding this comment

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

maybe a smaller diff if the fixture was named index?

Not just this PR, but in general maybe we shouldn't use the plural when creating fixtures since when the fixture is used it creates a single value at a time and so the plural name in the tests can sometimes be confusing.

return request.param
# copy to avoid mutation, e.g. setting .name
return indices_dict[request.param].copy()


@pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
Expand Down
22 changes: 12 additions & 10 deletions pandas/tests/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,14 @@ def test_view(self):
tm.assert_index_equal(result, i_view)

def test_map_callable(self):
expected = self.index + self.index.freq
result = self.index.map(lambda x: x + x.freq)
index = self.create_index()
Copy link
Member Author

Choose a reason for hiding this comment

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

Planning to convert self.create_index() into a fixture in a follow up PR; in this PR I've used it to replace references to indexes set via setup_method.

Copy link
Member

Choose a reason for hiding this comment

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

i'm probably not be following the logic correctly, but self.create_index() is a different index to self.index for the datetimelike tests?

i.e. tdi

    def setup_method(self, method):
        self.indices = dict(index=tm.makeTimedeltaIndex(10))
        self.setup_indices()

so self.index is created with self.setup_indices() and not the same as

    def create_index(self):
        return pd.to_timedelta(range(5), unit="d") + pd.offsets.Hour(1)

expected = index + index.freq
result = index.map(lambda x: x + x.freq)
tm.assert_index_equal(result, expected)

# map to NaT
result = self.index.map(lambda x: pd.NaT if x == self.index[0] else x)
expected = pd.Index([pd.NaT] + self.index[1:].tolist())
result = index.map(lambda x: pd.NaT if x == index[0] else x)
expected = pd.Index([pd.NaT] + index[1:].tolist())
tm.assert_index_equal(result, expected)

@pytest.mark.parametrize(
Expand All @@ -75,23 +76,24 @@ def test_map_callable(self):
],
)
def test_map_dictlike(self, mapper):
expected = self.index + self.index.freq
index = self.create_index()
expected = index + index.freq

# don't compare the freqs
if isinstance(expected, pd.DatetimeIndex):
expected.freq = None

result = self.index.map(mapper(expected, self.index))
result = index.map(mapper(expected, index))
tm.assert_index_equal(result, expected)

expected = pd.Index([pd.NaT] + self.index[1:].tolist())
result = self.index.map(mapper(expected, self.index))
expected = pd.Index([pd.NaT] + index[1:].tolist())
result = index.map(mapper(expected, index))
tm.assert_index_equal(result, expected)

# empty map; these map to np.nan because we cannot know
# to re-infer things
expected = pd.Index([np.nan] * len(self.index))
result = self.index.map(mapper([], []))
expected = pd.Index([np.nan] * len(index))
result = index.map(mapper([], []))
tm.assert_index_equal(result, expected)

def test_asobject_deprecated(self):
Expand Down
13 changes: 7 additions & 6 deletions pandas/tests/indexes/datetimes/test_datetimelike.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" generic tests from the Datetimelike class """
import pytest

from pandas import DatetimeIndex, date_range
from pandas.util import testing as tm
Expand All @@ -9,12 +10,12 @@
class TestDatetimeIndex(DatetimeLike):
_holder = DatetimeIndex

def setup_method(self, method):
self.indices = dict(
index=tm.makeDateIndex(10),
index_dec=date_range("20130110", periods=10, freq="-1D"),
)
self.setup_indices()
@pytest.fixture(
params=[tm.makeDateIndex(10), date_range("20130110", periods=10, freq="-1D")],
ids=["index_inc", "index_dec"],
)
def indices(self, request):
return request.param

def create_index(self):
return date_range("20130101", periods=5)
Expand Down
7 changes: 3 additions & 4 deletions pandas/tests/indexes/interval/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@ class TestBase(Base):

_holder = IntervalIndex

def setup_method(self, method):
self.index = IntervalIndex.from_arrays([0, 1], [1, 2])
self.index_with_nan = IntervalIndex.from_tuples([(0, 1), np.nan, (1, 2)])
self.indices = dict(intervalIndex=tm.makeIntervalIndex(10))
@pytest.fixture
def indices(self):
return tm.makeIntervalIndex(10)

def create_index(self, closed="right"):
return IntervalIndex.from_breaks(range(11), closed=closed)
Expand Down
15 changes: 9 additions & 6 deletions pandas/tests/indexes/period/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@
class TestPeriodIndex(DatetimeLike):
_holder = PeriodIndex

def setup_method(self, method):
self.indices = dict(
index=tm.makePeriodIndex(10),
index_dec=period_range("20130101", periods=10, freq="D")[::-1],
)
self.setup_indices()
@pytest.fixture(
params=[
tm.makePeriodIndex(10),
period_range("20130101", periods=10, freq="D")[::-1],
],
ids=["index_inc", "index_dec"],
)
def indices(self, request):
return request.param

def create_index(self):
return period_range("20130101", periods=5, freq="D")
Expand Down
Loading