Skip to content

Commit 9567ab5

Browse files
simonjayhawkinsPingviinituutti
authored andcommitted
STY: use pytest.raises context manager (indexes/period) (pandas-dev#25199)
1 parent 671f3fe commit 9567ab5

File tree

4 files changed

+109
-56
lines changed

4 files changed

+109
-56
lines changed

pandas/tests/indexes/period/test_asfreq.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,9 @@ def test_asfreq(self):
6767
assert pi7.asfreq('H', 'S') == pi5
6868
assert pi7.asfreq('Min', 'S') == pi6
6969

70-
pytest.raises(ValueError, pi7.asfreq, 'T', 'foo')
70+
msg = "How must be one of S or E"
71+
with pytest.raises(ValueError, match=msg):
72+
pi7.asfreq('T', 'foo')
7173
result1 = pi1.asfreq('3M')
7274
result2 = pi1.asfreq('M')
7375
expected = period_range(freq='M', start='2001-12', end='2001-12')

pandas/tests/indexes/period/test_construction.py

+60-28
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import numpy as np
22
import pytest
33

4+
from pandas._libs.tslibs.period import IncompatibleFrequency
45
from pandas.compat import PY3, lmap, lrange, text_type
56

67
from pandas.core.dtypes.dtypes import PeriodDtype
@@ -66,12 +67,17 @@ def test_constructor_field_arrays(self):
6667

6768
years = [2007, 2007, 2007]
6869
months = [1, 2]
69-
pytest.raises(ValueError, PeriodIndex, year=years, month=months,
70-
freq='M')
71-
pytest.raises(ValueError, PeriodIndex, year=years, month=months,
72-
freq='2M')
73-
pytest.raises(ValueError, PeriodIndex, year=years, month=months,
74-
freq='M', start=Period('2007-01', freq='M'))
70+
71+
msg = "Mismatched Period array lengths"
72+
with pytest.raises(ValueError, match=msg):
73+
PeriodIndex(year=years, month=months, freq='M')
74+
with pytest.raises(ValueError, match=msg):
75+
PeriodIndex(year=years, month=months, freq='2M')
76+
77+
msg = "Can either instantiate from fields or endpoints, but not both"
78+
with pytest.raises(ValueError, match=msg):
79+
PeriodIndex(year=years, month=months, freq='M',
80+
start=Period('2007-01', freq='M'))
7581

7682
years = [2007, 2007, 2007]
7783
months = [1, 2, 3]
@@ -81,8 +87,8 @@ def test_constructor_field_arrays(self):
8187

8288
def test_constructor_U(self):
8389
# U was used as undefined period
84-
pytest.raises(ValueError, period_range, '2007-1-1', periods=500,
85-
freq='X')
90+
with pytest.raises(ValueError, match="Invalid frequency: X"):
91+
period_range('2007-1-1', periods=500, freq='X')
8692

8793
def test_constructor_nano(self):
8894
idx = period_range(start=Period(ordinal=1, freq='N'),
@@ -103,17 +109,29 @@ def test_constructor_arrays_negative_year(self):
103109
tm.assert_index_equal(pindex.quarter, pd.Index(quarters))
104110

105111
def test_constructor_invalid_quarters(self):
106-
pytest.raises(ValueError, PeriodIndex, year=lrange(2000, 2004),
107-
quarter=lrange(4), freq='Q-DEC')
112+
msg = "Quarter must be 1 <= q <= 4"
113+
with pytest.raises(ValueError, match=msg):
114+
PeriodIndex(year=lrange(2000, 2004), quarter=lrange(4),
115+
freq='Q-DEC')
108116

109117
def test_constructor_corner(self):
110-
pytest.raises(ValueError, PeriodIndex, periods=10, freq='A')
118+
msg = "Not enough parameters to construct Period range"
119+
with pytest.raises(ValueError, match=msg):
120+
PeriodIndex(periods=10, freq='A')
111121

112122
start = Period('2007', freq='A-JUN')
113123
end = Period('2010', freq='A-DEC')
114-
pytest.raises(ValueError, PeriodIndex, start=start, end=end)
115-
pytest.raises(ValueError, PeriodIndex, start=start)
116-
pytest.raises(ValueError, PeriodIndex, end=end)
124+
125+
msg = "start and end must have same freq"
126+
with pytest.raises(ValueError, match=msg):
127+
PeriodIndex(start=start, end=end)
128+
129+
msg = ("Of the three parameters: start, end, and periods, exactly two"
130+
" must be specified")
131+
with pytest.raises(ValueError, match=msg):
132+
PeriodIndex(start=start)
133+
with pytest.raises(ValueError, match=msg):
134+
PeriodIndex(end=end)
117135

118136
result = period_range('2007-01', periods=10.5, freq='M')
119137
exp = period_range('2007-01', periods=10, freq='M')
@@ -126,10 +144,15 @@ def test_constructor_fromarraylike(self):
126144
tm.assert_index_equal(PeriodIndex(idx.values), idx)
127145
tm.assert_index_equal(PeriodIndex(list(idx.values)), idx)
128146

129-
pytest.raises(ValueError, PeriodIndex, idx._ndarray_values)
130-
pytest.raises(ValueError, PeriodIndex, list(idx._ndarray_values))
131-
pytest.raises(TypeError, PeriodIndex,
132-
data=Period('2007', freq='A'))
147+
msg = "freq not specified and cannot be inferred"
148+
with pytest.raises(ValueError, match=msg):
149+
PeriodIndex(idx._ndarray_values)
150+
with pytest.raises(ValueError, match=msg):
151+
PeriodIndex(list(idx._ndarray_values))
152+
153+
msg = "'Period' object is not iterable"
154+
with pytest.raises(TypeError, match=msg):
155+
PeriodIndex(data=Period('2007', freq='A'))
133156

134157
result = PeriodIndex(iter(idx))
135158
tm.assert_index_equal(result, idx)
@@ -160,7 +183,9 @@ def test_constructor_datetime64arr(self):
160183
vals = np.arange(100000, 100000 + 10000, 100, dtype=np.int64)
161184
vals = vals.view(np.dtype('M8[us]'))
162185

163-
pytest.raises(ValueError, PeriodIndex, vals, freq='D')
186+
msg = r"Wrong dtype: datetime64\[us\]"
187+
with pytest.raises(ValueError, match=msg):
188+
PeriodIndex(vals, freq='D')
164189

165190
@pytest.mark.parametrize('box', [None, 'series', 'index'])
166191
def test_constructor_datetime64arr_ok(self, box):
@@ -300,17 +325,20 @@ def test_constructor_simple_new_empty(self):
300325

301326
@pytest.mark.parametrize('floats', [[1.1, 2.1], np.array([1.1, 2.1])])
302327
def test_constructor_floats(self, floats):
303-
with pytest.raises(TypeError):
328+
msg = r"PeriodIndex\._simple_new does not accept floats"
329+
with pytest.raises(TypeError, match=msg):
304330
pd.PeriodIndex._simple_new(floats, freq='M')
305331

306-
with pytest.raises(TypeError):
332+
msg = "PeriodIndex does not allow floating point in construction"
333+
with pytest.raises(TypeError, match=msg):
307334
pd.PeriodIndex(floats, freq='M')
308335

309336
def test_constructor_nat(self):
310-
pytest.raises(ValueError, period_range, start='NaT',
311-
end='2011-01-01', freq='M')
312-
pytest.raises(ValueError, period_range, start='2011-01-01',
313-
end='NaT', freq='M')
337+
msg = "start and end must not be NaT"
338+
with pytest.raises(ValueError, match=msg):
339+
period_range(start='NaT', end='2011-01-01', freq='M')
340+
with pytest.raises(ValueError, match=msg):
341+
period_range(start='2011-01-01', end='NaT', freq='M')
314342

315343
def test_constructor_year_and_quarter(self):
316344
year = pd.Series([2001, 2002, 2003])
@@ -455,9 +483,12 @@ def test_constructor(self):
455483

456484
# Mixed freq should fail
457485
vals = [end_intv, Period('2006-12-31', 'w')]
458-
pytest.raises(ValueError, PeriodIndex, vals)
486+
msg = r"Input has different freq=W-SUN from PeriodIndex\(freq=B\)"
487+
with pytest.raises(IncompatibleFrequency, match=msg):
488+
PeriodIndex(vals)
459489
vals = np.array(vals)
460-
pytest.raises(ValueError, PeriodIndex, vals)
490+
with pytest.raises(IncompatibleFrequency, match=msg):
491+
PeriodIndex(vals)
461492

462493
def test_constructor_error(self):
463494
start = Period('02-Apr-2005', 'B')
@@ -508,7 +539,8 @@ def setup_method(self, method):
508539
self.series = Series(period_range('2000-01-01', periods=10, freq='D'))
509540

510541
def test_constructor_cant_cast_period(self):
511-
with pytest.raises(TypeError):
542+
msg = "Cannot cast PeriodArray to dtype float64"
543+
with pytest.raises(TypeError, match=msg):
512544
Series(period_range('2000-01-01', periods=10, freq='D'),
513545
dtype=float)
514546

pandas/tests/indexes/period/test_indexing.py

+21-8
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ def test_getitem_partial(self):
8484
rng = period_range('2007-01', periods=50, freq='M')
8585
ts = Series(np.random.randn(len(rng)), rng)
8686

87-
pytest.raises(KeyError, ts.__getitem__, '2006')
87+
with pytest.raises(KeyError, match=r"^'2006'$"):
88+
ts['2006']
8889

8990
result = ts['2008']
9091
assert (result.index.year == 2008).all()
@@ -326,7 +327,8 @@ def test_take_fill_value(self):
326327
with pytest.raises(ValueError, match=msg):
327328
idx.take(np.array([1, 0, -5]), fill_value=True)
328329

329-
with pytest.raises(IndexError):
330+
msg = "index -5 is out of bounds for size 3"
331+
with pytest.raises(IndexError, match=msg):
330332
idx.take(np.array([1, -5]))
331333

332334

@@ -335,7 +337,8 @@ class TestIndexing(object):
335337
def test_get_loc_msg(self):
336338
idx = period_range('2000-1-1', freq='A', periods=10)
337339
bad_period = Period('2012', 'A')
338-
pytest.raises(KeyError, idx.get_loc, bad_period)
340+
with pytest.raises(KeyError, match=r"^Period\('2012', 'A-DEC'\)$"):
341+
idx.get_loc(bad_period)
339342

340343
try:
341344
idx.get_loc(bad_period)
@@ -373,8 +376,13 @@ def test_get_loc(self):
373376
msg = "Cannot interpret 'foo' as period"
374377
with pytest.raises(KeyError, match=msg):
375378
idx0.get_loc('foo')
376-
pytest.raises(KeyError, idx0.get_loc, 1.1)
377-
pytest.raises(TypeError, idx0.get_loc, idx0)
379+
with pytest.raises(KeyError, match=r"^1\.1$"):
380+
idx0.get_loc(1.1)
381+
382+
msg = (r"'PeriodIndex\(\['2017-09-01', '2017-09-02', '2017-09-03'\],"
383+
r" dtype='period\[D\]', freq='D'\)' is an invalid key")
384+
with pytest.raises(TypeError, match=msg):
385+
idx0.get_loc(idx0)
378386

379387
# get the location of p1/p2 from
380388
# monotonic increasing PeriodIndex with duplicate
@@ -391,8 +399,13 @@ def test_get_loc(self):
391399
with pytest.raises(KeyError, match=msg):
392400
idx1.get_loc('foo')
393401

394-
pytest.raises(KeyError, idx1.get_loc, 1.1)
395-
pytest.raises(TypeError, idx1.get_loc, idx1)
402+
with pytest.raises(KeyError, match=r"^1\.1$"):
403+
idx1.get_loc(1.1)
404+
405+
msg = (r"'PeriodIndex\(\['2017-09-02', '2017-09-02', '2017-09-03'\],"
406+
r" dtype='period\[D\]', freq='D'\)' is an invalid key")
407+
with pytest.raises(TypeError, match=msg):
408+
idx1.get_loc(idx1)
396409

397410
# get the location of p1/p2 from
398411
# non-monotonic increasing/decreasing PeriodIndex with duplicate
@@ -569,7 +582,7 @@ def test_get_loc2(self):
569582
msg = 'Input has different freq=None from PeriodArray\\(freq=D\\)'
570583
with pytest.raises(ValueError, match=msg):
571584
idx.get_loc('2000-01-10', method='nearest', tolerance='1 hour')
572-
with pytest.raises(KeyError):
585+
with pytest.raises(KeyError, match=r"^Period\('2000-01-10', 'D'\)$"):
573586
idx.get_loc('2000-01-10', method='nearest', tolerance='1 day')
574587
with pytest.raises(
575588
ValueError,

pandas/tests/indexes/period/test_period.py

+25-19
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,12 @@ def test_fillna_period(self):
7171
pd.Period('2011-01-01', freq='D')), exp)
7272

7373
def test_no_millisecond_field(self):
74-
with pytest.raises(AttributeError):
74+
msg = "type object 'DatetimeIndex' has no attribute 'millisecond'"
75+
with pytest.raises(AttributeError, match=msg):
7576
DatetimeIndex.millisecond
7677

77-
with pytest.raises(AttributeError):
78+
msg = "'DatetimeIndex' object has no attribute 'millisecond'"
79+
with pytest.raises(AttributeError, match=msg):
7880
DatetimeIndex([]).millisecond
7981

8082
@pytest.mark.parametrize("sort", [None, False])
@@ -98,8 +100,8 @@ def test_difference_freq(self, sort):
98100

99101
def test_hash_error(self):
100102
index = period_range('20010101', periods=10)
101-
with pytest.raises(TypeError, match=("unhashable type: %r" %
102-
type(index).__name__)):
103+
msg = "unhashable type: '{}'".format(type(index).__name__)
104+
with pytest.raises(TypeError, match=msg):
103105
hash(index)
104106

105107
def test_make_time_series(self):
@@ -124,7 +126,8 @@ def test_shallow_copy_i8(self):
124126

125127
def test_shallow_copy_changing_freq_raises(self):
126128
pi = period_range("2018-01-01", periods=3, freq="2D")
127-
with pytest.raises(IncompatibleFrequency, match="are different"):
129+
msg = "specified freq and dtype are different"
130+
with pytest.raises(IncompatibleFrequency, match=msg):
128131
pi._shallow_copy(pi, freq="H")
129132

130133
def test_dtype_str(self):
@@ -214,21 +217,17 @@ def test_period_index_length(self):
214217
assert (i1 == i2).all()
215218
assert i1.freq == i2.freq
216219

217-
try:
220+
msg = "start and end must have same freq"
221+
with pytest.raises(ValueError, match=msg):
218222
period_range(start=start, end=end_intv)
219-
raise AssertionError('Cannot allow mixed freq for start and end')
220-
except ValueError:
221-
pass
222223

223224
end_intv = Period('2005-05-01', 'B')
224225
i1 = period_range(start=start, end=end_intv)
225226

226-
try:
227+
msg = ("Of the three parameters: start, end, and periods, exactly two"
228+
" must be specified")
229+
with pytest.raises(ValueError, match=msg):
227230
period_range(start=start)
228-
raise AssertionError(
229-
'Must specify periods if missing start or end')
230-
except ValueError:
231-
pass
232231

233232
# infer freq from first element
234233
i2 = PeriodIndex([end_intv, Period('2005-05-05', 'B')])
@@ -241,9 +240,12 @@ def test_period_index_length(self):
241240

242241
# Mixed freq should fail
243242
vals = [end_intv, Period('2006-12-31', 'w')]
244-
pytest.raises(ValueError, PeriodIndex, vals)
243+
msg = r"Input has different freq=W-SUN from PeriodIndex\(freq=B\)"
244+
with pytest.raises(IncompatibleFrequency, match=msg):
245+
PeriodIndex(vals)
245246
vals = np.array(vals)
246-
pytest.raises(ValueError, PeriodIndex, vals)
247+
with pytest.raises(ValueError, match=msg):
248+
PeriodIndex(vals)
247249

248250
def test_fields(self):
249251
# year, month, day, hour, minute
@@ -381,7 +383,9 @@ def test_contains_nat(self):
381383
assert np.nan in idx
382384

383385
def test_periods_number_check(self):
384-
with pytest.raises(ValueError):
386+
msg = ("Of the three parameters: start, end, and periods, exactly two"
387+
" must be specified")
388+
with pytest.raises(ValueError, match=msg):
385389
period_range('2011-1-1', '2012-1-1', 'B')
386390

387391
def test_start_time(self):
@@ -500,7 +504,8 @@ def test_is_full(self):
500504
assert index.is_full
501505

502506
index = PeriodIndex([2006, 2005, 2005], freq='A')
503-
pytest.raises(ValueError, getattr, index, 'is_full')
507+
with pytest.raises(ValueError, match="Index is not monotonic"):
508+
index.is_full
504509

505510
assert index[:0].is_full
506511

@@ -574,5 +579,6 @@ def test_maybe_convert_timedelta():
574579
assert pi._maybe_convert_timedelta(2) == 2
575580

576581
offset = offsets.BusinessDay()
577-
with pytest.raises(ValueError, match='freq'):
582+
msg = r"Input has different freq=B from PeriodIndex\(freq=D\)"
583+
with pytest.raises(ValueError, match=msg):
578584
pi._maybe_convert_timedelta(offset)

0 commit comments

Comments
 (0)