@@ -30,9 +30,9 @@ def setup_indices(self):
3030 for name , idx in self .indices .items ():
3131 setattr (self , name , idx )
3232
33- def verify_pickle (self , index ):
34- unpickled = tm .round_trip_pickle (index )
35- assert index .equals (unpickled )
33+ def verify_pickle (self , indices ):
34+ unpickled = tm .round_trip_pickle (indices )
35+ assert indices .equals (unpickled )
3636
3737 def test_pickle_compat_construction (self ):
3838 # this is testing for pickle compat
@@ -97,7 +97,7 @@ def test_numeric_compat(self):
9797 lambda : 1 * idx )
9898
9999 div_err = "cannot perform __truediv__" if PY3 \
100- else "cannot perform __div__"
100+ else "cannot perform __div__"
101101 tm .assert_raises_regex (TypeError , div_err , lambda : idx / 1 )
102102 tm .assert_raises_regex (TypeError , div_err , lambda : 1 / idx )
103103 tm .assert_raises_regex (TypeError , "cannot perform __floordiv__" ,
@@ -178,11 +178,10 @@ def test_str(self):
178178 assert "'foo'" in str (idx )
179179 assert idx .__class__ .__name__ in str (idx )
180180
181- def test_dtype_str (self ):
182- for idx in self .indices .values ():
183- dtype = idx .dtype_str
184- assert isinstance (dtype , compat .string_types )
185- assert dtype == str (idx .dtype )
181+ def test_dtype_str (self , indices ):
182+ dtype = indices .dtype_str
183+ assert isinstance (dtype , compat .string_types )
184+ assert dtype == str (indices .dtype )
186185
187186 def test_repr_max_seq_item_setting (self ):
188187 # GH10182
@@ -192,48 +191,43 @@ def test_repr_max_seq_item_setting(self):
192191 repr (idx )
193192 assert '...' not in str (idx )
194193
195- def test_wrong_number_names (self ):
194+ def test_wrong_number_names (self , indices ):
196195 def testit (ind ):
197196 ind .names = ["apple" , "banana" , "carrot" ]
197+ tm .assert_raises_regex (ValueError , "^Length" , testit , indices )
198198
199- for ind in self .indices .values ():
200- tm .assert_raises_regex (ValueError , "^Length" , testit , ind )
201-
202- def test_set_name_methods (self ):
199+ def test_set_name_methods (self , indices ):
203200 new_name = "This is the new name for this index"
204- for ind in self .indices .values ():
205-
206- # don't tests a MultiIndex here (as its tested separated)
207- if isinstance (ind , MultiIndex ):
208- continue
209201
210- original_name = ind .name
211- new_ind = ind .set_names ([new_name ])
212- assert new_ind .name == new_name
213- assert ind .name == original_name
214- res = ind .rename (new_name , inplace = True )
215-
216- # should return None
217- assert res is None
218- assert ind .name == new_name
219- assert ind .names == [new_name ]
220- # with tm.assert_raises_regex(TypeError, "list-like"):
221- # # should still fail even if it would be the right length
222- # ind.set_names("a")
223- with tm .assert_raises_regex (ValueError , "Level must be None" ):
224- ind .set_names ("a" , level = 0 )
225-
226- # rename in place just leaves tuples and other containers alone
227- name = ('A' , 'B' )
228- ind .rename (name , inplace = True )
229- assert ind .name == name
230- assert ind .names == [name ]
231-
232- def test_hash_error (self ):
233- for ind in self .indices .values ():
234- with tm .assert_raises_regex (TypeError , "unhashable type: %r" %
235- type (ind ).__name__ ):
236- hash (ind )
202+ # don't tests a MultiIndex here (as its tested separated)
203+ if isinstance (indices , MultiIndex ):
204+ return
205+ original_name = indices .name
206+ new_ind = indices .set_names ([new_name ])
207+ assert new_ind .name == new_name
208+ assert indices .name == original_name
209+ res = indices .rename (new_name , inplace = True )
210+
211+ # should return None
212+ assert res is None
213+ assert indices .name == new_name
214+ assert indices .names == [new_name ]
215+ # with tm.assert_raises_regex(TypeError, "list-like"):
216+ # # should still fail even if it would be the right length
217+ # ind.set_names("a")
218+ with tm .assert_raises_regex (ValueError , "Level must be None" ):
219+ indices .set_names ("a" , level = 0 )
220+
221+ # rename in place just leaves tuples and other containers alone
222+ name = ('A' , 'B' )
223+ indices .rename (name , inplace = True )
224+ assert indices .name == name
225+ assert indices .names == [name ]
226+
227+ def test_hash_error (self , indices ):
228+ index = indices
229+ tm .assert_raises_regex (TypeError , "unhashable type: %r" %
230+ type (index ).__name__ , hash , indices )
237231
238232 def test_copy_name (self ):
239233 # gh-12309: Check that the "name" argument
@@ -298,106 +292,87 @@ def test_ensure_copied_data(self):
298292 tm .assert_numpy_array_equal (index ._values , result ._values ,
299293 check_same = 'same' )
300294
301- def test_copy_and_deepcopy (self ):
295+ def test_copy_and_deepcopy (self , indices ):
302296 from copy import copy , deepcopy
303297
304- for ind in self .indices .values ():
298+ if isinstance (indices , MultiIndex ):
299+ return
300+ for func in (copy , deepcopy ):
301+ idx_copy = func (indices )
302+ assert idx_copy is not indices
303+ assert idx_copy .equals (indices )
305304
306- # don't tests a MultiIndex here (as its tested separated)
307- if isinstance (ind , MultiIndex ):
308- continue
305+ new_copy = indices .copy (deep = True , name = "banana" )
306+ assert new_copy .name == "banana"
309307
310- for func in (copy , deepcopy ):
311- idx_copy = func (ind )
312- assert idx_copy is not ind
313- assert idx_copy .equals (ind )
308+ def test_duplicates (self , indices ):
309+ if type (indices ) is not self ._holder :
310+ return
311+ if not len (indices ) or isinstance (indices , MultiIndex ):
312+ return
313+ idx = self ._holder ([indices [0 ]] * 5 )
314+ assert not idx .is_unique
315+ assert idx .has_duplicates
314316
315- new_copy = ind .copy (deep = True , name = "banana" )
316- assert new_copy .name == "banana"
317+ def test_get_unique_index (self , indices ):
318+ # MultiIndex tested separately
319+ if not len (indices ) or isinstance (indices , MultiIndex ):
320+ return
317321
318- def test_duplicates ( self ):
319- for ind in self . indices . values ():
322+ idx = indices [[ 0 ] * 5 ]
323+ idx_unique = indices [[ 0 ]]
320324
321- if not len (ind ):
322- continue
323- if isinstance (ind , MultiIndex ):
324- continue
325- idx = self ._holder ([ind [0 ]] * 5 )
326- assert not idx .is_unique
327- assert idx .has_duplicates
328-
329- # GH 10115
330- # preserve names
331- idx .name = 'foo'
332- result = idx .drop_duplicates ()
333- assert result .name == 'foo'
334- tm .assert_index_equal (result , Index ([ind [0 ]], name = 'foo' ))
335-
336- def test_get_unique_index (self ):
337- for ind in self .indices .values ():
338-
339- # MultiIndex tested separately
340- if not len (ind ) or isinstance (ind , MultiIndex ):
341- continue
325+ # We test against `idx_unique`, so first we make sure it's unique
326+ # and doesn't contain nans.
327+ assert idx_unique .is_unique
328+ try :
329+ assert not idx_unique .hasnans
330+ except NotImplementedError :
331+ pass
342332
343- idx = ind [[0 ] * 5 ]
344- idx_unique = ind [[0 ]]
333+ for dropna in [False , True ]:
334+ result = idx ._get_unique_index (dropna = dropna )
335+ tm .assert_index_equal (result , idx_unique )
345336
346- # We test against `idx_unique`, so first we make sure it's unique
347- # and doesn't contain nans.
348- assert idx_unique .is_unique
349- try :
350- assert not idx_unique .hasnans
351- except NotImplementedError :
352- pass
337+ # nans:
338+ if not indices ._can_hold_na :
339+ return
353340
354- for dropna in [False , True ]:
355- result = idx ._get_unique_index (dropna = dropna )
356- tm .assert_index_equal (result , idx_unique )
341+ if needs_i8_conversion (indices ):
342+ vals = indices .asi8 [[0 ] * 5 ]
343+ vals [0 ] = iNaT
344+ else :
345+ vals = indices .values [[0 ] * 5 ]
346+ vals [0 ] = np .nan
357347
358- # nans:
359- if not ind ._can_hold_na :
360- continue
348+ vals_unique = vals [:2 ]
349+ idx_nan = indices ._shallow_copy (vals )
350+ idx_unique_nan = indices ._shallow_copy (vals_unique )
351+ assert idx_unique_nan .is_unique
361352
362- if needs_i8_conversion (ind ):
363- vals = ind .asi8 [[0 ] * 5 ]
364- vals [0 ] = iNaT
365- else :
366- vals = ind .values [[0 ] * 5 ]
367- vals [0 ] = np .nan
368-
369- vals_unique = vals [:2 ]
370- idx_nan = ind ._shallow_copy (vals )
371- idx_unique_nan = ind ._shallow_copy (vals_unique )
372- assert idx_unique_nan .is_unique
373-
374- assert idx_nan .dtype == ind .dtype
375- assert idx_unique_nan .dtype == ind .dtype
376-
377- for dropna , expected in zip ([False , True ],
378- [idx_unique_nan , idx_unique ]):
379- for i in [idx_nan , idx_unique_nan ]:
380- result = i ._get_unique_index (dropna = dropna )
381- tm .assert_index_equal (result , expected )
382-
383- def test_sort (self ):
384- for ind in self .indices .values ():
385- pytest .raises (TypeError , ind .sort )
386-
387- def test_mutability (self ):
388- for ind in self .indices .values ():
389- if not len (ind ):
390- continue
391- pytest .raises (TypeError , ind .__setitem__ , 0 , ind [0 ])
353+ assert idx_nan .dtype == indices .dtype
354+ assert idx_unique_nan .dtype == indices .dtype
392355
393- def test_view (self ):
394- for ind in self .indices .values ():
395- i_view = ind .view ()
396- assert i_view .name == ind .name
356+ for dropna , expected in zip ([False , True ],
357+ [idx_unique_nan ,
358+ idx_unique ]):
359+ for i in [idx_nan , idx_unique_nan ]:
360+ result = i ._get_unique_index (dropna = dropna )
361+ tm .assert_index_equal (result , expected )
397362
398- def test_compat (self ):
399- for ind in self .indices .values ():
400- assert ind .tolist () == list (ind )
363+ def test_sort (self , indices ):
364+ pytest .raises (TypeError , indices .sort )
365+
366+ def test_mutability (self , indices ):
367+ if not len (indices ):
368+ return
369+ pytest .raises (TypeError , indices .__setitem__ , 0 , indices [0 ])
370+
371+ def test_view (self , indices ):
372+ assert indices .view ().name == indices .name
373+
374+ def test_compat (self , indices ):
375+ assert indices .tolist () == list (indices )
401376
402377 def test_memory_usage (self ):
403378 for name , index in compat .iteritems (self .indices ):
@@ -457,11 +432,11 @@ def test_numpy_argsort(self):
457432 tm .assert_raises_regex (ValueError , msg , np .argsort ,
458433 ind , order = ('a' , 'b' ))
459434
460- def test_pickle (self ):
461- for ind in self .indices . values ():
462- self . verify_pickle ( ind )
463- ind . name = 'foo'
464- self . verify_pickle ( ind )
435+ def test_pickle (self , indices ):
436+ self .verify_pickle ( indices )
437+ original_name , indices . name = indices . name , 'foo'
438+ self . verify_pickle ( indices )
439+ indices . name = original_name
465440
466441 def test_take (self ):
467442 indexer = [4 , 3 , 0 , 2 ]
@@ -962,46 +937,47 @@ def test_join_self_unique(self, how):
962937 joined = index .join (index , how = how )
963938 assert (index == joined ).all ()
964939
965- def test_searchsorted_monotonic (self ):
940+ def test_searchsorted_monotonic (self , indices ):
966941 # GH17271
967- for index in self .indices .values ():
968- # not implemented for tuple searches in MultiIndex
969- # or Intervals searches in IntervalIndex
970- if isinstance (index , (MultiIndex , IntervalIndex )):
971- continue
942+ # not implemented for tuple searches in MultiIndex
943+ # or Intervals searches in IntervalIndex
944+ if isinstance (indices , (MultiIndex , IntervalIndex )):
945+ return
972946
973- # nothing to test if the index is empty
974- if index .empty :
975- continue
976- value = index [0 ]
977-
978- # determine the expected results (handle dupes for 'right')
979- expected_left , expected_right = 0 , (index == value ).argmin ()
980- if expected_right == 0 :
981- # all values are the same, expected_right should be length
982- expected_right = len (index )
983-
984- # test _searchsorted_monotonic in all cases
985- # test searchsorted only for increasing
986- if index .is_monotonic_increasing :
987- ssm_left = index ._searchsorted_monotonic (value , side = 'left' )
988- assert expected_left == ssm_left
989-
990- ssm_right = index ._searchsorted_monotonic (value , side = 'right' )
991- assert expected_right == ssm_right
992-
993- ss_left = index .searchsorted (value , side = 'left' )
994- assert expected_left == ss_left
995-
996- ss_right = index .searchsorted (value , side = 'right' )
997- assert expected_right == ss_right
998- elif index .is_monotonic_decreasing :
999- ssm_left = index ._searchsorted_monotonic (value , side = 'left' )
1000- assert expected_left == ssm_left
1001-
1002- ssm_right = index ._searchsorted_monotonic (value , side = 'right' )
1003- assert expected_right == ssm_right
1004- else :
1005- # non-monotonic should raise.
1006- with pytest .raises (ValueError ):
1007- index ._searchsorted_monotonic (value , side = 'left' )
947+ # nothing to test if the index is empty
948+ if indices .empty :
949+ return
950+ value = indices [0 ]
951+
952+ # determine the expected results (handle dupes for 'right')
953+ expected_left , expected_right = 0 , (indices == value ).argmin ()
954+ if expected_right == 0 :
955+ # all values are the same, expected_right should be length
956+ expected_right = len (indices )
957+
958+ # test _searchsorted_monotonic in all cases
959+ # test searchsorted only for increasing
960+ if indices .is_monotonic_increasing :
961+ ssm_left = indices ._searchsorted_monotonic (value , side = 'left' )
962+ assert expected_left == ssm_left
963+
964+ ssm_right = indices ._searchsorted_monotonic (value , side = 'right' )
965+ assert expected_right == ssm_right
966+
967+ ss_left = indices .searchsorted (value , side = 'left' )
968+ assert expected_left == ss_left
969+
970+ ss_right = indices .searchsorted (value , side = 'right' )
971+ assert expected_right == ss_right
972+
973+ elif indices .is_monotonic_decreasing :
974+ ssm_left = indices ._searchsorted_monotonic (value , side = 'left' )
975+ assert expected_left == ssm_left
976+
977+ ssm_right = indices ._searchsorted_monotonic (value , side = 'right' )
978+ assert expected_right == ssm_right
979+
980+ else :
981+ # non-monotonic should raise.
982+ with pytest .raises (ValueError ):
983+ indices ._searchsorted_monotonic (value , side = 'left' )
0 commit comments