Skip to content

TST: Use fixtures in indexes common tests #17622

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 6 commits into from
Sep 25, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
325 changes: 150 additions & 175 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def test_numeric_compat(self):
lambda: 1 * idx)

div_err = "cannot perform __truediv__" if PY3 \
else "cannot perform __div__"
else "cannot perform __div__"
tm.assert_raises_regex(TypeError, div_err, lambda: idx / 1)
tm.assert_raises_regex(TypeError, div_err, lambda: 1 / idx)
tm.assert_raises_regex(TypeError, "cannot perform __floordiv__",
Expand Down Expand Up @@ -178,11 +178,10 @@ def test_str(self):
assert "'foo'" in str(idx)
assert idx.__class__.__name__ in str(idx)

def test_dtype_str(self):
for idx in self.indices.values():
dtype = idx.dtype_str
assert isinstance(dtype, compat.string_types)
assert dtype == str(idx.dtype)
def test_dtype_str(self, index):
dtype = index.dtype_str
assert isinstance(dtype, compat.string_types)
assert dtype == str(index.dtype)

def test_repr_max_seq_item_setting(self):
# GH10182
Expand All @@ -192,48 +191,42 @@ def test_repr_max_seq_item_setting(self):
repr(idx)
assert '...' not in str(idx)

def test_wrong_number_names(self):
def test_wrong_number_names(self, index):
def testit(ind):
ind.names = ["apple", "banana", "carrot"]
tm.assert_raises_regex(ValueError, "^Length", testit, index)

for ind in self.indices.values():
tm.assert_raises_regex(ValueError, "^Length", testit, ind)

def test_set_name_methods(self):
def test_set_name_methods(self, index):
new_name = "This is the new name for this index"
for ind in self.indices.values():

# don't tests a MultiIndex here (as its tested separated)
if isinstance(ind, MultiIndex):
continue

original_name = ind.name
new_ind = ind.set_names([new_name])
assert new_ind.name == new_name
assert ind.name == original_name
res = ind.rename(new_name, inplace=True)

# should return None
assert res is None
assert ind.name == new_name
assert ind.names == [new_name]
# with tm.assert_raises_regex(TypeError, "list-like"):
# # should still fail even if it would be the right length
# ind.set_names("a")
with tm.assert_raises_regex(ValueError, "Level must be None"):
ind.set_names("a", level=0)

# rename in place just leaves tuples and other containers alone
name = ('A', 'B')
ind.rename(name, inplace=True)
assert ind.name == name
assert ind.names == [name]

def test_hash_error(self):
for ind in self.indices.values():
with tm.assert_raises_regex(TypeError, "unhashable type: %r" %
type(ind).__name__):
hash(ind)
# don't tests a MultiIndex here (as its tested separated)
if isinstance(index, MultiIndex):
return
original_name = index.name
new_ind = index.set_names([new_name])
assert new_ind.name == new_name
assert index.name == original_name
res = index.rename(new_name, inplace=True)

# should return None
assert res is None
assert index.name == new_name
assert index.names == [new_name]
# with tm.assert_raises_regex(TypeError, "list-like"):
# # should still fail even if it would be the right length
# ind.set_names("a")
with tm.assert_raises_regex(ValueError, "Level must be None"):
index.set_names("a", level=0)

# rename in place just leaves tuples and other containers alone
name = ('A', 'B')
index.rename(name, inplace=True)
assert index.name == name
assert index.names == [name]

def test_hash_error(self, index):
tm.assert_raises_regex(TypeError, "unhashable type: %r" %
type(index).__name__, hash, index)

def test_copy_name(self):
# gh-12309: Check that the "name" argument
Expand Down Expand Up @@ -298,106 +291,87 @@ def test_ensure_copied_data(self):
tm.assert_numpy_array_equal(index._values, result._values,
check_same='same')

def test_copy_and_deepcopy(self):
def test_copy_and_deepcopy(self, index):
from copy import copy, deepcopy

for ind in self.indices.values():
if isinstance(index, MultiIndex):
return
for func in (copy, deepcopy):
idx_copy = func(index)
assert idx_copy is not index
assert idx_copy.equals(index)

# don't tests a MultiIndex here (as its tested separated)
if isinstance(ind, MultiIndex):
continue
new_copy = index.copy(deep=True, name="banana")
assert new_copy.name == "banana"

for func in (copy, deepcopy):
idx_copy = func(ind)
assert idx_copy is not ind
assert idx_copy.equals(ind)
def test_duplicates(self, index):
if not len(index):
return
if isinstance(index, MultiIndex):
return
idx = self._holder([index[0]] * 5)
assert not idx.is_unique
assert idx.has_duplicates

new_copy = ind.copy(deep=True, name="banana")
assert new_copy.name == "banana"
def test_get_unique_index(self, index):
# MultiIndex tested separately
if not len(index) or isinstance(index, MultiIndex):
return

def test_duplicates(self):
for ind in self.indices.values():
idx = index[[0] * 5]
idx_unique = index[[0]]

if not len(ind):
continue
if isinstance(ind, MultiIndex):
continue
idx = self._holder([ind[0]] * 5)
assert not idx.is_unique
assert idx.has_duplicates

# GH 10115
# preserve names
idx.name = 'foo'
result = idx.drop_duplicates()
assert result.name == 'foo'
tm.assert_index_equal(result, Index([ind[0]], name='foo'))

def test_get_unique_index(self):
for ind in self.indices.values():

# MultiIndex tested separately
if not len(ind) or isinstance(ind, MultiIndex):
continue
# We test against `idx_unique`, so first we make sure it's unique
# and doesn't contain nans.
assert idx_unique.is_unique
try:
assert not idx_unique.hasnans
except NotImplementedError:
pass

idx = ind[[0] * 5]
idx_unique = ind[[0]]
for dropna in [False, True]:
result = idx._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, idx_unique)

# We test against `idx_unique`, so first we make sure it's unique
# and doesn't contain nans.
assert idx_unique.is_unique
try:
assert not idx_unique.hasnans
except NotImplementedError:
pass
# nans:
if not index._can_hold_na:
return

for dropna in [False, True]:
result = idx._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, idx_unique)
if needs_i8_conversion(index):
vals = index.asi8[[0] * 5]
vals[0] = iNaT
else:
vals = index.values[[0] * 5]
vals[0] = np.nan

# nans:
if not ind._can_hold_na:
continue
vals_unique = vals[:2]
idx_nan = index._shallow_copy(vals)
idx_unique_nan = index._shallow_copy(vals_unique)
assert idx_unique_nan.is_unique

if needs_i8_conversion(ind):
vals = ind.asi8[[0] * 5]
vals[0] = iNaT
else:
vals = ind.values[[0] * 5]
vals[0] = np.nan

vals_unique = vals[:2]
idx_nan = ind._shallow_copy(vals)
idx_unique_nan = ind._shallow_copy(vals_unique)
assert idx_unique_nan.is_unique

assert idx_nan.dtype == ind.dtype
assert idx_unique_nan.dtype == ind.dtype

for dropna, expected in zip([False, True],
[idx_unique_nan, idx_unique]):
for i in [idx_nan, idx_unique_nan]:
result = i._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, expected)

def test_sort(self):
for ind in self.indices.values():
pytest.raises(TypeError, ind.sort)

def test_mutability(self):
for ind in self.indices.values():
if not len(ind):
continue
pytest.raises(TypeError, ind.__setitem__, 0, ind[0])
assert idx_nan.dtype == index.dtype
assert idx_unique_nan.dtype == index.dtype

def test_view(self):
for ind in self.indices.values():
i_view = ind.view()
assert i_view.name == ind.name
for dropna, expected in zip([False, True],
[idx_unique_nan,
idx_unique]):
for i in [idx_nan, idx_unique_nan]:
result = i._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, expected)

def test_compat(self):
for ind in self.indices.values():
assert ind.tolist() == list(ind)
def test_sort(self, index):
pytest.raises(TypeError, index.sort)

def test_mutability(self, index):
if not len(index):
return
pytest.raises(TypeError, index.__setitem__, 0, index[0])

def test_view(self, index):
assert index.view().name == index.name

def test_compat(self, index):
assert index.tolist() == list(index)

def test_memory_usage(self):
for name, index in compat.iteritems(self.indices):
Expand Down Expand Up @@ -457,11 +431,11 @@ def test_numpy_argsort(self):
tm.assert_raises_regex(ValueError, msg, np.argsort,
ind, order=('a', 'b'))

def test_pickle(self):
for ind in self.indices.values():
self.verify_pickle(ind)
ind.name = 'foo'
self.verify_pickle(ind)
def test_pickle(self, index):
self.verify_pickle(index)
original_name, index.name = index.name, 'foo'
self.verify_pickle(index)
index.name = original_name

def test_take(self):
indexer = [4, 3, 0, 2]
Expand Down Expand Up @@ -962,46 +936,47 @@ def test_join_self_unique(self, how):
joined = index.join(index, how=how)
assert (index == joined).all()

def test_searchsorted_monotonic(self):
def test_searchsorted_monotonic(self, index):
# GH17271
for index in self.indices.values():
# not implemented for tuple searches in MultiIndex
# or Intervals searches in IntervalIndex
if isinstance(index, (MultiIndex, IntervalIndex)):
continue
# not implemented for tuple searches in MultiIndex
# or Intervals searches in IntervalIndex
if isinstance(index, (MultiIndex, IntervalIndex)):
return

# nothing to test if the index is empty
if index.empty:
continue
value = index[0]

# determine the expected results (handle dupes for 'right')
expected_left, expected_right = 0, (index == value).argmin()
if expected_right == 0:
# all values are the same, expected_right should be length
expected_right = len(index)

# test _searchsorted_monotonic in all cases
# test searchsorted only for increasing
if index.is_monotonic_increasing:
ssm_left = index._searchsorted_monotonic(value, side='left')
assert expected_left == ssm_left

ssm_right = index._searchsorted_monotonic(value, side='right')
assert expected_right == ssm_right

ss_left = index.searchsorted(value, side='left')
assert expected_left == ss_left

ss_right = index.searchsorted(value, side='right')
assert expected_right == ss_right
elif index.is_monotonic_decreasing:
ssm_left = index._searchsorted_monotonic(value, side='left')
assert expected_left == ssm_left

ssm_right = index._searchsorted_monotonic(value, side='right')
assert expected_right == ssm_right
else:
# non-monotonic should raise.
with pytest.raises(ValueError):
index._searchsorted_monotonic(value, side='left')
# nothing to test if the index is empty
if index.empty:
return
value = index[0]

# determine the expected results (handle dupes for 'right')
expected_left, expected_right = 0, (index == value).argmin()
if expected_right == 0:
# all values are the same, expected_right should be length
expected_right = len(index)

# test _searchsorted_monotonic in all cases
# test searchsorted only for increasing
if index.is_monotonic_increasing:
ssm_left = index._searchsorted_monotonic(value, side='left')
assert expected_left == ssm_left

ssm_right = index._searchsorted_monotonic(value, side='right')
assert expected_right == ssm_right

ss_left = index.searchsorted(value, side='left')
assert expected_left == ss_left

ss_right = index.searchsorted(value, side='right')
assert expected_right == ss_right

elif index.is_monotonic_decreasing:
ssm_left = index._searchsorted_monotonic(value, side='left')
assert expected_left == ssm_left

ssm_right = index._searchsorted_monotonic(value, side='right')
assert expected_right == ssm_right

else:
# non-monotonic should raise.
with pytest.raises(ValueError):
index._searchsorted_monotonic(value, side='left')
Loading