From f78790f5932e0648da4edecffbb1aeceef35432a Mon Sep 17 00:00:00 2001 From: Simon Hawkins Date: Sat, 19 Jan 2019 21:29:35 +0000 Subject: [PATCH] STY: use pytest.raises context syntax (reshape) (#24838) --- pandas/core/reshape/merge.py | 2 +- pandas/tests/reshape/merge/test_join.py | 76 ++++++++++------- pandas/tests/reshape/merge/test_merge.py | 100 +++++++++++++++-------- pandas/tests/reshape/test_concat.py | 51 +++++++++--- pandas/tests/reshape/test_melt.py | 14 +++- pandas/tests/reshape/test_pivot.py | 75 +++++++++-------- 6 files changed, 204 insertions(+), 114 deletions(-) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 7861a122afdb6..e11847d2b8ce2 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1087,7 +1087,7 @@ def _validate(self, validate): elif validate in ["one_to_many", "1:m"]: if not left_unique: raise MergeError("Merge keys are not unique in left dataset;" - "not a one-to-many merge") + " not a one-to-many merge") elif validate in ["many_to_one", "m:1"]: if not right_unique: diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 8ee1e49f01ac1..e21f9d0291afa 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -195,38 +195,47 @@ def test_join_on(self): assert np.isnan(joined['three']['c']) # merge column not p resent - pytest.raises(KeyError, target.join, source, on='E') + with pytest.raises(KeyError, match="^'E'$"): + target.join(source, on='E') # overlap source_copy = source.copy() source_copy['A'] = 0 - pytest.raises(ValueError, target.join, source_copy, on='A') + msg = ("You are trying to merge on float64 and object columns. If" + " you wish to proceed you should use pd.concat") + with pytest.raises(ValueError, match=msg): + target.join(source_copy, on='A') def test_join_on_fails_with_different_right_index(self): - with pytest.raises(ValueError): - df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), - 'b': np.random.randn(3)}) - df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), - 'b': np.random.randn(10)}, - index=tm.makeCustomIndex(10, 2)) + df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), + 'b': np.random.randn(3)}) + df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), + 'b': np.random.randn(10)}, + index=tm.makeCustomIndex(10, 2)) + msg = (r'len\(left_on\) must equal the number of levels in the index' + ' of "right"') + with pytest.raises(ValueError, match=msg): merge(df, df2, left_on='a', right_index=True) def test_join_on_fails_with_different_left_index(self): - with pytest.raises(ValueError): - df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), - 'b': np.random.randn(3)}, - index=tm.makeCustomIndex(10, 2)) - df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), - 'b': np.random.randn(10)}) + df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), + 'b': np.random.randn(3)}, + index=tm.makeCustomIndex(3, 2)) + df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), + 'b': np.random.randn(10)}) + msg = (r'len\(right_on\) must equal the number of levels in the index' + ' of "left"') + with pytest.raises(ValueError, match=msg): merge(df, df2, right_on='b', left_index=True) def test_join_on_fails_with_different_column_counts(self): - with pytest.raises(ValueError): - df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), - 'b': np.random.randn(3)}) - df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), - 'b': np.random.randn(10)}, - index=tm.makeCustomIndex(10, 2)) + df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), + 'b': np.random.randn(3)}) + df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), + 'b': np.random.randn(10)}, + index=tm.makeCustomIndex(10, 2)) + msg = r"len\(right_on\) must equal len\(left_on\)" + with pytest.raises(ValueError, match=msg): merge(df, df2, right_on='a', left_on=['a', 'b']) @pytest.mark.parametrize("wrong_type", [2, 'str', None, np.array([0, 1])]) @@ -237,9 +246,11 @@ def test_join_on_fails_with_wrong_object_type(self, wrong_type): # Edited test to remove the Series object from test parameters df = DataFrame({'a': [1, 1]}) - with pytest.raises(TypeError, match=str(type(wrong_type))): + msg = ("Can only merge Series or DataFrame objects, a {} was passed" + .format(str(type(wrong_type)))) + with pytest.raises(TypeError, match=msg): merge(wrong_type, df, left_on='a', right_on='a') - with pytest.raises(TypeError, match=str(type(wrong_type))): + with pytest.raises(TypeError, match=msg): merge(df, wrong_type, left_on='a', right_on='a') def test_join_on_pass_vector(self): @@ -603,7 +614,9 @@ def _check_diff_index(df_list, result, exp_index): joined = df_list[0].join(df_list[1:], how='inner') _check_diff_index(df_list, joined, df.index[2:8]) - pytest.raises(ValueError, df_list[0].join, df_list[1:], on='a') + msg = "Joining multiple DataFrames only supported for joining on index" + with pytest.raises(ValueError, match=msg): + df_list[0].join(df_list[1:], on='a') def test_join_many_mixed(self): df = DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D']) @@ -725,10 +738,13 @@ def test_panel_join_many(self): tm.assert_panel_equal(joined, expected) # edge cases - pytest.raises(ValueError, panels[0].join, panels[1:], - how='outer', lsuffix='foo', rsuffix='bar') - pytest.raises(ValueError, panels[0].join, panels[1:], - how='right') + msg = "Suffixes not supported when passing multiple panels" + with pytest.raises(ValueError, match=msg): + panels[0].join(panels[1:], how='outer', lsuffix='foo', + rsuffix='bar') + msg = "Right join not supported with multiple panels" + with pytest.raises(ValueError, match=msg): + panels[0].join(panels[1:], how='right') def test_join_multi_to_multi(self, join_type): # GH 20475 @@ -749,10 +765,12 @@ def test_join_multi_to_multi(self, join_type): ) assert_frame_equal(expected, result) - with pytest.raises(ValueError): + msg = (r'len\(left_on\) must equal the number of levels in the index' + ' of "right"') + with pytest.raises(ValueError, match=msg): left.join(right, on='xy', how=join_type) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): right.join(left, on=['abc', 'xy'], how=join_type) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 2080fc542bc61..1d7c42b7328d0 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -119,25 +119,37 @@ def test_merge_index_singlekey_inner(self): assert_frame_equal(result, expected.loc[:, result.columns]) def test_merge_misspecified(self): - pytest.raises(ValueError, merge, self.left, self.right, - left_index=True) - pytest.raises(ValueError, merge, self.left, self.right, - right_index=True) - - pytest.raises(ValueError, merge, self.left, self.left, - left_on='key', on='key') - - pytest.raises(ValueError, merge, self.df, self.df2, - left_on=['key1'], right_on=['key1', 'key2']) + msg = "Must pass right_on or right_index=True" + with pytest.raises(pd.errors.MergeError, match=msg): + merge(self.left, self.right, left_index=True) + msg = "Must pass left_on or left_index=True" + with pytest.raises(pd.errors.MergeError, match=msg): + merge(self.left, self.right, right_index=True) + + msg = ('Can only pass argument "on" OR "left_on" and "right_on", not' + ' a combination of both') + with pytest.raises(pd.errors.MergeError, match=msg): + merge(self.left, self.left, left_on='key', on='key') + + msg = r"len\(right_on\) must equal len\(left_on\)" + with pytest.raises(ValueError, match=msg): + merge(self.df, self.df2, left_on=['key1'], + right_on=['key1', 'key2']) def test_index_and_on_parameters_confusion(self): - pytest.raises(ValueError, merge, self.df, self.df2, how='left', - left_index=False, right_index=['key1', 'key2']) - pytest.raises(ValueError, merge, self.df, self.df2, how='left', - left_index=['key1', 'key2'], right_index=False) - pytest.raises(ValueError, merge, self.df, self.df2, how='left', - left_index=['key1', 'key2'], - right_index=['key1', 'key2']) + msg = ("right_index parameter must be of type bool, not" + r" <(class|type) 'list'>") + with pytest.raises(ValueError, match=msg): + merge(self.df, self.df2, how='left', + left_index=False, right_index=['key1', 'key2']) + msg = ("left_index parameter must be of type bool, not " + r"<(class|type) 'list'>") + with pytest.raises(ValueError, match=msg): + merge(self.df, self.df2, how='left', + left_index=['key1', 'key2'], right_index=False) + with pytest.raises(ValueError, match=msg): + merge(self.df, self.df2, how='left', + left_index=['key1', 'key2'], right_index=['key1', 'key2']) def test_merge_overlap(self): merged = merge(self.left, self.left, on='key') @@ -269,7 +281,6 @@ def test_no_overlap_more_informative_error(self): df1 = DataFrame({'x': ['a']}, index=[dt]) df2 = DataFrame({'y': ['b', 'c']}, index=[dt, dt]) - pytest.raises(MergeError, merge, df1, df2) msg = ('No common columns to perform merge on. ' 'Merge options: left_on={lon}, right_on={ron}, ' @@ -566,7 +577,10 @@ def test_overlapping_columns_error_message(self): # #2649, #10639 df2.columns = ['key1', 'foo', 'foo'] - pytest.raises(ValueError, merge, df, df2) + msg = (r"Data columns not unique: Index\(\[u?'foo', u?'foo'\]," + r" dtype='object'\)") + with pytest.raises(MergeError, match=msg): + merge(df, df2) def test_merge_on_datetime64tz(self): @@ -717,9 +731,10 @@ def test_indicator(self): assert_frame_equal(test_custom_name, df_result_custom_name) # Check only accepts strings and booleans - with pytest.raises(ValueError): + msg = "indicator option can only accept boolean or string arguments" + with pytest.raises(ValueError, match=msg): merge(df1, df2, on='col1', how='outer', indicator=5) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df1.merge(df2, on='col1', how='outer', indicator=5) # Check result integrity @@ -743,20 +758,25 @@ def test_indicator(self): for i in ['_right_indicator', '_left_indicator', '_merge']: df_badcolumn = DataFrame({'col1': [1, 2], i: [2, 2]}) - with pytest.raises(ValueError): + msg = ("Cannot use `indicator=True` option when data contains a" + " column named {}|" + "Cannot use name of an existing column for indicator" + " column").format(i) + with pytest.raises(ValueError, match=msg): merge(df1, df_badcolumn, on='col1', how='outer', indicator=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df1.merge(df_badcolumn, on='col1', how='outer', indicator=True) # Check for name conflict with custom name df_badcolumn = DataFrame( {'col1': [1, 2], 'custom_column_name': [2, 2]}) - with pytest.raises(ValueError): + msg = "Cannot use name of an existing column for indicator column" + with pytest.raises(ValueError, match=msg): merge(df1, df_badcolumn, on='col1', how='outer', indicator='custom_column_name') - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df1.merge(df_badcolumn, on='col1', how='outer', indicator='custom_column_name') @@ -843,11 +863,13 @@ def test_validation(self): merge(left, right_w_dups, left_index=True, right_index=True, validate='one_to_many') - with pytest.raises(MergeError): + msg = ("Merge keys are not unique in right dataset; not a one-to-one" + " merge") + with pytest.raises(MergeError, match=msg): merge(left, right_w_dups, left_index=True, right_index=True, validate='one_to_one') - with pytest.raises(MergeError): + with pytest.raises(MergeError, match=msg): merge(left, right_w_dups, on='a', validate='one_to_one') # Dups on left @@ -856,26 +878,33 @@ def test_validation(self): merge(left_w_dups, right, left_index=True, right_index=True, validate='many_to_one') - with pytest.raises(MergeError): + msg = ("Merge keys are not unique in left dataset; not a one-to-one" + " merge") + with pytest.raises(MergeError, match=msg): merge(left_w_dups, right, left_index=True, right_index=True, validate='one_to_one') - with pytest.raises(MergeError): + with pytest.raises(MergeError, match=msg): merge(left_w_dups, right, on='a', validate='one_to_one') # Dups on both merge(left_w_dups, right_w_dups, on='a', validate='many_to_many') - with pytest.raises(MergeError): + msg = ("Merge keys are not unique in right dataset; not a many-to-one" + " merge") + with pytest.raises(MergeError, match=msg): merge(left_w_dups, right_w_dups, left_index=True, right_index=True, validate='many_to_one') - with pytest.raises(MergeError): + msg = ("Merge keys are not unique in left dataset; not a one-to-many" + " merge") + with pytest.raises(MergeError, match=msg): merge(left_w_dups, right_w_dups, on='a', validate='one_to_many') # Check invalid arguments - with pytest.raises(ValueError): + msg = "Not a valid argument for validate" + with pytest.raises(ValueError, match=msg): merge(left, right, on='a', validate='jibberish') # Two column merge, dups in both, but jointly no dups. @@ -896,7 +925,9 @@ def test_validation(self): 'um... weasel noise?']}, index=range(3)) - with pytest.raises(MergeError): + msg = ("Merge keys are not unique in either left or right dataset;" + " not a one-to-one merge") + with pytest.raises(MergeError, match=msg): merge(left, right, on='a', validate='1:1') result = merge(left, right, on=['a', 'b'], validate='1:1') @@ -1439,6 +1470,7 @@ def test_merge_series(on, left_on, right_on, left_index, right_index, nm): left_index=left_index, right_index=right_index) tm.assert_frame_equal(result, expected) else: - with pytest.raises(ValueError, match='a Series without a name'): + msg = "Cannot merge a Series without a name" + with pytest.raises(ValueError, match=msg): result = pd.merge(a, b, on=on, left_on=left_on, right_on=right_on, left_index=left_index, right_index=right_index) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 7814cbaba4a50..899daf488638a 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -777,7 +777,8 @@ def test_append(self, sort): assert appended is not self.frame # Overlap - with pytest.raises(ValueError): + msg = "Indexes have overlapping values" + with pytest.raises(ValueError, match=msg): self.frame.append(self.frame, verify_integrity=True) # see gh-6129: new columns @@ -960,13 +961,22 @@ def test_append_different_columns_types_raises( df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_can_append) ser = pd.Series([7, 8, 9], index=index_cannot_append_with_other, name=2) - with pytest.raises(TypeError): + msg = ("the other index needs to be an IntervalIndex too, but was" + r" type {}|" + r"object of type '(int|long|float|Timestamp)' has no len\(\)|" + "Expected tuple, got str") + with pytest.raises(TypeError, match=msg.format( + index_can_append.__class__.__name__)): df.append(ser) df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_cannot_append_with_other) ser = pd.Series([7, 8, 9], index=index_can_append, name=2) - with pytest.raises(TypeError): + msg = (r"unorderable types: (Interval|int)\(\) > " + r"(int|long|float|str)\(\)|" + r"Expected tuple, got (int|long|float|str)|" + r"Cannot compare type 'Timestamp' with type '(int|long)'") + with pytest.raises(TypeError, match=msg): df.append(ser) def test_append_dtype_coerce(self, sort): @@ -1291,11 +1301,15 @@ def test_concat_keys_levels_no_overlap(self): df = DataFrame(np.random.randn(1, 3), index=['a']) df2 = DataFrame(np.random.randn(1, 4), index=['b']) - pytest.raises(ValueError, concat, [df, df], - keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) + msg = "Values not found in passed level" + with pytest.raises(ValueError, match=msg): + concat([df, df], + keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) - pytest.raises(ValueError, concat, [df, df2], - keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) + msg = "Key one not in level" + with pytest.raises(ValueError, match=msg): + concat([df, df2], + keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) def test_concat_rename_index(self): a = DataFrame(np.random.rand(3, 3), @@ -1488,7 +1502,10 @@ def test_concat_mixed_objs(self): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) panel = tm.makePanel() - pytest.raises(ValueError, lambda: concat([panel, s1], axis=1)) + msg = ("cannot concatenate unaligned mixed dimensional NDFrame" + " objects") + with pytest.raises(ValueError, match=msg): + concat([panel, s1], axis=1) def test_empty_dtype_coerce(self): @@ -1666,7 +1683,8 @@ def test_concat_exclude_none(self): pieces = [df[:5], None, None, df[5:]] result = concat(pieces) tm.assert_frame_equal(result, df) - pytest.raises(ValueError, concat, [None, None]) + with pytest.raises(ValueError, match="All objects passed were None"): + concat([None, None]) def test_concat_datetime64_block(self): from pandas.core.indexes.datetimes import date_range @@ -1799,13 +1817,20 @@ def test_concat_invalid(self): # trying to concat a ndframe with a non-ndframe df1 = mkdf(10, 2) + msg = ('cannot concatenate object of type "{}";' + ' only pd.Series, pd.DataFrame, and pd.Panel' + r' \(deprecated\) objs are valid') for obj in [1, dict(), [1, 2], (1, 2)]: - pytest.raises(TypeError, lambda x: concat([df1, obj])) + with pytest.raises(TypeError, match=msg.format(type(obj))): + concat([df1, obj]) def test_concat_invalid_first_argument(self): df1 = mkdf(10, 2) df2 = mkdf(10, 2) - pytest.raises(TypeError, concat, df1, df2) + msg = ('first argument must be an iterable of pandas ' + 'objects, you passed an object of type "DataFrame"') + with pytest.raises(TypeError, match=msg): + concat(df1, df2) # generator ok though concat(DataFrame(np.random.rand(5, 5)) for _ in range(3)) @@ -2310,7 +2335,9 @@ def test_categorical_index_preserver(self): # wrong catgories df3 = DataFrame({'A': a, 'B': Categorical(b, categories=list('abe')) }).set_index('B') - pytest.raises(TypeError, lambda: pd.concat([df2, df3])) + msg = "categories must match existing categories when appending" + with pytest.raises(TypeError, match=msg): + pd.concat([df2, df3]) def test_concat_categoricalindex(self): # GH 16111, categories that aren't lexsorted diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index 6b633d7e77f52..6bd1958633e25 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -116,9 +116,11 @@ def test_tuple_vars_fail_with_multiindex(self): tuple_b = ('B', 'b') list_b = [tuple_b] + msg = (r"(id|value)_vars must be a list of tuples when columns are" + " a MultiIndex") for id_vars, value_vars in ((tuple_a, list_b), (list_a, tuple_b), (tuple_a, tuple_b)): - with pytest.raises(ValueError, match=r'MultiIndex'): + with pytest.raises(ValueError, match=msg): self.df1.melt(id_vars=id_vars, value_vars=value_vars) def test_custom_var_name(self): @@ -352,7 +354,9 @@ def test_pairs(self): spec = {'visitdt': ['visitdt%d' % i for i in range(1, 3)], 'wt': ['wt%d' % i for i in range(1, 4)]} - pytest.raises(ValueError, lreshape, df, spec) + msg = "All column lists must be same length" + with pytest.raises(ValueError, match=msg): + lreshape(df, spec) class TestWideToLong(object): @@ -603,7 +607,8 @@ def test_non_unique_idvars(self): 'B_B1': [1, 2, 3, 4, 5], 'x': [1, 1, 1, 1, 1] }) - with pytest.raises(ValueError): + msg = "the id variables need to uniquely identify each row" + with pytest.raises(ValueError, match=msg): wide_to_long(df, ['A_A', 'B_B'], i='x', j='colname') def test_cast_j_int(self): @@ -639,7 +644,8 @@ def test_identical_stubnames(self): 'A2011': [3.0, 4.0], 'B2010': [5.0, 6.0], 'A': ['X1', 'X2']}) - with pytest.raises(ValueError): + msg = "stubname can't be identical to a column name" + with pytest.raises(ValueError, match=msg): wide_to_long(df, ['A', 'B'], i='A', j='colname') def test_nonnumeric_suffix(self): diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 7c70f8177d846..e4fbb204af533 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -526,7 +526,7 @@ def test_pivot_with_tuple_of_values(self, method): 'bar': ['A', 'B', 'C', 'A', 'B', 'C'], 'baz': [1, 2, 3, 4, 5, 6], 'zoo': ['x', 'y', 'z', 'q', 'w', 't']}) - with pytest.raises(KeyError): + with pytest.raises(KeyError, match=r"^\('bar', 'baz'\)$"): # tuple is seen as a single column name if method: df.pivot(index='zoo', columns='foo', values=('bar', 'baz')) @@ -742,24 +742,27 @@ def test_margins_no_values_two_row_two_cols(self): index=['A', 'B'], columns=['C', 'D'], aggfunc=len, margins=True) assert result.All.tolist() == [3.0, 1.0, 4.0, 3.0, 11.0] - def test_pivot_table_with_margins_set_margin_name(self): + @pytest.mark.parametrize( + 'margin_name', ['foo', 'one', 666, None, ['a', 'b']]) + def test_pivot_table_with_margins_set_margin_name(self, margin_name): # see gh-3335 - for margin_name in ['foo', 'one', 666, None, ['a', 'b']]: - with pytest.raises(ValueError): - # multi-index index - pivot_table(self.data, values='D', index=['A', 'B'], - columns=['C'], margins=True, - margins_name=margin_name) - with pytest.raises(ValueError): - # multi-index column - pivot_table(self.data, values='D', index=['C'], - columns=['A', 'B'], margins=True, - margins_name=margin_name) - with pytest.raises(ValueError): - # non-multi-index index/column - pivot_table(self.data, values='D', index=['A'], - columns=['B'], margins=True, - margins_name=margin_name) + msg = (r'Conflicting name "{}" in margins|' + "margins_name argument must be a string").format(margin_name) + with pytest.raises(ValueError, match=msg): + # multi-index index + pivot_table(self.data, values='D', index=['A', 'B'], + columns=['C'], margins=True, + margins_name=margin_name) + with pytest.raises(ValueError, match=msg): + # multi-index column + pivot_table(self.data, values='D', index=['C'], + columns=['A', 'B'], margins=True, + margins_name=margin_name) + with pytest.raises(ValueError, match=msg): + # non-multi-index index/column + pivot_table(self.data, values='D', index=['A'], + columns=['B'], margins=True, + margins_name=margin_name) def test_pivot_timegrouper(self): df = DataFrame({ @@ -818,13 +821,14 @@ def test_pivot_timegrouper(self): values='Quantity', aggfunc=np.sum) tm.assert_frame_equal(result, expected.T) - pytest.raises(KeyError, lambda: pivot_table( - df, index=Grouper(freq='6MS', key='foo'), - columns='Buyer', values='Quantity', aggfunc=np.sum)) - pytest.raises(KeyError, lambda: pivot_table( - df, index='Buyer', - columns=Grouper(freq='6MS', key='foo'), - values='Quantity', aggfunc=np.sum)) + msg = "'The grouper name foo is not found'" + with pytest.raises(KeyError, match=msg): + pivot_table(df, index=Grouper(freq='6MS', key='foo'), + columns='Buyer', values='Quantity', aggfunc=np.sum) + with pytest.raises(KeyError, match=msg): + pivot_table(df, index='Buyer', + columns=Grouper(freq='6MS', key='foo'), + values='Quantity', aggfunc=np.sum) # passing the level df = df.set_index('Date') @@ -838,13 +842,14 @@ def test_pivot_timegrouper(self): values='Quantity', aggfunc=np.sum) tm.assert_frame_equal(result, expected.T) - pytest.raises(ValueError, lambda: pivot_table( - df, index=Grouper(freq='6MS', level='foo'), - columns='Buyer', values='Quantity', aggfunc=np.sum)) - pytest.raises(ValueError, lambda: pivot_table( - df, index='Buyer', - columns=Grouper(freq='6MS', level='foo'), - values='Quantity', aggfunc=np.sum)) + msg = "The level foo is not valid" + with pytest.raises(ValueError, match=msg): + pivot_table(df, index=Grouper(freq='6MS', level='foo'), + columns='Buyer', values='Quantity', aggfunc=np.sum) + with pytest.raises(ValueError, match=msg): + pivot_table(df, index='Buyer', + columns=Grouper(freq='6MS', level='foo'), + values='Quantity', aggfunc=np.sum) # double grouper df = DataFrame({ @@ -1279,7 +1284,8 @@ def test_pivot_number_of_levels_larger_than_int32(self): 'ind2': np.arange(2 ** 16), 'count': 0}) - with pytest.raises(ValueError, match='int32 overflow'): + msg = "Unstacked DataFrame is too big, causing int32 overflow" + with pytest.raises(ValueError, match=msg): df.pivot_table(index='ind1', columns='ind2', values='count', aggfunc='count') @@ -1421,8 +1427,9 @@ def test_crosstab_margins_set_margin_name(self): exp_rows = exp_rows.fillna(0).astype(np.int64) tm.assert_series_equal(all_rows, exp_rows) + msg = "margins_name argument must be a string" for margins_name in [666, None, ['a', 'b']]: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): crosstab(a, [b, c], rownames=['a'], colnames=('b', 'c'), margins=True, margins_name=margins_name)