Skip to content

Commit 72367b7

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (indexes) (#25447)
1 parent 778affc commit 72367b7

11 files changed

+222
-102
lines changed

pandas/tests/indexes/interval/test_interval.py

+26-12
Original file line numberDiff line numberDiff line change
@@ -403,13 +403,16 @@ def test_get_item(self, closed):
403403

404404
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
405405
def test_get_loc_value(self):
406-
pytest.raises(KeyError, self.index.get_loc, 0)
406+
with pytest.raises(KeyError, match="^0$"):
407+
self.index.get_loc(0)
407408
assert self.index.get_loc(0.5) == 0
408409
assert self.index.get_loc(1) == 0
409410
assert self.index.get_loc(1.5) == 1
410411
assert self.index.get_loc(2) == 1
411-
pytest.raises(KeyError, self.index.get_loc, -1)
412-
pytest.raises(KeyError, self.index.get_loc, 3)
412+
with pytest.raises(KeyError, match="^-1$"):
413+
self.index.get_loc(-1)
414+
with pytest.raises(KeyError, match="^3$"):
415+
self.index.get_loc(3)
413416

414417
idx = IntervalIndex.from_tuples([(0, 2), (1, 3)])
415418
assert idx.get_loc(0.5) == 0
@@ -419,10 +422,12 @@ def test_get_loc_value(self):
419422
tm.assert_numpy_array_equal(np.sort(idx.get_loc(2)),
420423
np.array([0, 1], dtype='intp'))
421424
assert idx.get_loc(3) == 1
422-
pytest.raises(KeyError, idx.get_loc, 3.5)
425+
with pytest.raises(KeyError, match=r"^3\.5$"):
426+
idx.get_loc(3.5)
423427

424428
idx = IntervalIndex.from_arrays([0, 2], [1, 3])
425-
pytest.raises(KeyError, idx.get_loc, 1.5)
429+
with pytest.raises(KeyError, match=r"^1\.5$"):
430+
idx.get_loc(1.5)
426431

427432
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
428433
def slice_locs_cases(self, breaks):
@@ -486,17 +491,22 @@ def test_slice_locs_decreasing_float64(self):
486491
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
487492
def test_slice_locs_fails(self):
488493
index = IntervalIndex.from_tuples([(1, 2), (0, 1), (2, 3)])
489-
with pytest.raises(KeyError):
494+
msg = ("'can only get slices from an IntervalIndex if bounds are"
495+
" non-overlapping and all monotonic increasing or decreasing'")
496+
with pytest.raises(KeyError, match=msg):
490497
index.slice_locs(1, 2)
491498

492499
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
493500
def test_get_loc_interval(self):
494501
assert self.index.get_loc(Interval(0, 1)) == 0
495502
assert self.index.get_loc(Interval(0, 0.5)) == 0
496503
assert self.index.get_loc(Interval(0, 1, 'left')) == 0
497-
pytest.raises(KeyError, self.index.get_loc, Interval(2, 3))
498-
pytest.raises(KeyError, self.index.get_loc,
499-
Interval(-1, 0, 'left'))
504+
msg = r"Interval\(2, 3, closed='right'\)"
505+
with pytest.raises(KeyError, match=msg):
506+
self.index.get_loc(Interval(2, 3))
507+
msg = r"Interval\(-1, 0, closed='left'\)"
508+
with pytest.raises(KeyError, match=msg):
509+
self.index.get_loc(Interval(-1, 0, 'left'))
500510

501511
# Make consistent with test_interval_new.py (see #16316, #16386)
502512
@pytest.mark.parametrize('item', [3, Interval(1, 4)])
@@ -981,9 +991,11 @@ def test_comparison(self):
981991
self.index > 0
982992
with pytest.raises(TypeError, match='unorderable types'):
983993
self.index <= 0
984-
with pytest.raises(TypeError):
994+
msg = r"unorderable types: Interval\(\) > int\(\)"
995+
with pytest.raises(TypeError, match=msg):
985996
self.index > np.arange(2)
986-
with pytest.raises(ValueError):
997+
msg = "Lengths must match to compare"
998+
with pytest.raises(ValueError, match=msg):
987999
self.index > np.arange(3)
9881000

9891001
def test_missing_values(self, closed):
@@ -993,7 +1005,9 @@ def test_missing_values(self, closed):
9931005
[np.nan, 0, 1], [np.nan, 1, 2], closed=closed)
9941006
assert idx.equals(idx2)
9951007

996-
with pytest.raises(ValueError):
1008+
msg = ("missing values must be missing in the same location both left"
1009+
" and right sides")
1010+
with pytest.raises(ValueError, match=msg):
9971011
IntervalIndex.from_arrays(
9981012
[np.nan, 0, 1], np.array([0, 1, 2]), closed=closed)
9991013

pandas/tests/indexes/test_base.py

+29-18
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from datetime import datetime, timedelta
55
import math
66
import operator
7+
import re
78
import sys
89

910
import numpy as np
@@ -107,7 +108,10 @@ def test_constructor_copy(self):
107108

108109
def test_constructor_corner(self):
109110
# corner case
110-
pytest.raises(TypeError, Index, 0)
111+
msg = (r"Index\(\.\.\.\) must be called with a collection of some"
112+
" kind, 0 was passed")
113+
with pytest.raises(TypeError, match=msg):
114+
Index(0)
111115

112116
@pytest.mark.parametrize("index_vals", [
113117
[('A', 1), 'B'], ['B', ('A', 1)]])
@@ -488,21 +492,22 @@ def test_constructor_cast(self):
488492
Index(["a", "b", "c"], dtype=float)
489493

490494
def test_view_with_args(self):
491-
492495
restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex',
493496
'empty']
494-
495-
for i in restricted:
496-
ind = self.indices[i]
497-
498-
# with arguments
499-
pytest.raises(TypeError, lambda: ind.view('i8'))
500-
501-
# these are ok
502497
for i in list(set(self.indices.keys()) - set(restricted)):
503498
ind = self.indices[i]
499+
ind.view('i8')
504500

505-
# with arguments
501+
@pytest.mark.parametrize('index_type', [
502+
'unicodeIndex',
503+
'strIndex',
504+
pytest.param('catIndex', marks=pytest.mark.xfail(reason="gh-25464")),
505+
'boolIndex',
506+
'empty'])
507+
def test_view_with_args_object_array_raises(self, index_type):
508+
ind = self.indices[index_type]
509+
msg = "Cannot change data-type for object array"
510+
with pytest.raises(TypeError, match=msg):
506511
ind.view('i8')
507512

508513
def test_astype(self):
@@ -565,8 +570,8 @@ def test_delete(self, pos, expected):
565570

566571
def test_delete_raises(self):
567572
index = Index(['a', 'b', 'c', 'd'], name='index')
568-
with pytest.raises((IndexError, ValueError)):
569-
# either depending on numpy version
573+
msg = "index 5 is out of bounds for axis 0 with size 4"
574+
with pytest.raises(IndexError, match=msg):
570575
index.delete(5)
571576

572577
def test_identical(self):
@@ -683,7 +688,9 @@ def test_empty_fancy_raises(self, attr):
683688

684689
assert index[[]].identical(empty_index)
685690
# np.ndarray only accepts ndarray of int & bool dtypes, so should Index
686-
pytest.raises(IndexError, index.__getitem__, empty_farr)
691+
msg = r"arrays used as indices must be of integer \(or boolean\) type"
692+
with pytest.raises(IndexError, match=msg):
693+
index[empty_farr]
687694

688695
@pytest.mark.parametrize("sort", [None, False])
689696
def test_intersection(self, sort):
@@ -1426,13 +1433,14 @@ def test_get_indexer_strings(self, method, expected):
14261433
def test_get_indexer_strings_raises(self):
14271434
index = pd.Index(['b', 'c'])
14281435

1429-
with pytest.raises(TypeError):
1436+
msg = r"unsupported operand type\(s\) for -: 'str' and 'str'"
1437+
with pytest.raises(TypeError, match=msg):
14301438
index.get_indexer(['a', 'b', 'c', 'd'], method='nearest')
14311439

1432-
with pytest.raises(TypeError):
1440+
with pytest.raises(TypeError, match=msg):
14331441
index.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=2)
14341442

1435-
with pytest.raises(TypeError):
1443+
with pytest.raises(TypeError, match=msg):
14361444
index.get_indexer(['a', 'b', 'c', 'd'], method='pad',
14371445
tolerance=[2, 2, 2, 2])
14381446

@@ -1685,8 +1693,11 @@ def test_drop_tuple(self, values, to_drop):
16851693
tm.assert_index_equal(result, expected)
16861694

16871695
removed = index.drop(to_drop[1])
1696+
msg = r"\"\[{}\] not found in axis\"".format(
1697+
re.escape(to_drop[1].__repr__()))
16881698
for drop_me in to_drop[1], [to_drop[1]]:
1689-
pytest.raises(KeyError, removed.drop, drop_me)
1699+
with pytest.raises(KeyError, match=msg):
1700+
removed.drop(drop_me)
16901701

16911702
@pytest.mark.parametrize("method,expected,sort", [
16921703
('intersection', np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B')],

pandas/tests/indexes/test_category.py

+46-31
Original file line numberDiff line numberDiff line change
@@ -181,18 +181,21 @@ def test_create_categorical(self):
181181
expected = Categorical(['a', 'b', 'c'])
182182
tm.assert_categorical_equal(result, expected)
183183

184-
def test_disallow_set_ops(self):
185-
184+
@pytest.mark.parametrize('func,op_name', [
185+
(lambda idx: idx - idx, '__sub__'),
186+
(lambda idx: idx + idx, '__add__'),
187+
(lambda idx: idx - ['a', 'b'], '__sub__'),
188+
(lambda idx: idx + ['a', 'b'], '__add__'),
189+
(lambda idx: ['a', 'b'] - idx, '__rsub__'),
190+
(lambda idx: ['a', 'b'] + idx, '__radd__'),
191+
])
192+
def test_disallow_set_ops(self, func, op_name):
186193
# GH 10039
187194
# set ops (+/-) raise TypeError
188195
idx = pd.Index(pd.Categorical(['a', 'b']))
189-
190-
pytest.raises(TypeError, lambda: idx - idx)
191-
pytest.raises(TypeError, lambda: idx + idx)
192-
pytest.raises(TypeError, lambda: idx - ['a', 'b'])
193-
pytest.raises(TypeError, lambda: idx + ['a', 'b'])
194-
pytest.raises(TypeError, lambda: ['a', 'b'] - idx)
195-
pytest.raises(TypeError, lambda: ['a', 'b'] + idx)
196+
msg = "cannot perform {} with this index type: CategoricalIndex"
197+
with pytest.raises(TypeError, match=msg.format(op_name)):
198+
func(idx)
196199

197200
def test_method_delegation(self):
198201

@@ -231,8 +234,9 @@ def test_method_delegation(self):
231234
list('aabbca'), categories=list('cabdef'), ordered=True))
232235

233236
# invalid
234-
pytest.raises(ValueError, lambda: ci.set_categories(
235-
list('cab'), inplace=True))
237+
msg = "cannot use inplace with CategoricalIndex"
238+
with pytest.raises(ValueError, match=msg):
239+
ci.set_categories(list('cab'), inplace=True)
236240

237241
def test_contains(self):
238242

@@ -357,20 +361,21 @@ def test_append(self):
357361
tm.assert_index_equal(result, ci, exact=True)
358362

359363
# appending with different categories or reordered is not ok
360-
pytest.raises(
361-
TypeError,
362-
lambda: ci.append(ci.values.set_categories(list('abcd'))))
363-
pytest.raises(
364-
TypeError,
365-
lambda: ci.append(ci.values.reorder_categories(list('abc'))))
364+
msg = "all inputs must be Index"
365+
with pytest.raises(TypeError, match=msg):
366+
ci.append(ci.values.set_categories(list('abcd')))
367+
with pytest.raises(TypeError, match=msg):
368+
ci.append(ci.values.reorder_categories(list('abc')))
366369

367370
# with objects
368371
result = ci.append(Index(['c', 'a']))
369372
expected = CategoricalIndex(list('aabbcaca'), categories=categories)
370373
tm.assert_index_equal(result, expected, exact=True)
371374

372375
# invalid objects
373-
pytest.raises(TypeError, lambda: ci.append(Index(['a', 'd'])))
376+
msg = "cannot append a non-category item to a CategoricalIndex"
377+
with pytest.raises(TypeError, match=msg):
378+
ci.append(Index(['a', 'd']))
374379

375380
# GH14298 - if base object is not categorical -> coerce to object
376381
result = Index(['c', 'a']).append(ci)
@@ -406,7 +411,10 @@ def test_insert(self):
406411
tm.assert_index_equal(result, expected, exact=True)
407412

408413
# invalid
409-
pytest.raises(TypeError, lambda: ci.insert(0, 'd'))
414+
msg = ("cannot insert an item into a CategoricalIndex that is not"
415+
" already an existing category")
416+
with pytest.raises(TypeError, match=msg):
417+
ci.insert(0, 'd')
410418

411419
# GH 18295 (test missing)
412420
expected = CategoricalIndex(['a', np.nan, 'a', 'b', 'c', 'b'])
@@ -633,12 +641,16 @@ def test_get_indexer(self):
633641
r1 = idx1.get_indexer(idx2)
634642
assert_almost_equal(r1, np.array([0, 1, 2, -1], dtype=np.intp))
635643

636-
pytest.raises(NotImplementedError,
637-
lambda: idx2.get_indexer(idx1, method='pad'))
638-
pytest.raises(NotImplementedError,
639-
lambda: idx2.get_indexer(idx1, method='backfill'))
640-
pytest.raises(NotImplementedError,
641-
lambda: idx2.get_indexer(idx1, method='nearest'))
644+
msg = ("method='pad' and method='backfill' not implemented yet for"
645+
" CategoricalIndex")
646+
with pytest.raises(NotImplementedError, match=msg):
647+
idx2.get_indexer(idx1, method='pad')
648+
with pytest.raises(NotImplementedError, match=msg):
649+
idx2.get_indexer(idx1, method='backfill')
650+
651+
msg = "method='nearest' not implemented yet for CategoricalIndex"
652+
with pytest.raises(NotImplementedError, match=msg):
653+
idx2.get_indexer(idx1, method='nearest')
642654

643655
def test_get_loc(self):
644656
# GH 12531
@@ -776,12 +788,15 @@ def test_equals_categorical(self):
776788
# invalid comparisons
777789
with pytest.raises(ValueError, match="Lengths must match"):
778790
ci1 == Index(['a', 'b', 'c'])
779-
pytest.raises(TypeError, lambda: ci1 == ci2)
780-
pytest.raises(
781-
TypeError, lambda: ci1 == Categorical(ci1.values, ordered=False))
782-
pytest.raises(
783-
TypeError,
784-
lambda: ci1 == Categorical(ci1.values, categories=list('abc')))
791+
792+
msg = ("categorical index comparisons must have the same categories"
793+
" and ordered attributes")
794+
with pytest.raises(TypeError, match=msg):
795+
ci1 == ci2
796+
with pytest.raises(TypeError, match=msg):
797+
ci1 == Categorical(ci1.values, ordered=False)
798+
with pytest.raises(TypeError, match=msg):
799+
ci1 == Categorical(ci1.values, categories=list('abc'))
785800

786801
# tests
787802
# make sure that we are testing for category inclusion properly

pandas/tests/indexes/test_common.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
any index subclass. Makes use of the `indices` fixture defined
44
in pandas/tests/indexes/conftest.py.
55
"""
6+
import re
7+
68
import numpy as np
79
import pytest
810

@@ -189,8 +191,14 @@ def test_unique(self, indices):
189191
result = indices.unique(level=level)
190192
tm.assert_index_equal(result, expected)
191193

192-
for level in 3, 'wrong':
193-
pytest.raises((IndexError, KeyError), indices.unique, level=level)
194+
msg = "Too many levels: Index has only 1 level, not 4"
195+
with pytest.raises(IndexError, match=msg):
196+
indices.unique(level=3)
197+
198+
msg = r"Level wrong must be same as name \({}\)".format(
199+
re.escape(indices.name.__repr__()))
200+
with pytest.raises(KeyError, match=msg):
201+
indices.unique(level='wrong')
194202

195203
def test_get_unique_index(self, indices):
196204
# MultiIndex tested separately
@@ -239,12 +247,16 @@ def test_get_unique_index(self, indices):
239247
tm.assert_index_equal(result, expected)
240248

241249
def test_sort(self, indices):
242-
pytest.raises(TypeError, indices.sort)
250+
msg = "cannot sort an Index object in-place, use sort_values instead"
251+
with pytest.raises(TypeError, match=msg):
252+
indices.sort()
243253

244254
def test_mutability(self, indices):
245255
if not len(indices):
246256
pytest.skip('Skip check for empty Index')
247-
pytest.raises(TypeError, indices.__setitem__, 0, indices[0])
257+
msg = "Index does not support mutable operations"
258+
with pytest.raises(TypeError, match=msg):
259+
indices[0] = indices[0]
248260

249261
def test_view(self, indices):
250262
assert indices.view().name == indices.name

0 commit comments

Comments
 (0)