Skip to content

Commit 3fd47fe

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (resample) (#24977)
1 parent bf693ff commit 3fd47fe

File tree

5 files changed

+75
-49
lines changed

5 files changed

+75
-49
lines changed

pandas/tests/resample/test_base.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,10 @@ def test_resample_interpolate_all_ts(frame):
9595
def test_raises_on_non_datetimelike_index():
9696
# this is a non datetimelike index
9797
xp = DataFrame()
98-
pytest.raises(TypeError, lambda: xp.resample('A').mean())
98+
msg = ("Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex,"
99+
" but got an instance of 'Index'")
100+
with pytest.raises(TypeError, match=msg):
101+
xp.resample('A').mean()
99102

100103

101104
@pytest.mark.parametrize('freq', ['M', 'D', 'H'])
@@ -189,8 +192,10 @@ def test_resample_loffset_arg_type_all_ts(frame, create_index):
189192

190193
# GH 13022, 7687 - TODO: fix resample w/ TimedeltaIndex
191194
if isinstance(expected.index, TimedeltaIndex):
192-
with pytest.raises(AssertionError):
195+
msg = "DataFrame are different"
196+
with pytest.raises(AssertionError, match=msg):
193197
assert_frame_equal(result_agg, expected)
198+
with pytest.raises(AssertionError, match=msg):
194199
assert_frame_equal(result_how, expected)
195200
else:
196201
assert_frame_equal(result_agg, expected)

pandas/tests/resample/test_datetime_index.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -113,16 +113,18 @@ def test_resample_basic_grouper(series):
113113
@pytest.mark.parametrize(
114114
'_index_start,_index_end,_index_name',
115115
[('1/1/2000 00:00:00', '1/1/2000 00:13:00', 'index')])
116-
@pytest.mark.parametrize('kwargs', [
117-
dict(label='righttt'),
118-
dict(closed='righttt'),
119-
dict(convention='starttt')
116+
@pytest.mark.parametrize('keyword,value', [
117+
('label', 'righttt'),
118+
('closed', 'righttt'),
119+
('convention', 'starttt')
120120
])
121-
def test_resample_string_kwargs(series, kwargs):
121+
def test_resample_string_kwargs(series, keyword, value):
122122
# see gh-19303
123123
# Check that wrong keyword argument strings raise an error
124-
with pytest.raises(ValueError, match='Unsupported value'):
125-
series.resample('5min', **kwargs)
124+
msg = "Unsupported value {value} for `{keyword}`".format(
125+
value=value, keyword=keyword)
126+
with pytest.raises(ValueError, match=msg):
127+
series.resample('5min', **({keyword: value}))
126128

127129

128130
@pytest.mark.parametrize(
@@ -676,7 +678,7 @@ def test_asfreq_non_unique():
676678
ts = Series(np.random.randn(len(rng2)), index=rng2)
677679

678680
msg = 'cannot reindex from a duplicate axis'
679-
with pytest.raises(Exception, match=msg):
681+
with pytest.raises(ValueError, match=msg):
680682
ts.asfreq('B')
681683

682684

pandas/tests/resample/test_period_index.py

+26-13
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import pandas as pd
1313
from pandas import DataFrame, Series, Timestamp
14+
from pandas.core.indexes.base import InvalidIndexError
1415
from pandas.core.indexes.datetimes import date_range
1516
from pandas.core.indexes.period import Period, PeriodIndex, period_range
1617
from pandas.core.resample import _get_period_range_edges
@@ -72,17 +73,19 @@ def test_asfreq_fill_value(self, series):
7273

7374
@pytest.mark.parametrize('freq', ['H', '12H', '2D', 'W'])
7475
@pytest.mark.parametrize('kind', [None, 'period', 'timestamp'])
75-
def test_selection(self, index, freq, kind):
76+
@pytest.mark.parametrize('kwargs', [dict(on='date'), dict(level='d')])
77+
def test_selection(self, index, freq, kind, kwargs):
7678
# This is a bug, these should be implemented
7779
# GH 14008
7880
rng = np.arange(len(index), dtype=np.int64)
7981
df = DataFrame({'date': index, 'a': rng},
8082
index=pd.MultiIndex.from_arrays([rng, index],
8183
names=['v', 'd']))
82-
with pytest.raises(NotImplementedError):
83-
df.resample(freq, on='date', kind=kind)
84-
with pytest.raises(NotImplementedError):
85-
df.resample(freq, level='d', kind=kind)
84+
msg = ("Resampling from level= or on= selection with a PeriodIndex is"
85+
r" not currently supported, use \.set_index\(\.\.\.\) to"
86+
" explicitly set index")
87+
with pytest.raises(NotImplementedError, match=msg):
88+
df.resample(freq, kind=kind, **kwargs)
8689

8790
@pytest.mark.parametrize('month', MONTHS)
8891
@pytest.mark.parametrize('meth', ['ffill', 'bfill'])
@@ -110,13 +113,20 @@ def test_basic_downsample(self, simple_period_range_series):
110113
assert_series_equal(ts.resample('a-dec').mean(), result)
111114
assert_series_equal(ts.resample('a').mean(), result)
112115

113-
def test_not_subperiod(self, simple_period_range_series):
116+
@pytest.mark.parametrize('rule,expected_error_msg', [
117+
('a-dec', '<YearEnd: month=12>'),
118+
('q-mar', '<QuarterEnd: startingMonth=3>'),
119+
('M', '<MonthEnd>'),
120+
('w-thu', '<Week: weekday=3>')
121+
])
122+
def test_not_subperiod(
123+
self, simple_period_range_series, rule, expected_error_msg):
114124
# These are incompatible period rules for resampling
115125
ts = simple_period_range_series('1/1/1990', '6/30/1995', freq='w-wed')
116-
pytest.raises(ValueError, lambda: ts.resample('a-dec').mean())
117-
pytest.raises(ValueError, lambda: ts.resample('q-mar').mean())
118-
pytest.raises(ValueError, lambda: ts.resample('M').mean())
119-
pytest.raises(ValueError, lambda: ts.resample('w-thu').mean())
126+
msg = ("Frequency <Week: weekday=2> cannot be resampled to {}, as they"
127+
" are not sub or super periods").format(expected_error_msg)
128+
with pytest.raises(IncompatibleFrequency, match=msg):
129+
ts.resample(rule).mean()
120130

121131
@pytest.mark.parametrize('freq', ['D', '2D'])
122132
def test_basic_upsample(self, freq, simple_period_range_series):
@@ -212,8 +222,9 @@ def test_resample_same_freq(self, resample_method):
212222
assert_series_equal(result, expected)
213223

214224
def test_resample_incompat_freq(self):
215-
216-
with pytest.raises(IncompatibleFrequency):
225+
msg = ("Frequency <MonthEnd> cannot be resampled to <Week: weekday=6>,"
226+
" as they are not sub or super periods")
227+
with pytest.raises(IncompatibleFrequency, match=msg):
217228
Series(range(3), index=pd.period_range(
218229
start='2000', periods=3, freq='M')).resample('W').mean()
219230

@@ -373,7 +384,9 @@ def test_resample_fill_missing(self):
373384
def test_cant_fill_missing_dups(self):
374385
rng = PeriodIndex([2000, 2005, 2005, 2007, 2007], freq='A')
375386
s = Series(np.random.randn(5), index=rng)
376-
pytest.raises(Exception, lambda: s.resample('A').ffill())
387+
msg = "Reindexing only valid with uniquely valued Index objects"
388+
with pytest.raises(InvalidIndexError, match=msg):
389+
s.resample('A').ffill()
377390

378391
@pytest.mark.parametrize('freq', ['5min'])
379392
@pytest.mark.parametrize('kind', ['period', None, 'timestamp'])

pandas/tests/resample/test_resample_api.py

+31-25
Original file line numberDiff line numberDiff line change
@@ -113,16 +113,14 @@ def test_getitem():
113113
test_frame.columns[[0, 1]])
114114

115115

116-
def test_select_bad_cols():
117-
116+
@pytest.mark.parametrize('key', [['D'], ['A', 'D']])
117+
def test_select_bad_cols(key):
118118
g = test_frame.resample('H')
119-
pytest.raises(KeyError, g.__getitem__, ['D'])
120-
121-
pytest.raises(KeyError, g.__getitem__, ['A', 'D'])
122-
with pytest.raises(KeyError, match='^[^A]+$'):
123-
# A should not be referenced as a bad column...
124-
# will have to rethink regex if you change message!
125-
g[['A', 'D']]
119+
# 'A' should not be referenced as a bad column...
120+
# will have to rethink regex if you change message!
121+
msg = r"^\"Columns not found: 'D'\"$"
122+
with pytest.raises(KeyError, match=msg):
123+
g[key]
126124

127125

128126
def test_attribute_access():
@@ -216,7 +214,9 @@ def test_fillna():
216214
result = r.fillna(method='bfill')
217215
assert_series_equal(result, expected)
218216

219-
with pytest.raises(ValueError):
217+
msg = (r"Invalid fill method\. Expecting pad \(ffill\), backfill"
218+
r" \(bfill\) or nearest\. Got 0")
219+
with pytest.raises(ValueError, match=msg):
220220
r.fillna(0)
221221

222222

@@ -437,12 +437,11 @@ def test_agg_misc():
437437

438438
# errors
439439
# invalid names in the agg specification
440+
msg = "\"Column 'B' does not exist!\""
440441
for t in cases:
441-
with pytest.raises(KeyError):
442-
with tm.assert_produces_warning(FutureWarning,
443-
check_stacklevel=False):
444-
t[['A']].agg({'A': ['sum', 'std'],
445-
'B': ['mean', 'std']})
442+
with pytest.raises(KeyError, match=msg):
443+
t[['A']].agg({'A': ['sum', 'std'],
444+
'B': ['mean', 'std']})
446445

447446

448447
def test_agg_nested_dicts():
@@ -464,11 +463,11 @@ def test_agg_nested_dicts():
464463
df.groupby(pd.Grouper(freq='2D'))
465464
]
466465

466+
msg = r"cannot perform renaming for r(1|2) with a nested dictionary"
467467
for t in cases:
468-
def f():
468+
with pytest.raises(pd.core.base.SpecificationError, match=msg):
469469
t.aggregate({'r1': {'A': ['mean', 'sum']},
470470
'r2': {'B': ['mean', 'sum']}})
471-
pytest.raises(ValueError, f)
472471

473472
for t in cases:
474473
expected = pd.concat([t['A'].mean(), t['A'].std(), t['B'].mean(),
@@ -499,7 +498,8 @@ def test_try_aggregate_non_existing_column():
499498
df = DataFrame(data).set_index('dt')
500499

501500
# Error as we don't have 'z' column
502-
with pytest.raises(KeyError):
501+
msg = "\"Column 'z' does not exist!\""
502+
with pytest.raises(KeyError, match=msg):
503503
df.resample('30T').agg({'x': ['mean'],
504504
'y': ['median'],
505505
'z': ['sum']})
@@ -517,23 +517,29 @@ def test_selection_api_validation():
517517
df_exp = DataFrame({'a': rng}, index=index)
518518

519519
# non DatetimeIndex
520-
with pytest.raises(TypeError):
520+
msg = ("Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex,"
521+
" but got an instance of 'Int64Index'")
522+
with pytest.raises(TypeError, match=msg):
521523
df.resample('2D', level='v')
522524

523-
with pytest.raises(ValueError):
525+
msg = "The Grouper cannot specify both a key and a level!"
526+
with pytest.raises(ValueError, match=msg):
524527
df.resample('2D', on='date', level='d')
525528

526-
with pytest.raises(TypeError):
529+
msg = "unhashable type: 'list'"
530+
with pytest.raises(TypeError, match=msg):
527531
df.resample('2D', on=['a', 'date'])
528532

529-
with pytest.raises(KeyError):
533+
msg = r"\"Level \['a', 'date'\] not found\""
534+
with pytest.raises(KeyError, match=msg):
530535
df.resample('2D', level=['a', 'date'])
531536

532537
# upsampling not allowed
533-
with pytest.raises(ValueError):
538+
msg = ("Upsampling from level= or on= selection is not supported, use"
539+
r" \.set_index\(\.\.\.\) to explicitly set index to datetime-like")
540+
with pytest.raises(ValueError, match=msg):
534541
df.resample('2D', level='d').asfreq()
535-
536-
with pytest.raises(ValueError):
542+
with pytest.raises(ValueError, match=msg):
537543
df.resample('2D', on='date').asfreq()
538544

539545
exp = df_exp.resample('2D').sum()

pandas/tests/resample/test_time_grouper.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def test_fails_on_no_datetime_index(name, func):
112112
df = DataFrame({'a': np.random.randn(n)}, index=index)
113113

114114
msg = ("Only valid with DatetimeIndex, TimedeltaIndex "
115-
"or PeriodIndex, but got an instance of %r" % name)
115+
"or PeriodIndex, but got an instance of '{}'".format(name))
116116
with pytest.raises(TypeError, match=msg):
117117
df.groupby(TimeGrouper('D'))
118118

0 commit comments

Comments
 (0)