diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 84d95a23bd446..81f2540b6f7e5 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -526,10 +526,11 @@ def setup(self, mode): def time_chained_indexing(self, mode): df = self.df N = self.N - with warnings.catch_warnings(record=True): - with option_context("mode.chained_assignment", mode): - df2 = df[df.A > N // 2] - df2["C"] = 1.0 + with warnings.catch_warnings( + record=True, + ), option_context("mode.chained_assignment", mode): + df2 = df[df.A > N // 2] + df2["C"] = 1.0 class Block: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index bdab641719ded..d7324cae97e9e 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1680,11 +1680,14 @@ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): # result to the whole group. Compute func result # and deal with possible broadcasting below. # Temporarily set observed for dealing with categoricals. - with com.temp_setattr(self, "observed", True): - with com.temp_setattr(self, "as_index", True): - # GH#49834 - result needs groups in the index for - # _wrap_transform_fast_result - result = getattr(self, func)(*args, **kwargs) + with com.temp_setattr( + self, + "observed", + True, + ), com.temp_setattr(self, "as_index", True): + # GH#49834 - result needs groups in the index for + # _wrap_transform_fast_result + result = getattr(self, func)(*args, **kwargs) return self._wrap_transform_fast_result(result) diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index c07f51d875d4d..8ac9699383121 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -444,32 +444,31 @@ def copy_windows(text): text = _stringifyText(text) # Converts non-str values to str. - with window() as hwnd: + with window() as hwnd, clipboard(hwnd): # http://msdn.com/ms649048 # If an application calls OpenClipboard with hwnd set to NULL, # EmptyClipboard sets the clipboard owner to NULL; # this causes SetClipboardData to fail. # => We need a valid hwnd to copy something. - with clipboard(hwnd): - safeEmptyClipboard() - - if text: - # http://msdn.com/ms649051 - # If the hMem parameter identifies a memory object, - # the object must have been allocated using the - # function with the GMEM_MOVEABLE flag. - count = wcslen(text) + 1 - handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar)) - locked_handle = safeGlobalLock(handle) - - ctypes.memmove( - c_wchar_p(locked_handle), - c_wchar_p(text), - count * sizeof(c_wchar), - ) - - safeGlobalUnlock(handle) - safeSetClipboardData(CF_UNICODETEXT, handle) + safeEmptyClipboard() + + if text: + # http://msdn.com/ms649051 + # If the hMem parameter identifies a memory object, + # the object must have been allocated using the + # function with the GMEM_MOVEABLE flag. + count = wcslen(text) + 1 + handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar)) + locked_handle = safeGlobalLock(handle) + + ctypes.memmove( + c_wchar_p(locked_handle), + c_wchar_p(text), + count * sizeof(c_wchar), + ) + + safeGlobalUnlock(handle) + safeSetClipboardData(CF_UNICODETEXT, handle) def paste_windows(): with clipboard(None): diff --git a/pandas/tests/apply/test_invalid_arg.py b/pandas/tests/apply/test_invalid_arg.py index d75b784302676..164cecf0872ae 100644 --- a/pandas/tests/apply/test_invalid_arg.py +++ b/pandas/tests/apply/test_invalid_arg.py @@ -288,9 +288,8 @@ def test_apply_broadcast_error(int_frame_const_col, func): def test_transform_and_agg_err_agg(axis, float_frame): # cannot both transform and agg msg = "cannot combine transform and aggregation operations" - with pytest.raises(ValueError, match=msg): - with np.errstate(all="ignore"): - float_frame.agg(["max", "sqrt"], axis=axis) + with pytest.raises(ValueError, match=msg), np.errstate(all="ignore"): + float_frame.agg(["max", "sqrt"], axis=axis) @pytest.mark.parametrize( @@ -305,9 +304,8 @@ def test_transform_and_agg_err_agg(axis, float_frame): ) 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"): - string_series.agg(func) + with pytest.raises(ValueError, match=msg), np.errstate(all="ignore"): + string_series.agg(func) @pytest.mark.parametrize("func", [["max", "min"], ["max", "sqrt"]]) @@ -327,9 +325,15 @@ def test_transform_wont_agg_series(string_series, func): warn = RuntimeWarning if func[0] == "sqrt" else None warn_msg = "invalid value encountered in sqrt" - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(warn, match=warn_msg, check_stacklevel=False): - string_series.transform(func) + with pytest.raises( + ValueError, + match=msg, + ), tm.assert_produces_warning( + warn, + match=warn_msg, + check_stacklevel=False, + ): + string_series.transform(func) @pytest.mark.parametrize( diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 7a079ae7795e6..fb03c2b6f06be 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -852,12 +852,16 @@ def test_pi_add_offset_array(self, box): # addition/subtraction ops with incompatible offsets should issue # a PerformanceWarning and _then_ raise a TypeError. msg = r"Input cannot be converted to Period\(freq=Q-DEC\)" - with pytest.raises(IncompatibleFrequency, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - pi + unanchored - with pytest.raises(IncompatibleFrequency, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - unanchored + pi + with pytest.raises( + IncompatibleFrequency, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + pi + unanchored + with pytest.raises( + IncompatibleFrequency, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + unanchored + pi @pytest.mark.parametrize("box", [np.array, pd.Index]) def test_pi_sub_offset_array(self, box): @@ -882,12 +886,16 @@ def test_pi_sub_offset_array(self, box): # addition/subtraction ops with anchored offsets should issue # a PerformanceWarning and _then_ raise a TypeError. msg = r"Input has different freq=-1M from Period\(freq=Q-DEC\)" - with pytest.raises(IncompatibleFrequency, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - pi - anchored - with pytest.raises(IncompatibleFrequency, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - anchored - pi + with pytest.raises( + IncompatibleFrequency, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + pi - anchored + with pytest.raises( + IncompatibleFrequency, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + anchored - pi def test_pi_add_iadd_int(self, one): # Variants of `one` for #19012 diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 7f44e329e6778..dba987cba1573 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -1387,18 +1387,26 @@ def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array): # addition/subtraction ops with anchored offsets should issue # a PerformanceWarning and _then_ raise a TypeError. msg = "has incorrect type|cannot add the type MonthEnd" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - tdi + anchored - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - anchored + tdi - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - tdi - anchored - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - anchored - tdi + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + tdi + anchored + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + anchored + tdi + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + tdi - anchored + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + anchored - tdi # ------------------------------------------------------------------ # Unsorted @@ -1422,9 +1430,11 @@ def test_td64arr_add_sub_object_array(self, box_with_array): tm.assert_equal(result, expected) msg = "unsupported operand type|cannot subtract a datelike" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(PerformanceWarning): - tdarr - other + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning(PerformanceWarning): + tdarr - other with tm.assert_produces_warning(PerformanceWarning): result = other - tdarr diff --git a/pandas/tests/arrays/categorical/test_warnings.py b/pandas/tests/arrays/categorical/test_warnings.py index 656da89c70196..2f608a2fda3ed 100644 --- a/pandas/tests/arrays/categorical/test_warnings.py +++ b/pandas/tests/arrays/categorical/test_warnings.py @@ -17,6 +17,5 @@ async def test_tab_complete_warning(self, ip): # GH 31324 newer jedi version raises Deprecation warning; # appears resolved 2021-02-02 - with tm.assert_produces_warning(None): - with provisionalcompleter("ignore"): - list(ip.Completer.completions("c.", 1)) + with tm.assert_produces_warning(None), provisionalcompleter("ignore"): + list(ip.Completer.completions("c.", 1)) diff --git a/pandas/tests/arrays/string_/test_string_arrow.py b/pandas/tests/arrays/string_/test_string_arrow.py index 45098e12ccb38..e9986f66b9b50 100644 --- a/pandas/tests/arrays/string_/test_string_arrow.py +++ b/pandas/tests/arrays/string_/test_string_arrow.py @@ -82,9 +82,11 @@ def test_from_sequence_wrong_dtype_raises(): ArrowStringArray._from_sequence(["a", None, "c"], dtype="string[pyarrow]") - with pytest.raises(AssertionError, match=None): - with pd.option_context("string_storage", "python"): - ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) + with pytest.raises( + AssertionError, + match=None, + ), pd.option_context("string_storage", "python"): + ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) with pd.option_context("string_storage", "pyarrow"): ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) @@ -108,9 +110,11 @@ def test_from_sequence_wrong_dtype_raises(): with pd.option_context("string_storage", "python"): StringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) - with pytest.raises(AssertionError, match=None): - with pd.option_context("string_storage", "pyarrow"): - StringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) + with pytest.raises( + AssertionError, + match=None, + ), pd.option_context("string_storage", "pyarrow"): + StringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("python")) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 9e402af931199..048093e79312d 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -319,15 +319,14 @@ def test_searchsorted_castable_strings(self, arr1d, box, string_storage): arr_type = "StringArray" if string_storage == "python" else "ArrowStringArray" - with pd.option_context("string_storage", string_storage): - with pytest.raises( - TypeError, - match=re.escape( - f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', " - f"or array of those. Got '{arr_type}' instead." - ), - ): - arr.searchsorted([str(arr[1]), "baz"]) + with pd.option_context("string_storage", string_storage), pytest.raises( + TypeError, + match=re.escape( + f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', " + f"or array of those. Got '{arr_type}' instead." + ), + ): + arr.searchsorted([str(arr[1]), "baz"]) def test_getitem_near_implementation_bounds(self): # We only check tz-naive for DTA bc the bounds are slightly different diff --git a/pandas/tests/config/test_localization.py b/pandas/tests/config/test_localization.py index 3907f557d1075..b9b442cdf320e 100644 --- a/pandas/tests/config/test_localization.py +++ b/pandas/tests/config/test_localization.py @@ -130,9 +130,8 @@ def test_set_locale(lang, enc): if not can_set_locale(new_locale): msg = "unsupported locale setting" - with pytest.raises(locale.Error, match=msg): - with set_locale(new_locale): - pass + with pytest.raises(locale.Error, match=msg), set_locale(new_locale): + pass else: with set_locale(new_locale) as normalized_locale: new_lang, new_enc = normalized_locale.split(".") diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py index f9b4ba295f3a0..09db59fa05909 100644 --- a/pandas/tests/copy_view/test_indexing.py +++ b/pandas/tests/copy_view/test_indexing.py @@ -163,9 +163,11 @@ def test_subset_column_slice(backend, using_copy_on_write, using_array_manager, else: # we only get a warning in case of a single block warn = SettingWithCopyWarning if single_block else None - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - subset.iloc[0, 0] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(warn): + subset.iloc[0, 0] = 0 expected = DataFrame({"b": [0, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)}) tm.assert_frame_equal(subset, expected) @@ -323,9 +325,11 @@ def test_subset_set_with_row_indexer(backend, indexer_si, indexer, using_copy_on else: # INFO iloc no longer raises warning since pandas 1.4 warn = SettingWithCopyWarning if indexer_si is tm.setitem else None - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - indexer_si(subset)[indexer] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(warn): + indexer_si(subset)[indexer] = 0 expected = DataFrame( {"a": [0, 0, 4], "b": [0, 0, 7], "c": [0.0, 0.0, 0.4]}, index=range(1, 4) @@ -352,9 +356,11 @@ def test_subset_set_with_mask(backend, using_copy_on_write): if using_copy_on_write: subset[mask] = 0 else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(SettingWithCopyWarning): - subset[mask] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(SettingWithCopyWarning): + subset[mask] = 0 expected = DataFrame( {"a": [2, 3, 0], "b": [0, 0, 0], "c": [0.20, 0.3, 0.4]}, index=range(1, 4) @@ -385,9 +391,11 @@ def test_subset_set_column(backend, using_copy_on_write): if using_copy_on_write: subset["a"] = arr else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(SettingWithCopyWarning): - subset["a"] = arr + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(SettingWithCopyWarning): + subset["a"] = arr subset._mgr._verify_integrity() expected = DataFrame( @@ -415,12 +423,13 @@ def test_subset_set_column_with_loc( if using_copy_on_write: subset.loc[:, "a"] = np.array([10, 11], dtype="int64") else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning( - None, - raise_on_extra_warnings=not using_array_manager, - ): - subset.loc[:, "a"] = np.array([10, 11], dtype="int64") + with pd.option_context( + "chained_assignment", "warn" + ), tm.assert_produces_warning( + None, + raise_on_extra_warnings=not using_array_manager, + ): + subset.loc[:, "a"] = np.array([10, 11], dtype="int64") subset._mgr._verify_integrity() expected = DataFrame( @@ -450,12 +459,14 @@ def test_subset_set_column_with_loc2(backend, using_copy_on_write, using_array_m if using_copy_on_write: subset.loc[:, "a"] = 0 else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning( - None, - raise_on_extra_warnings=not using_array_manager, - ): - subset.loc[:, "a"] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning( + None, + raise_on_extra_warnings=not using_array_manager, + ): + subset.loc[:, "a"] = 0 subset._mgr._verify_integrity() expected = DataFrame({"a": [0, 0]}, index=range(1, 3)) @@ -485,9 +496,11 @@ def test_subset_set_columns(backend, using_copy_on_write, dtype): if using_copy_on_write: subset[["a", "c"]] = 0 else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(SettingWithCopyWarning): - subset[["a", "c"]] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(SettingWithCopyWarning): + subset[["a", "c"]] = 0 subset._mgr._verify_integrity() if using_copy_on_write: @@ -892,9 +905,11 @@ def test_column_as_series(backend, using_copy_on_write, using_array_manager): s[0] = 0 else: warn = SettingWithCopyWarning if dtype_backend == "numpy" else None - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - s[0] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(warn): + s[0] = 0 expected = Series([0, 2, 3], name="a") tm.assert_series_equal(s, expected) @@ -927,9 +942,11 @@ def test_column_as_series_set_with_upcast( s[0] = "foo" expected = Series(["foo", 2, 3], dtype=object, name="a") else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(SettingWithCopyWarning): - s[0] = "foo" + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(SettingWithCopyWarning): + s[0] = "foo" expected = Series(["foo", 2, 3], dtype=object, name="a") tm.assert_series_equal(s, expected) @@ -973,9 +990,11 @@ def test_column_as_series_no_item_cache( s1.iloc[0] = 0 else: warn = SettingWithCopyWarning if dtype_backend == "numpy" else None - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - s1.iloc[0] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(warn): + s1.iloc[0] = 0 if using_copy_on_write: tm.assert_series_equal(s2, df_orig["a"]) diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 67fc91e0567ef..c3842e71d61af 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1573,9 +1573,11 @@ def test_get(using_copy_on_write, key): # for non-CoW it depends on whether we got a Series or DataFrame if it # is a view or copy or triggers a warning or not warn = SettingWithCopyWarning if isinstance(key, list) else None - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - result.iloc[0] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(warn): + result.iloc[0] = 0 if isinstance(key, list): tm.assert_frame_equal(df, df_orig) @@ -1605,9 +1607,11 @@ def test_xs(using_copy_on_write, using_array_manager, axis, key, dtype): if using_copy_on_write or is_view: result.iloc[0] = 0 else: - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(SettingWithCopyWarning): - result.iloc[0] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(SettingWithCopyWarning): + result.iloc[0] = 0 if using_copy_on_write or (not single_block and axis == 0): tm.assert_frame_equal(df, df_orig) @@ -1637,9 +1641,11 @@ def test_xs_multiindex(using_copy_on_write, using_array_manager, key, level, axi if not using_copy_on_write and not using_array_manager else None ) - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - result.iloc[0, 0] = 0 + with pd.option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(warn): + result.iloc[0, 0] = 0 tm.assert_frame_equal(df, df_orig) diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 9129e84700a55..18cdd8a6fc275 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -2640,9 +2640,14 @@ def test_dt_to_pydatetime_date_error(date_type): dtype=ArrowDtype(getattr(pa, f"date{date_type}")()), ) msg = "The behavior of ArrowTemporalProperties.to_pydatetime is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - with pytest.raises(ValueError, match="to_pydatetime cannot be called with"): - ser.dt.to_pydatetime() + with tm.assert_produces_warning( + FutureWarning, + match=msg, + ), pytest.raises( + ValueError, + match="to_pydatetime cannot be called with", + ): + ser.dt.to_pydatetime() def test_dt_tz_localize_unsupported_tz_options(): diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py index 9f44e85789cbd..16348e2f035e8 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -200,12 +200,16 @@ def test_from_records_bad_index_column(self): r"'None of \[2\] are in the columns'", ] ) - with pytest.raises(KeyError, match=msg): - with tm.assert_produces_warning(FutureWarning): - DataFrame.from_records(df, index=[2]) - with pytest.raises(KeyError, match=msg): - with tm.assert_produces_warning(FutureWarning): - DataFrame.from_records(df, index=2) + with pytest.raises( + KeyError, + match=msg, + ), tm.assert_produces_warning(FutureWarning): + DataFrame.from_records(df, index=[2]) + with pytest.raises( + KeyError, + match=msg, + ), tm.assert_produces_warning(FutureWarning): + DataFrame.from_records(df, index=2) def test_from_records_non_tuple(self): class Record: diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index e0d9d6c281fd5..da9078408eb51 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -306,9 +306,8 @@ async def test_tab_complete_warning(self, ip, frame_or_series): # GH 31324 newer jedi version raises Deprecation warning; # appears resolved 2021-02-02 - with tm.assert_produces_warning(None): - with provisionalcompleter("ignore"): - list(ip.Completer.completions("obj.", 1)) + with tm.assert_produces_warning(None), provisionalcompleter("ignore"): + list(ip.Completer.completions("obj.", 1)) def test_attrs(self): df = DataFrame({"A": [2, 3]}) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 52b60a0b83025..849052df3a393 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1113,9 +1113,8 @@ def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements, reques "index type: (DatetimeArray|TimedeltaArray)" ) - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(warn): - op(df, elem.value) + with pytest.raises(TypeError, match=msg), tm.assert_produces_warning(warn): + op(df, elem.value) elif (op, dtype) in skip: if op in [operator.add, operator.mul]: diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 47e307f561cf4..2ae4a5be827ef 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1074,14 +1074,13 @@ def test_constructor_maskedarray_nonfloat(self): # cast type msg = r"datetime64\[ns\] values and dtype=int64 is not supported" - with pytest.raises(TypeError, match=msg): - with warnings.catch_warnings(): - warnings.filterwarnings( - "ignore", - category=DeprecationWarning, - message="elementwise comparison failed", - ) - DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64) + with pytest.raises(TypeError, match=msg), warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="elementwise comparison failed", + ) + DataFrame(mat, columns=["A", "B", "C"], index=[1, 2], dtype=np.int64) # Check non-masked values mat2 = ma.copy(mat) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index aa4abd627066b..00d6867b4f938 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -1948,9 +1948,14 @@ def __init__(self, *args, **kwargs) -> None: index=[np.arange(2**16), np.arange(2**16)], ) msg = "The following operation may generate" - with tm.assert_produces_warning(PerformanceWarning, match=msg): - with pytest.raises(Exception, match="Don't compute final result."): - df.unstack() + with tm.assert_produces_warning( + PerformanceWarning, + match=msg, + ), pytest.raises( + Exception, + match="Don't compute final result.", + ): + df.unstack() @pytest.mark.parametrize( "levels", diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index 79f055909fdea..d63ca4f8610c7 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -64,9 +64,14 @@ def test_nonzero_single_element(self): with pytest.raises(ValueError, match=msg_err): bool(df) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err): - df.bool() + with tm.assert_produces_warning( + FutureWarning, + match=msg_warn, + ), pytest.raises( + ValueError, + match=msg_err, + ): + df.bool() def test_metadata_propagation_indiv_groupby(self): # groupby diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index ee0a7fb77f336..bc864035f290b 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -69,9 +69,14 @@ def test_nonzero_single_element_raise_2(self, data): ) msg_err = "bool cannot act on a non-boolean single element Series" series = Series([data]) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err): - series.bool() + with tm.assert_produces_warning( + FutureWarning, + match=msg_warn, + ), pytest.raises( + ValueError, + match=msg_err, + ): + series.bool() @pytest.mark.parametrize("data", [(True, True), (False, False)]) def test_nonzero_multiple_element_raise(self, data): @@ -84,9 +89,11 @@ def test_nonzero_multiple_element_raise(self, data): series = Series([data]) with pytest.raises(ValueError, match=msg_err): bool(series) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err): - series.bool() + with tm.assert_produces_warning( + FutureWarning, + match=msg_warn, + ), pytest.raises(ValueError, match=msg_err): + series.bool() @pytest.mark.parametrize("data", [1, 0, "a", 0.0]) def test_nonbool_single_element_raise(self, data): @@ -100,9 +107,11 @@ def test_nonbool_single_element_raise(self, data): series = Series([data]) with pytest.raises(ValueError, match=msg_err1): bool(series) - with tm.assert_produces_warning(FutureWarning, match=msg_warn): - with pytest.raises(ValueError, match=msg_err2): - series.bool() + with tm.assert_produces_warning( + FutureWarning, + match=msg_warn, + ), pytest.raises(ValueError, match=msg_err2): + series.bool() def test_metadata_propagation_indiv_resample(self): # resample diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 3558377907931..f8cee215a71bb 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -241,9 +241,14 @@ def test_agg_str_with_kwarg_axis_1_raises(df, reduction_func): error = ValueError msg = f"Operation {reduction_func} does not support axis=1" warn = None - with pytest.raises(error, match=msg): - with tm.assert_produces_warning(warn, match=warn_msg): - gb.agg(reduction_func, axis=1) + with pytest.raises( + error, + match=msg, + ), tm.assert_produces_warning( + warn, + match=warn_msg, + ): + gb.agg(reduction_func, axis=1) @pytest.mark.parametrize( diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 98fce9d668e44..c7e6abd37a359 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -524,9 +524,14 @@ def test_idxmin_idxmax_axis1(): gb2 = df.groupby("A") msg = "reduction operation 'argmax' not allowed for this dtype" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - gb2.idxmax(axis=1) + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + gb2.idxmax(axis=1) @pytest.mark.parametrize("numeric_only", [True, False, None]) @@ -568,9 +573,14 @@ def test_axis1_numeric_only(request, groupby_func, numeric_only): if numeric_only is not None and groupby_func in no_args: msg = "got an unexpected keyword argument 'numeric_only'" if groupby_func in ["cumprod", "cumsum"]: - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - method(*args, **kwargs) + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + method(*args, **kwargs) else: with pytest.raises(TypeError, match=msg): method(*args, **kwargs) @@ -591,9 +601,14 @@ def test_axis1_numeric_only(request, groupby_func, numeric_only): # cumsum, diff, pct_change "unsupported operand type", ) - with pytest.raises(TypeError, match=f"({'|'.join(msgs)})"): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - method(*args, **kwargs) + with pytest.raises( + TypeError, + match=f"({'|'.join(msgs)})", + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + method(*args, **kwargs) else: with tm.assert_produces_warning(FutureWarning, match=warn_msg): result = method(*args, **kwargs) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 0c6661b49d917..d9f982e924511 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -876,9 +876,14 @@ def test_groupby_as_index_corner(df, ts): msg = "as_index=False only valid for axis=0" depr_msg = "DataFrame.groupby with axis=1 is deprecated" - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - df.groupby(lambda x: x.lower(), as_index=False, axis=1) + with pytest.raises( + ValueError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=depr_msg, + ): + df.groupby(lambda x: x.lower(), as_index=False, axis=1) def test_groupby_multiple_key(): diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 41b7dde4bf631..1d1b0655d77b1 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -617,9 +617,14 @@ def test_groupby_level_index_names(self, axis): with tm.assert_produces_warning(FutureWarning, match=depr_msg): df.groupby(level="exp", axis=axis) msg = f"level name foo is not the name of the {df._get_axis_name(axis)}" - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=depr_msg): - df.groupby(level="foo", axis=axis) + with pytest.raises( + ValueError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=depr_msg, + ): + df.groupby(level="foo", axis=axis) @pytest.mark.parametrize("sort", [True, False]) def test_groupby_level_with_nas(self, sort): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index db317a819c520..d8a507497b6e6 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1225,9 +1225,8 @@ async def test_tab_complete_warning(self, ip): # GH 31324 newer jedi version raises Deprecation warning; # appears resolved 2021-02-02 - with tm.assert_produces_warning(None): - with provisionalcompleter("ignore"): - list(ip.Completer.completions("idx.", 4)) + with tm.assert_produces_warning(None), provisionalcompleter("ignore"): + list(ip.Completer.completions("idx.", 4)) def test_contains_method_removed(self, index): # GH#30103 method removed for all types except IntervalIndex diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 5e2e2b9bbec21..3b378a2465acb 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -65,9 +65,13 @@ def test_numpy_ufuncs_basic(index, func): # https://numpy.org/doc/stable/reference/ufuncs.html if isinstance(index, DatetimeIndexOpsMixin): - with tm.external_error_raised((TypeError, AttributeError)): - with np.errstate(all="ignore"): - func(index) + with tm.external_error_raised( + ( + TypeError, + AttributeError, + ) + ), np.errstate(all="ignore"): + func(index) elif is_numeric_dtype(index) and not ( is_complex_dtype(index) and func in [np.deg2rad, np.rad2deg] ): @@ -96,9 +100,13 @@ def test_numpy_ufuncs_basic(index, func): elif len(index) == 0: pass else: - with tm.external_error_raised((TypeError, AttributeError)): - with np.errstate(all="ignore"): - func(index) + with tm.external_error_raised( + ( + TypeError, + AttributeError, + ) + ), np.errstate(all="ignore"): + func(index) @pytest.mark.parametrize( diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index d2224988b70fc..78972b6576783 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -509,13 +509,17 @@ def test_detect_chained_assignment_warnings_errors(self, using_copy_on_write): df.loc[0]["A"] = 111 return - with option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(SettingWithCopyWarning): - df.loc[0]["A"] = 111 - - with option_context("chained_assignment", "raise"): - with pytest.raises(SettingWithCopyError, match=msg): - df.loc[0]["A"] = 111 + with option_context( + "chained_assignment", + "warn", + ), tm.assert_produces_warning(SettingWithCopyWarning): + df.loc[0]["A"] = 111 + + with option_context( + "chained_assignment", + "raise", + ), pytest.raises(SettingWithCopyError, match=msg): + df.loc[0]["A"] = 111 @pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})]) def test_detect_chained_assignment_warning_stacklevel( diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 2c39729097487..33a90a2a412fe 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -118,9 +118,14 @@ def test_setitem_index_object(self, val, exp_dtype): temp = obj.copy() warn_msg = "Series.__setitem__ treating keys as positions is deprecated" msg = "index 5 is out of bounds for axis 0 with size 4" - with pytest.raises(exp_dtype, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - temp[5] = 5 + with pytest.raises( + exp_dtype, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + temp[5] = 5 else: exp_index = pd.Index(list("abcd") + [val]) self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype) diff --git a/pandas/tests/io/excel/test_odswriter.py b/pandas/tests/io/excel/test_odswriter.py index 21d31ec8a7fb5..dd8d8686fc260 100644 --- a/pandas/tests/io/excel/test_odswriter.py +++ b/pandas/tests/io/excel/test_odswriter.py @@ -14,9 +14,8 @@ def test_write_append_mode_raises(ext): msg = "Append mode is not supported with odf!" - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=msg): - ExcelWriter(f, engine="odf", mode="a") + with tm.ensure_clean(ext) as f, pytest.raises(ValueError, match=msg): + ExcelWriter(f, engine="odf", mode="a") @pytest.mark.parametrize("engine_kwargs", [None, {"kwarg": 1}]) @@ -41,9 +40,8 @@ def test_engine_kwargs(ext, engine_kwargs): def test_book_and_sheets_consistent(ext): # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f) as writer: - assert writer.sheets == {} - table = odf.table.Table(name="test_name") - writer.book.spreadsheet.addElement(table) - assert writer.sheets == {"test_name": table} + with tm.ensure_clean(ext) as f, ExcelWriter(f) as writer: + assert writer.sheets == {} + table = odf.table.Table(name="test_name") + writer.book.spreadsheet.addElement(table) + assert writer.sheets == {"test_name": table} diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index b8d41164792e0..2daa9c38d9a25 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -90,11 +90,14 @@ def test_write_cells_merge_styled(ext): def test_engine_kwargs_write(ext, iso_dates): # GH 42286 GH 43445 engine_kwargs = {"iso_dates": iso_dates} - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="openpyxl", engine_kwargs=engine_kwargs) as writer: - assert writer.book.iso_dates == iso_dates - # ExcelWriter won't allow us to close without writing something - DataFrame().to_excel(writer) + with tm.ensure_clean(ext) as f, ExcelWriter( + f, + engine="openpyxl", + engine_kwargs=engine_kwargs, + ) as writer: + assert writer.book.iso_dates == iso_dates + # ExcelWriter won't allow us to close without writing something + DataFrame().to_excel(writer) def test_engine_kwargs_append_invalid(ext): @@ -107,12 +110,11 @@ def test_engine_kwargs_append_invalid(ext): match=re.escape( "load_workbook() got an unexpected keyword argument 'apple_banana'" ), - ): - with ExcelWriter( - f, engine="openpyxl", mode="a", engine_kwargs={"apple_banana": "fruit"} - ) as writer: - # ExcelWriter needs us to write something to close properly - DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2") + ), ExcelWriter( + f, engine="openpyxl", mode="a", engine_kwargs={"apple_banana": "fruit"} + ) as writer: + # ExcelWriter needs us to write something to close properly + DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2") @pytest.mark.parametrize("data_only, expected", [(True, 0), (False, "=1+1")]) @@ -239,13 +241,12 @@ def test_append_overlay_startrow_startcol(ext, startrow, startcol, greeting, goo def test_if_sheet_exists_raises(ext, if_sheet_exists, msg): # GH 40230 df = DataFrame({"fruit": ["pear"]}) - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=re.escape(msg)): - df.to_excel(f, "foo", engine="openpyxl") - with ExcelWriter( - f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists - ) as writer: - df.to_excel(writer, sheet_name="foo") + with tm.ensure_clean(ext) as f, pytest.raises(ValueError, match=re.escape(msg)): + df.to_excel(f, "foo", engine="openpyxl") + with ExcelWriter( + f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists + ) as writer: + df.to_excel(writer, sheet_name="foo") def test_to_excel_with_openpyxl_engine(ext): @@ -369,11 +370,10 @@ def test_read_empty_with_blank_row(datapath, ext, read_only): def test_book_and_sheets_consistent(ext): # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="openpyxl") as writer: - assert writer.sheets == {} - sheet = writer.book.create_sheet("test_name", 0) - assert writer.sheets == {"test_name": sheet} + with tm.ensure_clean(ext) as f, ExcelWriter(f, engine="openpyxl") as writer: + assert writer.sheets == {} + sheet = writer.book.create_sheet("test_name", 0) + assert writer.sheets == {"test_name": sheet} def test_ints_spelled_with_decimals(datapath, ext): diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 66dd090ec0783..975aa814de6fd 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1592,25 +1592,25 @@ def test_sheet_name(self, request, read_ext, df_ref): def test_bad_sheetname_raises(self, read_ext, sheet_name): # GH 39250 msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found" - with pytest.raises(ValueError, match=msg): - with pd.ExcelFile("blank" + read_ext) as excel: - excel.parse(sheet_name=sheet_name) + with pytest.raises( + ValueError, + match=msg, + ), pd.ExcelFile("blank" + read_ext) as excel: + excel.parse(sheet_name=sheet_name) def test_excel_read_buffer(self, engine, read_ext): pth = "test1" + read_ext expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0, engine=engine) - with open(pth, "rb") as f: - with pd.ExcelFile(f) as xls: - actual = pd.read_excel(xls, sheet_name="Sheet1", index_col=0) + with open(pth, "rb") as f, pd.ExcelFile(f) as xls: + actual = pd.read_excel(xls, sheet_name="Sheet1", index_col=0) tm.assert_frame_equal(expected, actual) def test_reader_closes_file(self, engine, read_ext): - with open("test1" + read_ext, "rb") as f: - with pd.ExcelFile(f) as xlsx: - # parses okay - pd.read_excel(xlsx, sheet_name="Sheet1", index_col=0, engine=engine) + with open("test1" + read_ext, "rb") as f, pd.ExcelFile(f) as xlsx: + # parses okay + pd.read_excel(xlsx, sheet_name="Sheet1", index_col=0, engine=engine) assert f.closed @@ -1618,9 +1618,11 @@ def test_conflicting_excel_engines(self, read_ext): # GH 26566 msg = "Engine should not be specified when passing an ExcelFile" - with pd.ExcelFile("test1" + read_ext) as xl: - with pytest.raises(ValueError, match=msg): - pd.read_excel(xl, engine="foo") + with pd.ExcelFile("test1" + read_ext) as xl, pytest.raises( + ValueError, + match=msg, + ): + pd.read_excel(xl, engine="foo") def test_excel_read_binary(self, engine, read_ext): # GH 15914 @@ -1641,9 +1643,14 @@ def test_excel_read_binary_via_read_excel(self, read_ext, engine): def test_read_excel_header_index_out_of_range(self, engine): # GH#43143 - with open("df_header_oob.xlsx", "rb") as f: - with pytest.raises(ValueError, match="exceeds maximum"): - pd.read_excel(f, header=[0, 1]) + with open( + "df_header_oob.xlsx", + "rb", + ) as f, pytest.raises( + ValueError, + match="exceeds maximum", + ): + pd.read_excel(f, header=[0, 1]) @pytest.mark.parametrize("filename", ["df_empty.xlsx", "df_equals.xlsx"]) def test_header_with_index_col(self, filename): @@ -1681,9 +1688,14 @@ def test_read_datetime_multiindex(self, request, engine, read_ext): def test_engine_invalid_option(self, read_ext): # read_ext includes the '.' hence the weird formatting - with pytest.raises(ValueError, match="Value must be one of *"): - with pd.option_context(f"io.excel{read_ext}.reader", "abc"): - pass + with pytest.raises( + ValueError, + match="Value must be one of *", + ), pd.option_context( + f"io.excel{read_ext}.reader", + "abc", + ): + pass def test_ignore_chartsheets(self, request, engine, read_ext): # GH 41448 diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 0560e12a00bf5..4d4f79c9a503d 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -1254,9 +1254,8 @@ def test_if_sheet_exists_raises(self, ext): # GH 40230 msg = "if_sheet_exists is only valid in append mode (mode='a')" - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=re.escape(msg)): - ExcelWriter(f, if_sheet_exists="replace") + with tm.ensure_clean(ext) as f, pytest.raises(ValueError, match=re.escape(msg)): + ExcelWriter(f, if_sheet_exists="replace") def test_excel_writer_empty_frame(self, engine, ext): # GH#45793 @@ -1285,13 +1284,12 @@ class TestExcelWriterEngineTests: ], ) def test_ExcelWriter_dispatch(self, klass, ext): - with tm.ensure_clean(ext) as path: - with ExcelWriter(path) as writer: - if ext == ".xlsx" and td.safe_import("xlsxwriter"): - # xlsxwriter has preference over openpyxl if both installed - assert isinstance(writer, _XlsxWriter) - else: - assert isinstance(writer, klass) + with tm.ensure_clean(ext) as path, ExcelWriter(path) as writer: + if ext == ".xlsx" and td.safe_import("xlsxwriter"): + # xlsxwriter has preference over openpyxl if both installed + assert isinstance(writer, _XlsxWriter) + else: + assert isinstance(writer, klass) def test_ExcelWriter_dispatch_raises(self): with pytest.raises(ValueError, match="No engine"): @@ -1354,9 +1352,8 @@ def test_excelfile_fspath(self): assert result == path def test_excelwriter_fspath(self): - with tm.ensure_clean("foo.xlsx") as path: - with ExcelWriter(path) as writer: - assert os.fspath(writer) == str(path) + with tm.ensure_clean("foo.xlsx") as path, ExcelWriter(path) as writer: + assert os.fspath(writer) == str(path) @pytest.mark.parametrize("klass", _writers.values()) diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index c4d02d71390cc..89987f1f4e3be 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -55,24 +55,25 @@ def test_column_format(ext): def test_write_append_mode_raises(ext): msg = "Append mode is not supported with xlsxwriter!" - with tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=msg): - ExcelWriter(f, engine="xlsxwriter", mode="a") + with tm.ensure_clean(ext) as f, pytest.raises(ValueError, match=msg): + ExcelWriter(f, engine="xlsxwriter", mode="a") @pytest.mark.parametrize("nan_inf_to_errors", [True, False]) def test_engine_kwargs(ext, nan_inf_to_errors): # GH 42286 engine_kwargs = {"options": {"nan_inf_to_errors": nan_inf_to_errors}} - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="xlsxwriter", engine_kwargs=engine_kwargs) as writer: - assert writer.book.nan_inf_to_errors == nan_inf_to_errors + with tm.ensure_clean(ext) as f, ExcelWriter( + f, + engine="xlsxwriter", + engine_kwargs=engine_kwargs, + ) as writer: + assert writer.book.nan_inf_to_errors == nan_inf_to_errors def test_book_and_sheets_consistent(ext): # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="xlsxwriter") as writer: - assert writer.sheets == {} - sheet = writer.book.add_worksheet("test_name") - assert writer.sheets == {"test_name": sheet} + with tm.ensure_clean(ext) as f, ExcelWriter(f, engine="xlsxwriter") as writer: + assert writer.sheets == {} + sheet = writer.book.add_worksheet("test_name") + assert writer.sheets == {"test_name": sheet} diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py index 1c84816ead140..41ad442c1e52e 100644 --- a/pandas/tests/io/formats/style/test_format.py +++ b/pandas/tests/io/formats/style/test_format.py @@ -495,9 +495,11 @@ def test_formatter_options_validator(formatter, exp): def test_formatter_options_raises(): msg = "Value must be an instance of" - with pytest.raises(ValueError, match=msg): - with option_context("styler.format.formatter", ["bad", "type"]): - DataFrame().style.to_latex() + with pytest.raises( + ValueError, + match=msg, + ), option_context("styler.format.formatter", ["bad", "type"]): + DataFrame().style.to_latex() def test_1level_multiindex(): diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 6acef0f564ef4..88a8212e0903d 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -209,10 +209,9 @@ def test_show_counts(self, row, columns, show_counts, result): with option_context( "display.max_info_rows", row, "display.max_info_columns", columns - ): - with StringIO() as buf: - df.info(buf=buf, show_counts=show_counts) - assert ("non-null" in buf.getvalue()) is result + ), StringIO() as buf: + df.info(buf=buf, show_counts=show_counts) + assert ("non-null" in buf.getvalue()) is result def test_repr_truncation(self): max_len = 20 @@ -248,9 +247,8 @@ def test_max_colwidth_negative_int_raises(self): # https://github.com/pandas-dev/pandas/issues/31532 with pytest.raises( ValueError, match="Value must be a nonnegative integer or None" - ): - with option_context("display.max_colwidth", -1): - pass + ), option_context("display.max_colwidth", -1): + pass def test_repr_chop_threshold(self): df = DataFrame([[0.1, 0.5], [0.5, -0.1]]) @@ -340,32 +338,31 @@ def test_expand_frame_repr(self): df_wide = DataFrame("hello", index=[0], columns=range(10)) df_tall = DataFrame("hello", index=range(30), columns=range(5)) - with option_context("mode.sim_interactive", True): - with option_context( - "display.max_columns", - 10, - "display.width", - 20, - "display.max_rows", - 20, - "display.show_dimensions", - True, - ): - with option_context("display.expand_frame_repr", True): - assert not has_truncated_repr(df_small) - assert not has_expanded_repr(df_small) - assert not has_truncated_repr(df_wide) - assert has_expanded_repr(df_wide) - assert has_vertically_truncated_repr(df_tall) - assert has_expanded_repr(df_tall) - - with option_context("display.expand_frame_repr", False): - assert not has_truncated_repr(df_small) - assert not has_expanded_repr(df_small) - assert not has_horizontally_truncated_repr(df_wide) - assert not has_expanded_repr(df_wide) - assert has_vertically_truncated_repr(df_tall) - assert not has_expanded_repr(df_tall) + with option_context("mode.sim_interactive", True), option_context( + "display.max_columns", + 10, + "display.width", + 20, + "display.max_rows", + 20, + "display.show_dimensions", + True, + ): + with option_context("display.expand_frame_repr", True): + assert not has_truncated_repr(df_small) + assert not has_expanded_repr(df_small) + assert not has_truncated_repr(df_wide) + assert has_expanded_repr(df_wide) + assert has_vertically_truncated_repr(df_tall) + assert has_expanded_repr(df_tall) + + with option_context("display.expand_frame_repr", False): + assert not has_truncated_repr(df_small) + assert not has_expanded_repr(df_small) + assert not has_horizontally_truncated_repr(df_wide) + assert not has_expanded_repr(df_wide) + assert has_vertically_truncated_repr(df_tall) + assert not has_expanded_repr(df_tall) def test_repr_non_interactive(self): # in non interactive mode, there can be no dependency on the @@ -546,28 +543,50 @@ def test_auto_detect(self): cols = range(int(term_width * fac)) index = range(10) df = DataFrame(index=index, columns=cols) - with option_context("mode.sim_interactive", True): - with option_context("display.max_rows", None): - with option_context("display.max_columns", None): - # Wrap around with None - assert has_expanded_repr(df) - with option_context("display.max_rows", 0): - with option_context("display.max_columns", 0): - # Truncate with auto detection. - assert has_horizontally_truncated_repr(df) + with option_context( + "mode.sim_interactive", + True, + ), option_context( + "display.max_rows", + None, + ), option_context( + "display.max_columns", + None, + ): + # Wrap around with None + assert has_expanded_repr(df) + with option_context( + "display.max_rows", + 0, + ), option_context( + "display.max_columns", + 0, + ): + # Truncate with auto detection. + assert has_horizontally_truncated_repr(df) - index = range(int(term_height * fac)) - df = DataFrame(index=index, columns=cols) - with option_context("display.max_rows", 0): - with option_context("display.max_columns", None): - # Wrap around with None - assert has_expanded_repr(df) - # Truncate vertically - assert has_vertically_truncated_repr(df) + index = range(int(term_height * fac)) + df = DataFrame(index=index, columns=cols) + with option_context( + "display.max_rows", + 0, + ), option_context( + "display.max_columns", + None, + ): + # Wrap around with None + assert has_expanded_repr(df) + # Truncate vertically + assert has_vertically_truncated_repr(df) - with option_context("display.max_rows", None): - with option_context("display.max_columns", 0): - assert has_horizontally_truncated_repr(df) + with option_context( + "display.max_rows", + None, + ), option_context( + "display.max_columns", + 0, + ): + assert has_horizontally_truncated_repr(df) def test_to_string_repr_unicode(self): buf = StringIO() diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index a208daaf9f77b..7fd2aca9c7661 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -78,9 +78,11 @@ def test_to_csv_quotechar(self): with open(path, encoding="utf-8") as f: assert f.read() == expected - with tm.ensure_clean("test.csv") as path: - with pytest.raises(TypeError, match="quotechar"): - df.to_csv(path, quoting=1, quotechar=None) + with tm.ensure_clean("test.csv") as path, pytest.raises( + TypeError, + match="quotechar", + ): + df.to_csv(path, quoting=1, quotechar=None) def test_to_csv_doublequote(self): df = DataFrame({"col": ['a"a', '"bb"']}) @@ -95,9 +97,11 @@ def test_to_csv_doublequote(self): with open(path, encoding="utf-8") as f: assert f.read() == expected - with tm.ensure_clean("test.csv") as path: - with pytest.raises(Error, match="escapechar"): - df.to_csv(path, doublequote=False) # no escapechar set + with tm.ensure_clean("test.csv") as path, pytest.raises( + Error, + match="escapechar", + ): + df.to_csv(path, doublequote=False) # no escapechar set def test_to_csv_escapechar(self): df = DataFrame({"col": ['a"a', '"bb"']}) @@ -582,9 +586,8 @@ def test_to_csv_compression_dict_no_method_raises(self): compression = {"some_option": True} msg = "must have key 'method'" - with tm.ensure_clean("out.zip") as path: - with pytest.raises(ValueError, match=msg): - df.to_csv(path, compression=compression) + with tm.ensure_clean("out.zip") as path, pytest.raises(ValueError, match=msg): + df.to_csv(path, compression=compression) @pytest.mark.parametrize("compression", ["zip", "infer"]) @pytest.mark.parametrize("archive_name", ["test_to_csv.csv", "test_to_csv.zip"]) @@ -702,12 +705,11 @@ def test_to_csv_encoding_binary_handle(self, mode): assert buffer.getvalue().startswith(content) # example from GH 13068 - with tm.ensure_clean() as path: - with open(path, "w+b") as handle: - DataFrame().to_csv(handle, mode=mode, encoding="utf-8-sig") + with tm.ensure_clean() as path, open(path, "w+b") as handle: + DataFrame().to_csv(handle, mode=mode, encoding="utf-8-sig") - handle.seek(0) - assert handle.read().startswith(b'\xef\xbb\xbf""') + handle.seek(0) + assert handle.read().startswith(b'\xef\xbb\xbf""') def test_to_csv_iterative_compression_name(compression): diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index 7d7614bc93845..0576db785dd38 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -130,11 +130,10 @@ def test_readjson_chunks(request, lines_json_df, chunksize, engine): def test_readjson_chunksize_requires_lines(lines_json_df, engine): msg = "chunksize can only be passed if lines=True" - with pytest.raises(ValueError, match=msg): - with read_json( - StringIO(lines_json_df), lines=False, chunksize=2, engine=engine - ) as _: - pass + with pytest.raises(ValueError, match=msg), read_json( + StringIO(lines_json_df), lines=False, chunksize=2, engine=engine + ) as _: + pass def test_readjson_chunks_series(request, engine): @@ -230,11 +229,10 @@ def test_readjson_chunks_closes(chunksize): def test_readjson_invalid_chunksize(lines_json_df, chunksize, engine): msg = r"'chunksize' must be an integer >=1" - with pytest.raises(ValueError, match=msg): - with read_json( - StringIO(lines_json_df), lines=True, chunksize=chunksize, engine=engine - ) as _: - pass + with pytest.raises(ValueError, match=msg), read_json( + StringIO(lines_json_df), lines=True, chunksize=chunksize, engine=engine + ) as _: + pass @pytest.mark.parametrize("chunksize", [None, 1, 2]) diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py index 6be7269cb8433..24a3146b5da82 100644 --- a/pandas/tests/io/parser/common/test_chunksize.py +++ b/pandas/tests/io/parser/common/test_chunksize.py @@ -63,9 +63,14 @@ def test_read_chunksize_bad(all_parsers, chunksize): parser = all_parsers msg = r"'chunksize' must be an integer >=1" - with pytest.raises(ValueError, match=msg): - with parser.read_csv(StringIO(data), chunksize=chunksize) as _: - pass + with pytest.raises( + ValueError, + match=msg, + ), parser.read_csv( + StringIO(data), + chunksize=chunksize, + ) as _: + pass @pytest.mark.parametrize("chunksize", [2, 8]) diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py index ba196a532adf6..f7e7128ae7a60 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -406,9 +406,11 @@ def test_context_manageri_user_provided(all_parsers, datapath): def test_file_descriptor_leak(all_parsers, using_copy_on_write): # GH 31488 parser = all_parsers - with tm.ensure_clean() as path: - with pytest.raises(EmptyDataError, match="No columns to parse from file"): - parser.read_csv(path) + with tm.ensure_clean() as path, pytest.raises( + EmptyDataError, + match="No columns to parse from file", + ): + parser.read_csv(path) def test_memory_map(all_parsers, csv_dir_path): diff --git a/pandas/tests/io/parser/common/test_iterator.py b/pandas/tests/io/parser/common/test_iterator.py index 58e5886aedd6b..5bd7ce9400424 100644 --- a/pandas/tests/io/parser/common/test_iterator.py +++ b/pandas/tests/io/parser/common/test_iterator.py @@ -85,9 +85,15 @@ def test_iterator_skipfooter_errors(all_parsers, kwargs): parser = all_parsers data = "a\n1\n2" - with pytest.raises(ValueError, match=msg): - with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _: - pass + with pytest.raises( + ValueError, + match=msg, + ), parser.read_csv( + StringIO(data), + skipfooter=1, + **kwargs, + ) as _: + pass def test_iteration_open_handle(all_parsers): diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py index 817daad9849c0..9225c2bcf2af5 100644 --- a/pandas/tests/io/parser/common/test_read_errors.py +++ b/pandas/tests/io/parser/common/test_read_errors.py @@ -52,9 +52,8 @@ def test_bad_stream_exception(all_parsers, csv_dir_path): # Stream must be binary UTF8. with open(path, "rb") as handle, codecs.StreamRecoder( handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter - ) as stream: - with pytest.raises(UnicodeDecodeError, match=msg): - parser.read_csv(stream) + ) as stream, pytest.raises(UnicodeDecodeError, match=msg): + parser.read_csv(stream) def test_malformed(all_parsers): @@ -85,9 +84,8 @@ def test_malformed_chunks(all_parsers, nrows): msg = "Expected 3 fields in line 6, saw 5" with parser.read_csv( StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2] - ) as reader: - with pytest.raises(ParserError, match=msg): - reader.read(nrows) + ) as reader, pytest.raises(ParserError, match=msg): + reader.read(nrows) def test_catch_too_many_names(all_parsers): diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py index 818c4f3522606..d3b7799e21349 100644 --- a/pandas/tests/io/parser/test_c_parser_only.py +++ b/pandas/tests/io/parser/test_c_parser_only.py @@ -113,15 +113,20 @@ def test_dtype_and_names_error(c_parser_only): """ # fallback casting, but not castable warning = RuntimeWarning if np_version_gte1p24 else None - with pytest.raises(ValueError, match="cannot safely convert"): - with tm.assert_produces_warning(warning, check_stacklevel=False): - parser.read_csv( - StringIO(data), - sep=r"\s+", - header=None, - names=["a", "b"], - dtype={"a": np.int32}, - ) + with pytest.raises( + ValueError, + match="cannot safely convert", + ), tm.assert_produces_warning( + warning, + check_stacklevel=False, + ): + parser.read_csv( + StringIO(data), + sep=r"\s+", + header=None, + names=["a", "b"], + dtype={"a": np.int32}, + ) @pytest.mark.parametrize( @@ -600,10 +605,16 @@ def test_file_handles_mmap(c_parser_only, csv1): # Don't close user provided file handles. parser = c_parser_only - with open(csv1, encoding="utf-8") as f: - with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: - parser.read_csv(m) - assert not m.closed + with open( + csv1, + encoding="utf-8", + ) as f, mmap.mmap( + f.fileno(), + 0, + access=mmap.ACCESS_READ, + ) as m: + parser.read_csv(m) + assert not m.closed def test_file_binary_mode(c_parser_only): diff --git a/pandas/tests/io/parser/test_compression.py b/pandas/tests/io/parser/test_compression.py index bcba9c4a1823d..871cbf10b0bec 100644 --- a/pandas/tests/io/parser/test_compression.py +++ b/pandas/tests/io/parser/test_compression.py @@ -83,10 +83,11 @@ def test_zip_error_no_files(parser_and_data): def test_zip_error_invalid_zip(parser_and_data): parser, _, _ = parser_and_data - with tm.ensure_clean() as path: - with open(path, "rb") as f: - with pytest.raises(zipfile.BadZipFile, match="File is not a zip file"): - parser.read_csv(f, compression="zip") + with tm.ensure_clean() as path, open(path, "rb") as f, pytest.raises( + zipfile.BadZipFile, + match="File is not a zip file", + ): + parser.read_csv(f, compression="zip") @skip_pyarrow @@ -179,15 +180,18 @@ def test_compression_tar_archive(all_parsers, csv_dir_path): def test_ignore_compression_extension(all_parsers): parser = all_parsers df = DataFrame({"a": [0, 1]}) - with tm.ensure_clean("test.csv") as path_csv: - with tm.ensure_clean("test.csv.zip") as path_zip: - # make sure to create un-compressed file with zip extension - df.to_csv(path_csv, index=False) - Path(path_zip).write_text( - Path(path_csv).read_text(encoding="utf-8"), encoding="utf-8" - ) + with tm.ensure_clean( + "test.csv", + ) as path_csv, tm.ensure_clean( + "test.csv.zip", + ) as path_zip: + # make sure to create un-compressed file with zip extension + df.to_csv(path_csv, index=False) + Path(path_zip).write_text( + Path(path_csv).read_text(encoding="utf-8"), encoding="utf-8" + ) - tm.assert_frame_equal(parser.read_csv(path_zip, compression=None), df) + tm.assert_frame_equal(parser.read_csv(path_zip, compression=None), df) @skip_pyarrow diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index 1a9d99b0b5c1f..a9e702e5b8ce7 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -183,9 +183,8 @@ def test_close_file_handle_on_invalid_usecols(all_parsers): with tm.ensure_clean("test.csv") as fname: Path(fname).write_text("col1,col2\na,b\n1,2") - with tm.assert_produces_warning(False): - with pytest.raises(error, match="col3"): - parser.read_csv(fname, usecols=["col1", "col2", "col3"]) + with tm.assert_produces_warning(False), pytest.raises(error, match="col3"): + parser.read_csv(fname, usecols=["col1", "col2", "col3"]) # unlink fails on windows if file handles still point to it os.unlink(fname) diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index b31a520924d5f..3ab9b13871482 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -27,69 +27,68 @@ def test_append(setup_path): - with ensure_clean_store(setup_path) as store: + with ensure_clean_store( + setup_path, + ) as store, catch_warnings(record=True): # this is allowed by almost always don't want to do it # tables.NaturalNameWarning): - with catch_warnings(record=True): - df = tm.makeTimeDataFrame() - _maybe_remove(store, "df1") - store.append("df1", df[:10]) - store.append("df1", df[10:]) - tm.assert_frame_equal(store["df1"], df) + df = tm.makeTimeDataFrame() + _maybe_remove(store, "df1") + store.append("df1", df[:10]) + store.append("df1", df[10:]) + tm.assert_frame_equal(store["df1"], df) - _maybe_remove(store, "df2") - store.put("df2", df[:10], format="table") - store.append("df2", df[10:]) - tm.assert_frame_equal(store["df2"], df) + _maybe_remove(store, "df2") + store.put("df2", df[:10], format="table") + store.append("df2", df[10:]) + tm.assert_frame_equal(store["df2"], df) - _maybe_remove(store, "df3") - store.append("/df3", df[:10]) - store.append("/df3", df[10:]) - tm.assert_frame_equal(store["df3"], df) + _maybe_remove(store, "df3") + store.append("/df3", df[:10]) + store.append("/df3", df[10:]) + tm.assert_frame_equal(store["df3"], df) - # this is allowed by almost always don't want to do it - # tables.NaturalNameWarning - _maybe_remove(store, "/df3 foo") - store.append("/df3 foo", df[:10]) - store.append("/df3 foo", df[10:]) - tm.assert_frame_equal(store["df3 foo"], df) - - # dtype issues - mizxed type in a single object column - df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]]) - df["mixed_column"] = "testing" - df.loc[2, "mixed_column"] = np.nan - _maybe_remove(store, "df") - store.append("df", df) - tm.assert_frame_equal(store["df"], df) + # this is allowed by almost always don't want to do it + # tables.NaturalNameWarning + _maybe_remove(store, "/df3 foo") + store.append("/df3 foo", df[:10]) + store.append("/df3 foo", df[10:]) + tm.assert_frame_equal(store["df3 foo"], df) + + # dtype issues - mizxed type in a single object column + df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]]) + df["mixed_column"] = "testing" + df.loc[2, "mixed_column"] = np.nan + _maybe_remove(store, "df") + store.append("df", df) + tm.assert_frame_equal(store["df"], df) - # uints - test storage of uints - uint_data = DataFrame( - { - "u08": Series( - np.random.randint(0, high=255, size=5), dtype=np.uint8 - ), - "u16": Series( - np.random.randint(0, high=65535, size=5), dtype=np.uint16 - ), - "u32": Series( - np.random.randint(0, high=2**30, size=5), dtype=np.uint32 - ), - "u64": Series( - [2**58, 2**59, 2**60, 2**61, 2**62], - dtype=np.uint64, - ), - }, - index=np.arange(5), - ) - _maybe_remove(store, "uints") - store.append("uints", uint_data) - tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True) + # uints - test storage of uints + uint_data = DataFrame( + { + "u08": Series(np.random.randint(0, high=255, size=5), dtype=np.uint8), + "u16": Series( + np.random.randint(0, high=65535, size=5), dtype=np.uint16 + ), + "u32": Series( + np.random.randint(0, high=2**30, size=5), dtype=np.uint32 + ), + "u64": Series( + [2**58, 2**59, 2**60, 2**61, 2**62], + dtype=np.uint64, + ), + }, + index=np.arange(5), + ) + _maybe_remove(store, "uints") + store.append("uints", uint_data) + tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True) - # uints - test storage of uints in indexable columns - _maybe_remove(store, "uints") - # 64-bit indices not yet supported - store.append("uints", uint_data, data_columns=["u08", "u16", "u32"]) - tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True) + # uints - test storage of uints in indexable columns + _maybe_remove(store, "uints") + # 64-bit indices not yet supported + store.append("uints", uint_data, data_columns=["u08", "u16", "u32"]) + tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True) def test_append_series(setup_path): @@ -342,82 +341,78 @@ def test_append_with_different_block_ordering(setup_path): def test_append_with_strings(setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - - def check_col(key, name, size): - assert ( - getattr(store.get_storer(key).table.description, name).itemsize - == size - ) - - # avoid truncation on elements - df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) - store.append("df_big", df) - tm.assert_frame_equal(store.select("df_big"), df) - check_col("df_big", "values_block_1", 15) - - # appending smaller string ok - df2 = DataFrame([[124, "asdqy"], [346, "dggnhefbdfb"]]) - store.append("df_big", df2) - expected = concat([df, df2]) - tm.assert_frame_equal(store.select("df_big"), expected) - check_col("df_big", "values_block_1", 15) - - # avoid truncation on elements - df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) - store.append("df_big2", df, min_itemsize={"values": 50}) - tm.assert_frame_equal(store.select("df_big2"), df) - check_col("df_big2", "values_block_1", 50) - - # bigger string on next append - store.append("df_new", df) - df_new = DataFrame( - [[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]] - ) - msg = ( - r"Trying to store a string with len \[26\] in " - r"\[values_block_1\] column but\n" - r"this column has a limit of \[15\]!\n" - "Consider using min_itemsize to preset the sizes on these " - "columns" + with ensure_clean_store(setup_path) as store, catch_warnings(record=True): + + def check_col(key, name, size): + assert ( + getattr(store.get_storer(key).table.description, name).itemsize == size ) - with pytest.raises(ValueError, match=msg): - store.append("df_new", df_new) - - # min_itemsize on Series index (GH 11412) - df = tm.makeMixedDataFrame().set_index("C") - store.append("ss", df["B"], min_itemsize={"index": 4}) - tm.assert_series_equal(store.select("ss"), df["B"]) - - # same as above, with data_columns=True - store.append("ss2", df["B"], data_columns=True, min_itemsize={"index": 4}) - tm.assert_series_equal(store.select("ss2"), df["B"]) - - # min_itemsize in index without appending (GH 10381) - store.put("ss3", df, format="table", min_itemsize={"index": 6}) - # just make sure there is a longer string: - df2 = df.copy().reset_index().assign(C="longer").set_index("C") - store.append("ss3", df2) - tm.assert_frame_equal(store.select("ss3"), concat([df, df2])) - - # same as above, with a Series - store.put("ss4", df["B"], format="table", min_itemsize={"index": 6}) - store.append("ss4", df2["B"]) - tm.assert_series_equal(store.select("ss4"), concat([df["B"], df2["B"]])) - - # with nans - _maybe_remove(store, "df") - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df.loc[df.index[1:4], "string"] = np.nan - df["string2"] = "bar" - df.loc[df.index[4:8], "string2"] = np.nan - df["string3"] = "bah" - df.loc[df.index[1:], "string3"] = np.nan - store.append("df", df) - result = store.select("df") - tm.assert_frame_equal(result, df) + + # avoid truncation on elements + df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) + store.append("df_big", df) + tm.assert_frame_equal(store.select("df_big"), df) + check_col("df_big", "values_block_1", 15) + + # appending smaller string ok + df2 = DataFrame([[124, "asdqy"], [346, "dggnhefbdfb"]]) + store.append("df_big", df2) + expected = concat([df, df2]) + tm.assert_frame_equal(store.select("df_big"), expected) + check_col("df_big", "values_block_1", 15) + + # avoid truncation on elements + df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) + store.append("df_big2", df, min_itemsize={"values": 50}) + tm.assert_frame_equal(store.select("df_big2"), df) + check_col("df_big2", "values_block_1", 50) + + # bigger string on next append + store.append("df_new", df) + df_new = DataFrame([[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]]) + msg = ( + r"Trying to store a string with len \[26\] in " + r"\[values_block_1\] column but\n" + r"this column has a limit of \[15\]!\n" + "Consider using min_itemsize to preset the sizes on these " + "columns" + ) + with pytest.raises(ValueError, match=msg): + store.append("df_new", df_new) + + # min_itemsize on Series index (GH 11412) + df = tm.makeMixedDataFrame().set_index("C") + store.append("ss", df["B"], min_itemsize={"index": 4}) + tm.assert_series_equal(store.select("ss"), df["B"]) + + # same as above, with data_columns=True + store.append("ss2", df["B"], data_columns=True, min_itemsize={"index": 4}) + tm.assert_series_equal(store.select("ss2"), df["B"]) + + # min_itemsize in index without appending (GH 10381) + store.put("ss3", df, format="table", min_itemsize={"index": 6}) + # just make sure there is a longer string: + df2 = df.copy().reset_index().assign(C="longer").set_index("C") + store.append("ss3", df2) + tm.assert_frame_equal(store.select("ss3"), concat([df, df2])) + + # same as above, with a Series + store.put("ss4", df["B"], format="table", min_itemsize={"index": 6}) + store.append("ss4", df2["B"]) + tm.assert_series_equal(store.select("ss4"), concat([df["B"], df2["B"]])) + + # with nans + _maybe_remove(store, "df") + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df.loc[df.index[1:4], "string"] = np.nan + df["string2"] = "bar" + df.loc[df.index[4:8], "string2"] = np.nan + df["string3"] = "bah" + df.loc[df.index[1:], "string3"] = np.nan + store.append("df", df) + result = store.select("df") + tm.assert_frame_equal(result, df) with ensure_clean_store(setup_path) as store: df = DataFrame({"A": "foo", "B": "bar"}, index=range(10)) diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py index 051221d165060..1079484ae9f2a 100644 --- a/pandas/tests/io/pytables/test_complex.py +++ b/pandas/tests/io/pytables/test_complex.py @@ -160,9 +160,8 @@ def test_complex_indexing_error(setup_path): "values to data_columns when initializing the table." ) - with ensure_clean_store(setup_path) as store: - with pytest.raises(TypeError, match=msg): - store.append("df", df, data_columns=["C"]) + with ensure_clean_store(setup_path) as store, pytest.raises(TypeError, match=msg): + store.append("df", df, data_columns=["C"]) def test_complex_series_error(tmp_path, setup_path): diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py index 295cce970889c..8b7092185c325 100644 --- a/pandas/tests/io/pytables/test_errors.py +++ b/pandas/tests/io/pytables/test_errors.py @@ -85,32 +85,29 @@ def test_unimplemented_dtypes_table_columns(setup_path): def test_invalid_terms(tmp_path, setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df.loc[df.index[0:4], "string"] = "bar" + with ensure_clean_store(setup_path) as store, catch_warnings(record=True): + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df.loc[df.index[0:4], "string"] = "bar" - store.put("df", df, format="table") + store.put("df", df, format="table") - # some invalid terms - msg = re.escape( - "__init__() missing 1 required positional argument: 'where'" - ) - with pytest.raises(TypeError, match=msg): - Term() + # some invalid terms + msg = re.escape("__init__() missing 1 required positional argument: 'where'") + with pytest.raises(TypeError, match=msg): + Term() - # more invalid - msg = re.escape( - "cannot process expression [df.index[3]], " - "[2000-01-06 00:00:00] is not a valid condition" - ) - with pytest.raises(ValueError, match=msg): - store.select("df", "df.index[3]") + # more invalid + msg = re.escape( + "cannot process expression [df.index[3]], " + "[2000-01-06 00:00:00] is not a valid condition" + ) + with pytest.raises(ValueError, match=msg): + store.select("df", "df.index[3]") - msg = "invalid syntax" - with pytest.raises(SyntaxError, match=msg): - store.select("df", "index>") + msg = "invalid syntax" + with pytest.raises(SyntaxError, match=msg): + store.select("df", "index>") # from the docs path = tmp_path / setup_path diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py index 49190daa37442..b0ace7530412d 100644 --- a/pandas/tests/io/pytables/test_file_handling.py +++ b/pandas/tests/io/pytables/test_file_handling.py @@ -47,9 +47,8 @@ def test_mode(setup_path, tmp_path, mode): # context if mode in ["r", "r+"]: - with pytest.raises(OSError, match=msg): - with HDFStore(path, mode=mode) as store: - pass + with pytest.raises(OSError, match=msg), HDFStore(path, mode=mode) as store: + pass else: with HDFStore(path, mode=mode) as store: assert store._handle.mode == mode @@ -434,6 +433,5 @@ def test_multiple_open_close(tmp_path, setup_path): def test_fspath(): - with tm.ensure_clean("foo.h5") as path: - with HDFStore(path) as store: - assert os.fspath(store) == str(path) + with tm.ensure_clean("foo.h5") as path, HDFStore(path) as store: + assert os.fspath(store) == str(path) diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py index 0dcc9f7f1b9c2..c3d255843c218 100644 --- a/pandas/tests/io/pytables/test_keys.py +++ b/pandas/tests/io/pytables/test_keys.py @@ -52,12 +52,11 @@ class Table3(tables.IsDescription): def test_keys_illegal_include_keyword_value(setup_path): - with ensure_clean_store(setup_path) as store: - with pytest.raises( - ValueError, - match="`include` should be either 'pandas' or 'native' but is 'illegal'", - ): - store.keys(include="illegal") + with ensure_clean_store(setup_path) as store, pytest.raises( + ValueError, + match="`include` should be either 'pandas' or 'native' but is 'illegal'", + ): + store.keys(include="illegal") def test_keys_ignore_hdf_softlink(setup_path): diff --git a/pandas/tests/io/pytables/test_pytables_missing.py b/pandas/tests/io/pytables/test_pytables_missing.py index 9adb0a6d227da..2a39dafdf347c 100644 --- a/pandas/tests/io/pytables/test_pytables_missing.py +++ b/pandas/tests/io/pytables/test_pytables_missing.py @@ -9,6 +9,5 @@ @td.skip_if_installed("tables") def test_pytables_raises(): df = pd.DataFrame({"A": [1, 2]}) - with pytest.raises(ImportError, match="tables"): - with tm.ensure_clean("foo.h5") as path: - df.to_hdf(path, "df") + with pytest.raises(ImportError, match="tables"), tm.ensure_clean("foo.h5") as path: + df.to_hdf(path, "df") diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py index f14a3ad7c5e10..eb7b7aecbdab3 100644 --- a/pandas/tests/io/pytables/test_select.py +++ b/pandas/tests/io/pytables/test_select.py @@ -120,41 +120,40 @@ def test_select_with_dups(setup_path): def test_select(setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - # select with columns= - df = tm.makeTimeDataFrame() - _maybe_remove(store, "df") - store.append("df", df) - result = store.select("df", columns=["A", "B"]) - expected = df.reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) + with ensure_clean_store(setup_path) as store, catch_warnings(record=True): + # select with columns= + df = tm.makeTimeDataFrame() + _maybe_remove(store, "df") + store.append("df", df) + result = store.select("df", columns=["A", "B"]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) - # equivalently - result = store.select("df", [("columns=['A', 'B']")]) - expected = df.reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) + # equivalently + result = store.select("df", [("columns=['A', 'B']")]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) - # with a data column - _maybe_remove(store, "df") - store.append("df", df, data_columns=["A"]) - result = store.select("df", ["A > 0"], columns=["A", "B"]) - expected = df[df.A > 0].reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) + # with a data column + _maybe_remove(store, "df") + store.append("df", df, data_columns=["A"]) + result = store.select("df", ["A > 0"], columns=["A", "B"]) + expected = df[df.A > 0].reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) - # all a data columns - _maybe_remove(store, "df") - store.append("df", df, data_columns=True) - result = store.select("df", ["A > 0"], columns=["A", "B"]) - expected = df[df.A > 0].reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) + # all a data columns + _maybe_remove(store, "df") + store.append("df", df, data_columns=True) + result = store.select("df", ["A > 0"], columns=["A", "B"]) + expected = df[df.A > 0].reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) - # with a data column, but different columns - _maybe_remove(store, "df") - store.append("df", df, data_columns=["A"]) - result = store.select("df", ["A > 0"], columns=["C", "D"]) - expected = df[df.A > 0].reindex(columns=["C", "D"]) - tm.assert_frame_equal(expected, result) + # with a data column, but different columns + _maybe_remove(store, "df") + store.append("df", df, data_columns=["A"]) + result = store.select("df", ["A > 0"], columns=["C", "D"]) + expected = df[df.A > 0].reindex(columns=["C", "D"]) + tm.assert_frame_equal(expected, result) def test_select_dtypes(setup_path): diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 2d87b719af36b..6706c995cbbc3 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -47,11 +47,10 @@ def test_context(setup_path): raise ValueError("blah") except ValueError: pass - with tm.ensure_clean(setup_path) as path: - with HDFStore(path) as tbl: - tbl["a"] = tm.makeDataFrame() - assert len(tbl) == 1 - assert type(tbl["a"]) == DataFrame + with tm.ensure_clean(setup_path) as path, HDFStore(path) as tbl: + tbl["a"] = tm.makeDataFrame() + assert len(tbl) == 1 + assert type(tbl["a"]) == DataFrame def test_no_track_times(tmp_path, setup_path): @@ -337,64 +336,62 @@ def test_to_hdf_errors(tmp_path, format, setup_path): def test_create_table_index(setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - - def col(t, column): - return getattr(store.get_storer(t).table.cols, column) + with ensure_clean_store(setup_path) as store, catch_warnings(record=True): - # data columns - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df["string2"] = "bar" - store.append("f", df, data_columns=["string", "string2"]) - assert col("f", "index").is_indexed is True - assert col("f", "string").is_indexed is True - assert col("f", "string2").is_indexed is True + def col(t, column): + return getattr(store.get_storer(t).table.cols, column) - # specify index=columns - store.append("f2", df, index=["string"], data_columns=["string", "string2"]) - assert col("f2", "index").is_indexed is False - assert col("f2", "string").is_indexed is True - assert col("f2", "string2").is_indexed is False - - # try to index a non-table - _maybe_remove(store, "f2") - store.put("f2", df) - msg = "cannot create table index on a Fixed format store" - with pytest.raises(TypeError, match=msg): - store.create_table_index("f2") + # data columns + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df["string2"] = "bar" + store.append("f", df, data_columns=["string", "string2"]) + assert col("f", "index").is_indexed is True + assert col("f", "string").is_indexed is True + assert col("f", "string2").is_indexed is True + + # specify index=columns + store.append("f2", df, index=["string"], data_columns=["string", "string2"]) + assert col("f2", "index").is_indexed is False + assert col("f2", "string").is_indexed is True + assert col("f2", "string2").is_indexed is False + + # try to index a non-table + _maybe_remove(store, "f2") + store.put("f2", df) + msg = "cannot create table index on a Fixed format store" + with pytest.raises(TypeError, match=msg): + store.create_table_index("f2") def test_create_table_index_data_columns_argument(setup_path): # GH 28156 - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): + with ensure_clean_store(setup_path) as store, catch_warnings(record=True): - def col(t, column): - return getattr(store.get_storer(t).table.cols, column) + def col(t, column): + return getattr(store.get_storer(t).table.cols, column) - # data columns - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df["string2"] = "bar" - store.append("f", df, data_columns=["string"]) - assert col("f", "index").is_indexed is True - assert col("f", "string").is_indexed is True + # data columns + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df["string2"] = "bar" + store.append("f", df, data_columns=["string"]) + assert col("f", "index").is_indexed is True + assert col("f", "string").is_indexed is True - msg = "'Cols' object has no attribute 'string2'" - with pytest.raises(AttributeError, match=msg): - col("f", "string2").is_indexed + msg = "'Cols' object has no attribute 'string2'" + with pytest.raises(AttributeError, match=msg): + col("f", "string2").is_indexed - # try to index a col which isn't a data_column - msg = ( - "column string2 is not a data_column.\n" - "In order to read column string2 you must reload the dataframe \n" - "into HDFStore and include string2 with the data_columns argument." - ) - with pytest.raises(AttributeError, match=msg): - store.create_table_index("f", columns=["string2"]) + # try to index a col which isn't a data_column + msg = ( + "column string2 is not a data_column.\n" + "In order to read column string2 you must reload the dataframe \n" + "into HDFStore and include string2 with the data_columns argument." + ) + with pytest.raises(AttributeError, match=msg): + store.create_table_index("f", columns=["string2"]) def test_mi_data_columns(setup_path): diff --git a/pandas/tests/io/sas/test_sas.py b/pandas/tests/io/sas/test_sas.py index 1e38baf4fc409..4c1e5ee2a6a7f 100644 --- a/pandas/tests/io/sas/test_sas.py +++ b/pandas/tests/io/sas/test_sas.py @@ -21,9 +21,13 @@ def test_sas_buffer_format(self): def test_sas_read_no_format_or_extension(self): # see gh-24548 msg = "unable to infer format of SAS file.+" - with tm.ensure_clean("test_file_no_extension") as path: - with pytest.raises(ValueError, match=msg): - read_sas(path) + with tm.ensure_clean( + "test_file_no_extension", + ) as path, pytest.raises( + ValueError, + match=msg, + ): + read_sas(path) def test_sas_archive(datapath): diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 435b9bdade944..4b56488716b81 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -96,9 +96,11 @@ def test_stringify_path_fspath(self): def test_stringify_file_and_path_like(self): # GH 38125: do not stringify file objects that are also path-like fsspec = pytest.importorskip("fsspec") - with tm.ensure_clean() as path: - with fsspec.open(f"file://{path}", mode="wb") as fsspec_obj: - assert fsspec_obj == icom.stringify_path(fsspec_obj) + with tm.ensure_clean() as path, fsspec.open( + f"file://{path}", + mode="wb", + ) as fsspec_obj: + assert fsspec_obj == icom.stringify_path(fsspec_obj) @pytest.mark.parametrize("path_type", path_types) def test_infer_compression_from_path(self, compression_format, path_type): @@ -509,12 +511,10 @@ def test_codecs_get_writer_reader(): # GH39247 expected = tm.makeDataFrame() with tm.ensure_clean() as path: - with open(path, "wb") as handle: - with codecs.getwriter("utf-8")(handle) as encoded: - expected.to_csv(encoded) - with open(path, "rb") as handle: - with codecs.getreader("utf-8")(handle) as encoded: - df = pd.read_csv(encoded, index_col=0) + with open(path, "wb") as handle, codecs.getwriter("utf-8")(handle) as encoded: + expected.to_csv(encoded) + with open(path, "rb") as handle, codecs.getreader("utf-8")(handle) as encoded: + df = pd.read_csv(encoded, index_col=0) tm.assert_frame_equal(expected, df) @@ -530,9 +530,8 @@ def test_explicit_encoding(io_class, mode, msg): # it is used. In the case of this test it leads to an error as intentionally the # wrong mode is requested expected = tm.makeDataFrame() - with io_class() as buffer: - with pytest.raises(TypeError, match=msg): - expected.to_csv(buffer, mode=f"w{mode}") + with io_class() as buffer, pytest.raises(TypeError, match=msg): + expected.to_csv(buffer, mode=f"w{mode}") @pytest.mark.parametrize("encoding_errors", [None, "strict", "replace"]) @@ -572,9 +571,11 @@ def test_encoding_errors(encoding_errors, format): def test_bad_encdoing_errors(): # GH 39777 - with tm.ensure_clean() as path: - with pytest.raises(LookupError, match="unknown error handler name"): - icom.get_handle(path, "w", errors="bad") + with tm.ensure_clean() as path, pytest.raises( + LookupError, + match="unknown error handler name", + ): + icom.get_handle(path, "w", errors="bad") def test_errno_attribute(): @@ -585,9 +586,8 @@ def test_errno_attribute(): def test_fail_mmap(): - with pytest.raises(UnsupportedOperation, match="fileno"): - with BytesIO() as buffer: - icom.get_handle(buffer, "rb", memory_map=True) + with pytest.raises(UnsupportedOperation, match="fileno"), BytesIO() as buffer: + icom.get_handle(buffer, "rb", memory_map=True) def test_close_on_error(): @@ -596,10 +596,14 @@ class TestError: def close(self): raise OSError("test") - with pytest.raises(OSError, match="test"): - with BytesIO() as buffer: - with icom.get_handle(buffer, "rb") as handles: - handles.created_handles.append(TestError()) + with pytest.raises( + OSError, + match="test", + ), BytesIO() as buffer, icom.get_handle( + buffer, + "rb", + ) as handles: + handles.created_handles.append(TestError()) @pytest.mark.parametrize( diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index eadf35aedd708..cb5f9278a1d45 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -129,10 +129,12 @@ def test_compression_warning(compression_only): 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], columns=["X", "Y", "Z"], ) - with tm.ensure_clean() as path: - with icom.get_handle(path, "w", compression=compression_only) as handles: - with tm.assert_produces_warning(RuntimeWarning): - df.to_csv(handles.handle, compression=compression_only) + with tm.ensure_clean() as path, icom.get_handle( + path, + "w", + compression=compression_only, + ) as handles, tm.assert_produces_warning(RuntimeWarning): + df.to_csv(handles.handle, compression=compression_only) def test_compression_binary(compression_only): @@ -320,21 +322,21 @@ def test_tar_gz_to_different_filename(): [["1", "2"]], columns=["foo", "bar"], ).to_csv(file, compression={"method": "tar", "mode": "w:gz"}, index=False) - with gzip.open(file) as uncompressed: - with tarfile.TarFile(fileobj=uncompressed) as archive: - members = archive.getmembers() - assert len(members) == 1 - content = archive.extractfile(members[0]).read().decode("utf8") + with gzip.open(file) as uncompressed, tarfile.TarFile( + fileobj=uncompressed, + ) as archive: + members = archive.getmembers() + assert len(members) == 1 + content = archive.extractfile(members[0]).read().decode("utf8") - if is_platform_windows(): - expected = "foo,bar\r\n1,2\r\n" - else: - expected = "foo,bar\n1,2\n" + if is_platform_windows(): + expected = "foo,bar\r\n1,2\r\n" + else: + expected = "foo,bar\n1,2\n" - assert content == expected + assert content == expected def test_tar_no_error_on_close(): - with io.BytesIO() as buffer: - with icom._BytesTarFile(fileobj=buffer, mode="w"): - pass + with io.BytesIO() as buffer, icom._BytesTarFile(fileobj=buffer, mode="w"): + pass diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 01e1be5529bad..d6f028b513113 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -20,17 +20,15 @@ def check_error_on_write(self, df, exc, err_msg): # check that we are raising the exception # on writing - with pytest.raises(exc, match=err_msg): - with tm.ensure_clean() as path: - to_feather(df, path) + with pytest.raises(exc, match=err_msg), tm.ensure_clean() as path: + to_feather(df, path) def check_external_error_on_write(self, df): # check that we are raising the exception # on writing - with tm.external_error_raised(Exception): - with tm.ensure_clean() as path: - to_feather(df, path) + with tm.external_error_raised(Exception), tm.ensure_clean() as path: + to_feather(df, path) def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs): if expected is None: diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 57ef03b380601..3d29fb540603c 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -365,15 +365,13 @@ def test_cross_engine_fp_pa(df_cross_compat, pa, fp): class Base: def check_error_on_write(self, df, engine, exc, err_msg): # check that we are raising the exception on writing - with tm.ensure_clean() as path: - with pytest.raises(exc, match=err_msg): - to_parquet(df, path, engine, compression=None) + with tm.ensure_clean() as path, pytest.raises(exc, match=err_msg): + to_parquet(df, path, engine, compression=None) def check_external_error_on_write(self, df, engine, exc): # check that an external library is raising the exception on writing - with tm.ensure_clean() as path: - with tm.external_error_raised(exc): - to_parquet(df, path, engine, compression=None) + with tm.ensure_clean() as path, tm.external_error_raised(exc): + to_parquet(df, path, engine, compression=None) @pytest.mark.network @tm.network( @@ -1233,9 +1231,11 @@ def test_use_nullable_dtypes_not_supported(self, fp): with tm.ensure_clean() as path: df.to_parquet(path) - with pytest.raises(ValueError, match="not supported for the fastparquet"): - with tm.assert_produces_warning(FutureWarning): - read_parquet(path, engine="fastparquet", use_nullable_dtypes=True) + with pytest.raises( + ValueError, + match="not supported for the fastparquet", + ), tm.assert_produces_warning(FutureWarning): + read_parquet(path, engine="fastparquet", use_nullable_dtypes=True) with pytest.raises(ValueError, match="not supported for the fastparquet"): read_parquet(path, engine="fastparquet", dtype_backend="pyarrow") @@ -1260,11 +1260,10 @@ def test_bytes_file_name(self, engine): def test_filesystem_notimplemented(self): pytest.importorskip("fastparquet") df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]}) - with tm.ensure_clean() as path: - with pytest.raises( - NotImplementedError, match="filesystem is not implemented" - ): - df.to_parquet(path, engine="fastparquet", filesystem="foo") + with tm.ensure_clean() as path, pytest.raises( + NotImplementedError, match="filesystem is not implemented" + ): + df.to_parquet(path, engine="fastparquet", filesystem="foo") with tm.ensure_clean() as path: pathlib.Path(path).write_bytes(b"foo") @@ -1276,11 +1275,10 @@ def test_filesystem_notimplemented(self): def test_invalid_filesystem(self): pytest.importorskip("pyarrow") df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]}) - with tm.ensure_clean() as path: - with pytest.raises( - ValueError, match="filesystem must be a pyarrow or fsspec FileSystem" - ): - df.to_parquet(path, engine="pyarrow", filesystem="foo") + with tm.ensure_clean() as path, pytest.raises( + ValueError, match="filesystem must be a pyarrow or fsspec FileSystem" + ): + df.to_parquet(path, engine="pyarrow", filesystem="foo") with tm.ensure_clean() as path: pathlib.Path(path).write_bytes(b"foo") @@ -1292,17 +1290,16 @@ def test_invalid_filesystem(self): def test_unsupported_pa_filesystem_storage_options(self): pa_fs = pytest.importorskip("pyarrow.fs") df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]}) - with tm.ensure_clean() as path: - with pytest.raises( - NotImplementedError, - match="storage_options not supported with a pyarrow FileSystem.", - ): - df.to_parquet( - path, - engine="pyarrow", - filesystem=pa_fs.LocalFileSystem(), - storage_options={"foo": "bar"}, - ) + with tm.ensure_clean() as path, pytest.raises( + NotImplementedError, + match="storage_options not supported with a pyarrow FileSystem.", + ): + df.to_parquet( + path, + engine="pyarrow", + filesystem=pa_fs.LocalFileSystem(), + storage_options={"foo": "bar"}, + ) with tm.ensure_clean() as path: pathlib.Path(path).write_bytes(b"foo") diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 60506aa2fbd0a..3350aed313e89 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -256,10 +256,9 @@ def compress_file(self, src_path, dest_path, compression): with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_DEFLATED) as f: f.write(src_path, os.path.basename(src_path)) elif compression == "tar": - with open(src_path, "rb") as fh: - with tarfile.open(dest_path, mode="w") as tar: - tarinfo = tar.gettarinfo(src_path, os.path.basename(src_path)) - tar.addfile(tarinfo, fh) + with open(src_path, "rb") as fh, tarfile.open(dest_path, mode="w") as tar: + tarinfo = tar.gettarinfo(src_path, os.path.basename(src_path)) + tar.addfile(tarinfo, fh) elif compression == "xz": f = get_lzma_file()(dest_path, "w") elif compression == "zstd": @@ -269,9 +268,8 @@ def compress_file(self, src_path, dest_path, compression): raise ValueError(msg) if compression not in ["zip", "tar"]: - with open(src_path, "rb") as fh: - with f: - f.write(fh.read()) + with open(src_path, "rb") as fh, f: + f.write(fh.read()) def test_write_explicit(self, compression, get_random_path): base = get_random_path @@ -285,9 +283,11 @@ def test_write_explicit(self, compression, get_random_path): df.to_pickle(p1, compression=compression) # decompress - with tm.decompress_file(p1, compression=compression) as f: - with open(p2, "wb") as fh: - fh.write(f.read()) + with tm.decompress_file( + p1, + compression=compression, + ) as f, open(p2, "wb") as fh: + fh.write(f.read()) # read decompressed file df2 = pd.read_pickle(p2, compression=None) @@ -296,10 +296,12 @@ def test_write_explicit(self, compression, get_random_path): @pytest.mark.parametrize("compression", ["", "None", "bad", "7z"]) def test_write_explicit_bad(self, compression, get_random_path): - with pytest.raises(ValueError, match="Unrecognized compression type"): - with tm.ensure_clean(get_random_path) as path: - df = tm.makeDataFrame() - df.to_pickle(path, compression=compression) + with pytest.raises( + ValueError, + match="Unrecognized compression type", + ), tm.ensure_clean(get_random_path) as path: + df = tm.makeDataFrame() + df.to_pickle(path, compression=compression) def test_write_infer(self, compression_ext, get_random_path): base = get_random_path @@ -314,9 +316,11 @@ def test_write_infer(self, compression_ext, get_random_path): df.to_pickle(p1) # decompress - with tm.decompress_file(p1, compression=compression) as f: - with open(p2, "wb") as fh: - fh.write(f.read()) + with tm.decompress_file( + p1, + compression=compression, + ) as f, open(p2, "wb") as fh: + fh.write(f.read()) # read decompressed file df2 = pd.read_pickle(p2, compression=None) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index a864903d9c6d1..7f7cf4f7ece59 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -155,11 +155,10 @@ def create_and_load_iris(conn, iris_file: Path, dialect: str): params = [dict(zip(header, row)) for row in reader] stmt = insert(iris).values(params) if isinstance(conn, Engine): - with conn.connect() as conn: - with conn.begin(): - iris.drop(conn, checkfirst=True) - iris.create(bind=conn) - conn.execute(stmt) + with conn.connect() as conn, conn.begin(): + iris.drop(conn, checkfirst=True) + iris.create(bind=conn) + conn.execute(stmt) else: with conn.begin(): iris.drop(conn, checkfirst=True) @@ -178,9 +177,8 @@ def create_and_load_iris_view(conn): stmt = text(stmt) if isinstance(conn, Engine): - with conn.connect() as conn: - with conn.begin(): - conn.execute(stmt) + with conn.connect() as conn, conn.begin(): + conn.execute(stmt) else: with conn.begin(): conn.execute(stmt) @@ -249,11 +247,10 @@ def create_and_load_types(conn, types_data: list[dict], dialect: str): stmt = insert(types).values(types_data) if isinstance(conn, Engine): - with conn.connect() as conn: - with conn.begin(): - types.drop(conn, checkfirst=True) - types.create(bind=conn) - conn.execute(stmt) + with conn.connect() as conn, conn.begin(): + types.drop(conn, checkfirst=True) + types.create(bind=conn) + conn.execute(stmt) else: with conn.begin(): types.drop(conn, checkfirst=True) @@ -410,10 +407,9 @@ def mysql_pymysql_engine(iris_path, types_data): entry.pop("DateColWithTz") create_and_load_types(engine, types_data, "mysql") yield engine - with engine.connect() as conn: - with conn.begin(): - stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;") - conn.execute(stmt) + with engine.connect() as conn, conn.begin(): + stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;") + conn.execute(stmt) engine.dispose() @@ -437,10 +433,9 @@ def postgresql_psycopg2_engine(iris_path, types_data): if not insp.has_table("types"): create_and_load_types(engine, types_data, "postgresql") yield engine - with engine.connect() as conn: - with conn.begin(): - stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;") - conn.execute(stmt) + with engine.connect() as conn, conn.begin(): + stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;") + conn.execute(stmt) engine.dispose() @@ -494,9 +489,10 @@ def sqlite_iris_conn(sqlite_iris_engine): @pytest.fixture def sqlite_buildin(): - with contextlib.closing(sqlite3.connect(":memory:")) as closing_conn: - with closing_conn as conn: - yield conn + with contextlib.closing( + sqlite3.connect(":memory:"), + ) as closing_conn, closing_conn as conn: + yield conn @pytest.fixture @@ -762,9 +758,8 @@ def test_read_procedure(conn, request): END""" proc = text(proc) if isinstance(conn, Engine): - with conn.connect() as engine_conn: - with engine_conn.begin(): - engine_conn.execute(proc) + with conn.connect() as engine_conn, engine_conn.begin(): + engine_conn.execute(proc) else: with conn.begin(): conn.execute(proc) @@ -818,13 +813,15 @@ def psql_insert_copy(table, conn, keys, data_iter): def test_execute_typeerror(sqlite_iris_engine): - with pytest.raises(TypeError, match="pandas.io.sql.execute requires a connection"): - with tm.assert_produces_warning( - FutureWarning, - match="`pandas.io.sql.execute` is deprecated and " - "will be removed in the future version.", - ): - sql.execute("select * from iris", sqlite_iris_engine) + with pytest.raises( + TypeError, + match="pandas.io.sql.execute requires a connection", + ), tm.assert_produces_warning( + FutureWarning, + match="`pandas.io.sql.execute` is deprecated and " + "will be removed in the future version.", + ): + sql.execute("select * from iris", sqlite_iris_engine) def test_execute_deprecated(sqlite_buildin_iris): @@ -1566,9 +1563,8 @@ def test_not_reflect_all_tables(self): ] for query in query_list: if isinstance(self.conn, Engine): - with self.conn.connect() as conn: - with conn.begin(): - conn.execute(query) + with self.conn.connect() as conn, conn.begin(): + conn.execute(query) else: with self.conn.begin(): self.conn.execute(query) @@ -1758,9 +1754,10 @@ def __getattr__(self, name): def close(self): self.conn.close() - with contextlib.closing(MockSqliteConnection(":memory:")) as conn: - with tm.assert_produces_warning(UserWarning): - sql.read_sql("SELECT 1", conn) + with contextlib.closing( + MockSqliteConnection(":memory:"), + ) as conn, tm.assert_produces_warning(UserWarning): + sql.read_sql("SELECT 1", conn) def test_read_sql_delegate(self): iris_frame1 = sql.read_sql_query("SELECT * FROM iris", self.conn) @@ -2241,9 +2238,8 @@ def test_get_schema_create_table(self, test_frame3): self.drop_table(tbl, self.conn) create_sql = text(create_sql) if isinstance(self.conn, Engine): - with self.conn.connect() as conn: - with conn.begin(): - conn.execute(create_sql) + with self.conn.connect() as conn, conn.begin(): + conn.execute(create_sql) else: with self.conn.begin(): self.conn.execute(create_sql) @@ -2380,9 +2376,8 @@ def test_connectable(conn): def main(connectable): if isinstance(connectable, Engine): - with connectable.connect() as conn: - with conn.begin(): - test_connectable(conn) + with connectable.connect() as conn, conn.begin(): + test_connectable(conn) else: test_connectable(connectable) @@ -2445,13 +2440,12 @@ class Temporary(Base): id = Column(Integer, primary_key=True) spam = Column(Unicode(30), nullable=False) - with Session(self.conn) as session: - with session.begin(): - conn = session.connection() - Temporary.__table__.create(conn) - session.add(Temporary(spam=test_data)) - session.flush() - df = sql.read_sql_query(sql=select(Temporary.spam), con=conn) + with Session(self.conn) as session, session.begin(): + conn = session.connection() + Temporary.__table__.create(conn) + session.add(Temporary(spam=test_data)) + session.flush() + df = sql.read_sql_query(sql=select(Temporary.spam), con=conn) tm.assert_frame_equal(df, expected) # -- SQL Engine tests (in the base class for now) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 1b0a1d740677b..549ef783ba015 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -789,9 +789,8 @@ def test_excessively_long_string(self): r"this restriction\. Use the\n'version=117' parameter to write " r"the newer \(Stata 13 and later\) format\." ) - with pytest.raises(ValueError, match=msg): - with tm.ensure_clean() as path: - original.to_stata(path) + with pytest.raises(ValueError, match=msg), tm.ensure_clean() as path: + original.to_stata(path) def test_missing_value_generator(self): types = ("b", "h", "l") @@ -1356,13 +1355,10 @@ def test_invalid_variable_label_encoding(self, version, mixed_frame): mixed_frame.index.name = "index" variable_labels = {"a": "very long" * 10, "b": "City Exponent", "c": "City"} variable_labels["a"] = "invalid character Œ" - with tm.ensure_clean() as path: - with pytest.raises( - ValueError, match="Variable labels must contain only characters" - ): - mixed_frame.to_stata( - path, variable_labels=variable_labels, version=version - ) + with tm.ensure_clean() as path, pytest.raises( + ValueError, match="Variable labels must contain only characters" + ): + mixed_frame.to_stata(path, variable_labels=variable_labels, version=version) def test_write_variable_label_errors(self, mixed_frame): values = ["\u03A1", "\u0391", "\u039D", "\u0394", "\u0391", "\u03A3"] @@ -1377,9 +1373,8 @@ def test_write_variable_label_errors(self, mixed_frame): "Variable labels must contain only characters that can be " "encoded in Latin-1" ) - with pytest.raises(ValueError, match=msg): - with tm.ensure_clean() as path: - mixed_frame.to_stata(path, variable_labels=variable_labels_utf8) + with pytest.raises(ValueError, match=msg), tm.ensure_clean() as path: + mixed_frame.to_stata(path, variable_labels=variable_labels_utf8) variable_labels_long = { "a": "City Rank", @@ -1390,9 +1385,8 @@ def test_write_variable_label_errors(self, mixed_frame): } msg = "Variable labels must be 80 characters or fewer" - with pytest.raises(ValueError, match=msg): - with tm.ensure_clean() as path: - mixed_frame.to_stata(path, variable_labels=variable_labels_long) + with pytest.raises(ValueError, match=msg), tm.ensure_clean() as path: + mixed_frame.to_stata(path, variable_labels=variable_labels_long) def test_default_date_conversion(self): # GH 12259 @@ -1427,9 +1421,8 @@ def test_unsupported_type(self): original = DataFrame({"a": [1 + 2j, 2 + 4j]}) msg = "Data type complex128 not supported" - with pytest.raises(NotImplementedError, match=msg): - with tm.ensure_clean() as path: - original.to_stata(path) + with pytest.raises(NotImplementedError, match=msg), tm.ensure_clean() as path: + original.to_stata(path) def test_unsupported_datetype(self): dates = [ @@ -1446,9 +1439,8 @@ def test_unsupported_datetype(self): ) msg = "Format %tC not implemented" - with pytest.raises(NotImplementedError, match=msg): - with tm.ensure_clean() as path: - original.to_stata(path, convert_dates={"dates": "tC"}) + with pytest.raises(NotImplementedError, match=msg), tm.ensure_clean() as path: + original.to_stata(path, convert_dates={"dates": "tC"}) dates = pd.date_range("1-1-1990", periods=3, tz="Asia/Hong_Kong") original = DataFrame( @@ -1458,9 +1450,11 @@ def test_unsupported_datetype(self): "dates": dates, } ) - with pytest.raises(NotImplementedError, match="Data type datetime64"): - with tm.ensure_clean() as path: - original.to_stata(path) + with pytest.raises( + NotImplementedError, + match="Data type datetime64", + ), tm.ensure_clean() as path: + original.to_stata(path) def test_repeated_column_labels(self, datapath): # GH 13923, 25772 @@ -1508,9 +1502,8 @@ def test_out_of_range_double(self): r"Column ColumnTooBig has a maximum value \(.+\) outside the range " r"supported by Stata \(.+\)" ) - with pytest.raises(ValueError, match=msg): - with tm.ensure_clean() as path: - df.to_stata(path) + with pytest.raises(ValueError, match=msg), tm.ensure_clean() as path: + df.to_stata(path) def test_out_of_range_float(self): original = DataFrame( @@ -1548,9 +1541,8 @@ def test_inf(self, infval): "Column WithInf contains infinity or -infinity" "which is outside the range supported by Stata." ) - with pytest.raises(ValueError, match=msg): - with tm.ensure_clean() as path: - df.to_stata(path) + with pytest.raises(ValueError, match=msg), tm.ensure_clean() as path: + df.to_stata(path) def test_path_pathlib(self): df = tm.makeDataFrame() @@ -1686,13 +1678,12 @@ def test_convert_strl_name_swap(self): ) original.index.name = "index" - with tm.assert_produces_warning(InvalidColumnName): - with tm.ensure_clean() as path: - original.to_stata(path, convert_strl=["long", 1], version=117) - reread = self.read_dta(path) - reread = reread.set_index("index") - reread.columns = original.columns - tm.assert_frame_equal(reread, original, check_index_type=False) + with tm.assert_produces_warning(InvalidColumnName), tm.ensure_clean() as path: + original.to_stata(path, convert_strl=["long", 1], version=117) + reread = self.read_dta(path) + reread = reread.set_index("index") + reread.columns = original.columns + tm.assert_frame_equal(reread, original, check_index_type=False) def test_invalid_date_conversion(self): # GH 12259 @@ -1782,9 +1773,11 @@ def test_all_none_exception(self, version): output = [{"none": "none", "number": 0}, {"none": None, "number": 1}] output = DataFrame(output) output["none"] = None - with tm.ensure_clean() as path: - with pytest.raises(ValueError, match="Column `none` cannot be exported"): - output.to_stata(path, version=version) + with tm.ensure_clean() as path, pytest.raises( + ValueError, + match="Column `none` cannot be exported", + ): + output.to_stata(path, version=version) @pytest.mark.parametrize("version", [114, 117, 118, 119, None]) def test_invalid_file_not_written(self, version): @@ -1905,12 +1898,16 @@ def test_utf8_writer(self, version): def test_writer_118_exceptions(self): df = DataFrame(np.zeros((1, 33000), dtype=np.int8)) - with tm.ensure_clean() as path: - with pytest.raises(ValueError, match="version must be either 118 or 119."): - StataWriterUTF8(path, df, version=117) - with tm.ensure_clean() as path: - with pytest.raises(ValueError, match="You must use version 119"): - StataWriterUTF8(path, df, version=118) + with tm.ensure_clean() as path, pytest.raises( + ValueError, + match="version must be either 118 or 119.", + ): + StataWriterUTF8(path, df, version=117) + with tm.ensure_clean() as path, pytest.raises( + ValueError, + match="You must use version 119", + ): + StataWriterUTF8(path, df, version=118) @pytest.mark.parametrize("version", [105, 108, 111, 113, 114]) @@ -1933,17 +1930,19 @@ def test_direct_read(datapath, monkeypatch): assert not isinstance(reader._path_or_buf, io.BytesIO) # Test that we use a given fp exactly, if possible. - with open(file_path, "rb") as fp: - with StataReader(fp) as reader: - assert not reader.read().empty - assert reader._path_or_buf is fp + with open(file_path, "rb") as fp, StataReader(fp) as reader: + assert not reader.read().empty + assert reader._path_or_buf is fp # Test that we use a given BytesIO exactly, if possible. - with open(file_path, "rb") as fp: - with io.BytesIO(fp.read()) as bio: - with StataReader(bio) as reader: - assert not reader.read().empty - assert reader._path_or_buf is bio + with open( + file_path, + "rb", + ) as fp, io.BytesIO( + fp.read() + ) as bio, StataReader(bio) as reader: + assert not reader.read().empty + assert reader._path_or_buf is bio def test_statareader_warns_when_used_without_context(datapath): @@ -2057,18 +2056,24 @@ def test_chunked_categorical(version): def test_chunked_categorical_partial(datapath): dta_file = datapath("io", "data", "stata", "stata-dta-partially-labeled.dta") values = ["a", "b", "a", "b", 3.0] - with StataReader(dta_file, chunksize=2) as reader: - with tm.assert_produces_warning(CategoricalConversionWarning): - for i, block in enumerate(reader): - assert list(block.cats) == values[2 * i : 2 * (i + 1)] - if i < 2: - idx = pd.Index(["a", "b"]) - else: - idx = pd.Index([3.0], dtype="float64") - tm.assert_index_equal(block.cats.cat.categories, idx) - with tm.assert_produces_warning(CategoricalConversionWarning): - with StataReader(dta_file, chunksize=5) as reader: - large_chunk = reader.__next__() + with StataReader( + dta_file, + chunksize=2, + ) as reader, tm.assert_produces_warning(CategoricalConversionWarning): + for i, block in enumerate(reader): + assert list(block.cats) == values[2 * i : 2 * (i + 1)] + if i < 2: + idx = pd.Index(["a", "b"]) + else: + idx = pd.Index([3.0], dtype="float64") + tm.assert_index_equal(block.cats.cat.categories, idx) + with tm.assert_produces_warning( + CategoricalConversionWarning, + ), StataReader( + dta_file, + chunksize=5, + ) as reader: + large_chunk = reader.__next__() direct = read_stata(dta_file) tm.assert_frame_equal(direct, large_chunk) @@ -2076,9 +2081,14 @@ def test_chunked_categorical_partial(datapath): @pytest.mark.parametrize("chunksize", (-1, 0, "apple")) def test_iterator_errors(datapath, chunksize): dta_file = datapath("io", "data", "stata", "stata-dta-partially-labeled.dta") - with pytest.raises(ValueError, match="chunksize must be a positive"): - with StataReader(dta_file, chunksize=chunksize): - pass + with pytest.raises( + ValueError, + match="chunksize must be a positive", + ), StataReader( + dta_file, + chunksize=chunksize, + ): + pass def test_iterator_value_labels(): diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py index 1f1f44f408fc1..b7c24e71b18fa 100644 --- a/pandas/tests/io/xml/test_to_xml.py +++ b/pandas/tests/io/xml/test_to_xml.py @@ -1123,9 +1123,11 @@ def test_incorrect_xsl_apply(): """ - with pytest.raises(XSLTApplyError, match=("Cannot resolve URI")): - with tm.ensure_clean("test.xml") as path: - geom_df.to_xml(path, stylesheet=xsl) + with pytest.raises( + XSLTApplyError, + match=("Cannot resolve URI"), + ), tm.ensure_clean("test.xml") as path: + geom_df.to_xml(path, stylesheet=xsl) def test_stylesheet_with_etree(): @@ -1329,9 +1331,11 @@ def test_ea_dtypes(any_numeric_ea_dtype, parser): def test_unsuported_compression(parser): - with pytest.raises(ValueError, match="Unrecognized compression type"): - with tm.ensure_clean() as path: - geom_df.to_xml(path, parser=parser, compression="7z") + with pytest.raises( + ValueError, + match="Unrecognized compression type", + ), tm.ensure_clean() as path: + geom_df.to_xml(path, parser=parser, compression="7z") # STORAGE OPTIONS diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index 04abebe4a0a71..33c4a6346de66 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -265,11 +265,17 @@ def read_xml_iterparse(data, **kwargs): def read_xml_iterparse_comp(comp_path, compression_only, **kwargs): - with get_handle(comp_path, "r", compression=compression_only) as handles: - with tm.ensure_clean() as path: - with open(path, "w", encoding="utf-8") as f: - f.write(handles.handle.read()) - return read_xml(path, **kwargs) + with get_handle( + comp_path, + "r", + compression=compression_only, + ) as handles, tm.ensure_clean() as path, open( + path, + "w", + encoding="utf-8", + ) as f: + f.write(handles.handle.read()) + return read_xml(path, **kwargs) # FILE / URL @@ -1457,28 +1463,25 @@ def test_file_io_iterparse(datapath, parser, mode): filename, mode, encoding="utf-8" if mode == "r" else None, - ) as f: - with funcIO(f.read()) as b: - if mode == "r" and parser == "lxml": - with pytest.raises( - TypeError, match=("reading file objects must return bytes objects") - ): - read_xml( - b, - parser=parser, - iterparse={ - "book": ["category", "title", "year", "author", "price"] - }, - ) - return None - else: - df_fileio = read_xml( + ) as f, funcIO(f.read()) as b: + if mode == "r" and parser == "lxml": + with pytest.raises( + TypeError, match=("reading file objects must return bytes objects") + ): + read_xml( b, parser=parser, iterparse={ "book": ["category", "title", "year", "author", "price"] }, ) + return None + else: + df_fileio = read_xml( + b, + parser=parser, + iterparse={"book": ["category", "title", "year", "author", "price"]}, + ) df_expected = DataFrame( { @@ -1800,9 +1803,11 @@ def test_wrong_compression(parser, compression, compression_only): def test_unsuported_compression(parser): - with pytest.raises(ValueError, match="Unrecognized compression type"): - with tm.ensure_clean() as path: - read_xml(path, parser=parser, compression="7z") + with pytest.raises( + ValueError, + match="Unrecognized compression type", + ), tm.ensure_clean() as path: + read_xml(path, parser=parser, compression="7z") # STORAGE OPTIONS diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 793e31295b8c3..ddbfd59ccd18e 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -968,13 +968,23 @@ def test_args_kwargs_depr(method, raises): warn_msg = f"Passing additional args to DatetimeIndexResampler.{method}" if raises: - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - with pytest.raises(UnsupportedFunctionCall, match=error_msg): - func(*args, 1, 2, 3) + with tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ), pytest.raises( + UnsupportedFunctionCall, + match=error_msg, + ): + func(*args, 1, 2, 3) else: - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - with pytest.raises(TypeError, match=error_msg_type): - func(*args, 1, 2, 3) + with tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ), pytest.raises( + TypeError, + match=error_msg_type, + ): + func(*args, 1, 2, 3) def test_df_axis_param_depr(): diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index 1682edb42915d..f62298d2d626d 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -38,9 +38,8 @@ async def test_tab_complete_ipython6_warning(ip): # GH 31324 newer jedi version raises Deprecation warning; # appears resolved 2021-02-02 - with tm.assert_produces_warning(None): - with provisionalcompleter("ignore"): - list(ip.Completer.completions("rs.", 1)) + with tm.assert_produces_warning(None), provisionalcompleter("ignore"): + list(ip.Completer.completions("rs.", 1)) def test_deferred_with_groupby(): diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index b40f0f7a45263..5e357843fa3a0 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2054,11 +2054,16 @@ def __init__(self, *args, **kwargs) -> None: ) msg = "The following operation may generate" - with tm.assert_produces_warning(PerformanceWarning, match=msg): - with pytest.raises(Exception, match="Don't compute final result."): - df.pivot_table( - index="ind1", columns="ind2", values="count", aggfunc="count" - ) + with tm.assert_produces_warning( + PerformanceWarning, + match=msg, + ), pytest.raises( + Exception, + match="Don't compute final result.", + ): + df.pivot_table( + index="ind1", columns="ind2", values="count", aggfunc="count" + ) def test_pivot_table_aggfunc_dropna(self, dropna): # GH 22159 diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 8bfa59c5d9f08..d26d3a827c30b 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -73,17 +73,27 @@ def test_getitem_negative_out_of_bounds(self): msg = "index -11 is out of bounds for axis 0 with size 10" warn_msg = "Series.__getitem__ treating keys as positions is deprecated" - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - ser[-11] + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + ser[-11] def test_getitem_out_of_bounds_indexerror(self, datetime_series): # don't segfault, GH#495 msg = r"index \d+ is out of bounds for axis 0 with size \d+" warn_msg = "Series.__getitem__ treating keys as positions is deprecated" - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - datetime_series[len(datetime_series)] + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + datetime_series[len(datetime_series)] def test_getitem_out_of_bounds_empty_rangeindex_keyerror(self): # GH#917 diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 83cae8d148feb..e1f6c4a4dedc2 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -29,25 +29,45 @@ def test_basic_indexing(): warn_msg = "Series.__[sg]etitem__ treating keys as positions is deprecated" msg = "index 5 is out of bounds for axis 0 with size 5" - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - s[5] - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - s[5] = 0 + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + s[5] + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + s[5] = 0 with pytest.raises(KeyError, match=r"^'c'$"): s["c"] s = s.sort_index() - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - s[5] + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + s[5] msg = r"index 5 is out of bounds for axis (0|1) with size 5|^5$" - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - s[5] = 0 + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + s[5] = 0 def test_getitem_numeric_should_not_fallback_to_positional(any_numeric_dtype): diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index e87a968dee323..0631ea55a23df 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -177,9 +177,14 @@ def test_setitem_negative_out_of_bounds(self): msg = "index -11 is out of bounds for axis 0 with size 10" warn_msg = "Series.__setitem__ treating keys as positions is deprecated" - with pytest.raises(IndexError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - ser[-11] = "foo" + with pytest.raises( + IndexError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + ser[-11] = "foo" @pytest.mark.parametrize("indexer", [tm.loc, tm.at]) @pytest.mark.parametrize("ser_index", [0, 1]) diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py index 19412db91b487..1f5ad1c27e247 100644 --- a/pandas/tests/series/test_logical_ops.py +++ b/pandas/tests/series/test_logical_ops.py @@ -97,9 +97,14 @@ def test_logical_operators_int_dtype_with_float(self): with pytest.raises(TypeError, match=msg): s_0123 & 3.14 msg = "unsupported operand type.+for &:" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - s_0123 & [0.1, 4, 3.14, 2] + with pytest.raises( + TypeError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + s_0123 & [0.1, 4, 3.14, 2] with pytest.raises(TypeError, match=msg): s_0123 & np.array([0.1, 4, 3.14, 2]) with pytest.raises(TypeError, match=msg): @@ -116,9 +121,14 @@ def test_logical_operators_int_dtype_with_str(self): msg = "Cannot perform 'and_' with a dtyped.+array and scalar of type" with pytest.raises(TypeError, match=msg): s_1111 & "a" - with pytest.raises(TypeError, match="unsupported operand.+for &"): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - s_1111 & ["a", "b", "c", "d"] + with pytest.raises( + TypeError, + match="unsupported operand.+for &", + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + s_1111 & ["a", "b", "c", "d"] def test_logical_operators_int_dtype_with_bool(self): # GH#9016: support bitwise op for integer types diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py index 89718b1b35f12..12ef9f8d6c92e 100644 --- a/pandas/tests/strings/test_find_replace.py +++ b/pandas/tests/strings/test_find_replace.py @@ -429,11 +429,10 @@ def test_replace_callable_raises(any_string_dtype, repl): r"((takes)|(missing)) (?(2)from \d+ to )?\d+ " r"(?(3)required )positional arguments?" ) - with pytest.raises(TypeError, match=msg): - with tm.maybe_produces_warning( - PerformanceWarning, any_string_dtype == "string[pyarrow]" - ): - values.str.replace("a", repl, regex=True) + with pytest.raises(TypeError, match=msg), tm.maybe_produces_warning( + PerformanceWarning, any_string_dtype == "string[pyarrow]" + ): + values.str.replace("a", repl, regex=True) def test_replace_callable_named_groups(any_string_dtype): diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 4466ee96235f5..5d1c21d407d6c 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1402,9 +1402,14 @@ def test_datetime_invalid_index(self, values, format): r"^second must be in 0..59: 00:01:99, at position 0$", ] ) - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(warn, match="Could not infer format"): - to_datetime(values, errors="raise", format=format) + with pytest.raises( + ValueError, + match=msg, + ), tm.assert_produces_warning( + warn, + match="Could not infer format", + ): + to_datetime(values, errors="raise", format=format) @pytest.mark.parametrize("utc", [True, None]) @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) @@ -1585,14 +1590,11 @@ def test_to_datetime_malformed_raise(self): with pytest.raises( ValueError, match=msg, - ): - with tm.assert_produces_warning( - UserWarning, match="Could not infer format" - ): - to_datetime( - ts_strings, - errors="raise", - ) + ), tm.assert_produces_warning(UserWarning, match="Could not infer format"): + to_datetime( + ts_strings, + errors="raise", + ) def test_iso_8601_strings_with_same_offset(self): # GH 17697, 11736 @@ -1743,9 +1745,14 @@ def test_to_datetime_month_or_year_unit_non_round_float(self, cache, unit): msg = f"Conversion of non-round float with unit={unit} is ambiguous" with pytest.raises(ValueError, match=msg): to_datetime([1.5], unit=unit, errors="raise") - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - to_datetime(["1.5"], unit=unit, errors="raise") + with pytest.raises( + ValueError, + match=msg, + ), tm.assert_produces_warning( + FutureWarning, + match=warn_msg, + ): + to_datetime(["1.5"], unit=unit, errors="raise") # with errors="ignore" we also end up raising within the Timestamp # constructor; this may not be ideal @@ -2377,11 +2384,16 @@ def test_to_datetime_respects_dayfirst(self, cache): # The msg here is not important since it isn't actually raised yet. msg = "Invalid date specified" - with pytest.raises(ValueError, match=msg): + with pytest.raises( + ValueError, + match=msg, + ), tm.assert_produces_warning( + UserWarning, + match="Provide format", + ): # if dayfirst is respected, then this would parse as month=13, which # would raise - with tm.assert_produces_warning(UserWarning, match="Provide format"): - to_datetime("01-13-2012", dayfirst=True, cache=cache) + to_datetime("01-13-2012", dayfirst=True, cache=cache) def test_to_datetime_on_datetime64_series(self, cache): # #2699 diff --git a/pandas/tests/util/test_assert_produces_warning.py b/pandas/tests/util/test_assert_produces_warning.py index 5c27a3ee79d4a..f38cc86fd8ffc 100644 --- a/pandas/tests/util/test_assert_produces_warning.py +++ b/pandas/tests/util/test_assert_produces_warning.py @@ -65,9 +65,13 @@ def f(): def test_assert_produces_warning_honors_filter(): # Raise by default. msg = r"Caused unexpected warning\(s\)" - with pytest.raises(AssertionError, match=msg): - with tm.assert_produces_warning(RuntimeWarning): - f() + with pytest.raises( + AssertionError, + match=msg, + ), tm.assert_produces_warning( + RuntimeWarning, + ): + f() with tm.assert_produces_warning(RuntimeWarning, raise_on_extra_warnings=False): f() @@ -103,10 +107,15 @@ def test_fail_to_match_runtime_warning(): r"\[RuntimeWarning\('This is not a match.'\), " r"RuntimeWarning\('Another unmatched warning.'\)\]" ) - with pytest.raises(AssertionError, match=unmatched): - with tm.assert_produces_warning(category, match=match): - warnings.warn("This is not a match.", category) - warnings.warn("Another unmatched warning.", category) + with pytest.raises( + AssertionError, + match=unmatched, + ), tm.assert_produces_warning( + category, + match=match, + ): + warnings.warn("This is not a match.", category) + warnings.warn("Another unmatched warning.", category) def test_fail_to_match_future_warning(): @@ -118,10 +127,15 @@ def test_fail_to_match_future_warning(): r"\[FutureWarning\('This is not a match.'\), " r"FutureWarning\('Another unmatched warning.'\)\]" ) - with pytest.raises(AssertionError, match=unmatched): - with tm.assert_produces_warning(category, match=match): - warnings.warn("This is not a match.", category) - warnings.warn("Another unmatched warning.", category) + with pytest.raises( + AssertionError, + match=unmatched, + ), tm.assert_produces_warning( + category, + match=match, + ): + warnings.warn("This is not a match.", category) + warnings.warn("Another unmatched warning.", category) def test_fail_to_match_resource_warning(): @@ -133,18 +147,25 @@ def test_fail_to_match_resource_warning(): r"\[ResourceWarning\('This is not a match.'\), " r"ResourceWarning\('Another unmatched warning.'\)\]" ) - with pytest.raises(AssertionError, match=unmatched): - with tm.assert_produces_warning(category, match=match): - warnings.warn("This is not a match.", category) - warnings.warn("Another unmatched warning.", category) + with pytest.raises( + AssertionError, + match=unmatched, + ), tm.assert_produces_warning( + category, + match=match, + ): + warnings.warn("This is not a match.", category) + warnings.warn("Another unmatched warning.", category) def test_fail_to_catch_actual_warning(pair_different_warnings): expected_category, actual_category = pair_different_warnings match = "Did not see expected warning of class" - with pytest.raises(AssertionError, match=match): - with tm.assert_produces_warning(expected_category): - warnings.warn("warning message", actual_category) + with pytest.raises( + AssertionError, + match=match, + ), tm.assert_produces_warning(expected_category): + warnings.warn("warning message", actual_category) def test_ignore_extra_warning(pair_different_warnings): @@ -157,10 +178,12 @@ def test_ignore_extra_warning(pair_different_warnings): def test_raise_on_extra_warning(pair_different_warnings): expected_category, extra_category = pair_different_warnings match = r"Caused unexpected warning\(s\)" - with pytest.raises(AssertionError, match=match): - with tm.assert_produces_warning(expected_category): - warnings.warn("Expected warning", expected_category) - warnings.warn("Unexpected warning NOT OK", extra_category) + with pytest.raises( + AssertionError, + match=match, + ), tm.assert_produces_warning(expected_category): + warnings.warn("Expected warning", expected_category) + warnings.warn("Unexpected warning NOT OK", extra_category) def test_same_category_different_messages_first_match(): @@ -189,19 +212,26 @@ def test_match_multiple_warnings(): def test_right_category_wrong_match_raises(pair_different_warnings): target_category, other_category = pair_different_warnings - with pytest.raises(AssertionError, match="Did not see warning.*matching"): - with tm.assert_produces_warning(target_category, match=r"^Match this"): - warnings.warn("Do not match it", target_category) - warnings.warn("Match this", other_category) + with pytest.raises( + AssertionError, + match="Did not see warning.*matching", + ), tm.assert_produces_warning( + target_category, + match=r"^Match this", + ): + warnings.warn("Do not match it", target_category) + warnings.warn("Match this", other_category) @pytest.mark.parametrize("false_or_none", [False, None]) class TestFalseOrNoneExpectedWarning: def test_raise_on_warning(self, false_or_none): msg = r"Caused unexpected warning\(s\)" - with pytest.raises(AssertionError, match=msg): - with tm.assert_produces_warning(false_or_none): - f() + with pytest.raises( + AssertionError, + match=msg, + ), tm.assert_produces_warning(false_or_none): + f() def test_no_raise_without_warning(self, false_or_none): with tm.assert_produces_warning(false_or_none): @@ -214,28 +244,35 @@ def test_no_raise_with_false_raise_on_extra(self, false_or_none): def test_raises_during_exception(): msg = "Did not see expected warning of class 'UserWarning'" - with pytest.raises(AssertionError, match=msg): - with tm.assert_produces_warning(UserWarning): - raise ValueError - - with pytest.raises(AssertionError, match=msg): - with tm.assert_produces_warning(UserWarning): - warnings.warn("FutureWarning", FutureWarning) - raise IndexError + with pytest.raises( + AssertionError, + match=msg, + ), tm.assert_produces_warning(UserWarning): + raise ValueError + + with pytest.raises( + AssertionError, + match=msg, + ), tm.assert_produces_warning(UserWarning): + warnings.warn("FutureWarning", FutureWarning) + raise IndexError msg = "Caused unexpected warning" - with pytest.raises(AssertionError, match=msg): - with tm.assert_produces_warning(None): - warnings.warn("FutureWarning", FutureWarning) - raise SystemError + with pytest.raises(AssertionError, match=msg), tm.assert_produces_warning(None): + warnings.warn("FutureWarning", FutureWarning) + raise SystemError def test_passes_during_exception(): - with pytest.raises(SyntaxError, match="Error"): - with tm.assert_produces_warning(None): - raise SyntaxError("Error") - - with pytest.raises(ValueError, match="Error"): - with tm.assert_produces_warning(FutureWarning, match="FutureWarning"): - warnings.warn("FutureWarning", FutureWarning) - raise ValueError("Error") + with pytest.raises(SyntaxError, match="Error"), tm.assert_produces_warning(None): + raise SyntaxError("Error") + + with pytest.raises( + ValueError, + match="Error", + ), tm.assert_produces_warning( + FutureWarning, + match="FutureWarning", + ): + warnings.warn("FutureWarning", FutureWarning) + raise ValueError("Error") diff --git a/pandas/tests/util/test_numba.py b/pandas/tests/util/test_numba.py index 27b68ff0f6044..f8604100db7c9 100644 --- a/pandas/tests/util/test_numba.py +++ b/pandas/tests/util/test_numba.py @@ -7,6 +7,8 @@ @td.skip_if_installed("numba") def test_numba_not_installed_option_context(): - with pytest.raises(ImportError, match="Missing optional"): - with option_context("compute.use_numba", True): - pass + with pytest.raises( + ImportError, + match="Missing optional", + ), option_context("compute.use_numba", True): + pass diff --git a/pandas/tests/util/test_rewrite_warning.py b/pandas/tests/util/test_rewrite_warning.py index f847a06d8ea8d..765a39744f120 100644 --- a/pandas/tests/util/test_rewrite_warning.py +++ b/pandas/tests/util/test_rewrite_warning.py @@ -32,8 +32,8 @@ def test_rewrite_warning(target_category, target_message, hit, new_category): else: expected_category = FutureWarning expected_message = "Target message" - with tm.assert_produces_warning(expected_category, match=expected_message): - with rewrite_warning( - target_message, target_category, new_message, new_category - ): - warnings.warn(message="Target message", category=FutureWarning) + with tm.assert_produces_warning( + expected_category, + match=expected_message, + ), rewrite_warning(target_message, target_category, new_message, new_category): + warnings.warn(message="Target message", category=FutureWarning) diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index 265ef29e42c48..a08efafd08520 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -686,6 +686,8 @@ def test_nat_axis_error(msg, axis): warn_msg = "The 'axis' keyword in DataFrame.rolling is deprecated" if axis == 1: warn_msg = "Support for axis=1 in DataFrame.rolling is deprecated" - with pytest.raises(ValueError, match=f"{msg} values must not have NaT"): - with tm.assert_produces_warning(FutureWarning, match=warn_msg): - df.rolling("D", axis=axis).mean() + with pytest.raises( + ValueError, + match=f"{msg} values must not have NaT", + ), tm.assert_produces_warning(FutureWarning, match=warn_msg): + df.rolling("D", axis=axis).mean() diff --git a/pyproject.toml b/pyproject.toml index f9dfe65ab2a01..e65b21fa00564 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -232,7 +232,9 @@ select = [ # comprehensions "C4", # pygrep-hooks - "PGH" + "PGH", + # flake8-simplify + "SIM117", ] ignore = [