Skip to content

Commit 139228b

Browse files
authored
TST: Avoid bare pytest.raises in multiple files (pandas-dev#32816)
1 parent f76763f commit 139228b

19 files changed

+94
-56
lines changed

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ def _get_axis_number(cls, axis):
354354
return cls._AXIS_NUMBERS[axis]
355355
except KeyError:
356356
pass
357-
raise ValueError(f"No axis named {axis} for object type {cls}")
357+
raise ValueError(f"No axis named {axis} for object type {cls.__name__}")
358358

359359
@classmethod
360360
def _get_axis_name(cls, axis):

pandas/core/ops/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -685,7 +685,8 @@ def to_series(right):
685685

686686
elif right.ndim > 2:
687687
raise ValueError(
688-
f"Unable to coerce to Series/DataFrame, dim must be <= 2: {right.shape}"
688+
"Unable to coerce to Series/DataFrame, "
689+
f"dimension must be <= 2: {right.shape}"
689690
)
690691

691692
elif is_list_like(right) and not isinstance(right, (ABCSeries, ABCDataFrame)):

pandas/tests/frame/methods/test_quantile.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,10 @@ def test_quantile_axis_parameter(self):
100100
result = df.quantile(0.5, axis="columns")
101101
tm.assert_series_equal(result, expected)
102102

103-
msg = "No axis named -1 for object type <class 'pandas.core.frame.DataFrame'>"
103+
msg = "No axis named -1 for object type DataFrame"
104104
with pytest.raises(ValueError, match=msg):
105105
df.quantile(0.1, axis=-1)
106-
msg = (
107-
"No axis named column for object type "
108-
"<class 'pandas.core.frame.DataFrame'>"
109-
)
106+
msg = "No axis named column for object type DataFrame"
110107
with pytest.raises(ValueError, match=msg):
111108
df.quantile(0.1, axis="column")
112109

pandas/tests/frame/methods/test_sort_values.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def test_sort_values(self):
4343
sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False])
4444
tm.assert_frame_equal(sorted_df, expected)
4545

46-
msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>"
46+
msg = "No axis named 2 for object type DataFrame"
4747
with pytest.raises(ValueError, match=msg):
4848
frame.sort_values(by=["A", "B"], axis=2, inplace=True)
4949

pandas/tests/frame/test_analytics.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -919,7 +919,7 @@ def test_idxmin(self, float_frame, int_frame):
919919
expected = df.apply(Series.idxmin, axis=axis, skipna=skipna)
920920
tm.assert_series_equal(result, expected)
921921

922-
msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>"
922+
msg = "No axis named 2 for object type DataFrame"
923923
with pytest.raises(ValueError, match=msg):
924924
frame.idxmin(axis=2)
925925

@@ -934,7 +934,7 @@ def test_idxmax(self, float_frame, int_frame):
934934
expected = df.apply(Series.idxmax, axis=axis, skipna=skipna)
935935
tm.assert_series_equal(result, expected)
936936

937-
msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>"
937+
msg = "No axis named 2 for object type DataFrame"
938938
with pytest.raises(ValueError, match=msg):
939939
frame.idxmax(axis=2)
940940

pandas/tests/frame/test_api.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -371,10 +371,7 @@ def test_swapaxes(self):
371371
tm.assert_frame_equal(df.T, df.swapaxes(0, 1))
372372
tm.assert_frame_equal(df.T, df.swapaxes(1, 0))
373373
tm.assert_frame_equal(df, df.swapaxes(0, 0))
374-
msg = (
375-
"No axis named 2 for object type "
376-
r"<class 'pandas.core(.sparse)?.frame.(Sparse)?DataFrame'>"
377-
)
374+
msg = "No axis named 2 for object type DataFrame"
378375
with pytest.raises(ValueError, match=msg):
379376
df.swapaxes(2, 5)
380377

pandas/tests/frame/test_apply.py

+19-9
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ def test_apply(self, float_frame):
4949

5050
# invalid axis
5151
df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"])
52-
with pytest.raises(ValueError):
52+
msg = "No axis named 2 for object type DataFrame"
53+
with pytest.raises(ValueError, match=msg):
5354
df.apply(lambda x: x, 2)
5455

5556
# GH 9573
@@ -221,18 +222,20 @@ def test_apply_broadcast_error(self, int_frame_const_col):
221222
df = int_frame_const_col
222223

223224
# > 1 ndim
224-
with pytest.raises(ValueError):
225+
msg = "too many dims to broadcast"
226+
with pytest.raises(ValueError, match=msg):
225227
df.apply(
226228
lambda x: np.array([1, 2]).reshape(-1, 2),
227229
axis=1,
228230
result_type="broadcast",
229231
)
230232

231233
# cannot broadcast
232-
with pytest.raises(ValueError):
234+
msg = "cannot broadcast result"
235+
with pytest.raises(ValueError, match=msg):
233236
df.apply(lambda x: [1, 2], axis=1, result_type="broadcast")
234237

235-
with pytest.raises(ValueError):
238+
with pytest.raises(ValueError, match=msg):
236239
df.apply(lambda x: Series([1, 2]), axis=1, result_type="broadcast")
237240

238241
def test_apply_raw(self, float_frame, mixed_type_frame):
@@ -950,7 +953,11 @@ def test_result_type_error(self, result_type, int_frame_const_col):
950953
# allowed result_type
951954
df = int_frame_const_col
952955

953-
with pytest.raises(ValueError):
956+
msg = (
957+
"invalid value for result_type, must be one of "
958+
"{None, 'reduce', 'broadcast', 'expand'}"
959+
)
960+
with pytest.raises(ValueError, match=msg):
954961
df.apply(lambda x: [1, 2, 3], axis=1, result_type=result_type)
955962

956963
@pytest.mark.parametrize(
@@ -1046,14 +1053,16 @@ def test_agg_transform(self, axis, float_frame):
10461053

10471054
def test_transform_and_agg_err(self, axis, float_frame):
10481055
# cannot both transform and agg
1049-
with pytest.raises(ValueError):
1056+
msg = "transforms cannot produce aggregated results"
1057+
with pytest.raises(ValueError, match=msg):
10501058
float_frame.transform(["max", "min"], axis=axis)
10511059

1052-
with pytest.raises(ValueError):
1060+
msg = "cannot combine transform and aggregation operations"
1061+
with pytest.raises(ValueError, match=msg):
10531062
with np.errstate(all="ignore"):
10541063
float_frame.agg(["max", "sqrt"], axis=axis)
10551064

1056-
with pytest.raises(ValueError):
1065+
with pytest.raises(ValueError, match=msg):
10571066
with np.errstate(all="ignore"):
10581067
float_frame.transform(["max", "sqrt"], axis=axis)
10591068

@@ -1387,7 +1396,8 @@ def test_agg_cython_table_transform(self, df, func, expected, axis):
13871396
)
13881397
def test_agg_cython_table_raises(self, df, func, expected, axis):
13891398
# GH 21224
1390-
with pytest.raises(expected):
1399+
msg = "can't multiply sequence by non-int of type 'str'"
1400+
with pytest.raises(expected, match=msg):
13911401
df.agg(func, axis=axis)
13921402

13931403
@pytest.mark.parametrize("num_cols", [2, 3, 5])

pandas/tests/frame/test_arithmetic.py

+14-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from collections import deque
22
from datetime import datetime
33
import operator
4+
import re
45

56
import numpy as np
67
import pytest
@@ -46,13 +47,16 @@ def check(df, df2):
4647
)
4748
tm.assert_frame_equal(result, expected)
4849

49-
with pytest.raises(TypeError):
50+
msg = re.escape(
51+
"Invalid comparison between dtype=datetime64[ns] and ndarray"
52+
)
53+
with pytest.raises(TypeError, match=msg):
5054
x >= y
51-
with pytest.raises(TypeError):
55+
with pytest.raises(TypeError, match=msg):
5256
x > y
53-
with pytest.raises(TypeError):
57+
with pytest.raises(TypeError, match=msg):
5458
x < y
55-
with pytest.raises(TypeError):
59+
with pytest.raises(TypeError, match=msg):
5660
x <= y
5761

5862
# GH4968
@@ -98,9 +102,13 @@ def test_timestamp_compare(self):
98102
result = right_f(pd.Timestamp("20010109"), df)
99103
tm.assert_frame_equal(result, expected)
100104
else:
101-
with pytest.raises(TypeError):
105+
msg = (
106+
"'(<|>)=?' not supported between "
107+
"instances of 'Timestamp' and 'float'"
108+
)
109+
with pytest.raises(TypeError, match=msg):
102110
left_f(df, pd.Timestamp("20010109"))
103-
with pytest.raises(TypeError):
111+
with pytest.raises(TypeError, match=msg):
104112
right_f(pd.Timestamp("20010109"), df)
105113
# nats
106114
expected = left_f(df, pd.Timestamp("nat"))

pandas/tests/frame/test_axis_select_reindex.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -173,13 +173,15 @@ def test_drop_api_equivalence(self):
173173
res2 = df.drop(index=["a"], columns=["d"])
174174
tm.assert_frame_equal(res1, res2)
175175

176-
with pytest.raises(ValueError):
176+
msg = "Cannot specify both 'labels' and 'index'/'columns'"
177+
with pytest.raises(ValueError, match=msg):
177178
df.drop(labels="a", index="b")
178179

179-
with pytest.raises(ValueError):
180+
with pytest.raises(ValueError, match=msg):
180181
df.drop(labels="a", columns="b")
181182

182-
with pytest.raises(ValueError):
183+
msg = "Need to specify at least one of 'labels', 'index' or 'columns'"
184+
with pytest.raises(ValueError, match=msg):
183185
df.drop(axis=1)
184186

185187
def test_merge_join_different_levels(self):
@@ -616,7 +618,8 @@ def test_align_float(self, float_frame):
616618
tm.assert_index_equal(bf.index, Index([]))
617619

618620
# Try to align DataFrame to Series along bad axis
619-
with pytest.raises(ValueError):
621+
msg = "No axis named 2 for object type DataFrame"
622+
with pytest.raises(ValueError, match=msg):
620623
float_frame.align(af.iloc[0, :3], join="inner", axis=2)
621624

622625
# align dataframe to series with broadcast or not

pandas/tests/frame/test_constructors.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from datetime import date, datetime, timedelta
33
import functools
44
import itertools
5+
import re
56

67
import numpy as np
78
import numpy.ma as ma
@@ -1401,7 +1402,8 @@ def test_constructor_list_of_dataclasses_error_thrown(self):
14011402
Point = make_dataclass("Point", [("x", int), ("y", int)])
14021403

14031404
# expect TypeError
1404-
with pytest.raises(TypeError):
1405+
msg = "asdict() should be called on dataclass instances"
1406+
with pytest.raises(TypeError, match=re.escape(msg)):
14051407
DataFrame([Point(0, 0), {"x": 1, "y": 0}])
14061408

14071409
def test_constructor_list_of_dict_order(self):

pandas/tests/frame/test_dtypes.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from collections import OrderedDict
22
from datetime import timedelta
3+
import re
34

45
import numpy as np
56
import pytest
@@ -636,7 +637,11 @@ def test_arg_for_errors_in_astype(self):
636637

637638
df = DataFrame([1, 2, 3])
638639

639-
with pytest.raises(ValueError):
640+
msg = (
641+
"Expected value of kwarg 'errors' to be one of "
642+
"['raise', 'ignore']. Supplied value is 'True'"
643+
)
644+
with pytest.raises(ValueError, match=re.escape(msg)):
640645
df.astype(np.float64, errors=True)
641646

642647
df.astype(np.int8, errors="ignore")

pandas/tests/frame/test_missing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def test_dropna(self):
114114
tm.assert_frame_equal(dropped, expected)
115115

116116
# bad input
117-
msg = "No axis named 3 for object type <class 'pandas.core.frame.DataFrame'>"
117+
msg = "No axis named 3 for object type DataFrame"
118118
with pytest.raises(ValueError, match=msg):
119119
df.dropna(axis=3)
120120

pandas/tests/frame/test_operators.py

+26-10
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from decimal import Decimal
22
import operator
3+
import re
34

45
import numpy as np
56
import pytest
@@ -51,9 +52,13 @@ def test_neg_object(self, df, expected):
5152
],
5253
)
5354
def test_neg_raises(self, df):
54-
with pytest.raises(TypeError):
55+
msg = (
56+
"bad operand type for unary -: 'str'|"
57+
r"Unary negative expects numeric dtype, not datetime64\[ns\]"
58+
)
59+
with pytest.raises(TypeError, match=msg):
5560
(-df)
56-
with pytest.raises(TypeError):
61+
with pytest.raises(TypeError, match=msg):
5762
(-df["a"])
5863

5964
def test_invert(self, float_frame):
@@ -116,9 +121,10 @@ def test_pos_object(self, df):
116121
"df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})]
117122
)
118123
def test_pos_raises(self, df):
119-
with pytest.raises(TypeError):
124+
msg = re.escape("Unary plus expects numeric dtype, not datetime64[ns]")
125+
with pytest.raises(TypeError, match=msg):
120126
(+df)
121-
with pytest.raises(TypeError):
127+
with pytest.raises(TypeError, match=msg):
122128
(+df["a"])
123129

124130

@@ -173,12 +179,14 @@ def test_logical_ops_invalid(self):
173179

174180
df1 = DataFrame(1.0, index=[1], columns=["A"])
175181
df2 = DataFrame(True, index=[1], columns=["A"])
176-
with pytest.raises(TypeError):
182+
msg = re.escape("unsupported operand type(s) for |: 'float' and 'bool'")
183+
with pytest.raises(TypeError, match=msg):
177184
df1 | df2
178185

179186
df1 = DataFrame("foo", index=[1], columns=["A"])
180187
df2 = DataFrame(True, index=[1], columns=["A"])
181-
with pytest.raises(TypeError):
188+
msg = re.escape("unsupported operand type(s) for |: 'str' and 'bool'")
189+
with pytest.raises(TypeError, match=msg):
182190
df1 | df2
183191

184192
def test_logical_operators(self):
@@ -565,7 +573,11 @@ def test_comp(func):
565573
result = func(df1, df2)
566574
tm.assert_numpy_array_equal(result.values, func(df1.values, df2.values))
567575

568-
with pytest.raises(ValueError, match="dim must be <= 2"):
576+
msg = (
577+
"Unable to coerce to Series/DataFrame, "
578+
"dimension must be <= 2: (30, 4, 1, 1, 1)"
579+
)
580+
with pytest.raises(ValueError, match=re.escape(msg)):
569581
func(df1, ndim_5)
570582

571583
result2 = func(simple_frame, row)
@@ -594,7 +606,8 @@ def test_strings_to_numbers_comparisons_raises(self, compare_operators_no_eq_ne)
594606
)
595607

596608
f = getattr(operator, compare_operators_no_eq_ne)
597-
with pytest.raises(TypeError):
609+
msg = "'[<>]=?' not supported between instances of 'str' and 'int'"
610+
with pytest.raises(TypeError, match=msg):
598611
f(df, 0)
599612

600613
def test_comparison_protected_from_errstate(self):
@@ -881,9 +894,12 @@ def test_alignment_non_pandas(self):
881894
align(df, val, "columns")
882895

883896
val = np.zeros((3, 3, 3))
884-
with pytest.raises(ValueError):
897+
msg = re.escape(
898+
"Unable to coerce to Series/DataFrame, dimension must be <= 2: (3, 3, 3)"
899+
)
900+
with pytest.raises(ValueError, match=msg):
885901
align(df, val, "index")
886-
with pytest.raises(ValueError):
902+
with pytest.raises(ValueError, match=msg):
887903
align(df, val, "columns")
888904

889905
def test_no_warning(self, all_arithmetic_operators):

pandas/tests/frame/test_reshape.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -695,10 +695,11 @@ def test_unstack_dtypes(self):
695695
def test_unstack_non_unique_index_names(self):
696696
idx = MultiIndex.from_tuples([("a", "b"), ("c", "d")], names=["c1", "c1"])
697697
df = DataFrame([1, 2], index=idx)
698-
with pytest.raises(ValueError):
698+
msg = "The name c1 occurs multiple times, use a level number"
699+
with pytest.raises(ValueError, match=msg):
699700
df.unstack("c1")
700701

701-
with pytest.raises(ValueError):
702+
with pytest.raises(ValueError, match=msg):
702703
df.T.stack("c1")
703704

704705
def test_unstack_unused_levels(self):

pandas/tests/generic/test_generic.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -692,10 +692,10 @@ def test_squeeze(self):
692692
tm.assert_series_equal(df.squeeze(axis=1), df.iloc[:, 0])
693693
tm.assert_series_equal(df.squeeze(axis="columns"), df.iloc[:, 0])
694694
assert df.squeeze() == df.iloc[0, 0]
695-
msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>"
695+
msg = "No axis named 2 for object type DataFrame"
696696
with pytest.raises(ValueError, match=msg):
697697
df.squeeze(axis=2)
698-
msg = "No axis named x for object type <class 'pandas.core.frame.DataFrame'>"
698+
msg = "No axis named x for object type DataFrame"
699699
with pytest.raises(ValueError, match=msg):
700700
df.squeeze(axis="x")
701701

pandas/tests/series/methods/test_between_time.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,6 @@ def test_between_time_axis(self):
139139

140140
assert len(ts.between_time(stime, etime)) == expected_length
141141
assert len(ts.between_time(stime, etime, axis=0)) == expected_length
142-
msg = "No axis named 1 for object type <class 'pandas.core.series.Series'>"
142+
msg = "No axis named 1 for object type Series"
143143
with pytest.raises(ValueError, match=msg):
144144
ts.between_time(stime, etime, axis=1)

0 commit comments

Comments
 (0)