Skip to content

Commit 306e733

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context syntax (series/indexing/*) (#24750)
1 parent cef5e8a commit 306e733

File tree

6 files changed

+157
-80
lines changed

6 files changed

+157
-80
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-31
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):
@@ -168,14 +175,13 @@ def test_where_unsafe_upcast(dtype):
168175
@pytest.mark.parametrize("dtype", [
169176
np.int8, np.int16, np.int32, np.float32
170177
])
171-
def test_where_unsafe_itemsize_fail(dtype):
172-
# Can't do these, as we are forced to change the
173-
# item size of the input to something we cannot.
178+
def test_where_upcast(dtype):
179+
# see gh-9743
174180
s = Series(np.arange(10), dtype=dtype)
175181
mask = s < 5
176182

177183
values = [2.5, 3.5, 4.5, 5.5, 6.5]
178-
pytest.raises(Exception, s.__setitem__, tuple(mask), values)
184+
s[mask] = values
179185

180186

181187
def test_where_unsafe():
@@ -206,10 +212,11 @@ def test_where_unsafe():
206212
s = Series(np.arange(10))
207213
mask = s > 5
208214

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

212-
with pytest.raises(ValueError):
219+
with pytest.raises(ValueError, match=msg):
213220
s[mask] = [0] * 5
214221

215222
# dtype changes
@@ -276,8 +283,11 @@ def test_where_error():
276283
s = Series(np.random.randn(5))
277284
cond = s > 0
278285

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

282292
# GH 2745
283293
s = Series([1, 2])
@@ -286,10 +296,13 @@ def test_where_error():
286296
assert_series_equal(s, expected)
287297

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

294307

295308
@pytest.mark.parametrize('klass', [list, tuple, np.array, Series])
@@ -349,10 +362,13 @@ def test_where_setitem_invalid():
349362
# GH 2702
350363
# make sure correct exceptions are raised on invalid list assignment
351364

365+
msg = ("cannot set using a {} indexer with a different length than"
366+
" the value")
367+
352368
# slice
353369
s = Series(list('abc'))
354370

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

358374
s[0:3] = list(range(3))
@@ -362,7 +378,7 @@ def test_where_setitem_invalid():
362378
# slice with step
363379
s = Series(list('abcdef'))
364380

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

368384
s = Series(list('abcdef'))
@@ -373,7 +389,7 @@ def test_where_setitem_invalid():
373389
# neg slices
374390
s = Series(list('abcdef'))
375391

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

379395
s[-3:-1] = list(range(2))
@@ -383,12 +399,12 @@ def test_where_setitem_invalid():
383399
# list
384400
s = Series(list('abc'))
385401

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

389405
s = Series(list('abc'))
390406

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

394410
# scalar
@@ -590,8 +606,11 @@ def test_mask():
590606
rs2 = s2.mask(cond[:3], -s2)
591607
assert_series_equal(rs, rs2)
592608

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

596615
# dtype changes
597616
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"^947289600000000000L?$"):
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"^947289600000000000L?$"):
414+
s[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"^947116800000000000L?$"):
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)