Skip to content

Commit befc7ea

Browse files
authored
TST: Use pytest or assert_produces_warnings instead of catch_warnings (#54390)
* TST: Use pytest or assert_produces_warnings instead of catch_warnings * Full path * Simplfy message * Fix some runtimewarnings showing up * Don't recommend catch_warnings
1 parent 315797c commit befc7ea

35 files changed

+545
-753
lines changed

doc/source/development/contributing_codebase.rst

-10
Original file line numberDiff line numberDiff line change
@@ -576,16 +576,6 @@ ignore the error.
576576
def test_thing(self):
577577
pass
578578
579-
If you need finer-grained control, you can use Python's
580-
`warnings module <https://docs.python.org/3/library/warnings.html>`__
581-
to control whether a warning is ignored or raised at different places within
582-
a single test.
583-
584-
.. code-block:: python
585-
586-
with warnings.catch_warnings():
587-
warnings.simplefilter("ignore", FutureWarning)
588-
589579
Testing an exception
590580
^^^^^^^^^^^^^^^^^^^^
591581

pandas/tests/apply/test_frame_apply.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ def test_apply_mixed_dtype_corner_indexing():
293293
tm.assert_series_equal(result, expected)
294294

295295

296+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
296297
@pytest.mark.parametrize("ax", ["index", "columns"])
297298
@pytest.mark.parametrize(
298299
"func", [lambda x: x, lambda x: x.mean()], ids=["identity", "mean"]
@@ -303,9 +304,7 @@ def test_apply_empty_infer_type(ax, func, raw, axis):
303304
df = DataFrame(**{ax: ["a", "b", "c"]})
304305

305306
with np.errstate(all="ignore"):
306-
with warnings.catch_warnings(record=True):
307-
warnings.simplefilter("ignore", RuntimeWarning)
308-
test_res = func(np.array([], dtype="f8"))
307+
test_res = func(np.array([], dtype="f8"))
309308
is_reduction = not isinstance(test_res, np.ndarray)
310309

311310
result = df.apply(func, axis=axis, raw=raw)

pandas/tests/apply/test_invalid_arg.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
from itertools import chain
1010
import re
11-
import warnings
1211

1312
import numpy as np
1413
import pytest
@@ -298,6 +297,7 @@ def test_transform_and_agg_err_agg(axis, float_frame):
298297
float_frame.agg(["max", "sqrt"], axis=axis)
299298

300299

300+
@pytest.mark.filterwarnings("ignore::FutureWarning") # GH53325
301301
@pytest.mark.parametrize(
302302
"func, msg",
303303
[
@@ -312,10 +312,7 @@ def test_transform_and_agg_err_series(string_series, func, msg):
312312
# we are trying to transform with an aggregator
313313
with pytest.raises(ValueError, match=msg):
314314
with np.errstate(all="ignore"):
315-
# GH53325
316-
with warnings.catch_warnings():
317-
warnings.simplefilter("ignore", FutureWarning)
318-
string_series.agg(func)
315+
string_series.agg(func)
319316

320317

321318
@pytest.mark.parametrize("func", [["max", "min"], ["max", "sqrt"]])

pandas/tests/arithmetic/test_datetime64.py

+22-27
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
starmap,
1212
)
1313
import operator
14-
import warnings
1514

1615
import numpy as np
1716
import pytest
@@ -1166,6 +1165,7 @@ def test_dt64arr_add_sub_parr(
11661165
)
11671166
assert_invalid_addsub_type(dtarr, parr, msg)
11681167

1168+
@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
11691169
def test_dt64arr_addsub_time_objects_raises(self, box_with_array, tz_naive_fixture):
11701170
# https://github.com/pandas-dev/pandas/issues/10329
11711171

@@ -1183,14 +1183,10 @@ def test_dt64arr_addsub_time_objects_raises(self, box_with_array, tz_naive_fixtu
11831183
"cannot subtract DatetimeArray from ndarray",
11841184
]
11851185
)
1186-
1187-
with warnings.catch_warnings(record=True):
1188-
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
1189-
# applied to Series or DatetimeIndex
1190-
# we aren't testing that here, so ignore.
1191-
warnings.simplefilter("ignore", PerformanceWarning)
1192-
1193-
assert_invalid_addsub_type(obj1, obj2, msg=msg)
1186+
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
1187+
# applied to Series or DatetimeIndex
1188+
# we aren't testing that here, so ignore.
1189+
assert_invalid_addsub_type(obj1, obj2, msg=msg)
11941190

11951191
# -------------------------------------------------------------
11961192
# Other invalid operations
@@ -1370,6 +1366,7 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array):
13701366

13711367
# TODO: redundant with test_dt64arr_add_sub_DateOffset? that includes
13721368
# tz-aware cases which this does not
1369+
@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
13731370
@pytest.mark.parametrize(
13741371
"cls_and_kwargs",
13751372
[
@@ -1458,28 +1455,26 @@ def test_dt64arr_add_sub_DateOffsets(
14581455

14591456
offset_cls = getattr(pd.offsets, cls_name)
14601457

1461-
with warnings.catch_warnings(record=True):
1462-
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
1463-
# applied to Series or DatetimeIndex
1464-
# we aren't testing that here, so ignore.
1465-
warnings.simplefilter("ignore", PerformanceWarning)
1458+
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
1459+
# applied to Series or DatetimeIndex
1460+
# we aren't testing that here, so ignore.
14661461

1467-
offset = offset_cls(n, normalize=normalize, **kwargs)
1462+
offset = offset_cls(n, normalize=normalize, **kwargs)
14681463

1469-
expected = DatetimeIndex([x + offset for x in vec_items])
1470-
expected = tm.box_expected(expected, box_with_array)
1471-
tm.assert_equal(expected, vec + offset)
1464+
expected = DatetimeIndex([x + offset for x in vec_items])
1465+
expected = tm.box_expected(expected, box_with_array)
1466+
tm.assert_equal(expected, vec + offset)
14721467

1473-
expected = DatetimeIndex([x - offset for x in vec_items])
1474-
expected = tm.box_expected(expected, box_with_array)
1475-
tm.assert_equal(expected, vec - offset)
1468+
expected = DatetimeIndex([x - offset for x in vec_items])
1469+
expected = tm.box_expected(expected, box_with_array)
1470+
tm.assert_equal(expected, vec - offset)
14761471

1477-
expected = DatetimeIndex([offset + x for x in vec_items])
1478-
expected = tm.box_expected(expected, box_with_array)
1479-
tm.assert_equal(expected, offset + vec)
1480-
msg = "(bad|unsupported) operand type for unary"
1481-
with pytest.raises(TypeError, match=msg):
1482-
offset - vec
1472+
expected = DatetimeIndex([offset + x for x in vec_items])
1473+
expected = tm.box_expected(expected, box_with_array)
1474+
tm.assert_equal(expected, offset + vec)
1475+
msg = "(bad|unsupported) operand type for unary"
1476+
with pytest.raises(TypeError, match=msg):
1477+
offset - vec
14831478

14841479
def test_dt64arr_add_sub_DateOffset(self, box_with_array):
14851480
# GH#10699

pandas/tests/arrays/categorical/test_operators.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import warnings
2-
31
import numpy as np
42
import pytest
53

@@ -210,6 +208,7 @@ def test_comparison_with_tuple(self):
210208
result = cat != (0, 1)
211209
tm.assert_numpy_array_equal(result, ~expected)
212210

211+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
213212
def test_comparison_of_ordered_categorical_with_nan_to_scalar(
214213
self, compare_operators_no_eq_ne
215214
):
@@ -220,12 +219,11 @@ def test_comparison_of_ordered_categorical_with_nan_to_scalar(
220219

221220
cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
222221
scalar = 2
223-
with warnings.catch_warnings():
224-
warnings.simplefilter("ignore", RuntimeWarning)
225-
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)
222+
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)
226223
actual = getattr(cat, compare_operators_no_eq_ne)(scalar)
227224
tm.assert_numpy_array_equal(actual, expected)
228225

226+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
229227
def test_comparison_of_ordered_categorical_with_nan_to_listlike(
230228
self, compare_operators_no_eq_ne
231229
):
@@ -235,9 +233,7 @@ def test_comparison_of_ordered_categorical_with_nan_to_listlike(
235233

236234
cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
237235
other = Categorical([2, 2, 2, 2], categories=[1, 2, 3], ordered=True)
238-
with warnings.catch_warnings():
239-
warnings.simplefilter("ignore", RuntimeWarning)
240-
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
236+
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
241237
actual = getattr(cat, compare_operators_no_eq_ne)(other)
242238
tm.assert_numpy_array_equal(actual, expected)
243239

pandas/tests/arrays/test_datetimelike.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ def period_index(freqstr):
4949
# TODO: non-monotone indexes; NaTs, different start dates
5050
with warnings.catch_warnings():
5151
# suppress deprecation of Period[B]
52-
warnings.simplefilter("ignore")
52+
warnings.filterwarnings(
53+
"ignore", message="Period with BDay freq", category=FutureWarning
54+
)
5355
pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
5456
return pi
5557

0 commit comments

Comments
 (0)