Skip to content

Commit baaace3

Browse files
committed
split test_multi.py into separate files and address the comments from pull request
1 parent 7a3753f commit baaace3

18 files changed

+771
-760
lines changed

pandas/tests/indexes/multi/conftest.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
@pytest.fixture
99
def idx():
10+
# a MultiIndex used to test the general functionality of the
11+
# general functionality of this object
1012
major_axis = Index(['foo', 'bar', 'baz', 'qux'])
1113
minor_axis = Index(['one', 'two'])
1214

@@ -24,14 +26,18 @@ def idx():
2426

2527
@pytest.fixture
2628
def index_names():
29+
# names that match those in the idx fixture for testing equality of
30+
# names assigned to the idx
2731
return ['first', 'second']
2832

2933

3034
@pytest.fixture
31-
def _holder():
35+
def holder():
36+
# the MultiIndex constructor used to base compatibility with pickle
3237
return MultiIndex
3338

3439

3540
@pytest.fixture
36-
def _compat_props():
41+
def compat_props():
42+
# a MultiIndex must have these properties associated with it
3743
return ['shape', 'ndim', 'size']
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import pytest
2+
3+
4+
def test_shift(idx):
5+
6+
# GH8083 test the base class for shift
7+
pytest.raises(NotImplementedError, idx.shift, 1)
8+
pytest.raises(NotImplementedError, idx.shift, 1, 2)

pandas/tests/indexes/multi/test_compat.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,8 @@ def test_logical_compat(idx):
3434

3535
def test_boolean_context_compat(idx):
3636

37-
# boolean context compat
38-
def f():
39-
if idx:
40-
pass
41-
42-
tm.assert_raises_regex(ValueError, 'The truth value of a', f)
37+
with pytest.raises(ValueError):
38+
bool(idx)
4339

4440

4541
def test_boolean_context_compat2():
@@ -50,11 +46,8 @@ def test_boolean_context_compat2():
5046
i2 = MultiIndex.from_tuples([('A', 1), ('A', 3)])
5147
common = i1.intersection(i2)
5248

53-
def f():
54-
if common:
55-
pass
56-
57-
tm.assert_raises_regex(ValueError, 'The truth value of a', f)
49+
with pytest.raises(ValueError):
50+
bool(common)
5851

5952

6053
def test_inplace_mutation_resets_values():
@@ -103,12 +96,12 @@ def test_inplace_mutation_resets_values():
10396
tm.assert_almost_equal(mi2.values, new_values)
10497

10598

106-
def test_ndarray_compat_properties(idx, _compat_props):
99+
def test_ndarray_compat_properties(idx, compat_props):
107100
assert idx.T.equals(idx)
108101
assert idx.transpose().equals(idx)
109102

110103
values = idx.values
111-
for prop in _compat_props:
104+
for prop in compat_props:
112105
assert getattr(idx, prop) == getattr(values, prop)
113106

114107
# test for validity
@@ -120,10 +113,10 @@ def test_compat(indices):
120113
assert indices.tolist() == list(indices)
121114

122115

123-
def test_pickle_compat_construction(_holder):
116+
def test_pickle_compat_construction(holder):
124117
# this is testing for pickle compat
125-
if _holder is None:
118+
if holder is None:
126119
return
127120

128121
# need an object to create with
129-
pytest.raises(TypeError, _holder)
122+
pytest.raises(TypeError, holder)

pandas/tests/indexes/multi/test_constructor.py

Lines changed: 1 addition & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import pandas as pd
77
import pandas.util.testing as tm
88
import pytest
9-
from pandas import DataFrame, Index, MultiIndex, date_range
9+
from pandas import Index, MultiIndex, date_range
1010
from pandas._libs.tslib import Timestamp
1111
from pandas.compat import lrange, range
1212
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
@@ -91,82 +91,6 @@ def test_copy_in_constructor():
9191
assert mi.levels[0][0] == val
9292

9393

94-
def test_reconstruct_sort():
95-
96-
# starts off lexsorted & monotonic
97-
mi = MultiIndex.from_arrays([
98-
['A', 'A', 'B', 'B', 'B'], [1, 2, 1, 2, 3]
99-
])
100-
assert mi.is_lexsorted()
101-
assert mi.is_monotonic
102-
103-
recons = mi._sort_levels_monotonic()
104-
assert recons.is_lexsorted()
105-
assert recons.is_monotonic
106-
assert mi is recons
107-
108-
assert mi.equals(recons)
109-
assert Index(mi.values).equals(Index(recons.values))
110-
111-
# cannot convert to lexsorted
112-
mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
113-
('x', 'b'), ('y', 'a'), ('z', 'b')],
114-
names=['one', 'two'])
115-
assert not mi.is_lexsorted()
116-
assert not mi.is_monotonic
117-
118-
recons = mi._sort_levels_monotonic()
119-
assert not recons.is_lexsorted()
120-
assert not recons.is_monotonic
121-
122-
assert mi.equals(recons)
123-
assert Index(mi.values).equals(Index(recons.values))
124-
125-
# cannot convert to lexsorted
126-
mi = MultiIndex(levels=[['b', 'd', 'a'], [1, 2, 3]],
127-
labels=[[0, 1, 0, 2], [2, 0, 0, 1]],
128-
names=['col1', 'col2'])
129-
assert not mi.is_lexsorted()
130-
assert not mi.is_monotonic
131-
132-
recons = mi._sort_levels_monotonic()
133-
assert not recons.is_lexsorted()
134-
assert not recons.is_monotonic
135-
136-
assert mi.equals(recons)
137-
assert Index(mi.values).equals(Index(recons.values))
138-
139-
140-
def test_reconstruct_remove_unused():
141-
# xref to GH 2770
142-
df = DataFrame([['deleteMe', 1, 9],
143-
['keepMe', 2, 9],
144-
['keepMeToo', 3, 9]],
145-
columns=['first', 'second', 'third'])
146-
df2 = df.set_index(['first', 'second'], drop=False)
147-
df2 = df2[df2['first'] != 'deleteMe']
148-
149-
# removed levels are there
150-
expected = MultiIndex(levels=[['deleteMe', 'keepMe', 'keepMeToo'],
151-
[1, 2, 3]],
152-
labels=[[1, 2], [1, 2]],
153-
names=['first', 'second'])
154-
result = df2.index
155-
tm.assert_index_equal(result, expected)
156-
157-
expected = MultiIndex(levels=[['keepMe', 'keepMeToo'],
158-
[2, 3]],
159-
labels=[[0, 1], [0, 1]],
160-
names=['first', 'second'])
161-
result = df2.index.remove_unused_levels()
162-
tm.assert_index_equal(result, expected)
163-
164-
# idempotent
165-
result2 = result.remove_unused_levels()
166-
tm.assert_index_equal(result2, expected)
167-
assert result2.is_(result)
168-
169-
17094
def test_from_arrays(idx):
17195
arrays = []
17296
for lev, lab in zip(idx.levels, idx.labels):

pandas/tests/indexes/multi/test_contains.py

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -91,39 +91,3 @@ def test_isin_level_kwarg():
9191
tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level='B'))
9292

9393
pytest.raises(KeyError, idx.isin, vals_1, level='C')
94-
95-
96-
def test_hasnans_isnans(idx):
97-
# GH 11343, added tests for hasnans / isnans
98-
# TODO: remove or change test not valid for MultiIndex
99-
if isinstance(idx, MultiIndex):
100-
pass
101-
# else:
102-
# _index = idx.copy()
103-
104-
# # cases in indices doesn't include NaN
105-
# expected = np.array([False] * len(_index), dtype=bool)
106-
# tm.assert_numpy_array_equal(_index._isnan, expected)
107-
# assert not _index.hasnans
108-
109-
# _index = idx.copy()
110-
# values = _index.values
111-
112-
# if len(idx) == 0:
113-
# continue
114-
# elif isinstance(idx, DatetimeIndexOpsMixin):
115-
# values[1] = iNaT
116-
# elif isinstance(idx, (Int64Index, UInt64Index)):
117-
# continue
118-
# else:
119-
# values[1] = np.nan
120-
121-
# if isinstance(idx, PeriodIndex):
122-
# _index = idx.__class__(values, freq=idx.freq)
123-
# else:
124-
# _index = idx.__class__(values)
125-
126-
# expected = np.array([False] * len(_index), dtype=bool)
127-
# expected[1] = True
128-
# tm.assert_numpy_array_equal(_index._isnan, expected)
129-
# assert _index.hasnans

pandas/tests/indexes/multi/test_conversion.py

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,10 @@ def test_to_hierarchical():
8787
assert result.names == index.names
8888

8989

90-
def test_legacy_pickle():
91-
if PY3:
92-
pytest.skip("testing for legacy pickles not "
93-
"support on py3")
90+
@pytest.mark.skipif(PY3, reason="testing legacy pickles not support on py3")
91+
def test_legacy_pickle(datapath):
9492

95-
path = tm.get_data_path('multiindex_v1.pickle')
93+
path = datapath('indexes', 'multi', 'data', 'multiindex_v1.pickle')
9694
obj = pd.read_pickle(path)
9795

9896
obj2 = MultiIndex.from_tuples(obj.values)
@@ -109,10 +107,10 @@ def test_legacy_pickle():
109107
assert_almost_equal(exp, exp2)
110108

111109

112-
def test_legacy_v2_unpickle():
110+
def test_legacy_v2_unpickle(datapath):
113111

114112
# 0.7.3 -> 0.8.0 format manage
115-
path = tm.get_data_path('mindex_073.pickle')
113+
path = datapath('indexes', 'multi', 'data', 'mindex_073.pickle')
116114
obj = pd.read_pickle(path)
117115

118116
obj2 = MultiIndex.from_tuples(obj.values)
@@ -148,3 +146,31 @@ def test_pickle(indices):
148146
unpickled = tm.round_trip_pickle(indices)
149147
assert indices.equals(unpickled)
150148
indices.name = original_name
149+
150+
151+
def test_to_series(idx):
152+
# assert that we are creating a copy of the index
153+
154+
s = idx.to_series()
155+
assert s.values is not idx.values
156+
assert s.index is not idx
157+
assert s.name == idx.name
158+
159+
160+
def test_to_series_with_arguments(idx):
161+
# GH18699
162+
163+
# index kwarg
164+
s = idx.to_series(index=idx)
165+
166+
assert s.values is not idx.values
167+
assert s.index is idx
168+
assert s.name == idx.name
169+
170+
# name kwarg
171+
idx = idx
172+
s = idx.to_series(name='__test')
173+
174+
assert s.values is not idx.values
175+
assert s.index is not idx
176+
assert s.name != idx.name

pandas/tests/indexes/multi/test_copy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: utf-8 -*-
22

3+
from copy import copy, deepcopy
34

45
import pandas.util.testing as tm
56
from pandas import (CategoricalIndex, IntervalIndex, MultiIndex, PeriodIndex,
@@ -111,7 +112,6 @@ def test_ensure_copied_data(idx):
111112

112113

113114
def test_copy_and_deepcopy(indices):
114-
from copy import copy, deepcopy
115115

116116
if isinstance(indices, MultiIndex):
117117
return

pandas/tests/indexes/multi/test_drop.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -124,25 +124,3 @@ def test_drop_not_lexsorted():
124124
with tm.assert_produces_warning(PerformanceWarning):
125125
tm.assert_index_equal(lexsorted_mi.drop('a'),
126126
not_lexsorted_mi.drop('a'))
127-
128-
129-
def test_dropna():
130-
# GH 6194
131-
idx = pd.MultiIndex.from_arrays([[1, np.nan, 3, np.nan, 5],
132-
[1, 2, np.nan, np.nan, 5],
133-
['a', 'b', 'c', np.nan, 'e']])
134-
135-
exp = pd.MultiIndex.from_arrays([[1, 5],
136-
[1, 5],
137-
['a', 'e']])
138-
tm.assert_index_equal(idx.dropna(), exp)
139-
tm.assert_index_equal(idx.dropna(how='any'), exp)
140-
141-
exp = pd.MultiIndex.from_arrays([[1, np.nan, 3, 5],
142-
[1, 2, np.nan, 5],
143-
['a', 'b', 'c', 'e']])
144-
tm.assert_index_equal(idx.dropna(how='all'), exp)
145-
146-
msg = "invalid how option: xxx"
147-
with tm.assert_raises_regex(ValueError, msg):
148-
idx.dropna(how='xxx')

pandas/tests/indexes/multi/test_equivalence.py

Lines changed: 4 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
import numpy as np
55
import pandas as pd
66
import pandas.util.testing as tm
7-
from pandas import (Index, MultiIndex, PeriodIndex, RangeIndex, Series, compat,
8-
isna)
7+
from pandas import Index, MultiIndex, RangeIndex, Series, compat
98
from pandas.compat import lrange, lzip, range
109

1110

@@ -33,8 +32,6 @@ def test_equals(idx):
3332
def test_equals_op(idx):
3433
# GH9947, GH10637
3534
index_a = idx
36-
if isinstance(index_a, PeriodIndex):
37-
return
3835

3936
n = len(index_a)
4037
index_b = index_a[0:-1]
@@ -208,37 +205,10 @@ def test_is_numeric(idx):
208205
assert not idx.is_numeric()
209206

210207

211-
def test_nulls(idx):
212-
# this is really a smoke test for the methods
213-
# as these are adequately tested for function elsewhere
214-
215-
# TODO: Remove or Refactor. MultiIndex not Implemeted.
216-
for name, index in [('idx', idx), ]:
217-
if len(index) == 0:
218-
tm.assert_numpy_array_equal(
219-
index.isna(), np.array([], dtype=bool))
220-
elif isinstance(index, MultiIndex):
221-
idx = index.copy()
222-
msg = "isna is not defined for MultiIndex"
223-
with tm.assert_raises_regex(NotImplementedError, msg):
224-
idx.isna()
225-
else:
226-
227-
if not index.hasnans:
228-
tm.assert_numpy_array_equal(
229-
index.isna(), np.zeros(len(index), dtype=bool))
230-
tm.assert_numpy_array_equal(
231-
index.notna(), np.ones(len(index), dtype=bool))
232-
else:
233-
result = isna(index)
234-
tm.assert_numpy_array_equal(index.isna(), result)
235-
tm.assert_numpy_array_equal(index.notna(), ~result)
236-
237-
238208
def test_multiindex_compare():
239-
# GH 21149
240-
# Ensure comparison operations for MultiIndex with nlevels == 1
241-
# behave consistently with those for MultiIndex with nlevels > 1
209+
# GH 21149
210+
# Ensure comparison operations for MultiIndex with nlevels == 1
211+
# behave consistently with those for MultiIndex with nlevels > 1
242212

243213
midx = pd.MultiIndex.from_product([[0, 1]])
244214

0 commit comments

Comments
 (0)