Skip to content

Commit 9991d5e

Browse files
authored
CLN/BUG: Allow assert_produces_warning to raise during an exception (#50614)
* Remove old deprecations, make assert_produces_warning check when exceptions are raised * cleanup more tests, add test for change * Add more thorough tests * Fix other uncessary warnings * Fix min version pyarrow tests * Fix for 32 bit build
1 parent d3995f7 commit 9991d5e

25 files changed

+113
-122
lines changed

pandas/_libs/tslibs/offsets.pyx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,6 @@ cdef class BaseOffset:
389389
_attributes = tuple(["n", "normalize"])
390390
_use_relativedelta = False
391391
_adjust_dst = True
392-
_deprecations = frozenset(["isAnchored", "onOffset"])
393392

394393
# cdef readonly:
395394
# int64_t n

pandas/_testing/_warnings.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -87,22 +87,22 @@ class for all warnings. To raise multiple types of exceptions,
8787

8888
with warnings.catch_warnings(record=True) as w:
8989
warnings.simplefilter(filter_level)
90-
yield w
91-
92-
if expected_warning:
93-
expected_warning = cast(Type[Warning], expected_warning)
94-
_assert_caught_expected_warning(
95-
caught_warnings=w,
96-
expected_warning=expected_warning,
97-
match=match,
98-
check_stacklevel=check_stacklevel,
99-
)
100-
101-
if raise_on_extra_warnings:
102-
_assert_caught_no_extra_warnings(
103-
caught_warnings=w,
104-
expected_warning=expected_warning,
105-
)
90+
try:
91+
yield w
92+
finally:
93+
if expected_warning:
94+
expected_warning = cast(Type[Warning], expected_warning)
95+
_assert_caught_expected_warning(
96+
caught_warnings=w,
97+
expected_warning=expected_warning,
98+
match=match,
99+
check_stacklevel=check_stacklevel,
100+
)
101+
if raise_on_extra_warnings:
102+
_assert_caught_no_extra_warnings(
103+
caught_warnings=w,
104+
expected_warning=expected_warning,
105+
)
106106

107107

108108
def maybe_produces_warning(warning: type[Warning], condition: bool, **kwargs):

pandas/core/arrays/datetimes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2182,8 +2182,8 @@ def objects_to_datetime64ns(
21822182

21832183
def maybe_convert_dtype(data, copy: bool, tz: tzinfo | None = None):
21842184
"""
2185-
Convert data based on dtype conventions, issuing deprecation warnings
2186-
or errors where appropriate.
2185+
Convert data based on dtype conventions, issuing
2186+
errors where appropriate.
21872187
21882188
Parameters
21892189
----------

pandas/tests/apply/test_invalid_arg.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def test_transform_wont_agg_series(string_series, func):
348348
warn = RuntimeWarning if func[0] == "sqrt" else None
349349
warn_msg = "invalid value encountered in sqrt"
350350
with pytest.raises(ValueError, match=msg):
351-
with tm.assert_produces_warning(warn, match=warn_msg):
351+
with tm.assert_produces_warning(warn, match=warn_msg, check_stacklevel=False):
352352
string_series.transform(func)
353353

354354

pandas/tests/extension/test_arrow.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,9 @@ def test_groupby_extension_transform(self, data_for_grouping, request):
533533
)
534534
)
535535
with tm.maybe_produces_warning(
536-
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
536+
PerformanceWarning,
537+
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
538+
check_stacklevel=False,
537539
):
538540
super().test_groupby_extension_transform(data_for_grouping)
539541

@@ -549,7 +551,9 @@ def test_groupby_extension_apply(
549551
)
550552
)
551553
with tm.maybe_produces_warning(
552-
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
554+
PerformanceWarning,
555+
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
556+
check_stacklevel=False,
553557
):
554558
super().test_groupby_extension_apply(data_for_grouping, groupby_apply_op)
555559

@@ -571,7 +575,9 @@ def test_groupby_extension_agg(self, as_index, data_for_grouping, request):
571575
)
572576
)
573577
with tm.maybe_produces_warning(
574-
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
578+
PerformanceWarning,
579+
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
580+
check_stacklevel=False,
575581
):
576582
super().test_groupby_extension_agg(as_index, data_for_grouping)
577583

@@ -810,7 +816,9 @@ def test_value_counts_with_normalize(self, data, request):
810816
)
811817
)
812818
with tm.maybe_produces_warning(
813-
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
819+
PerformanceWarning,
820+
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
821+
check_stacklevel=False,
814822
):
815823
super().test_value_counts_with_normalize(data)
816824

@@ -929,7 +937,9 @@ def test_sort_values_frame(self, data_for_sorting, ascending, request):
929937
)
930938
)
931939
with tm.maybe_produces_warning(
932-
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
940+
PerformanceWarning,
941+
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
942+
check_stacklevel=False,
933943
):
934944
super().test_sort_values_frame(data_for_sorting, ascending)
935945

pandas/tests/extension/test_sparse.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -480,8 +480,7 @@ class TestParsing(BaseSparseTests, base.BaseParsingTests):
480480
def test_EA_types(self, engine, data):
481481
expected_msg = r".*must implement _from_sequence_of_strings.*"
482482
with pytest.raises(NotImplementedError, match=expected_msg):
483-
with tm.assert_produces_warning(FutureWarning, match="astype from"):
484-
super().test_EA_types(engine, data)
483+
super().test_EA_types(engine, data)
485484

486485

487486
class TestNoNumericAccumulations(base.BaseAccumulateTests):

pandas/tests/frame/indexing/test_getitem.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,8 +156,7 @@ def test_getitem_listlike(self, idx_type, levels, float_frame):
156156

157157
idx = idx_type(keys + [missing])
158158
with pytest.raises(KeyError, match="not in index"):
159-
with tm.assert_produces_warning(FutureWarning):
160-
frame[idx]
159+
frame[idx]
161160

162161
def test_getitem_iloc_generator(self):
163162
# GH#39614
@@ -357,8 +356,7 @@ def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_col
357356
df = df_dup_cols
358357
msg = "cannot reindex on an axis with duplicate labels"
359358
with pytest.raises(ValueError, match=msg):
360-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
361-
df[df.A > 6]
359+
df[df.A > 6]
362360

363361
def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols):
364362
# boolean indexing

pandas/tests/frame/indexing/test_setitem.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,7 @@ def test_setitem_error_msmgs(self):
8585
)
8686
msg = "cannot reindex on an axis with duplicate labels"
8787
with pytest.raises(ValueError, match=msg):
88-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
89-
df["newcol"] = ser
88+
df["newcol"] = ser
9089

9190
# GH 4107, more descriptive error message
9291
df = DataFrame(np.random.randint(0, 2, (4, 4)), columns=["a", "b", "c", "d"])

pandas/tests/frame/methods/test_reindex.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -808,8 +808,7 @@ def test_reindex_dups(self):
808808
# reindex fails
809809
msg = "cannot reindex on an axis with duplicate labels"
810810
with pytest.raises(ValueError, match=msg):
811-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
812-
df.reindex(index=list(range(len(df))))
811+
df.reindex(index=list(range(len(df))))
813812

814813
def test_reindex_with_duplicate_columns(self):
815814

@@ -819,11 +818,9 @@ def test_reindex_with_duplicate_columns(self):
819818
)
820819
msg = "cannot reindex on an axis with duplicate labels"
821820
with pytest.raises(ValueError, match=msg):
822-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
823-
df.reindex(columns=["bar"])
821+
df.reindex(columns=["bar"])
824822
with pytest.raises(ValueError, match=msg):
825-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
826-
df.reindex(columns=["bar", "foo"])
823+
df.reindex(columns=["bar", "foo"])
827824

828825
def test_reindex_axis_style(self):
829826
# https://github.com/pandas-dev/pandas/issues/12392
@@ -1091,8 +1088,7 @@ def test_reindex_with_categoricalindex(self):
10911088
# passed duplicate indexers are not allowed
10921089
msg = "cannot reindex on an axis with duplicate labels"
10931090
with pytest.raises(ValueError, match=msg):
1094-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
1095-
df2.reindex(["a", "b"])
1091+
df2.reindex(["a", "b"])
10961092

10971093
# args NotImplemented ATM
10981094
msg = r"argument {} is not implemented for CategoricalIndex\.reindex"

pandas/tests/frame/methods/test_sort_index.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,12 @@ def test_sort_index_and_reconstruction_doc_example(self):
4444
assert result.index.is_monotonic_increasing
4545
tm.assert_frame_equal(result, expected)
4646

47-
# FIXME: the FutureWarning is issued on a setitem-with-expansion
48-
# which will *not* change behavior, so should not get a warning.
49-
@pytest.mark.filterwarnings("ignore:.*will attempt to set.*:FutureWarning")
5047
def test_sort_index_non_existent_label_multiindex(self):
5148
# GH#12261
5249
df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []]))
53-
df.loc["b", "2"] = 1
54-
df.loc["a", "3"] = 1
50+
with tm.assert_produces_warning(None):
51+
df.loc["b", "2"] = 1
52+
df.loc["a", "3"] = 1
5553
result = df.sort_index().index.is_monotonic_increasing
5654
assert result is True
5755

pandas/tests/frame/test_arithmetic.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1067,7 +1067,7 @@ def test_frame_with_frame_reindex(self):
10671067
],
10681068
ids=lambda x: x.__name__,
10691069
)
1070-
def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements):
1070+
def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements, request):
10711071

10721072
skip = {
10731073
(operator.truediv, "bool"),
@@ -1099,10 +1099,14 @@ def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements):
10991099
msg = None
11001100
elif dtype == "complex128":
11011101
msg = "ufunc 'remainder' not supported for the input types"
1102-
warn = UserWarning # "evaluating in Python space because ..."
11031102
elif op is operator.sub:
11041103
msg = "numpy boolean subtract, the `-` operator, is "
1105-
warn = UserWarning # "evaluating in Python space because ..."
1104+
if (
1105+
dtype == "bool"
1106+
and expr.USE_NUMEXPR
1107+
and switch_numexpr_min_elements == 0
1108+
):
1109+
warn = UserWarning # "evaluating in Python space because ..."
11061110
else:
11071111
msg = (
11081112
f"cannot perform __{op.__name__}__ with this "

pandas/tests/groupby/test_categorical.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1893,10 +1893,7 @@ def test_category_order_transformer(
18931893
df = df.set_index(keys)
18941894
args = get_groupby_method_args(transformation_func, df)
18951895
gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed)
1896-
msg = "is deprecated and will be removed in a future version"
1897-
warn = FutureWarning if transformation_func == "tshift" else None
1898-
with tm.assert_produces_warning(warn, match=msg):
1899-
op_result = getattr(gb, transformation_func)(*args)
1896+
op_result = getattr(gb, transformation_func)(*args)
19001897
result = op_result.index.get_level_values("a").categories
19011898
expected = Index([1, 4, 3, 2])
19021899
tm.assert_index_equal(result, expected)

pandas/tests/groupby/transform/test_transform.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1362,10 +1362,7 @@ def test_null_group_str_transformer(request, dropna, transformation_func):
13621362
# ngroup/cumcount always returns a Series as it counts the groups, not values
13631363
expected = expected["B"].rename(None)
13641364

1365-
warn = FutureWarning if transformation_func in ("backfill", "pad") else None
1366-
msg = f"{transformation_func} is deprecated"
1367-
with tm.assert_produces_warning(warn, match=msg):
1368-
result = gb.transform(transformation_func, *args)
1365+
result = gb.transform(transformation_func, *args)
13691366

13701367
tm.assert_equal(result, expected)
13711368

@@ -1411,7 +1408,7 @@ def test_null_group_str_reducer_series(request, dropna, reduction_func):
14111408
tm.assert_series_equal(result, expected)
14121409

14131410

1414-
def test_null_group_str_transformer_series(request, dropna, transformation_func):
1411+
def test_null_group_str_transformer_series(dropna, transformation_func):
14151412
# GH 17093
14161413
ser = Series([1, 2, 2], index=[1, 2, 3])
14171414
args = get_groupby_method_args(transformation_func, ser)
@@ -1432,9 +1429,7 @@ def test_null_group_str_transformer_series(request, dropna, transformation_func)
14321429
buffer.append(Series([np.nan], index=[3], dtype=dtype))
14331430
expected = concat(buffer)
14341431

1435-
warn = FutureWarning if transformation_func in ("backfill", "pad") else None
1436-
msg = f"{transformation_func} is deprecated"
1437-
with tm.assert_produces_warning(warn, match=msg):
1432+
with tm.assert_produces_warning(None):
14381433
result = gb.transform(transformation_func, *args)
14391434

14401435
tm.assert_equal(result, expected)

pandas/tests/indexes/interval/test_base.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,7 @@ def test_getitem_2d_deprecated(self, simple_index):
6161
# GH#30588 multi-dim indexing is deprecated, but raising is also acceptable
6262
idx = simple_index
6363
with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
64-
with tm.assert_produces_warning(FutureWarning):
65-
idx[:, None]
64+
idx[:, None]
6665
with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
6766
# GH#44051
6867
idx[True]

pandas/tests/indexes/multi/test_reindex.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,7 @@ def test_reindex_non_unique():
106106

107107
msg = "cannot handle a non-unique multi-index!"
108108
with pytest.raises(ValueError, match=msg):
109-
with tm.assert_produces_warning(FutureWarning, match="non-unique"):
110-
a.reindex(new_idx)
109+
a.reindex(new_idx)
111110

112111

113112
@pytest.mark.parametrize("values", [[["a"], ["x"]], [[], []]])

pandas/tests/indexes/test_common.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import pandas as pd
2424
from pandas import (
2525
CategoricalIndex,
26-
DatetimeIndex,
2726
MultiIndex,
2827
PeriodIndex,
2928
RangeIndex,
@@ -389,14 +388,7 @@ def test_astype_preserves_name(self, index, dtype):
389388
index.name = "idx"
390389

391390
warn = None
392-
if (
393-
isinstance(index, DatetimeIndex)
394-
and index.tz is not None
395-
and dtype == "datetime64[ns]"
396-
):
397-
# This astype is deprecated in favor of tz_localize
398-
warn = FutureWarning
399-
elif index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
391+
if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
400392
# imaginary components discarded
401393
warn = np.ComplexWarning
402394

pandas/tests/indexing/test_indexing.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,7 @@ def test_setitem_ndarray_1d_2(self):
6969

7070
msg = "Must have equal len keys and value when setting with an iterable"
7171
with pytest.raises(ValueError, match=msg):
72-
with tm.assert_produces_warning(FutureWarning, match="label-based"):
73-
df[2:5] = np.arange(1, 4) * 1j
72+
df[2:5] = np.arange(1, 4) * 1j
7473

7574
def test_getitem_ndarray_3d(
7675
self, index, frame_or_series, indexer_sli, using_array_manager

pandas/tests/io/parser/test_parse_dates.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -924,9 +924,7 @@ def test_parse_dates_custom_euro_format(all_parsers, kwargs):
924924
tm.assert_frame_equal(df, expected)
925925
else:
926926
msg = "got an unexpected keyword argument 'day_first'"
927-
with pytest.raises(TypeError, match=msg), tm.assert_produces_warning(
928-
FutureWarning
929-
):
927+
with pytest.raises(TypeError, match=msg):
930928
parser.read_csv(
931929
StringIO(data),
932930
names=["time", "Q", "NTU"],

pandas/tests/io/test_stata.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1725,8 +1725,7 @@ def test_invalid_file_not_written(self, version):
17251725
r"ordinal not in range\(128\)"
17261726
)
17271727
with pytest.raises(UnicodeEncodeError, match=f"{msg1}|{msg2}"):
1728-
with tm.assert_produces_warning(ResourceWarning):
1729-
df.to_stata(path)
1728+
df.to_stata(path)
17301729

17311730
def test_strl_latin1(self):
17321731
# GH 23573, correct GSO data to reflect correct size

0 commit comments

Comments
 (0)