Skip to content

Commit ba60432

Browse files
authored
TST: Added match argument for most uses of tm.assert_produces_warning (#58396)
* Fix for all FutureWarnings * Add match for most warnings * Cleaner code --------- Co-authored-by: Abdulaziz Aloqeely <[email protected]>
1 parent 9e7565a commit ba60432

39 files changed

+130
-116
lines changed

doc/source/development/contributing_codebase.rst

+3-2
Original file line numberDiff line numberDiff line change
@@ -557,11 +557,12 @@ is being raised, using ``pytest.raises`` instead.
557557
Testing a warning
558558
^^^^^^^^^^^^^^^^^
559559

560-
Use ``tm.assert_produces_warning`` as a context manager to check that a block of code raises a warning.
560+
Use ``tm.assert_produces_warning`` as a context manager to check that a block of code raises a warning
561+
and specify the warning message using the ``match`` argument.
561562

562563
.. code-block:: python
563564
564-
with tm.assert_produces_warning(DeprecationWarning):
565+
with tm.assert_produces_warning(DeprecationWarning, match="the warning message"):
565566
pd.deprecated_function()
566567
567568
If a warning should specifically not happen in a block of code, pass ``False`` into the context manager.

pandas/tests/arrays/sparse/test_constructors.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,13 @@ def test_constructor_warns_when_losing_timezone(self):
9090
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
9191

9292
expected = SparseArray(np.asarray(dti, dtype="datetime64[ns]"))
93-
94-
with tm.assert_produces_warning(UserWarning):
93+
msg = "loses timezone information"
94+
with tm.assert_produces_warning(UserWarning, match=msg):
9595
result = SparseArray(dti)
9696

9797
tm.assert_sp_array_equal(result, expected)
9898

99-
with tm.assert_produces_warning(UserWarning):
99+
with tm.assert_produces_warning(UserWarning, match=msg):
100100
result = SparseArray(pd.Series(dti))
101101

102102
tm.assert_sp_array_equal(result, expected)

pandas/tests/arrays/test_datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -778,7 +778,7 @@ def test_to_period_2d(self, arr1d):
778778
arr2d = arr1d.reshape(1, -1)
779779

780780
warn = None if arr1d.tz is None else UserWarning
781-
with tm.assert_produces_warning(warn):
781+
with tm.assert_produces_warning(warn, match="will drop timezone information"):
782782
result = arr2d.to_period("D")
783783
expected = arr1d.to_period("D").reshape(1, -1)
784784
tm.assert_period_array_equal(result, expected)

pandas/tests/computation/test_eval.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1014,7 +1014,8 @@ def test_performance_warning_for_poor_alignment(
10141014
else:
10151015
seen = False
10161016

1017-
with tm.assert_produces_warning(seen):
1017+
msg = "Alignment difference on axis 1 is larger than an order of magnitude"
1018+
with tm.assert_produces_warning(seen, match=msg):
10181019
pd.eval("df + s", engine=engine, parser=parser)
10191020

10201021
s = Series(np.random.default_rng(2).standard_normal(1000))
@@ -1036,7 +1037,7 @@ def test_performance_warning_for_poor_alignment(
10361037
else:
10371038
wrn = False
10381039

1039-
with tm.assert_produces_warning(wrn) as w:
1040+
with tm.assert_produces_warning(wrn, match=msg) as w:
10401041
pd.eval("df + s", engine=engine, parser=parser)
10411042

10421043
if not is_python_engine and performance_warning:

pandas/tests/dtypes/test_common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -797,5 +797,5 @@ def test_pandas_dtype_numpy_warning():
797797

798798
def test_pandas_dtype_ea_not_instance():
799799
# GH 31356 GH 54592
800-
with tm.assert_produces_warning(UserWarning):
800+
with tm.assert_produces_warning(UserWarning, match="without any arguments"):
801801
assert pandas_dtype(CategoricalDtype) == CategoricalDtype()

pandas/tests/dtypes/test_generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def test_setattr_warnings():
124124
# this should not raise a warning
125125
df.two.not_an_index = [1, 2]
126126

127-
with tm.assert_produces_warning(UserWarning):
127+
with tm.assert_produces_warning(UserWarning, match="doesn't allow columns"):
128128
# warn when setting column to nonexistent name
129129
df.four = df.two + 2
130130
assert df.four.sum() > df.two.sum()

pandas/tests/frame/indexing/test_indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def test_getitem_boolean(self, mixed_float_frame, mixed_int_frame, datetime_fram
145145
# we are producing a warning that since the passed boolean
146146
# key is not the same as the given index, we will reindex
147147
# not sure this is really necessary
148-
with tm.assert_produces_warning(UserWarning):
148+
with tm.assert_produces_warning(UserWarning, match="will be reindexed"):
149149
indexer_obj = indexer_obj.reindex(datetime_frame.index[::-1])
150150
subframe_obj = datetime_frame[indexer_obj]
151151
tm.assert_frame_equal(subframe_obj, subframe)

pandas/tests/frame/indexing/test_setitem.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -711,7 +711,10 @@ def test_setitem_npmatrix_2d(self):
711711
df["np-array"] = a
712712

713713
# Instantiation of `np.matrix` gives PendingDeprecationWarning
714-
with tm.assert_produces_warning(PendingDeprecationWarning):
714+
with tm.assert_produces_warning(
715+
PendingDeprecationWarning,
716+
match="matrix subclass is not the recommended way to represent matrices",
717+
):
715718
df["np-matrix"] = np.matrix(a)
716719

717720
tm.assert_frame_equal(df, expected)

pandas/tests/frame/methods/test_to_dict.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def test_to_dict_not_unique_warning(self):
166166
# GH#16927: When converting to a dict, if a column has a non-unique name
167167
# it will be dropped, throwing a warning.
168168
df = DataFrame([[1, 2, 3]], columns=["a", "a", "b"])
169-
with tm.assert_produces_warning(UserWarning):
169+
with tm.assert_produces_warning(UserWarning, match="columns will be omitted"):
170170
df.to_dict()
171171

172172
@pytest.mark.filterwarnings("ignore::UserWarning")

pandas/tests/frame/test_arithmetic.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -1097,25 +1097,24 @@ def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements):
10971097
and expr.USE_NUMEXPR
10981098
and switch_numexpr_min_elements == 0
10991099
):
1100-
warn = UserWarning # "evaluating in Python space because ..."
1100+
warn = UserWarning
11011101
else:
11021102
msg = (
11031103
f"cannot perform __{op.__name__}__ with this "
11041104
"index type: (DatetimeArray|TimedeltaArray)"
11051105
)
11061106

11071107
with pytest.raises(TypeError, match=msg):
1108-
with tm.assert_produces_warning(warn):
1108+
with tm.assert_produces_warning(warn, match="evaluating in Python"):
11091109
op(df, elem.value)
11101110

11111111
elif (op, dtype) in skip:
11121112
if op in [operator.add, operator.mul]:
11131113
if expr.USE_NUMEXPR and switch_numexpr_min_elements == 0:
1114-
# "evaluating in Python space because ..."
11151114
warn = UserWarning
11161115
else:
11171116
warn = None
1118-
with tm.assert_produces_warning(warn):
1117+
with tm.assert_produces_warning(warn, match="evaluating in Python"):
11191118
op(df, elem.value)
11201119

11211120
else:

pandas/tests/frame/test_reductions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,7 @@ def test_mode_sortwarning(self, using_infer_string):
699699
expected = DataFrame({"A": ["a", np.nan]})
700700

701701
warning = None if using_infer_string else UserWarning
702-
with tm.assert_produces_warning(warning):
702+
with tm.assert_produces_warning(warning, match="Unable to sort modes"):
703703
result = df.mode(dropna=False)
704704
result = result.sort_values(by="A").reset_index(drop=True)
705705

pandas/tests/indexes/base_class/test_setops.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,13 @@ def test_union_sort_other_incomparable(self):
8484
# https://github.com/pandas-dev/pandas/issues/24959
8585
idx = Index([1, pd.Timestamp("2000")])
8686
# default (sort=None)
87-
with tm.assert_produces_warning(RuntimeWarning):
87+
with tm.assert_produces_warning(RuntimeWarning, match="not supported between"):
8888
result = idx.union(idx[:1])
8989

9090
tm.assert_index_equal(result, idx)
9191

9292
# sort=None
93-
with tm.assert_produces_warning(RuntimeWarning):
93+
with tm.assert_produces_warning(RuntimeWarning, match="not supported between"):
9494
result = idx.union(idx[:1], sort=None)
9595
tm.assert_index_equal(result, idx)
9696

pandas/tests/indexes/datetimes/methods/test_to_period.py

+7-13
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,10 @@ def test_to_period_infer(self):
117117
freq="5min",
118118
)
119119

120-
with tm.assert_produces_warning(UserWarning):
120+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
121121
pi1 = rng.to_period("5min")
122122

123-
with tm.assert_produces_warning(UserWarning):
123+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
124124
pi2 = rng.to_period()
125125

126126
tm.assert_index_equal(pi1, pi2)
@@ -143,8 +143,7 @@ def test_to_period_millisecond(self):
143143
]
144144
)
145145

146-
with tm.assert_produces_warning(UserWarning):
147-
# warning that timezone info will be lost
146+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
148147
period = index.to_period(freq="ms")
149148
assert 2 == len(period)
150149
assert period[0] == Period("2007-01-01 10:11:12.123Z", "ms")
@@ -158,8 +157,7 @@ def test_to_period_microsecond(self):
158157
]
159158
)
160159

161-
with tm.assert_produces_warning(UserWarning):
162-
# warning that timezone info will be lost
160+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
163161
period = index.to_period(freq="us")
164162
assert 2 == len(period)
165163
assert period[0] == Period("2007-01-01 10:11:12.123456Z", "us")
@@ -172,19 +170,15 @@ def test_to_period_microsecond(self):
172170
def test_to_period_tz(self, tz):
173171
ts = date_range("1/1/2000", "2/1/2000", tz=tz)
174172

175-
with tm.assert_produces_warning(UserWarning):
176-
# GH#21333 warning that timezone info will be lost
177-
# filter warning about freq deprecation
178-
173+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
179174
result = ts.to_period()[0]
180175
expected = ts[0].to_period(ts.freq)
181176

182177
assert result == expected
183178

184179
expected = date_range("1/1/2000", "2/1/2000").to_period()
185180

186-
with tm.assert_produces_warning(UserWarning):
187-
# GH#21333 warning that timezone info will be lost
181+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
188182
result = ts.to_period(ts.freq)
189183

190184
tm.assert_index_equal(result, expected)
@@ -193,7 +187,7 @@ def test_to_period_tz(self, tz):
193187
def test_to_period_tz_utc_offset_consistency(self, tz):
194188
# GH#22905
195189
ts = date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1")
196-
with tm.assert_produces_warning(UserWarning):
190+
with tm.assert_produces_warning(UserWarning, match="drop timezone info"):
197191
result = ts.to_period()[0]
198192
expected = ts[0].to_period(ts.freq)
199193
assert result == expected

pandas/tests/indexes/multi/test_setops.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ def test_union_sort_other_incomparable():
382382
idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])
383383

384384
# default, sort=None
385-
with tm.assert_produces_warning(RuntimeWarning):
385+
with tm.assert_produces_warning(RuntimeWarning, match="are unorderable"):
386386
result = idx.union(idx[:1])
387387
tm.assert_index_equal(result, idx)
388388

pandas/tests/indexes/test_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1065,10 +1065,10 @@ def test_outer_join_sort(self):
10651065
left_index = Index(np.random.default_rng(2).permutation(15))
10661066
right_index = date_range("2020-01-01", periods=10)
10671067

1068-
with tm.assert_produces_warning(RuntimeWarning):
1068+
with tm.assert_produces_warning(RuntimeWarning, match="not supported between"):
10691069
result = left_index.join(right_index, how="outer")
10701070

1071-
with tm.assert_produces_warning(RuntimeWarning):
1071+
with tm.assert_produces_warning(RuntimeWarning, match="not supported between"):
10721072
expected = left_index.astype(object).union(right_index.astype(object))
10731073

10741074
tm.assert_index_equal(result, expected)

pandas/tests/indexes/test_index_new.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -142,25 +142,18 @@ def test_constructor_infer_nat_dt_like(
142142
data = [ctor]
143143
data.insert(pos, nulls_fixture)
144144

145-
warn = None
146145
if nulls_fixture is NA:
147146
expected = Index([NA, NaT])
148147
mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884")
149148
request.applymarker(mark)
150-
# GH#35942 numpy will emit a DeprecationWarning within the
151-
# assert_index_equal calls. Since we can't do anything
152-
# about it until GH#31884 is fixed, we suppress that warning.
153-
warn = DeprecationWarning
154149

155150
result = Index(data)
156151

157-
with tm.assert_produces_warning(warn):
158-
tm.assert_index_equal(result, expected)
152+
tm.assert_index_equal(result, expected)
159153

160154
result = Index(np.array(data, dtype=object))
161155

162-
with tm.assert_produces_warning(warn):
163-
tm.assert_index_equal(result, expected)
156+
tm.assert_index_equal(result, expected)
164157

165158
@pytest.mark.parametrize("swap_objs", [True, False])
166159
def test_constructor_mixed_nat_objs_infers_object(self, swap_objs):

pandas/tests/indexes/test_setops.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,7 @@ def test_difference_incomparable(self, opname):
882882
b = Index([2, Timestamp("1999"), 1])
883883
op = operator.methodcaller(opname, b)
884884

885-
with tm.assert_produces_warning(RuntimeWarning):
885+
with tm.assert_produces_warning(RuntimeWarning, match="not supported between"):
886886
# sort=None, the default
887887
result = op(a)
888888
expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")])

pandas/tests/internals/test_internals.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -1280,19 +1280,20 @@ def test_interval_can_hold_element(self, dtype, element):
12801280
# `elem` to not have the same length as `arr`
12811281
ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither")
12821282
elem = element(ii2)
1283-
with tm.assert_produces_warning(FutureWarning):
1283+
msg = "Setting an item of incompatible dtype is deprecated"
1284+
with tm.assert_produces_warning(FutureWarning, match=msg):
12841285
self.check_series_setitem(elem, ii, False)
12851286
assert not blk._can_hold_element(elem)
12861287

12871288
ii3 = IntervalIndex.from_breaks([Timestamp(1), Timestamp(3), Timestamp(4)])
12881289
elem = element(ii3)
1289-
with tm.assert_produces_warning(FutureWarning):
1290+
with tm.assert_produces_warning(FutureWarning, match=msg):
12901291
self.check_series_setitem(elem, ii, False)
12911292
assert not blk._can_hold_element(elem)
12921293

12931294
ii4 = IntervalIndex.from_breaks([Timedelta(1), Timedelta(3), Timedelta(4)])
12941295
elem = element(ii4)
1295-
with tm.assert_produces_warning(FutureWarning):
1296+
with tm.assert_produces_warning(FutureWarning, match=msg):
12961297
self.check_series_setitem(elem, ii, False)
12971298
assert not blk._can_hold_element(elem)
12981299

@@ -1312,12 +1313,13 @@ def test_period_can_hold_element(self, element):
13121313
# `elem` to not have the same length as `arr`
13131314
pi2 = pi.asfreq("D")[:-1]
13141315
elem = element(pi2)
1315-
with tm.assert_produces_warning(FutureWarning):
1316+
msg = "Setting an item of incompatible dtype is deprecated"
1317+
with tm.assert_produces_warning(FutureWarning, match=msg):
13161318
self.check_series_setitem(elem, pi, False)
13171319

13181320
dti = pi.to_timestamp("s")[:-1]
13191321
elem = element(dti)
1320-
with tm.assert_produces_warning(FutureWarning):
1322+
with tm.assert_produces_warning(FutureWarning, match=msg):
13211323
self.check_series_setitem(elem, pi, False)
13221324

13231325
def check_can_hold_element(self, obj, elem, inplace: bool):

pandas/tests/io/formats/test_css.py

+15-14
Original file line numberDiff line numberDiff line change
@@ -38,30 +38,31 @@ def test_css_parse_normalisation(name, norm, abnorm):
3838

3939

4040
@pytest.mark.parametrize(
41-
"invalid_css,remainder",
41+
"invalid_css,remainder,msg",
4242
[
4343
# No colon
44-
("hello-world", ""),
45-
("border-style: solid; hello-world", "border-style: solid"),
44+
("hello-world", "", "expected a colon"),
45+
("border-style: solid; hello-world", "border-style: solid", "expected a colon"),
4646
(
4747
"border-style: solid; hello-world; font-weight: bold",
4848
"border-style: solid; font-weight: bold",
49+
"expected a colon",
4950
),
5051
# Unclosed string fail
5152
# Invalid size
52-
("font-size: blah", "font-size: 1em"),
53-
("font-size: 1a2b", "font-size: 1em"),
54-
("font-size: 1e5pt", "font-size: 1em"),
55-
("font-size: 1+6pt", "font-size: 1em"),
56-
("font-size: 1unknownunit", "font-size: 1em"),
57-
("font-size: 10", "font-size: 1em"),
58-
("font-size: 10 pt", "font-size: 1em"),
53+
("font-size: blah", "font-size: 1em", "Unhandled size"),
54+
("font-size: 1a2b", "font-size: 1em", "Unhandled size"),
55+
("font-size: 1e5pt", "font-size: 1em", "Unhandled size"),
56+
("font-size: 1+6pt", "font-size: 1em", "Unhandled size"),
57+
("font-size: 1unknownunit", "font-size: 1em", "Unhandled size"),
58+
("font-size: 10", "font-size: 1em", "Unhandled size"),
59+
("font-size: 10 pt", "font-size: 1em", "Unhandled size"),
5960
# Too many args
60-
("border-top: 1pt solid red green", "border-top: 1pt solid green"),
61+
("border-top: 1pt solid red green", "border-top: 1pt solid green", "Too many"),
6162
],
6263
)
63-
def test_css_parse_invalid(invalid_css, remainder):
64-
with tm.assert_produces_warning(CSSWarning):
64+
def test_css_parse_invalid(invalid_css, remainder, msg):
65+
with tm.assert_produces_warning(CSSWarning, match=msg):
6566
assert_same_resolution(invalid_css, remainder)
6667

6768

@@ -120,7 +121,7 @@ def test_css_side_shorthands(shorthand, expansions):
120121
{top: "1pt", right: "4pt", bottom: "2pt", left: "0pt"},
121122
)
122123

123-
with tm.assert_produces_warning(CSSWarning):
124+
with tm.assert_produces_warning(CSSWarning, match="Could not expand"):
124125
assert_resolves(f"{shorthand}: 1pt 1pt 1pt 1pt 1pt", {})
125126

126127

pandas/tests/io/formats/test_to_excel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ def test_css_to_excel_bad_colors(input_color):
325325
if input_color is not None:
326326
expected["fill"] = {"patternType": "solid"}
327327

328-
with tm.assert_produces_warning(CSSWarning):
328+
with tm.assert_produces_warning(CSSWarning, match="Unhandled color format"):
329329
convert = CSSToExcelConverter()
330330
assert expected == convert(css)
331331

pandas/tests/io/json/test_json_table_schema.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -639,7 +639,7 @@ def test_warns_non_roundtrippable_names(self, idx):
639639
# GH 19130
640640
df = DataFrame(index=idx)
641641
df.index.name = "index"
642-
with tm.assert_produces_warning():
642+
with tm.assert_produces_warning(UserWarning, match="not round-trippable"):
643643
set_default_names(df)
644644

645645
def test_timestamp_in_columns(self):

0 commit comments

Comments
 (0)