Skip to content

Commit 42ef409

Browse files
authored
TST: Avoid bare pytest.raises in mult files (#32906)
1 parent 3439327 commit 42ef409

20 files changed

+107
-58
lines changed

pandas/core/dtypes/common.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,9 @@ def ensure_python_int(value: Union[int, np.integer]) -> int:
188188
TypeError: if the value isn't an int or can't be converted to one.
189189
"""
190190
if not is_scalar(value):
191-
raise TypeError(f"Value needs to be a scalar value, was type {type(value)}")
191+
raise TypeError(
192+
f"Value needs to be a scalar value, was type {type(value).__name__}"
193+
)
192194
try:
193195
new_value = int(value)
194196
assert new_value == value

pandas/tests/groupby/test_groupby.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1765,7 +1765,7 @@ def test_tuple_as_grouping():
17651765
}
17661766
)
17671767

1768-
with pytest.raises(KeyError):
1768+
with pytest.raises(KeyError, match=r"('a', 'b')"):
17691769
df[["a", "b", "c"]].groupby(("a", "b"))
17701770

17711771
result = df.groupby(("a", "b"))["c"].sum()

pandas/tests/groupby/test_timegrouper.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ def test_timegrouper_with_reg_groups(self):
214214
result = df.groupby([pd.Grouper(freq="1M", level=0), "Buyer"]).sum()
215215
tm.assert_frame_equal(result, expected)
216216

217-
with pytest.raises(ValueError):
217+
with pytest.raises(ValueError, match="The level foo is not valid"):
218218
df.groupby([pd.Grouper(freq="1M", level="foo"), "Buyer"]).sum()
219219

220220
# multi names
@@ -235,7 +235,8 @@ def test_timegrouper_with_reg_groups(self):
235235
tm.assert_frame_equal(result, expected)
236236

237237
# error as we have both a level and a name!
238-
with pytest.raises(ValueError):
238+
msg = "The Grouper cannot specify both a key and a level!"
239+
with pytest.raises(ValueError, match=msg):
239240
df.groupby(
240241
[pd.Grouper(freq="1M", key="Date", level="Date"), "Buyer"]
241242
).sum()

pandas/tests/indexes/datetimes/test_to_period.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,8 @@ def test_to_period_tz_utc_offset_consistency(self, tz):
147147

148148
def test_to_period_nofreq(self):
149149
idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"])
150-
with pytest.raises(ValueError):
150+
msg = "You must pass a freq argument as current index has none."
151+
with pytest.raises(ValueError, match=msg):
151152
idx.to_period()
152153

153154
idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="infer")

pandas/tests/indexes/multi/test_compat.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ def test_logical_compat(idx, method):
3737

3838
def test_boolean_context_compat(idx):
3939

40-
with pytest.raises(ValueError):
40+
msg = (
41+
"The truth value of a MultiIndex is ambiguous. "
42+
r"Use a.empty, a.bool\(\), a.item\(\), a.any\(\) or a.all\(\)."
43+
)
44+
with pytest.raises(ValueError, match=msg):
4145
bool(idx)
4246

4347

pandas/tests/indexes/multi/test_duplicates.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -83,12 +83,14 @@ def test_get_unique_index(idx, dropna):
8383
def test_duplicate_multiindex_codes():
8484
# GH 17464
8585
# Make sure that a MultiIndex with duplicate levels throws a ValueError
86-
with pytest.raises(ValueError):
86+
msg = r"Level values must be unique: \[[A', ]+\] on level 0"
87+
with pytest.raises(ValueError, match=msg):
8788
mi = MultiIndex([["A"] * 10, range(10)], [[0] * 10, range(10)])
8889

8990
# And that using set_levels with duplicate levels fails
9091
mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]])
91-
with pytest.raises(ValueError):
92+
msg = r"Level values must be unique: \[[AB', ]+\] on level 0"
93+
with pytest.raises(ValueError, match=msg):
9294
mi.set_levels([["A", "B", "A", "A", "B"], [2, 1, 3, -2, 5]], inplace=True)
9395

9496

pandas/tests/indexes/multi/test_format.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ def test_repr_with_unicode_data():
5858

5959
def test_repr_roundtrip_raises():
6060
mi = MultiIndex.from_product([list("ab"), range(3)], names=["first", "second"])
61-
with pytest.raises(TypeError):
61+
msg = "Must pass both levels and codes"
62+
with pytest.raises(TypeError, match=msg):
6263
eval(repr(mi))
6364

6465

pandas/tests/indexes/multi/test_setops.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,8 @@ def test_difference_sort_incomparable():
209209
# sort=None, the default
210210
# MultiIndex.difference deviates here from other difference
211211
# implementations in not catching the TypeError
212-
with pytest.raises(TypeError):
212+
msg = "'<' not supported between instances of 'Timestamp' and 'int'"
213+
with pytest.raises(TypeError, match=msg):
213214
result = idx.difference(other)
214215

215216
# sort=False

pandas/tests/indexes/period/test_shift.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ def test_shift_corner_cases(self):
6363
# GH#9903
6464
idx = PeriodIndex([], name="xxx", freq="H")
6565

66-
with pytest.raises(TypeError):
66+
msg = "`freq` argument is not supported for PeriodArray._time_shift"
67+
with pytest.raises(TypeError, match=msg):
6768
# period shift doesn't accept freq
6869
idx.shift(1, freq="H")
6970

pandas/tests/indexes/ranges/test_constructors.py

+22-14
Original file line numberDiff line numberDiff line change
@@ -37,28 +37,36 @@ def test_constructor_invalid_args(self):
3737
with pytest.raises(TypeError, match=msg):
3838
RangeIndex(name="Foo")
3939

40-
# invalid args
41-
for i in [
40+
# we don't allow on a bare Index
41+
msg = (
42+
r"Index\(\.\.\.\) must be called with a collection of some "
43+
r"kind, 0 was passed"
44+
)
45+
with pytest.raises(TypeError, match=msg):
46+
Index(0, 1000)
47+
48+
@pytest.mark.parametrize(
49+
"args",
50+
[
4251
Index(["a", "b"]),
4352
Series(["a", "b"]),
4453
np.array(["a", "b"]),
4554
[],
46-
"foo",
47-
datetime(2000, 1, 1, 0, 0),
4855
np.arange(0, 10),
4956
np.array([1]),
5057
[1],
51-
]:
52-
with pytest.raises(TypeError):
53-
RangeIndex(i)
58+
],
59+
)
60+
def test_constructor_additional_invalid_args(self, args):
61+
msg = f"Value needs to be a scalar value, was type {type(args).__name__}"
62+
with pytest.raises(TypeError, match=msg):
63+
RangeIndex(args)
5464

55-
# we don't allow on a bare Index
56-
msg = (
57-
r"Index\(\.\.\.\) must be called with a collection of some "
58-
r"kind, 0 was passed"
59-
)
65+
@pytest.mark.parametrize("args", ["foo", datetime(2000, 1, 1, 0, 0)])
66+
def test_constructor_invalid_args_wrong_type(self, args):
67+
msg = f"Wrong type {type(args)} for value {args}"
6068
with pytest.raises(TypeError, match=msg):
61-
Index(0, 1000)
69+
RangeIndex(args)
6270

6371
def test_constructor_same(self):
6472

@@ -81,7 +89,7 @@ def test_constructor_same(self):
8189

8290
def test_constructor_range(self):
8391

84-
msg = "Value needs to be a scalar value, was type <class 'range'>"
92+
msg = "Value needs to be a scalar value, was type range"
8593
with pytest.raises(TypeError, match=msg):
8694
result = RangeIndex(range(1, 5, 2))
8795

pandas/tests/indexes/ranges/test_range.py

+15-9
Original file line numberDiff line numberDiff line change
@@ -304,14 +304,19 @@ def test_nbytes(self):
304304
i2 = RangeIndex(0, 10)
305305
assert i.nbytes == i2.nbytes
306306

307-
def test_cant_or_shouldnt_cast(self):
308-
# can't
309-
with pytest.raises(TypeError):
310-
RangeIndex("foo", "bar", "baz")
311-
312-
# shouldn't
313-
with pytest.raises(TypeError):
314-
RangeIndex("0", "1", "2")
307+
@pytest.mark.parametrize(
308+
"start,stop,step",
309+
[
310+
# can't
311+
("foo", "bar", "baz"),
312+
# shouldn't
313+
("0", "1", "2"),
314+
],
315+
)
316+
def test_cant_or_shouldnt_cast(self, start, stop, step):
317+
msg = f"Wrong type {type(start)} for value {start}"
318+
with pytest.raises(TypeError, match=msg):
319+
RangeIndex(start, stop, step)
315320

316321
def test_view_index(self):
317322
index = self.create_index()
@@ -350,7 +355,8 @@ def test_take_fill_value(self):
350355
with pytest.raises(ValueError, match=msg):
351356
idx.take(np.array([1, 0, -5]), fill_value=True)
352357

353-
with pytest.raises(IndexError):
358+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
359+
with pytest.raises(IndexError, match=msg):
354360
idx.take(np.array([1, -5]))
355361

356362
def test_repr_roundtrip(self):

pandas/tests/indexes/test_base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2263,7 +2263,8 @@ def test_contains_method_removed(self, indices):
22632263
if isinstance(indices, pd.IntervalIndex):
22642264
indices.contains(1)
22652265
else:
2266-
with pytest.raises(AttributeError):
2266+
msg = f"'{type(indices).__name__}' object has no attribute 'contains'"
2267+
with pytest.raises(AttributeError, match=msg):
22672268
indices.contains(1)
22682269

22692270

pandas/tests/indexes/test_frozen.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ def check_mutable_error(self, *args, **kwargs):
1717
# Pass whatever function you normally would to pytest.raises
1818
# (after the Exception kind).
1919
mutable_regex = re.compile("does not support mutable operations")
20-
with pytest.raises(TypeError):
20+
msg = "'(_s)?re.(SRE_)?Pattern' object is not callable"
21+
with pytest.raises(TypeError, match=msg):
2122
mutable_regex(*args, **kwargs)
2223

2324
def test_no_mutable_funcs(self):

pandas/tests/indexes/test_numeric.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,8 @@ def test_take_fill_value(self):
506506
with pytest.raises(ValueError, match=msg):
507507
idx.take(np.array([1, 0, -5]), fill_value=True)
508508

509-
with pytest.raises(IndexError):
509+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
510+
with pytest.raises(IndexError, match=msg):
510511
idx.take(np.array([1, -5]))
511512

512513

@@ -645,7 +646,8 @@ def test_take_fill_value(self):
645646
with pytest.raises(ValueError, match=msg):
646647
idx.take(np.array([1, 0, -5]), fill_value=True)
647648

648-
with pytest.raises(IndexError):
649+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
650+
with pytest.raises(IndexError, match=msg):
649651
idx.take(np.array([1, -5]))
650652

651653

pandas/tests/indexes/timedeltas/test_constructors.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,11 @@ def test_constructor_coverage(self):
168168
with pytest.raises(TypeError, match=msg):
169169
timedelta_range(start="1 days", periods="foo", freq="D")
170170

171-
with pytest.raises(TypeError):
171+
msg = (
172+
r"TimedeltaIndex\(\) must be called with a collection of some kind,"
173+
" '1 days' was passed"
174+
)
175+
with pytest.raises(TypeError, match=msg):
172176
TimedeltaIndex("1 days")
173177

174178
# generator expression
@@ -220,5 +224,6 @@ def test_constructor_no_precision_raises(self):
220224
pd.Index(["2000"], dtype="timedelta64")
221225

222226
def test_constructor_wrong_precision_raises(self):
223-
with pytest.raises(ValueError):
227+
msg = r"dtype timedelta64\[us\] cannot be converted to timedelta64\[ns\]"
228+
with pytest.raises(ValueError, match=msg):
224229
pd.TimedeltaIndex(["2000"], dtype="timedelta64[us]")

pandas/tests/indexes/timedeltas/test_indexing.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,8 @@ def test_take_fill_value(self):
184184
with pytest.raises(ValueError, match=msg):
185185
idx.take(np.array([1, 0, -5]), fill_value=True)
186186

187-
with pytest.raises(IndexError):
187+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
188+
with pytest.raises(IndexError, match=msg):
188189
idx.take(np.array([1, -5]))
189190

190191

pandas/tests/indexes/timedeltas/test_shift.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,5 +71,5 @@ def test_tdi_shift_nonstandard_freq(self):
7171
def test_shift_no_freq(self):
7272
# GH#19147
7373
tdi = TimedeltaIndex(["1 days 01:00:00", "2 days 01:00:00"], freq=None)
74-
with pytest.raises(NullFrequencyError):
74+
with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"):
7575
tdi.shift(2)

pandas/tests/indexing/multiindex/test_setitem.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,8 @@ def test_multiindex_setitem(self):
137137
tm.assert_frame_equal(df.loc[["bar"]], expected)
138138

139139
# raise because these have differing levels
140-
with pytest.raises(TypeError):
140+
msg = "cannot align on a multi-index with out specifying the join levels"
141+
with pytest.raises(TypeError, match=msg):
141142
df.loc["bar"] *= 2
142143

143144
# from SO
@@ -203,10 +204,14 @@ def test_multiindex_assignment(self):
203204
tm.assert_series_equal(df.loc[4, "c"], exp)
204205

205206
# invalid assignments
206-
with pytest.raises(ValueError):
207+
msg = (
208+
"cannot set using a multi-index selection indexer "
209+
"with a different length than the value"
210+
)
211+
with pytest.raises(ValueError, match=msg):
207212
df.loc[4, "c"] = [0, 1, 2, 3]
208213

209-
with pytest.raises(ValueError):
214+
with pytest.raises(ValueError, match=msg):
210215
df.loc[4, "c"] = [0]
211216

212217
# groupby example

pandas/tests/indexing/multiindex/test_slice.py

+18-12
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,11 @@ def test_per_axis_per_level_getitem(self):
111111
expected = df.iloc[[2, 3]]
112112
tm.assert_frame_equal(result, expected)
113113

114-
with pytest.raises(ValueError):
114+
msg = (
115+
"cannot index with a boolean indexer "
116+
"that is not the same length as the index"
117+
)
118+
with pytest.raises(ValueError, match=msg):
115119
df.loc[(slice(None), np.array([True, False])), :]
116120

117121
# ambiguous notation
@@ -411,7 +415,11 @@ def test_per_axis_per_level_doc_examples(self):
411415
tm.assert_frame_equal(result, expected)
412416

413417
# not sorted
414-
with pytest.raises(UnsortedIndexError):
418+
msg = (
419+
"MultiIndex slicing requires the index to be lexsorted: "
420+
r"slicing on levels \[1\], lexsort depth 1"
421+
)
422+
with pytest.raises(UnsortedIndexError, match=msg):
415423
df.loc["A1", ("a", slice("foo"))]
416424

417425
# GH 16734: not sorted, but no real slicing
@@ -480,14 +488,10 @@ def test_loc_axis_arguments(self):
480488
tm.assert_frame_equal(result, expected)
481489

482490
# invalid axis
483-
with pytest.raises(ValueError):
484-
df.loc(axis=-1)[:, :, ["C1", "C3"]]
485-
486-
with pytest.raises(ValueError):
487-
df.loc(axis=2)[:, :, ["C1", "C3"]]
488-
489-
with pytest.raises(ValueError):
490-
df.loc(axis="foo")[:, :, ["C1", "C3"]]
491+
for i in [-1, 2, "foo"]:
492+
msg = f"No axis named {i} for object type DataFrame"
493+
with pytest.raises(ValueError, match=msg):
494+
df.loc(axis=i)[:, :, ["C1", "C3"]]
491495

492496
def test_loc_axis_single_level_multi_col_indexing_multiindex_col_df(self):
493497

@@ -628,12 +632,14 @@ def test_per_axis_per_level_setitem(self):
628632
# not enough values
629633
df = df_orig.copy()
630634

631-
with pytest.raises(ValueError):
635+
msg = "setting an array element with a sequence."
636+
with pytest.raises(ValueError, match=msg):
632637
df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array(
633638
[[100], [100, 100]], dtype="int64"
634639
)
635640

636-
with pytest.raises(ValueError):
641+
msg = "Must have equal len keys and value when setting with an iterable"
642+
with pytest.raises(ValueError, match=msg):
637643
df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array(
638644
[100, 100, 100, 100], dtype="int64"
639645
)

pandas/tests/indexing/test_coercion.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,8 @@ def test_setitem_index_object(self, val, exp_dtype):
297297

298298
if exp_dtype is IndexError:
299299
temp = obj.copy()
300-
with pytest.raises(exp_dtype):
300+
msg = "index 5 is out of bounds for axis 0 with size 4"
301+
with pytest.raises(exp_dtype, match=msg):
301302
temp[5] = 5
302303
else:
303304
exp_index = pd.Index(list("abcd") + [val])

0 commit comments

Comments
 (0)