Skip to content

TST: Use pytest or assert_produces_warnings instead of catch_warnings #54390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Aug 5, 2023
Merged
10 changes: 0 additions & 10 deletions doc/source/development/contributing_codebase.rst
Original file line number Diff line number Diff line change
Expand Up @@ -576,16 +576,6 @@ ignore the error.
def test_thing(self):
pass

If you need finer-grained control, you can use Python's
`warnings module <https://docs.python.org/3/library/warnings.html>`__
to control whether a warning is ignored or raised at different places within
a single test.

.. code-block:: python

with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)

Testing an exception
^^^^^^^^^^^^^^^^^^^^

Expand Down
5 changes: 2 additions & 3 deletions pandas/tests/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ def test_apply_mixed_dtype_corner_indexing():
tm.assert_series_equal(result, expected)


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

with np.errstate(all="ignore"):
with warnings.catch_warnings(record=True):
warnings.simplefilter("ignore", RuntimeWarning)
test_res = func(np.array([], dtype="f8"))
test_res = func(np.array([], dtype="f8"))
is_reduction = not isinstance(test_res, np.ndarray)

result = df.apply(func, axis=axis, raw=raw)
Expand Down
7 changes: 2 additions & 5 deletions pandas/tests/apply/test_invalid_arg.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

from itertools import chain
import re
import warnings

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


@pytest.mark.filterwarnings("ignore::FutureWarning") # GH53325
@pytest.mark.parametrize(
"func, msg",
[
Expand All @@ -312,10 +312,7 @@ def test_transform_and_agg_err_series(string_series, func, msg):
# we are trying to transform with an aggregator
with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
# GH53325
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
string_series.agg(func)
string_series.agg(func)


@pytest.mark.parametrize("func", [["max", "min"], ["max", "sqrt"]])
Expand Down
49 changes: 22 additions & 27 deletions pandas/tests/arithmetic/test_datetime64.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
starmap,
)
import operator
import warnings

import numpy as np
import pytest
Expand Down Expand Up @@ -1166,6 +1165,7 @@ def test_dt64arr_add_sub_parr(
)
assert_invalid_addsub_type(dtarr, parr, msg)

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

Expand All @@ -1183,14 +1183,10 @@ def test_dt64arr_addsub_time_objects_raises(self, box_with_array, tz_naive_fixtu
"cannot subtract DatetimeArray from ndarray",
]
)

with warnings.catch_warnings(record=True):
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
# applied to Series or DatetimeIndex
# we aren't testing that here, so ignore.
warnings.simplefilter("ignore", PerformanceWarning)

assert_invalid_addsub_type(obj1, obj2, msg=msg)
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
# applied to Series or DatetimeIndex
# we aren't testing that here, so ignore.
assert_invalid_addsub_type(obj1, obj2, msg=msg)

# -------------------------------------------------------------
# Other invalid operations
Expand Down Expand Up @@ -1370,6 +1366,7 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array):

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

offset_cls = getattr(pd.offsets, cls_name)

with warnings.catch_warnings(record=True):
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
# applied to Series or DatetimeIndex
# we aren't testing that here, so ignore.
warnings.simplefilter("ignore", PerformanceWarning)
# pandas.errors.PerformanceWarning: Non-vectorized DateOffset being
# applied to Series or DatetimeIndex
# we aren't testing that here, so ignore.

offset = offset_cls(n, normalize=normalize, **kwargs)
offset = offset_cls(n, normalize=normalize, **kwargs)

expected = DatetimeIndex([x + offset for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, vec + offset)
expected = DatetimeIndex([x + offset for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, vec + offset)

expected = DatetimeIndex([x - offset for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, vec - offset)
expected = DatetimeIndex([x - offset for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, vec - offset)

expected = DatetimeIndex([offset + x for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, offset + vec)
msg = "(bad|unsupported) operand type for unary"
with pytest.raises(TypeError, match=msg):
offset - vec
expected = DatetimeIndex([offset + x for x in vec_items])
expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(expected, offset + vec)
msg = "(bad|unsupported) operand type for unary"
with pytest.raises(TypeError, match=msg):
offset - vec

def test_dt64arr_add_sub_DateOffset(self, box_with_array):
# GH#10699
Expand Down
12 changes: 4 additions & 8 deletions pandas/tests/arrays/categorical/test_operators.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import warnings

import numpy as np
import pytest

Expand Down Expand Up @@ -196,6 +194,7 @@ def test_comparison_with_tuple(self):
result = cat != (0, 1)
tm.assert_numpy_array_equal(result, ~expected)

@pytest.mark.filterwarnings("ignore::RuntimeWarning")
def test_comparison_of_ordered_categorical_with_nan_to_scalar(
self, compare_operators_no_eq_ne
):
Expand All @@ -206,12 +205,11 @@ def test_comparison_of_ordered_categorical_with_nan_to_scalar(

cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
scalar = 2
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)
actual = getattr(cat, compare_operators_no_eq_ne)(scalar)
tm.assert_numpy_array_equal(actual, expected)

@pytest.mark.filterwarnings("ignore::RuntimeWarning")
def test_comparison_of_ordered_categorical_with_nan_to_listlike(
self, compare_operators_no_eq_ne
):
Expand All @@ -221,9 +219,7 @@ def test_comparison_of_ordered_categorical_with_nan_to_listlike(

cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
other = Categorical([2, 2, 2, 2], categories=[1, 2, 3], ordered=True)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
actual = getattr(cat, compare_operators_no_eq_ne)(other)
tm.assert_numpy_array_equal(actual, expected)

Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ def period_index(freqstr):
# TODO: non-monotone indexes; NaTs, different start dates
with warnings.catch_warnings():
# suppress deprecation of Period[B]
warnings.simplefilter("ignore")
warnings.filterwarnings(
"ignore", message="Period with BDay freq", category=FutureWarning
)
pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
return pi

Expand Down
Loading