Skip to content

Commit 139228b

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

19 files changed

+94
-56
lines changed

pandas/core/generic.py

Lines changed: 1 addition & 1 deletion
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

Lines changed: 2 additions & 1 deletion
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

Lines changed: 2 additions & 5 deletions
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 2 additions & 2 deletions
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

Lines changed: 1 addition & 4 deletions
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

Lines changed: 19 additions & 9 deletions
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

Lines changed: 14 additions & 6 deletions
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

Lines changed: 7 additions & 4 deletions
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

Lines changed: 3 additions & 1 deletion
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):

0 commit comments

Comments
 (0)