From c66028cab32b32f3e0fbb592eba5d05cce5eb443 Mon Sep 17 00:00:00 2001 From: Simon Hawkins Date: Sun, 3 Mar 2019 01:46:07 +0000 Subject: [PATCH] STY: use pytest.raises context manager (plotting, reductions, scalar...) (#25483) * STY: use pytest.raises context manager (plotting, reductions, scalar...) * revert removed testing in test_timedelta.py * remove TODO from test_frame.py * skip py2 ci failure --- pandas/tests/plotting/test_boxplot_method.py | 21 ++++++--- pandas/tests/plotting/test_datetimelike.py | 13 +++-- pandas/tests/plotting/test_hist_method.py | 17 ++++--- pandas/tests/plotting/test_misc.py | 14 ++++-- pandas/tests/reductions/test_reductions.py | 4 +- pandas/tests/scalar/period/test_period.py | 21 +++++---- .../tests/scalar/timedelta/test_timedelta.py | 45 +++++++++++++----- .../tests/scalar/timestamp/test_timestamp.py | 8 +++- pandas/tests/sparse/frame/test_frame.py | 47 +++++++++++++------ pandas/tests/sparse/series/test_series.py | 34 +++++++++----- pandas/tests/tseries/offsets/test_offsets.py | 17 +++++-- .../tests/tseries/offsets/test_yqm_offsets.py | 20 +++++--- 12 files changed, 180 insertions(+), 81 deletions(-) diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 7d721c7de3398..e6b9795aebe7c 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -267,13 +267,20 @@ def test_grouped_box_return_type(self): def test_grouped_box_layout(self): df = self.hist_df - pytest.raises(ValueError, df.boxplot, column=['weight', 'height'], - by=df.gender, layout=(1, 1)) - pytest.raises(ValueError, df.boxplot, - column=['height', 'weight', 'category'], - layout=(2, 1), return_type='dict') - pytest.raises(ValueError, df.boxplot, column=['weight', 'height'], - by=df.gender, layout=(-1, -1)) + msg = "Layout of 1x1 must be larger than required size 2" + with pytest.raises(ValueError, match=msg): + df.boxplot(column=['weight', 'height'], by=df.gender, + layout=(1, 1)) + + msg = "The 'layout' keyword is not supported when 'by' is None" + with pytest.raises(ValueError, match=msg): + df.boxplot(column=['height', 'weight', 'category'], + layout=(2, 1), return_type='dict') + + msg = "At least one dimension of layout must be positive" + with pytest.raises(ValueError, match=msg): + df.boxplot(column=['weight', 'height'], by=df.gender, + layout=(-1, -1)) # _check_plot_works adds an ax so catch warning. see GH #13188 with tm.assert_produces_warning(UserWarning): diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index ad79cc97f8b77..6702ad6cfb761 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -97,7 +97,9 @@ def test_nonnumeric_exclude(self): assert len(ax.get_lines()) == 1 # B was plotted self.plt.close(fig) - pytest.raises(TypeError, df['A'].plot) + msg = "Empty 'DataFrame': no numeric data to plot" + with pytest.raises(TypeError, match=msg): + df['A'].plot() def test_tsplot_deprecated(self): from pandas.tseries.plotting import tsplot @@ -140,10 +142,15 @@ def f(*args, **kwds): def test_both_style_and_color(self): ts = tm.makeTimeSeries() - pytest.raises(ValueError, ts.plot, style='b-', color='#000099') + msg = ("Cannot pass 'style' string with a color symbol and 'color' " + "keyword argument. Please use one or the other or pass 'style'" + " without a color symbol") + with pytest.raises(ValueError, match=msg): + ts.plot(style='b-', color='#000099') s = ts.reset_index(drop=True) - pytest.raises(ValueError, s.plot, style='b-', color='#000099') + with pytest.raises(ValueError, match=msg): + s.plot(style='b-', color='#000099') @pytest.mark.slow def test_high_freq(self): diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 7bdbdac54f7a6..4f0bef52b5e15 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -332,12 +332,17 @@ def test_grouped_hist_legacy2(self): @pytest.mark.slow def test_grouped_hist_layout(self): df = self.hist_df - pytest.raises(ValueError, df.hist, column='weight', by=df.gender, - layout=(1, 1)) - pytest.raises(ValueError, df.hist, column='height', by=df.category, - layout=(1, 3)) - pytest.raises(ValueError, df.hist, column='height', by=df.category, - layout=(-1, -1)) + msg = "Layout of 1x1 must be larger than required size 2" + with pytest.raises(ValueError, match=msg): + df.hist(column='weight', by=df.gender, layout=(1, 1)) + + msg = "Layout of 1x3 must be larger than required size 4" + with pytest.raises(ValueError, match=msg): + df.hist(column='height', by=df.category, layout=(1, 3)) + + msg = "At least one dimension of layout must be positive" + with pytest.raises(ValueError, match=msg): + df.hist(column='height', by=df.category, layout=(-1, -1)) with tm.assert_produces_warning(UserWarning): axes = _check_plot_works(df.hist, column='height', by=df.gender, diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 44b95f7d1b00b..98248586f3d27 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -278,14 +278,20 @@ def test_subplot_titles(self, iris): assert [p.get_title() for p in plot] == title # Case len(title) > len(df) - pytest.raises(ValueError, df.plot, subplots=True, - title=title + ["kittens > puppies"]) + msg = ("The length of `title` must equal the number of columns if" + " using `title` of type `list` and `subplots=True`") + with pytest.raises(ValueError, match=msg): + df.plot(subplots=True, title=title + ["kittens > puppies"]) # Case len(title) < len(df) - pytest.raises(ValueError, df.plot, subplots=True, title=title[:2]) + with pytest.raises(ValueError, match=msg): + df.plot(subplots=True, title=title[:2]) # Case subplots=False and title is of type list - pytest.raises(ValueError, df.plot, subplots=False, title=title) + msg = ("Using `title` of type `list` is not supported unless" + " `subplots=True` is passed") + with pytest.raises(ValueError, match=msg): + df.plot(subplots=False, title=title) # Case df with 3 numeric columns but layout of (2,2) plot = df.drop('SepalWidth', axis=1).plot(subplots=True, layout=(2, 2), diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 8520855d14918..fbf7f610688ba 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -276,7 +276,9 @@ def test_timedelta_ops(self): # invalid ops for op in ['skew', 'kurt', 'sem', 'prod']: - pytest.raises(TypeError, getattr(td, op)) + msg = "reduction operation '{}' not allowed for this dtype" + with pytest.raises(TypeError, match=msg.format(op)): + getattr(td, op)() # GH#10040 # make sure NaT is properly handled by median() diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index d0f87618ad3af..8ca19745055a3 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -8,6 +8,7 @@ from pandas._libs.tslibs.ccalendar import DAYS, MONTHS from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG from pandas._libs.tslibs.parsing import DateParseError +from pandas._libs.tslibs.period import IncompatibleFrequency from pandas._libs.tslibs.timezones import dateutil_gettz, maybe_get_tz from pandas.compat import iteritems, text_type from pandas.compat.numpy import np_datetime64_compat @@ -35,7 +36,9 @@ def test_construction(self): i4 = Period('2005', freq='M') i5 = Period('2005', freq='m') - pytest.raises(ValueError, i1.__ne__, i4) + msg = r"Input has different freq=M from Period\(freq=A-DEC\)" + with pytest.raises(IncompatibleFrequency, match=msg): + i1 != i4 assert i4 == i5 i1 = Period.now('Q') @@ -74,9 +77,12 @@ def test_construction(self): freq='U') assert i1 == expected - pytest.raises(ValueError, Period, ordinal=200701) + msg = "Must supply freq for ordinal value" + with pytest.raises(ValueError, match=msg): + Period(ordinal=200701) - pytest.raises(ValueError, Period, '2007-1-1', freq='X') + with pytest.raises(ValueError, match="Invalid frequency: X"): + Period('2007-1-1', freq='X') def test_construction_bday(self): @@ -233,10 +239,6 @@ def test_period_constructor_offsets(self): freq='U') assert i1 == expected - pytest.raises(ValueError, Period, ordinal=200701) - - pytest.raises(ValueError, Period, '2007-1-1', freq='X') - def test_invalid_arguments(self): with pytest.raises(ValueError): Period(datetime.now()) @@ -925,8 +927,9 @@ def test_properties_secondly(self): class TestPeriodField(object): def test_get_period_field_array_raises_on_out_of_range(self): - pytest.raises(ValueError, libperiod.get_period_field_arr, -1, - np.empty(1), 0) + msg = "Buffer dtype mismatch, expected 'int64_t' but got 'double'" + with pytest.raises(ValueError, match=msg): + libperiod.get_period_field_arr(-1, np.empty(1), 0) class TestComparisons(object): diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index bf71c37aa9c3d..ee2c2e9e1959c 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -250,9 +250,13 @@ def check(value): assert rng.microseconds == 0 assert rng.nanoseconds == 0 - pytest.raises(AttributeError, lambda: rng.hours) - pytest.raises(AttributeError, lambda: rng.minutes) - pytest.raises(AttributeError, lambda: rng.milliseconds) + msg = "'Timedelta' object has no attribute '{}'" + with pytest.raises(AttributeError, match=msg.format('hours')): + rng.hours + with pytest.raises(AttributeError, match=msg.format('minutes')): + rng.minutes + with pytest.raises(AttributeError, match=msg.format('milliseconds')): + rng.milliseconds # GH 10050 check(rng.days) @@ -272,9 +276,13 @@ def check(value): assert rng.seconds == 10 * 3600 + 11 * 60 + 12 assert rng.microseconds == 100 * 1000 + 123 assert rng.nanoseconds == 456 - pytest.raises(AttributeError, lambda: rng.hours) - pytest.raises(AttributeError, lambda: rng.minutes) - pytest.raises(AttributeError, lambda: rng.milliseconds) + msg = "'Timedelta' object has no attribute '{}'" + with pytest.raises(AttributeError, match=msg.format('hours')): + rng.hours + with pytest.raises(AttributeError, match=msg.format('minutes')): + rng.minutes + with pytest.raises(AttributeError, match=msg.format('milliseconds')): + rng.milliseconds # components tup = pd.to_timedelta(-1, 'us').components @@ -449,8 +457,12 @@ def test_round(self): assert r2 == s2 # invalid - for freq in ['Y', 'M', 'foobar']: - pytest.raises(ValueError, lambda: t1.round(freq)) + for freq, msg in [ + ('Y', ' is a non-fixed frequency'), + ('M', ' is a non-fixed frequency'), + ('foobar', 'Invalid frequency: foobar')]: + with pytest.raises(ValueError, match=msg): + t1.round(freq) t1 = timedelta_range('1 days', periods=3, freq='1 min 2 s 3 us') t2 = -1 * t1 @@ -495,11 +507,15 @@ def test_round(self): r1 = t1.round(freq) tm.assert_index_equal(r1, s1) r2 = t2.round(freq) - tm.assert_index_equal(r2, s2) + tm.assert_index_equal(r2, s2) # invalid - for freq in ['Y', 'M', 'foobar']: - pytest.raises(ValueError, lambda: t1.round(freq)) + for freq, msg in [ + ('Y', ' is a non-fixed frequency'), + ('M', ' is a non-fixed frequency'), + ('foobar', 'Invalid frequency: foobar')]: + with pytest.raises(ValueError, match=msg): + t1.round(freq) def test_contains(self): # Checking for any NaT-like objects @@ -609,9 +625,12 @@ def test_overflow(self): assert np.allclose(result.value / 1000, expected.value / 1000) # sum - pytest.raises(ValueError, lambda: (s - s.min()).sum()) + msg = "overflow in timedelta operation" + with pytest.raises(ValueError, match=msg): + (s - s.min()).sum() s1 = s[0:10000] - pytest.raises(ValueError, lambda: (s1 - s1.min()).sum()) + with pytest.raises(ValueError, match=msg): + (s1 - s1.min()).sum() s2 = s[0:1000] result = (s2 - s2.min()).sum() diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 7d81d905eac4f..b55d00b44fd67 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -60,7 +60,9 @@ def check(value, equal): check(ts.hour, 9) check(ts.minute, 6) check(ts.second, 3) - pytest.raises(AttributeError, lambda: ts.millisecond) + msg = "'Timestamp' object has no attribute 'millisecond'" + with pytest.raises(AttributeError, match=msg): + ts.millisecond check(ts.microsecond, 100) check(ts.nanosecond, 1) check(ts.dayofweek, 6) @@ -78,7 +80,9 @@ def check(value, equal): check(ts.hour, 23) check(ts.minute, 59) check(ts.second, 0) - pytest.raises(AttributeError, lambda: ts.millisecond) + msg = "'Timestamp' object has no attribute 'millisecond'" + with pytest.raises(AttributeError, match=msg): + ts.millisecond check(ts.microsecond, 0) check(ts.nanosecond, 0) check(ts.dayofweek, 2) diff --git a/pandas/tests/sparse/frame/test_frame.py b/pandas/tests/sparse/frame/test_frame.py index bfb5103c97adc..b31738794c854 100644 --- a/pandas/tests/sparse/frame/test_frame.py +++ b/pandas/tests/sparse/frame/test_frame.py @@ -7,7 +7,7 @@ import pytest from pandas._libs.sparse import BlockIndex, IntIndex -from pandas.compat import lrange +from pandas.compat import PY2, lrange from pandas.errors import PerformanceWarning import pandas as pd @@ -145,8 +145,9 @@ def test_constructor_ndarray(self, float_frame): tm.assert_sp_frame_equal(sp, float_frame.reindex(columns=['A'])) # raise on level argument - pytest.raises(TypeError, float_frame.reindex, columns=['A'], - level=1) + msg = "Reindex by level not supported for sparse" + with pytest.raises(TypeError, match=msg): + float_frame.reindex(columns=['A'], level=1) # wrong length index / columns with pytest.raises(ValueError, match="^Index length"): @@ -433,7 +434,8 @@ def test_getitem(self): exp = sdf.reindex(columns=['a', 'b']) tm.assert_sp_frame_equal(result, exp) - pytest.raises(Exception, sdf.__getitem__, ['a', 'd']) + with pytest.raises(KeyError, match=r"\['d'\] not in index"): + sdf[['a', 'd']] def test_iloc(self, float_frame): @@ -504,7 +506,9 @@ def test_getitem_overload(self, float_frame): subframe = float_frame[indexer] tm.assert_index_equal(subindex, subframe.index) - pytest.raises(Exception, float_frame.__getitem__, indexer[:-1]) + msg = "Item wrong length 9 instead of 10" + with pytest.raises(ValueError, match=msg): + float_frame[indexer[:-1]] def test_setitem(self, float_frame, float_frame_int_kind, float_frame_dense, @@ -551,8 +555,9 @@ def _check_frame(frame, orig): assert len(frame['I'].sp_values) == N // 2 # insert ndarray wrong size - pytest.raises(Exception, frame.__setitem__, 'foo', - np.random.randn(N - 1)) + msg = "Length of values does not match length of index" + with pytest.raises(AssertionError, match=msg): + frame['foo'] = np.random.randn(N - 1) # scalar value frame['J'] = 5 @@ -625,17 +630,22 @@ def test_delitem(self, float_frame): def test_set_columns(self, float_frame): float_frame.columns = float_frame.columns - pytest.raises(Exception, setattr, float_frame, 'columns', - float_frame.columns[:-1]) + msg = ("Length mismatch: Expected axis has 4 elements, new values have" + " 3 elements") + with pytest.raises(ValueError, match=msg): + float_frame.columns = float_frame.columns[:-1] def test_set_index(self, float_frame): float_frame.index = float_frame.index - pytest.raises(Exception, setattr, float_frame, 'index', - float_frame.index[:-1]) + msg = ("Length mismatch: Expected axis has 10 elements, new values" + " have 9 elements") + with pytest.raises(ValueError, match=msg): + float_frame.index = float_frame.index[:-1] def test_ctor_reindex(self): idx = pd.Index([0, 1, 2, 3]) - with pytest.raises(ValueError, match=''): + msg = "Length of passed values is 2, index implies 4" + with pytest.raises(ValueError, match=msg): pd.SparseDataFrame({"A": [1, 2]}, index=idx) def test_append(self, float_frame): @@ -858,6 +868,7 @@ def test_describe(self, float_frame): str(float_frame) desc = float_frame.describe() # noqa + @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails") def test_join(self, float_frame): left = float_frame.loc[:, ['A', 'B']] right = float_frame.loc[:, ['C', 'D']] @@ -865,7 +876,10 @@ def test_join(self, float_frame): tm.assert_sp_frame_equal(joined, float_frame, exact_indices=False) right = float_frame.loc[:, ['B', 'D']] - pytest.raises(Exception, left.join, right) + msg = (r"columns overlap but no suffix specified: Index\(\['B'\]," + r" dtype='object'\)") + with pytest.raises(ValueError, match=msg): + left.join(right) with pytest.raises(ValueError, match='Other Series must have a name'): float_frame.join(Series( @@ -1046,8 +1060,11 @@ def _check(frame): _check(float_frame_int_kind) # for now - pytest.raises(Exception, _check, float_frame_fill0) - pytest.raises(Exception, _check, float_frame_fill2) + msg = "This routine assumes NaN fill value" + with pytest.raises(TypeError, match=msg): + _check(float_frame_fill0) + with pytest.raises(TypeError, match=msg): + _check(float_frame_fill2) def test_transpose(self, float_frame, float_frame_int_kind, float_frame_dense, diff --git a/pandas/tests/sparse/series/test_series.py b/pandas/tests/sparse/series/test_series.py index 7eed47d0de888..93cf629f20957 100644 --- a/pandas/tests/sparse/series/test_series.py +++ b/pandas/tests/sparse/series/test_series.py @@ -452,12 +452,13 @@ def _check_getitem(sp, dense): _check_getitem(self.ziseries, self.ziseries.to_dense()) # exception handling - pytest.raises(Exception, self.bseries.__getitem__, - len(self.bseries) + 1) + with pytest.raises(IndexError, match="Out of bounds access"): + self.bseries[len(self.bseries) + 1] # index not contained - pytest.raises(Exception, self.btseries.__getitem__, - self.btseries.index[-1] + BDay()) + msg = r"Timestamp\('2011-01-31 00:00:00', freq='B'\)" + with pytest.raises(KeyError, match=msg): + self.btseries[self.btseries.index[-1] + BDay()] def test_get_get_value(self): tm.assert_almost_equal(self.bseries.get(10), self.bseries[10]) @@ -523,8 +524,9 @@ def _compare(idx): self._check_all(_compare_with_dense) - pytest.raises(Exception, self.bseries.take, - [0, len(self.bseries) + 1]) + msg = "index 21 is out of bounds for size 20" + with pytest.raises(IndexError, match=msg): + self.bseries.take([0, len(self.bseries) + 1]) # Corner case # XXX: changed test. Why wsa this considered a corner case? @@ -1138,25 +1140,35 @@ def test_to_coo_text_names_text_row_levels_nosort(self): def test_to_coo_bad_partition_nonnull_intersection(self): ss = self.sparse_series[0] - pytest.raises(ValueError, ss.to_coo, ['A', 'B', 'C'], ['C', 'D']) + msg = "Is not a partition because intersection is not null" + with pytest.raises(ValueError, match=msg): + ss.to_coo(['A', 'B', 'C'], ['C', 'D']) def test_to_coo_bad_partition_small_union(self): ss = self.sparse_series[0] - pytest.raises(ValueError, ss.to_coo, ['A'], ['C', 'D']) + msg = "Is not a partition because union is not the whole" + with pytest.raises(ValueError, match=msg): + ss.to_coo(['A'], ['C', 'D']) def test_to_coo_nlevels_less_than_two(self): ss = self.sparse_series[0] ss.index = np.arange(len(ss.index)) - pytest.raises(ValueError, ss.to_coo) + msg = "to_coo requires MultiIndex with nlevels > 2" + with pytest.raises(ValueError, match=msg): + ss.to_coo() def test_to_coo_bad_ilevel(self): ss = self.sparse_series[0] - pytest.raises(KeyError, ss.to_coo, ['A', 'B'], ['C', 'D', 'E']) + with pytest.raises(KeyError, match="Level E not found"): + ss.to_coo(['A', 'B'], ['C', 'D', 'E']) def test_to_coo_duplicate_index_entries(self): ss = pd.concat([self.sparse_series[0], self.sparse_series[0]]).to_sparse() - pytest.raises(ValueError, ss.to_coo, ['A', 'B'], ['C', 'D']) + msg = ("Duplicate index entries are not allowed in to_coo" + " transformation") + with pytest.raises(ValueError, match=msg): + ss.to_coo(['A', 'B'], ['C', 'D']) def test_from_coo_dense_index(self): ss = SparseSeries.from_coo(self.coo_matrices[0], dense_index=True) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 621572da57541..e6f21a7b47c3b 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -9,6 +9,7 @@ from pandas._libs.tslibs.frequencies import ( INVALID_FREQ_ERR_MSG, get_freq_code, get_freq_str) import pandas._libs.tslibs.offsets as liboffsets +from pandas._libs.tslibs.offsets import ApplyTypeError import pandas.compat as compat from pandas.compat import range from pandas.compat.numpy import np_datetime64_compat @@ -150,7 +151,8 @@ def test_sub(self): # offset2 attr return off = self.offset2 - with pytest.raises(Exception): + msg = "Cannot subtract datetime from offset" + with pytest.raises(TypeError, match=msg): off - self.d assert 2 * off - off == off @@ -736,7 +738,10 @@ def test_apply_large_n(self): assert rs == xp def test_apply_corner(self): - pytest.raises(TypeError, BDay().apply, BMonthEnd()) + msg = ("Only know how to combine business day with datetime or" + " timedelta") + with pytest.raises(ApplyTypeError, match=msg): + BDay().apply(BMonthEnd()) class TestBusinessHour(Base): @@ -812,7 +817,8 @@ def test_sub(self): # we have to override test_sub here becasue self.offset2 is not # defined as self._offset(2) off = self.offset2 - with pytest.raises(Exception): + msg = "Cannot subtract datetime from offset" + with pytest.raises(TypeError, match=msg): off - self.d assert 2 * off - off == off @@ -1796,7 +1802,10 @@ def test_apply_large_n(self): assert rs == xp def test_apply_corner(self): - pytest.raises(Exception, CDay().apply, BMonthEnd()) + msg = ("Only know how to combine trading day with datetime, datetime64" + " or timedelta") + with pytest.raises(ApplyTypeError, match=msg): + CDay().apply(BMonthEnd()) def test_holidays(self): # Define a TradingDay offset diff --git a/pandas/tests/tseries/offsets/test_yqm_offsets.py b/pandas/tests/tseries/offsets/test_yqm_offsets.py index 8023ee3139dd5..9ee03d2e886f3 100644 --- a/pandas/tests/tseries/offsets/test_yqm_offsets.py +++ b/pandas/tests/tseries/offsets/test_yqm_offsets.py @@ -713,7 +713,8 @@ class TestYearBegin(Base): _offset = YearBegin def test_misspecified(self): - pytest.raises(ValueError, YearBegin, month=13) + with pytest.raises(ValueError, match="Month must go from 1 to 12"): + YearBegin(month=13) offset_cases = [] offset_cases.append((YearBegin(), { @@ -804,7 +805,8 @@ class TestYearEnd(Base): _offset = YearEnd def test_misspecified(self): - pytest.raises(ValueError, YearEnd, month=13) + with pytest.raises(ValueError, match="Month must go from 1 to 12"): + YearEnd(month=13) offset_cases = [] offset_cases.append((YearEnd(), { @@ -900,8 +902,11 @@ class TestBYearBegin(Base): _offset = BYearBegin def test_misspecified(self): - pytest.raises(ValueError, BYearBegin, month=13) - pytest.raises(ValueError, BYearEnd, month=13) + msg = "Month must go from 1 to 12" + with pytest.raises(ValueError, match=msg): + BYearBegin(month=13) + with pytest.raises(ValueError, match=msg): + BYearEnd(month=13) offset_cases = [] offset_cases.append((BYearBegin(), { @@ -993,8 +998,11 @@ class TestBYearEndLagged(Base): _offset = BYearEnd def test_bad_month_fail(self): - pytest.raises(Exception, BYearEnd, month=13) - pytest.raises(Exception, BYearEnd, month=0) + msg = "Month must go from 1 to 12" + with pytest.raises(ValueError, match=msg): + BYearEnd(month=13) + with pytest.raises(ValueError, match=msg): + BYearEnd(month=0) offset_cases = [] offset_cases.append((BYearEnd(month=6), {