@@ -71,7 +71,10 @@ def test_basic(dtype):
7171 assert agged [1 ] == 21
7272
7373 # corner cases
74- pytest .raises (Exception , grouped .aggregate , lambda x : x * 2 )
74+ msg = "Must produce aggregated value"
75+ # exception raised is type Exception
76+ with pytest .raises (Exception , match = msg ):
77+ grouped .aggregate (lambda x : x * 2 )
7578
7679
7780def test_groupby_nonobject_dtype (mframe , df_mixed_floats ):
@@ -330,12 +333,17 @@ def f3(x):
330333 assert_frame_equal (result1 , result2 )
331334
332335 # should fail (not the same number of levels)
333- pytest .raises (AssertionError , df .groupby ('a' ).apply , f2 )
334- pytest .raises (AssertionError , df2 .groupby ('a' ).apply , f2 )
336+ msg = "Cannot concat indices that do not have the same number of levels"
337+ with pytest .raises (AssertionError , match = msg ):
338+ df .groupby ('a' ).apply (f2 )
339+ with pytest .raises (AssertionError , match = msg ):
340+ df2 .groupby ('a' ).apply (f2 )
335341
336342 # should fail (incorrect shape)
337- pytest .raises (AssertionError , df .groupby ('a' ).apply , f3 )
338- pytest .raises (AssertionError , df2 .groupby ('a' ).apply , f3 )
343+ with pytest .raises (AssertionError , match = msg ):
344+ df .groupby ('a' ).apply (f3 )
345+ with pytest .raises (AssertionError , match = msg ):
346+ df2 .groupby ('a' ).apply (f3 )
339347
340348
341349def test_attr_wrapper (ts ):
@@ -356,7 +364,9 @@ def test_attr_wrapper(ts):
356364 expected = grouped .agg (lambda x : x .dtype )
357365
358366 # make sure raises error
359- pytest .raises (AttributeError , getattr , grouped , 'foo' )
367+ msg = "'SeriesGroupBy' object has no attribute 'foo'"
368+ with pytest .raises (AttributeError , match = msg ):
369+ getattr (grouped , 'foo' )
360370
361371
362372def test_frame_groupby (tsframe ):
@@ -664,11 +674,13 @@ def test_groupby_as_index_series_scalar(df):
664674
665675
666676def test_groupby_as_index_corner (df , ts ):
667- pytest .raises (TypeError , ts .groupby , lambda x : x .weekday (),
668- as_index = False )
677+ msg = "as_index=False only valid with DataFrame"
678+ with pytest .raises (TypeError , match = msg ):
679+ ts .groupby (lambda x : x .weekday (), as_index = False )
669680
670- pytest .raises (ValueError , df .groupby , lambda x : x .lower (),
671- as_index = False , axis = 1 )
681+ msg = "as_index=False only valid for axis=0"
682+ with pytest .raises (ValueError , match = msg ):
683+ df .groupby (lambda x : x .lower (), as_index = False , axis = 1 )
672684
673685
674686def test_groupby_multiple_key (df ):
@@ -722,8 +734,11 @@ def test_omit_nuisance(df):
722734
723735 # won't work with axis = 1
724736 grouped = df .groupby ({'A' : 0 , 'C' : 0 , 'D' : 1 , 'E' : 1 }, axis = 1 )
725- result = pytest .raises (TypeError , grouped .agg ,
726- lambda x : x .sum (0 , numeric_only = False ))
737+ msg = (r'\("unsupported operand type\(s\) for \+: '
738+ "'Timestamp' and 'float'\" "
739+ r", u?'occurred at index 0'\)" )
740+ with pytest .raises (TypeError , match = msg ):
741+ grouped .agg (lambda x : x .sum (0 , numeric_only = False ))
727742
728743
729744def test_omit_nuisance_python_multiple (three_group ):
@@ -756,7 +771,9 @@ def test_empty_groups_corner(mframe):
756771
757772def test_nonsense_func ():
758773 df = DataFrame ([0 ])
759- pytest .raises (Exception , df .groupby , lambda x : x + 'foo' )
774+ msg = r"unsupported operand type\(s\) for \+: '(int|long)' and 'str'"
775+ with pytest .raises (TypeError , match = msg ):
776+ df .groupby (lambda x : x + 'foo' )
760777
761778
762779def test_wrap_aggregated_output_multindex (mframe ):
@@ -823,12 +840,22 @@ def test_groupby_level_nonmulti():
823840 result = s .groupby (level = [- 1 ]).sum ()
824841 tm .assert_series_equal (result , expected )
825842
826- pytest .raises (ValueError , s .groupby , level = 1 )
827- pytest .raises (ValueError , s .groupby , level = - 2 )
828- pytest .raises (ValueError , s .groupby , level = [])
829- pytest .raises (ValueError , s .groupby , level = [0 , 0 ])
830- pytest .raises (ValueError , s .groupby , level = [0 , 1 ])
831- pytest .raises (ValueError , s .groupby , level = [1 ])
843+ msg = "level > 0 or level < -1 only valid with MultiIndex"
844+ with pytest .raises (ValueError , match = msg ):
845+ s .groupby (level = 1 )
846+ with pytest .raises (ValueError , match = msg ):
847+ s .groupby (level = - 2 )
848+ msg = "No group keys passed!"
849+ with pytest .raises (ValueError , match = msg ):
850+ s .groupby (level = [])
851+ msg = "multiple levels only valid with MultiIndex"
852+ with pytest .raises (ValueError , match = msg ):
853+ s .groupby (level = [0 , 0 ])
854+ with pytest .raises (ValueError , match = msg ):
855+ s .groupby (level = [0 , 1 ])
856+ msg = "level > 0 or level < -1 only valid with MultiIndex"
857+ with pytest .raises (ValueError , match = msg ):
858+ s .groupby (level = [1 ])
832859
833860
834861def test_groupby_complex ():
@@ -1101,7 +1128,8 @@ def test_groupby_list_infer_array_like(df):
11011128 expected = df .groupby (df ['A' ]).mean ()
11021129 assert_frame_equal (result , expected , check_names = False )
11031130
1104- pytest .raises (Exception , df .groupby , list (df ['A' ][:- 1 ]))
1131+ with pytest .raises (KeyError , match = r"^'foo'$" ):
1132+ df .groupby (list (df ['A' ][:- 1 ]))
11051133
11061134 # pathological case of ambiguity
11071135 df = DataFrame ({'foo' : [0 , 1 ],
@@ -1128,10 +1156,13 @@ def test_groupby_keys_same_size_as_index():
11281156
11291157def test_groupby_one_row ():
11301158 # GH 11741
1159+ msg = r"^'Z'$"
11311160 df1 = pd .DataFrame (np .random .randn (1 , 4 ), columns = list ('ABCD' ))
1132- pytest .raises (KeyError , df1 .groupby , 'Z' )
1161+ with pytest .raises (KeyError , match = msg ):
1162+ df1 .groupby ('Z' )
11331163 df2 = pd .DataFrame (np .random .randn (2 , 4 ), columns = list ('ABCD' ))
1134- pytest .raises (KeyError , df2 .groupby , 'Z' )
1164+ with pytest .raises (KeyError , match = msg ):
1165+ df2 .groupby ('Z' )
11351166
11361167
11371168def test_groupby_nat_exclude ():
@@ -1169,7 +1200,8 @@ def test_groupby_nat_exclude():
11691200 tm .assert_frame_equal (
11701201 grouped .get_group (Timestamp ('2013-02-01' )), df .iloc [[3 , 5 ]])
11711202
1172- pytest .raises (KeyError , grouped .get_group , pd .NaT )
1203+ with pytest .raises (KeyError , match = r"^NaT$" ):
1204+ grouped .get_group (pd .NaT )
11731205
11741206 nan_df = DataFrame ({'nan' : [np .nan , np .nan , np .nan ],
11751207 'nat' : [pd .NaT , pd .NaT , pd .NaT ]})
@@ -1181,8 +1213,10 @@ def test_groupby_nat_exclude():
11811213 assert grouped .groups == {}
11821214 assert grouped .ngroups == 0
11831215 assert grouped .indices == {}
1184- pytest .raises (KeyError , grouped .get_group , np .nan )
1185- pytest .raises (KeyError , grouped .get_group , pd .NaT )
1216+ with pytest .raises (KeyError , match = r"^nan$" ):
1217+ grouped .get_group (np .nan )
1218+ with pytest .raises (KeyError , match = r"^NaT$" ):
1219+ grouped .get_group (pd .NaT )
11861220
11871221
11881222@pytest .mark .filterwarnings ("ignore:\\ nPanel:FutureWarning" )
@@ -1643,7 +1677,7 @@ def test_pivot_table_values_key_error():
16431677 df ['year' ] = df .set_index ('eventDate' ).index .year
16441678 df ['month' ] = df .set_index ('eventDate' ).index .month
16451679
1646- with pytest .raises (KeyError ):
1680+ with pytest .raises (KeyError , match = "'badname'" ):
16471681 df .reset_index ().pivot_table (index = 'year' , columns = 'month' ,
16481682 values = 'badname' , aggfunc = 'count' )
16491683
@@ -1689,7 +1723,7 @@ def test_tuple_correct_keyerror():
16891723 df = pd .DataFrame (1 , index = range (3 ),
16901724 columns = pd .MultiIndex .from_product ([[1 , 2 ],
16911725 [3 , 4 ]]))
1692- with pytest .raises (KeyError , match = " (7, 8) " ):
1726+ with pytest .raises (KeyError , match = r"^\ (7, 8\)$ " ):
16931727 df .groupby ((7 , 8 )).mean ()
16941728
16951729
0 commit comments