Skip to content

Commit cc9fdef

Browse files
STY: use pytest.raises context syntax
1 parent 33f91d8 commit cc9fdef

File tree

6 files changed

+156
-77
lines changed

6 files changed

+156
-77
lines changed

pandas/tests/series/indexing/test_alter_index.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,10 @@ def test_reindex_corner(test_data):
243243

244244
# bad fill method
245245
ts = test_data.ts[::2]
246-
pytest.raises(Exception, ts.reindex, test_data.ts.index, method='foo')
246+
msg = (r"Invalid fill method\. Expecting pad \(ffill\), backfill"
247+
r" \(bfill\) or nearest\. Got foo")
248+
with pytest.raises(ValueError, match=msg):
249+
ts.reindex(test_data.ts.index, method='foo')
247250

248251

249252
def test_reindex_pad():

pandas/tests/series/indexing/test_boolean.py

+50-28
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,12 @@ def test_getitem_boolean_empty():
4949

5050
# invalid because of the boolean indexer
5151
# that's empty or not-aligned
52-
with pytest.raises(IndexingError):
52+
msg = (r"Unalignable boolean Series provided as indexer \(index of"
53+
r" the boolean Series and of the indexed object do not match")
54+
with pytest.raises(IndexingError, match=msg):
5355
s[Series([], dtype=bool)]
5456

55-
with pytest.raises(IndexingError):
57+
with pytest.raises(IndexingError, match=msg):
5658
s[Series([True], dtype=bool)]
5759

5860

@@ -77,8 +79,11 @@ def test_getitem_boolean_object(test_data):
7779

7880
# nans raise exception
7981
omask[5:10] = np.nan
80-
pytest.raises(Exception, s.__getitem__, omask)
81-
pytest.raises(Exception, s.__setitem__, omask, 5)
82+
msg = "cannot index with vector containing NA / NaN values"
83+
with pytest.raises(ValueError, match=msg):
84+
s[omask]
85+
with pytest.raises(ValueError, match=msg):
86+
s[omask] = 5
8287

8388

8489
def test_getitem_setitem_boolean_corner(test_data):
@@ -87,15 +92,17 @@ def test_getitem_setitem_boolean_corner(test_data):
8792

8893
# these used to raise...??
8994

90-
pytest.raises(Exception, ts.__getitem__, mask_shifted)
91-
pytest.raises(Exception, ts.__setitem__, mask_shifted, 1)
92-
# ts[mask_shifted]
93-
# ts[mask_shifted] = 1
95+
msg = (r"Unalignable boolean Series provided as indexer \(index of"
96+
r" the boolean Series and of the indexed object do not match")
97+
with pytest.raises(IndexingError, match=msg):
98+
ts[mask_shifted]
99+
with pytest.raises(IndexingError, match=msg):
100+
ts[mask_shifted] = 1
94101

95-
pytest.raises(Exception, ts.loc.__getitem__, mask_shifted)
96-
pytest.raises(Exception, ts.loc.__setitem__, mask_shifted, 1)
97-
# ts.loc[mask_shifted]
98-
# ts.loc[mask_shifted] = 2
102+
with pytest.raises(IndexingError, match=msg):
103+
ts.loc[mask_shifted]
104+
with pytest.raises(IndexingError, match=msg):
105+
ts.loc[mask_shifted] = 1
99106

100107

101108
def test_setitem_boolean(test_data):
@@ -165,6 +172,7 @@ def test_where_unsafe_upcast(dtype):
165172
assert_series_equal(s, expected)
166173

167174

175+
@pytest.mark.xfail
168176
@pytest.mark.parametrize("dtype", [
169177
np.int8, np.int16, np.int32, np.float32
170178
])
@@ -175,7 +183,8 @@ def test_where_unsafe_itemsize_fail(dtype):
175183
mask = s < 5
176184

177185
values = [2.5, 3.5, 4.5, 5.5, 6.5]
178-
pytest.raises(Exception, s.__setitem__, tuple(mask), values)
186+
with pytest.raises(Exception):
187+
s[mask] = values
179188

180189

181190
def test_where_unsafe():
@@ -206,10 +215,11 @@ def test_where_unsafe():
206215
s = Series(np.arange(10))
207216
mask = s > 5
208217

209-
with pytest.raises(ValueError):
218+
msg = "cannot assign mismatch length to masked array"
219+
with pytest.raises(ValueError, match=msg):
210220
s[mask] = [5, 4, 3, 2, 1]
211221

212-
with pytest.raises(ValueError):
222+
with pytest.raises(ValueError, match=msg):
213223
s[mask] = [0] * 5
214224

215225
# dtype changes
@@ -276,8 +286,11 @@ def test_where_error():
276286
s = Series(np.random.randn(5))
277287
cond = s > 0
278288

279-
pytest.raises(ValueError, s.where, 1)
280-
pytest.raises(ValueError, s.where, cond[:3].values, -s)
289+
msg = "Array conditional must be same shape as self"
290+
with pytest.raises(ValueError, match=msg):
291+
s.where(1)
292+
with pytest.raises(ValueError, match=msg):
293+
s.where(cond[:3].values, -s)
281294

282295
# GH 2745
283296
s = Series([1, 2])
@@ -286,10 +299,13 @@ def test_where_error():
286299
assert_series_equal(s, expected)
287300

288301
# failures
289-
pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]),
290-
[0, 2, 3])
291-
pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]),
292-
[])
302+
msg = "cannot assign mismatch length to masked array"
303+
with pytest.raises(ValueError, match=msg):
304+
s[[True, False]] = [0, 2, 3]
305+
msg = ("NumPy boolean array indexing assignment cannot assign 0 input"
306+
" values to the 1 output values where the mask is true")
307+
with pytest.raises(ValueError, match=msg):
308+
s[[True, False]] = []
293309

294310

295311
@pytest.mark.parametrize('klass', [list, tuple, np.array, Series])
@@ -349,10 +365,13 @@ def test_where_setitem_invalid():
349365
# GH 2702
350366
# make sure correct exceptions are raised on invalid list assignment
351367

368+
msg = ("cannot set using a {} indexer with a different length than"
369+
" the value")
370+
352371
# slice
353372
s = Series(list('abc'))
354373

355-
with pytest.raises(ValueError):
374+
with pytest.raises(ValueError, match=msg.format('slice')):
356375
s[0:3] = list(range(27))
357376

358377
s[0:3] = list(range(3))
@@ -362,7 +381,7 @@ def test_where_setitem_invalid():
362381
# slice with step
363382
s = Series(list('abcdef'))
364383

365-
with pytest.raises(ValueError):
384+
with pytest.raises(ValueError, match=msg.format('slice')):
366385
s[0:4:2] = list(range(27))
367386

368387
s = Series(list('abcdef'))
@@ -373,7 +392,7 @@ def test_where_setitem_invalid():
373392
# neg slices
374393
s = Series(list('abcdef'))
375394

376-
with pytest.raises(ValueError):
395+
with pytest.raises(ValueError, match=msg.format('slice')):
377396
s[:-1] = list(range(27))
378397

379398
s[-3:-1] = list(range(2))
@@ -383,12 +402,12 @@ def test_where_setitem_invalid():
383402
# list
384403
s = Series(list('abc'))
385404

386-
with pytest.raises(ValueError):
405+
with pytest.raises(ValueError, match=msg.format('list-like')):
387406
s[[0, 1, 2]] = list(range(27))
388407

389408
s = Series(list('abc'))
390409

391-
with pytest.raises(ValueError):
410+
with pytest.raises(ValueError, match=msg.format('list-like')):
392411
s[[0, 1, 2]] = list(range(2))
393412

394413
# scalar
@@ -590,8 +609,11 @@ def test_mask():
590609
rs2 = s2.mask(cond[:3], -s2)
591610
assert_series_equal(rs, rs2)
592611

593-
pytest.raises(ValueError, s.mask, 1)
594-
pytest.raises(ValueError, s.mask, cond[:3].values, -s)
612+
msg = "Array conditional must be same shape as self"
613+
with pytest.raises(ValueError, match=msg):
614+
s.mask(1)
615+
with pytest.raises(ValueError, match=msg):
616+
s.mask(cond[:3].values, -s)
595617

596618
# dtype changes
597619
s = Series([1, 2, 3, 4])

pandas/tests/series/indexing/test_datetime.py

+15-8
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ def test_fancy_getitem():
3333
assert s['2009-1-2'] == 48
3434
assert s[datetime(2009, 1, 2)] == 48
3535
assert s[Timestamp(datetime(2009, 1, 2))] == 48
36-
pytest.raises(KeyError, s.__getitem__, '2009-1-3')
37-
36+
with pytest.raises(KeyError, match=r"^'2009-1-3'$"):
37+
s['2009-1-3']
3838
assert_series_equal(s['3/6/2009':'2009-06-05'],
3939
s[datetime(2009, 3, 6):datetime(2009, 6, 5)])
4040

@@ -298,7 +298,8 @@ def test_getitem_setitem_datetimeindex():
298298

299299
lb = datetime(1990, 1, 1, 4)
300300
rb = datetime(1990, 1, 1, 7)
301-
with pytest.raises(TypeError):
301+
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
302+
with pytest.raises(TypeError, match=msg):
302303
# tznaive vs tzaware comparison is invalid
303304
# see GH#18376, GH#18162
304305
ts[(ts.index >= lb) & (ts.index <= rb)]
@@ -400,15 +401,17 @@ def test_datetime_indexing():
400401
s = Series(len(index), index=index)
401402
stamp = Timestamp('1/8/2000')
402403

403-
pytest.raises(KeyError, s.__getitem__, stamp)
404+
with pytest.raises(KeyError, match=r"^947289600000000000$"):
405+
s[stamp]
404406
s[stamp] = 0
405407
assert s[stamp] == 0
406408

407409
# not monotonic
408410
s = Series(len(index), index=index)
409411
s = s[::-1]
410412

411-
pytest.raises(KeyError, s.__getitem__, stamp)
413+
with pytest.raises(KeyError, match=r"^947289600000000000$"):
414+
s.__getitem__(stamp)
412415
s[stamp] = 0
413416
assert s[stamp] == 0
414417

@@ -499,7 +502,8 @@ def test_duplicate_dates_indexing(dups):
499502
expected = Series(np.where(mask, 0, ts), index=ts.index)
500503
assert_series_equal(cp, expected)
501504

502-
pytest.raises(KeyError, ts.__getitem__, datetime(2000, 1, 6))
505+
with pytest.raises(KeyError, match=r"^947116800000000000$"):
506+
ts[datetime(2000, 1, 6)]
503507

504508
# new index
505509
ts[datetime(2000, 1, 6)] = 0
@@ -664,8 +668,11 @@ def test_indexing():
664668
expected = df.loc[[df.index[2]]]
665669

666670
# this is a single date, so will raise
667-
pytest.raises(KeyError, df.__getitem__, '2012-01-02 18:01:02', )
668-
pytest.raises(KeyError, df.__getitem__, df.index[2], )
671+
with pytest.raises(KeyError, match=r"^'2012-01-02 18:01:02'$"):
672+
df['2012-01-02 18:01:02']
673+
msg = r"Timestamp\('2012-01-02 18:01:02-0600', tz='US/Central', freq='S'\)"
674+
with pytest.raises(KeyError, match=msg):
675+
df[df.index[2]]
669676

670677

671678
"""

0 commit comments

Comments
 (0)