diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index f582bf8b13975..8179ab08895da 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -469,7 +469,7 @@ class TestMultiplicationDivision: pytest.param( pd.Index, marks=pytest.mark.xfail( - reason="Index.__div__ always " "raises", raises=TypeError + reason="Index.__div__ always raises", raises=TypeError ), ), pd.Series, diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index bd21335a7f9c7..e54c16c7a27a4 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -960,7 +960,7 @@ def test_add_iadd_timedeltalike_annual(self): def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self, mismatched_freq): other = mismatched_freq rng = pd.period_range("2014", "2024", freq="A") - msg = "Input has different freq(=.+)? " "from Period.*?\\(freq=A-DEC\\)" + msg = "Input has different freq(=.+)? from Period.*?\\(freq=A-DEC\\)" with pytest.raises(IncompatibleFrequency, match=msg): rng + other with pytest.raises(IncompatibleFrequency, match=msg): diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 06c4a6ece4bcc..326c565308124 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -318,19 +318,19 @@ def _check(result, expected): _check(result, expected) # tz mismatches - msg = "Timestamp subtraction must have the same timezones or no" " timezones" + msg = "Timestamp subtraction must have the same timezones or no timezones" with pytest.raises(TypeError, match=msg): dt_tz - ts msg = "can't subtract offset-naive and offset-aware datetimes" with pytest.raises(TypeError, match=msg): dt_tz - dt - msg = "Timestamp subtraction must have the same timezones or no" " timezones" + msg = "Timestamp subtraction must have the same timezones or no timezones" with pytest.raises(TypeError, match=msg): dt_tz - ts_tz2 msg = "can't subtract offset-naive and offset-aware datetimes" with pytest.raises(TypeError, match=msg): dt - dt_tz - msg = "Timestamp subtraction must have the same timezones or no" " timezones" + msg = "Timestamp subtraction must have the same timezones or no timezones" with pytest.raises(TypeError, match=msg): ts - dt_tz with pytest.raises(TypeError, match=msg): @@ -1771,7 +1771,7 @@ def test_td64arr_floordiv_int(self, box_with_array): result = idx // 1 tm.assert_equal(result, idx) - pattern = "floor_divide cannot use operands|" "Cannot divide int by Timedelta*" + pattern = "floor_divide cannot use operands|Cannot divide int by Timedelta*" with pytest.raises(TypeError, match=pattern): 1 // idx diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index cd8ec7fcb787d..697ee483db6d9 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -313,7 +313,7 @@ def test_unordered_different_categories_raises(self): c1 = Categorical(["a", "b"], categories=["a", "b"], ordered=False) c2 = Categorical(["a", "c"], categories=["c", "a"], ordered=False) - with pytest.raises(TypeError, match=("Categoricals can " "only be compared")): + with pytest.raises(TypeError, match=("Categoricals can only be compared")): c1 == c2 def test_compare_different_lengths(self): diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index c01b52456ff87..dfdb08fa78cbc 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -88,7 +88,7 @@ def test_repr_dtype(dtype, expected): def test_repr_array(): result = repr(integer_array([1, None, 3])) - expected = "\n" "[1, NaN, 3]\n" "Length: 3, dtype: Int64" + expected = "\n[1, NaN, 3]\nLength: 3, dtype: Int64" assert result == expected diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py index fab59d312fb9d..252f278242fcc 100644 --- a/pandas/tests/arrays/test_period.py +++ b/pandas/tests/arrays/test_period.py @@ -259,7 +259,7 @@ def test_repr_small(): arr = period_array(["2000", "2001"], freq="D") result = str(arr) expected = ( - "\n" "['2000-01-01', '2001-01-01']\n" "Length: 2, dtype: period[D]" + "\n['2000-01-01', '2001-01-01']\nLength: 2, dtype: period[D]" ) assert result == expected diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 2fd7c8f04c8be..37a885e33847f 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -92,7 +92,7 @@ def _eval_single_bin(lhs, cmp1, rhs, engine): return c(lhs, rhs) except ValueError as e: if str(e).startswith( - "negative number cannot be " "raised to a fractional power" + "negative number cannot be raised to a fractional power" ): return np.nan raise @@ -362,7 +362,7 @@ def get_expected_pow_result(self, lhs, rhs): expected = _eval_single_bin(lhs, "**", rhs, self.engine) except ValueError as e: if str(e).startswith( - "negative number cannot be " "raised to a fractional power" + "negative number cannot be raised to a fractional power" ): if self.engine == "python": pytest.skip(str(e)) @@ -1944,7 +1944,7 @@ def test_empty_string_raises(engine, parser): def test_more_than_one_expression_raises(engine, parser): - with pytest.raises(SyntaxError, match=("only a single expression " "is allowed")): + with pytest.raises(SyntaxError, match=("only a single expression is allowed")): pd.eval("1 + 1; 2 + 2", engine=engine, parser=parser) diff --git a/pandas/tests/extension/arrow/bool.py b/pandas/tests/extension/arrow/bool.py index ee043a6bb837c..eb75d6d968073 100644 --- a/pandas/tests/extension/arrow/bool.py +++ b/pandas/tests/extension/arrow/bool.py @@ -33,7 +33,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string)) + raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) @classmethod def construct_array_type(cls): diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 90e6a91fbb91a..c28ff956a33a4 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -40,7 +40,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string)) + raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) @property def _is_numeric(self): @@ -172,7 +172,7 @@ def _reduce(self, name, skipna=True, **kwargs): op = getattr(self.data, name) except AttributeError: raise NotImplementedError( - "decimal does not support " "the {} operation".format(name) + "decimal does not support the {} operation".format(name) ) return op(axis=0) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 272936f6ec9f0..9dec023f4073a 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -207,7 +207,7 @@ def test_series_repr(self, data): # TODO(extension) @pytest.mark.xfail( reason=( - "raising AssertionError as this is not implemented, " "though easy enough to do" + "raising AssertionError as this is not implemented, though easy enough to do" ) ) def test_series_constructor_coerce_data_to_extension_dtype_raises(): diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index ece1924b1b228..21c4ac8f055a2 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -44,7 +44,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string)) + raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) class JSONArray(ExtensionArray): diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 2ce65bd15387e..912e8b5fba233 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -1304,7 +1304,7 @@ def test_rename_axis_style_raises(self): df = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["0", "1"]) # Named target and axis - over_spec_msg = "Cannot specify both 'axis' and " "any of 'index' or 'columns'" + over_spec_msg = "Cannot specify both 'axis' and any of 'index' or 'columns'" with pytest.raises(TypeError, match=over_spec_msg): df.rename(index=str.lower, axis=1) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 13ffa8d17d47c..d5c66f0c1dd64 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -363,9 +363,7 @@ def test_corr_cov_independent_index_column(self): def test_corr_invalid_method(self): # GH 22298 df = pd.DataFrame(np.random.normal(size=(10, 2))) - msg = ( - "method must be either 'pearson', " "'spearman', 'kendall', or a callable, " - ) + msg = "method must be either 'pearson', 'spearman', 'kendall', or a callable, " with pytest.raises(ValueError, match=msg): df.corr(method="____") @@ -1441,7 +1439,7 @@ def test_mean_datetimelike(self): tm.assert_series_equal(result, expected) @pytest.mark.xfail( - reason="casts to object-dtype and then tries to " "add timestamps", + reason="casts to object-dtype and then tries to add timestamps", raises=TypeError, strict=True, ) @@ -1643,7 +1641,7 @@ def test_idxmin(self, float_frame, int_frame): expected = df.apply(Series.idxmin, axis=axis, skipna=skipna) tm.assert_series_equal(result, expected) - msg = "No axis named 2 for object type" " " + msg = "No axis named 2 for object type " with pytest.raises(ValueError, match=msg): frame.idxmin(axis=2) @@ -1658,7 +1656,7 @@ def test_idxmax(self, float_frame, int_frame): expected = df.apply(Series.idxmax, axis=axis, skipna=skipna) tm.assert_series_equal(result, expected) - msg = "No axis named 2 for object type" " " + msg = "No axis named 2 for object type " with pytest.raises(ValueError, match=msg): frame.idxmax(axis=2) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 93508d7ddc50b..76a210e129eb3 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -149,7 +149,7 @@ def test_not_hashable(self): empty_frame = DataFrame() df = self.klass([1]) - msg = "'(Sparse)?DataFrame' objects are mutable, thus they cannot be" " hashed" + msg = "'(Sparse)?DataFrame' objects are mutable, thus they cannot be hashed" with pytest.raises(TypeError, match=msg): hash(df) with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 37b0d61ee31d9..1b6ee91317996 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -286,7 +286,7 @@ def f(dtype): data = list(itertools.repeat((datetime(2001, 1, 1), "aa", 20), 9)) return DataFrame(data=data, columns=["A", "B", "C"], dtype=dtype) - msg = "compound dtypes are not implemented in the DataFrame" " constructor" + msg = "compound dtypes are not implemented in the DataFrame constructor" with pytest.raises(NotImplementedError, match=msg): f([("A", "datetime64[h]"), ("B", "str"), ("C", "int32")]) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index a16ca7045cfdd..349e2d9c578be 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -474,7 +474,7 @@ def test_constructor_error_msgs(self): with pytest.raises(ValueError, match=msg): DataFrame((range(10), range(10, 20)), columns=("ones", "twos")) - msg = "If using all scalar " "values, you must pass " "an index" + msg = "If using all scalar values, you must pass an index" with pytest.raises(ValueError, match=msg): DataFrame({"a": False, "b": True}) diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index ba6a9d2aa6ee9..00be13b1c0e72 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -686,9 +686,7 @@ def test_astype_dict_like(self, dtype_class): # in the keys of the dtype dict dt4 = dtype_class({"b": str, 2: str}) dt5 = dtype_class({"e": str}) - msg = ( - "Only a column name can be used for the key in a dtype mappings" " argument" - ) + msg = "Only a column name can be used for the key in a dtype mappings argument" with pytest.raises(KeyError, match=msg): df.astype(dt4) with pytest.raises(KeyError, match=msg): @@ -1194,11 +1192,11 @@ def test_astype_str(self, timezone_frame): with option_context("display.max_columns", 20): result = str(timezone_frame) assert ( - "0 2013-01-01 2013-01-01 00:00:00-05:00 " "2013-01-01 00:00:00+01:00" + "0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00" ) in result assert ( - "1 2013-01-02 " "NaT NaT" + "1 2013-01-02 NaT NaT" ) in result assert ( - "2 2013-01-03 2013-01-03 00:00:00-05:00 " "2013-01-03 00:00:00+01:00" + "2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00" ) in result diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index c63a5ba64495f..94667ecfa837d 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -126,7 +126,7 @@ def test_dropna(self): assert_frame_equal(dropped, expected) # bad input - msg = "No axis named 3 for object type" " " + msg = "No axis named 3 for object type " with pytest.raises(ValueError, match=msg): df.dropna(axis=3) @@ -362,7 +362,7 @@ def test_na_actions_categorical(self): res = df.fillna(value={"cats": 3, "vals": "b"}) tm.assert_frame_equal(res, df_exp_fill) - with pytest.raises(ValueError, match=("fill value must " "be in categories")): + with pytest.raises(ValueError, match=("fill value must be in categories")): df.fillna(value={"cats": 4, "vals": "c"}) res = df.fillna(method="pad") diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index bbb3395fb23af..236cadf67735d 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -90,9 +90,7 @@ def test_quantile_axis_parameter(self): result = df.quantile(0.5, axis="columns") assert_series_equal(result, expected) - msg = ( - "No axis named -1 for object type" " " - ) + msg = "No axis named -1 for object type " with pytest.raises(ValueError, match=msg): df.quantile(0.1, axis=-1) msg = ( diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index b6442d8938843..24833f8c02df0 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -55,7 +55,7 @@ def test_sort_values(self): sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False]) assert_frame_equal(sorted_df, expected) - msg = "No axis named 2 for object type" " " + msg = "No axis named 2 for object type " with pytest.raises(ValueError, match=msg): frame.sort_values(by=["A", "B"], axis=2, inplace=True) diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 92801b02dee22..1ca8333154c13 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -901,7 +901,7 @@ def test_frame_to_period(self): pts = df.to_period("M", axis=1) tm.assert_index_equal(pts.columns, exp.columns.asfreq("M")) - msg = "No axis named 2 for object type" " " + msg = "No axis named 2 for object type " with pytest.raises(ValueError, match=msg): df.to_period(axis=2) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index aef6c3fe8070c..b2b38980d0ceb 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -724,10 +724,10 @@ def test_squeeze(self): tm.assert_series_equal(df.squeeze(axis=1), df.iloc[:, 0]) tm.assert_series_equal(df.squeeze(axis="columns"), df.iloc[:, 0]) assert df.squeeze() == df.iloc[0, 0] - msg = "No axis named 2 for object type " + msg = "No axis named 2 for object type " with pytest.raises(ValueError, match=msg): df.squeeze(axis=2) - msg = "No axis named x for object type " + msg = "No axis named x for object type " with pytest.raises(ValueError, match=msg): df.squeeze(axis="x") diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 68e3db3a1ccb0..efc3142b25b82 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -92,7 +92,7 @@ def test_builtins_apply(keys, f): result = df.groupby(keys).apply(f) ngroups = len(df.drop_duplicates(subset=keys)) - assert_msg = "invalid frame shape: {} " "(expected ({}, 3))".format( + assert_msg = "invalid frame shape: {} (expected ({}, 3))".format( result.shape, ngroups ) assert result.shape == (ngroups, 3), assert_msg @@ -1220,7 +1220,7 @@ def test_size_groupby_all_null(): def test_quantile(interpolation, a_vals, b_vals, q): if interpolation == "nearest" and q == 0.5 and b_vals == [4, 3, 2, 1]: pytest.skip( - "Unclear numpy expectation for nearest result with " "equidistant data" + "Unclear numpy expectation for nearest result with equidistant data" ) a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation) @@ -1243,9 +1243,7 @@ def test_quantile_raises(): [["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"] ) - with pytest.raises( - TypeError, match="cannot be performed against " "'object' dtypes" - ): + with pytest.raises(TypeError, match="cannot be performed against 'object' dtypes"): df.groupby("key").quantile() diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 1fd67caadf2e4..72099f2fa3f11 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -378,7 +378,7 @@ def test_groupby_grouper_f_sanity_checked(self): ts.groupby(lambda key: key[0:6]) def test_grouping_error_on_multidim_input(self, df): - msg = "Grouper for ''" " not 1-dimensional" + msg = "Grouper for '' not 1-dimensional" with pytest.raises(ValueError, match=msg): Grouping(df.index, df[["A", "A"]]) diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 705e4080cf34e..1eab3ba253f4d 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -768,7 +768,7 @@ def test_transform_with_non_scalar_group(): @pytest.mark.parametrize("agg_func", ["count", "rank", "size"]) def test_transform_numeric_ret(cols, exp, comp_func, agg_func): if agg_func == "size" and isinstance(cols, list): - pytest.xfail("'size' transformation not supported with " "NDFrameGroupy") + pytest.xfail("'size' transformation not supported with NDFrameGroupy") # GH 19200 df = pd.DataFrame( diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index 03e10ff44c299..ee380c6108c38 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -232,9 +232,7 @@ def test_groupby_blacklist(df_letters): blacklist.extend(to_methods) # e.g., to_csv - defined_but_not_allowed = ( - "(?:^Cannot.+{0!r}.+{1!r}.+try using the " "'apply' method$)" - ) + defined_but_not_allowed = "(?:^Cannot.+{0!r}.+{1!r}.+try using the 'apply' method$)" # e.g., query, eval not_defined = "(?:^{1!r} object has no attribute {0!r}$)" diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index f22c820253ee5..6708feda7dd1e 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -663,7 +663,7 @@ def test_constructor_dtype(self): DatetimeIndex(idx, dtype="datetime64[ns]") # this is effectively trying to convert tz's - msg = "data is already tz-aware US/Eastern, unable to set specified" " tz: CET" + msg = "data is already tz-aware US/Eastern, unable to set specified tz: CET" with pytest.raises(TypeError, match=msg): DatetimeIndex(idx, dtype="datetime64[ns, CET]") msg = "cannot supply both a tz and a dtype with a tz" diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py index f0aae748092e3..33a744cc25ca1 100644 --- a/pandas/tests/indexes/datetimes/test_formats.py +++ b/pandas/tests/indexes/datetimes/test_formats.py @@ -83,8 +83,8 @@ def test_dti_representation(self, method): ) exp = [] - exp.append("""DatetimeIndex([], dtype='datetime64[ns]', freq='D')""") - exp.append("DatetimeIndex(['2011-01-01'], dtype='datetime64[ns]', " "freq='D')") + exp.append("DatetimeIndex([], dtype='datetime64[ns]', freq='D')") + exp.append("DatetimeIndex(['2011-01-01'], dtype='datetime64[ns]', freq='D')") exp.append( "DatetimeIndex(['2011-01-01', '2011-01-02'], " "dtype='datetime64[ns]', freq='D')" @@ -132,9 +132,9 @@ def test_dti_representation_to_series(self): exp1 = """Series([], dtype: datetime64[ns])""" - exp2 = "0 2011-01-01\n" "dtype: datetime64[ns]" + exp2 = "0 2011-01-01\ndtype: datetime64[ns]" - exp3 = "0 2011-01-01\n" "1 2011-01-02\n" "dtype: datetime64[ns]" + exp3 = "0 2011-01-01\n1 2011-01-02\ndtype: datetime64[ns]" exp4 = ( "0 2011-01-01\n" @@ -186,13 +186,13 @@ def test_dti_summary(self): ["2011-01-01 09:00", "2011-01-01 10:00", pd.NaT], tz="US/Eastern" ) - exp1 = "DatetimeIndex: 0 entries\n" "Freq: D" + exp1 = "DatetimeIndex: 0 entries\nFreq: D" - exp2 = "DatetimeIndex: 1 entries, 2011-01-01 to 2011-01-01\n" "Freq: D" + exp2 = "DatetimeIndex: 1 entries, 2011-01-01 to 2011-01-01\nFreq: D" - exp3 = "DatetimeIndex: 2 entries, 2011-01-01 to 2011-01-02\n" "Freq: D" + exp3 = "DatetimeIndex: 2 entries, 2011-01-01 to 2011-01-02\nFreq: D" - exp4 = "DatetimeIndex: 3 entries, 2011-01-01 to 2011-01-03\n" "Freq: D" + exp4 = "DatetimeIndex: 3 entries, 2011-01-01 to 2011-01-03\nFreq: D" exp5 = ( "DatetimeIndex: 3 entries, 2011-01-01 09:00:00+09:00 " diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index ec4310dbc8396..10d422e8aa52c 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -352,7 +352,7 @@ def test_to_datetime_iso_week_year_format(self, s, _format, dt): [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", - "1999 " "Monday", + "1999 Monday", "%G %A", ], [ diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index dfe3a97ec9b90..962ed2b1cf8ed 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -389,7 +389,7 @@ def test_frame_repr(self): {"A": [1, 2, 3, 4]}, index=pd.IntervalIndex.from_breaks([0, 1, 2, 3, 4]) ) result = repr(df) - expected = " A\n" "(0, 1] 1\n" "(1, 2] 2\n" "(2, 3] 3\n" "(3, 4] 4" + expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4" assert result == expected @pytest.mark.parametrize( @@ -406,7 +406,7 @@ def test_frame_repr(self): ), ( pd.DataFrame, - (" 0\n" "(0.0, 1.0] a\n" "NaN b\n" "(2.0, 3.0] c"), + (" 0\n(0.0, 1.0] a\nNaN b\n(2.0, 3.0] c"), ), ], ) diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index 7f5d57db8da88..36152bc4b60cd 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -212,9 +212,7 @@ def test_take_fill_value(): expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"]) tm.assert_index_equal(result, expected) - msg = ( - "When allow_fill=True and fill_value is not None, " "all indices must be >= -1" - ) + msg = "When allow_fill=True and fill_value is not None, all indices must be >= -1" with pytest.raises(ValueError, match=msg): idx.take(np.array([1, 0, -2]), fill_value=True) with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/indexes/multi/test_constructor.py b/pandas/tests/indexes/multi/test_constructor.py index 1b6177ede30ec..86c9ee3455d0b 100644 --- a/pandas/tests/indexes/multi/test_constructor.py +++ b/pandas/tests/indexes/multi/test_constructor.py @@ -454,7 +454,7 @@ def test_from_product_empty_three_levels(N): "invalid_input", [1, [1], [1, 2], [[1], 2], "a", ["a"], ["a", "b"], [["a"], "b"]] ) def test_from_product_invalid_input(invalid_input): - msg = r"Input must be a list / sequence of iterables|" "Input must be list-like" + msg = r"Input must be a list / sequence of iterables|Input must be list-like" with pytest.raises(TypeError, match=msg): MultiIndex.from_product(iterables=invalid_input) diff --git a/pandas/tests/indexes/multi/test_contains.py b/pandas/tests/indexes/multi/test_contains.py index 21b71613f00f0..64d2859cd13db 100644 --- a/pandas/tests/indexes/multi/test_contains.py +++ b/pandas/tests/indexes/multi/test_contains.py @@ -81,7 +81,7 @@ def test_isin_level_kwarg(): msg = "Too many levels: Index has only 2 levels, not 6" with pytest.raises(IndexError, match=msg): idx.isin(vals_0, level=5) - msg = "Too many levels: Index has only 2 levels, -5 is not a valid level" " number" + msg = "Too many levels: Index has only 2 levels, -5 is not a valid level number" with pytest.raises(IndexError, match=msg): idx.isin(vals_0, level=-5) diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 75dea68eadbf7..d366dbd8bc0a8 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -187,9 +187,7 @@ def test_get_indexer(): def test_get_indexer_nearest(): midx = MultiIndex.from_tuples([("a", 1), ("b", 2)]) - msg = ( - "method='nearest' not implemented yet for MultiIndex; see GitHub" " issue 9365" - ) + msg = "method='nearest' not implemented yet for MultiIndex; see GitHub issue 9365" with pytest.raises(NotImplementedError, match=msg): midx.get_indexer(["a"], method="nearest") msg = "tolerance not implemented yet for MultiIndex" @@ -275,7 +273,7 @@ def test_get_loc(idx): with pytest.raises(KeyError, match=r"^'quux'$"): idx.get_loc("quux") - msg = "only the default get_loc method is currently supported for" " MultiIndex" + msg = "only the default get_loc method is currently supported for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.get_loc("foo", method="nearest") diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_arithmetic.py index 1057ca7bbd662..80e4b1fe1e430 100644 --- a/pandas/tests/indexes/period/test_arithmetic.py +++ b/pandas/tests/indexes/period/test_arithmetic.py @@ -72,19 +72,19 @@ def test_shift_corner_cases(self): tm.assert_index_equal(idx.shift(3), idx) idx = pd.PeriodIndex( - ["2011-01-01 10:00", "2011-01-01 11:00" "2011-01-01 12:00"], + ["2011-01-01 10:00", "2011-01-01 11:00", "2011-01-01 12:00"], name="xxx", freq="H", ) tm.assert_index_equal(idx.shift(0), idx) exp = pd.PeriodIndex( - ["2011-01-01 13:00", "2011-01-01 14:00" "2011-01-01 15:00"], + ["2011-01-01 13:00", "2011-01-01 14:00", "2011-01-01 15:00"], name="xxx", freq="H", ) tm.assert_index_equal(idx.shift(3), exp) exp = pd.PeriodIndex( - ["2011-01-01 07:00", "2011-01-01 08:00" "2011-01-01 09:00"], + ["2011-01-01 07:00", "2011-01-01 08:00", "2011-01-01 09:00"], name="xxx", freq="H", ) diff --git a/pandas/tests/indexes/period/test_construction.py b/pandas/tests/indexes/period/test_construction.py index 7c10239faad42..eab55b91b3e60 100644 --- a/pandas/tests/indexes/period/test_construction.py +++ b/pandas/tests/indexes/period/test_construction.py @@ -394,15 +394,15 @@ def test_constructor_freq_mult(self, func, warning): ) tm.assert_index_equal(pidx, expected) - msg = "Frequency must be positive, because it" " represents span: -1M" + msg = "Frequency must be positive, because it represents span: -1M" with pytest.raises(ValueError, match=msg): PeriodIndex(["2011-01"], freq="-1M") - msg = "Frequency must be positive, because it" " represents span: 0M" + msg = "Frequency must be positive, because it represents span: 0M" with pytest.raises(ValueError, match=msg): PeriodIndex(["2011-01"], freq="0M") - msg = "Frequency must be positive, because it" " represents span: 0M" + msg = "Frequency must be positive, because it represents span: 0M" with pytest.raises(ValueError, match=msg): period_range("2011-01", periods=3, freq="0M") diff --git a/pandas/tests/indexes/period/test_formats.py b/pandas/tests/indexes/period/test_formats.py index c5566f74af11e..2a88b79f381c4 100644 --- a/pandas/tests/indexes/period/test_formats.py +++ b/pandas/tests/indexes/period/test_formats.py @@ -48,7 +48,7 @@ class TestPeriodIndexRendering: def test_frame_repr(self): df = pd.DataFrame({"A": [1, 2, 3]}, index=pd.date_range("2000", periods=3)) result = repr(df) - expected = " A\n" "2000-01-01 1\n" "2000-01-02 2\n" "2000-01-03 3" + expected = " A\n2000-01-01 1\n2000-01-02 2\n2000-01-03 3" assert result == expected @pytest.mark.parametrize("method", ["__repr__", "__str__"]) @@ -65,13 +65,11 @@ def test_representation(self, method): idx9 = pd.period_range("2013Q1", periods=3, freq="Q") idx10 = PeriodIndex(["2011-01-01", "2011-02-01"], freq="3D") - exp1 = """PeriodIndex([], dtype='period[D]', freq='D')""" + exp1 = "PeriodIndex([], dtype='period[D]', freq='D')" - exp2 = """PeriodIndex(['2011-01-01'], dtype='period[D]', freq='D')""" + exp2 = "PeriodIndex(['2011-01-01'], dtype='period[D]', freq='D')" - exp3 = ( - "PeriodIndex(['2011-01-01', '2011-01-02'], dtype='period[D]', " "freq='D')" - ) + exp3 = "PeriodIndex(['2011-01-01', '2011-01-02'], dtype='period[D]', freq='D')" exp4 = ( "PeriodIndex(['2011-01-01', '2011-01-02', '2011-01-03'], " @@ -88,11 +86,9 @@ def test_representation(self, method): "dtype='period[H]', freq='H')" ) - exp7 = "PeriodIndex(['2013Q1'], dtype='period[Q-DEC]', " "freq='Q-DEC')" + exp7 = "PeriodIndex(['2013Q1'], dtype='period[Q-DEC]', freq='Q-DEC')" - exp8 = ( - "PeriodIndex(['2013Q1', '2013Q2'], dtype='period[Q-DEC]', " "freq='Q-DEC')" - ) + exp8 = "PeriodIndex(['2013Q1', '2013Q2'], dtype='period[Q-DEC]', freq='Q-DEC')" exp9 = ( "PeriodIndex(['2013Q1', '2013Q2', '2013Q3'], " diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index 94b061330002f..03e4bd5834166 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -91,7 +91,7 @@ def test_union(self, sort): ["2000-01-01 09:01", "2000-01-01 09:03", "2000-01-01 09:05"], freq="T" ) other5 = pd.PeriodIndex( - ["2000-01-01 09:01", "2000-01-01 09:05" "2000-01-01 09:08"], freq="T" + ["2000-01-01 09:01", "2000-01-01 09:05", "2000-01-01 09:08"], freq="T" ) expected5 = pd.PeriodIndex( [ diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index e52954a114578..1db2c5c3a8dac 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -270,7 +270,7 @@ def test_to_timestamp_pi_nat(self): tm.assert_index_equal(result3, exp) assert result3.freqstr == "3M" - msg = "Frequency must be positive, because it" " represents span: -2A" + msg = "Frequency must be positive, because it represents span: -2A" with pytest.raises(ValueError, match=msg): result.to_period(freq="-2A") diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f0382a040e063..e75d80bec1fdf 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -564,7 +564,7 @@ def test_constructor_overflow_int64(self): with pytest.raises(OverflowError, match=msg): Index([np.iinfo(np.uint64).max - 1], dtype="int64") - @pytest.mark.xfail(reason="see GH#21311: Index " "doesn't enforce dtype argument") + @pytest.mark.xfail(reason="see GH#21311: Index doesn't enforce dtype argument") def test_constructor_cast(self): msg = "could not convert string to float" with pytest.raises(ValueError, match=msg): @@ -728,9 +728,7 @@ def test_nanosecond_index_access(self): # this does not yet work, as parsing strings is done via dateutil # assert first_value == x['2013-01-01 00:00:00.000000050+0000'] - expected_ts = np_datetime64_compat( - "2013-01-01 00:00:00.000000050+" "0000", "ns" - ) + expected_ts = np_datetime64_compat("2013-01-01 00:00:00.000000050+0000", "ns") assert first_value == x[Timestamp(expected_ts)] def test_booleanindex(self): @@ -2361,7 +2359,7 @@ def test_string_index_repr(self, index, expected): # short ( pd.Index(["あ", "いい", "ううう"]), - ("Index(['あ', 'いい', 'ううう'], " "dtype='object')"), + ("Index(['あ', 'いい', 'ううう'], dtype='object')"), ), # multiple lines ( diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 465b7f5e23bb8..b9bdaf40f8589 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -348,7 +348,7 @@ def test_has_duplicates(self, indices): # MultiIndex tested separately in: # tests/indexes/multi/test_unique_and_duplicates. # RangeIndex is unique by definition. - pytest.skip("Skip check for empty Index, MultiIndex, " "and RangeIndex") + pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex") idx = holder([indices[0]] * 5) assert idx.is_unique is False diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 1feb82a923b19..f246307e63e3b 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -172,7 +172,7 @@ def test_constructor_invalid(self): ) with pytest.raises(TypeError, match=msg): Float64Index(["a", "b", 0.0]) - msg = r"float\(\) argument must be a string or a number, not" " 'Timestamp'" + msg = r"float\(\) argument must be a string or a number, not 'Timestamp'" with pytest.raises(TypeError, match=msg): Float64Index([Timestamp("20130101")]) @@ -569,9 +569,7 @@ def test_take_fill_value(self): tm.assert_index_equal(result, expected) name = self._holder.__name__ - msg = ("Unable to fill values because " "{name} cannot contain NA").format( - name=name - ) + msg = "Unable to fill values because {name} cannot contain NA".format(name=name) # fill_value=True with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index 0f51a6333ab2d..4544657f79af7 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -215,9 +215,7 @@ def test_ops_ndarray(self): msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'" with pytest.raises(TypeError, match=msg): td + np.array([1]) - msg = ( - r"unsupported operand type\(s\) for \+: 'numpy.ndarray' and" " 'Timedelta'" - ) + msg = r"unsupported operand type\(s\) for \+: 'numpy.ndarray' and 'Timedelta'" with pytest.raises(TypeError, match=msg): np.array([1]) + td @@ -227,7 +225,7 @@ def test_ops_ndarray(self): msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'" with pytest.raises(TypeError, match=msg): td - np.array([1]) - msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and" " 'Timedelta'" + msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timedelta'" with pytest.raises(TypeError, match=msg): np.array([1]) - td diff --git a/pandas/tests/indexes/timedeltas/test_formats.py b/pandas/tests/indexes/timedeltas/test_formats.py index ebc5f720d46fb..1dfc5b5305008 100644 --- a/pandas/tests/indexes/timedeltas/test_formats.py +++ b/pandas/tests/indexes/timedeltas/test_formats.py @@ -13,13 +13,11 @@ def test_representation(self, method): idx4 = TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D") idx5 = TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"]) - exp1 = """TimedeltaIndex([], dtype='timedelta64[ns]', freq='D')""" + exp1 = "TimedeltaIndex([], dtype='timedelta64[ns]', freq='D')" - exp2 = "TimedeltaIndex(['1 days'], dtype='timedelta64[ns]', " "freq='D')" + exp2 = "TimedeltaIndex(['1 days'], dtype='timedelta64[ns]', freq='D')" - exp3 = ( - "TimedeltaIndex(['1 days', '2 days'], " "dtype='timedelta64[ns]', freq='D')" - ) + exp3 = "TimedeltaIndex(['1 days', '2 days'], dtype='timedelta64[ns]', freq='D')" exp4 = ( "TimedeltaIndex(['1 days', '2 days', '3 days'], " @@ -47,11 +45,11 @@ def test_representation_to_series(self): exp1 = """Series([], dtype: timedelta64[ns])""" - exp2 = "0 1 days\n" "dtype: timedelta64[ns]" + exp2 = "0 1 days\ndtype: timedelta64[ns]" - exp3 = "0 1 days\n" "1 2 days\n" "dtype: timedelta64[ns]" + exp3 = "0 1 days\n1 2 days\ndtype: timedelta64[ns]" - exp4 = "0 1 days\n" "1 2 days\n" "2 3 days\n" "dtype: timedelta64[ns]" + exp4 = "0 1 days\n1 2 days\n2 3 days\ndtype: timedelta64[ns]" exp5 = ( "0 1 days 00:00:01\n" @@ -75,15 +73,15 @@ def test_summary(self): idx4 = TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D") idx5 = TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"]) - exp1 = "TimedeltaIndex: 0 entries\n" "Freq: D" + exp1 = "TimedeltaIndex: 0 entries\nFreq: D" - exp2 = "TimedeltaIndex: 1 entries, 1 days to 1 days\n" "Freq: D" + exp2 = "TimedeltaIndex: 1 entries, 1 days to 1 days\nFreq: D" - exp3 = "TimedeltaIndex: 2 entries, 1 days to 2 days\n" "Freq: D" + exp3 = "TimedeltaIndex: 2 entries, 1 days to 2 days\nFreq: D" - exp4 = "TimedeltaIndex: 3 entries, 1 days to 3 days\n" "Freq: D" + exp4 = "TimedeltaIndex: 3 entries, 1 days to 3 days\nFreq: D" - exp5 = "TimedeltaIndex: 3 entries, 1 days 00:00:01 to 3 days " "00:00:00" + exp5 = "TimedeltaIndex: 3 entries, 1 days 00:00:01 to 3 days 00:00:00" for idx, expected in zip( [idx1, idx2, idx3, idx4, idx5], [exp1, exp2, exp3, exp4, exp5] diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 3549d81623e10..0dccf023c66f8 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -378,7 +378,7 @@ def test_loc_listlike_dtypes(self): exp = DataFrame({"A": [1, 1, 2], "B": [4, 4, 5]}, index=exp_index) tm.assert_frame_equal(res, exp, check_index_type=True) - msg = "a list-indexer must only include " "values that are in the categories" + msg = "a list-indexer must only include values that are in the categories" with pytest.raises(KeyError, match=msg): df.loc[["a", "x"]] @@ -401,7 +401,7 @@ def test_loc_listlike_dtypes(self): ) tm.assert_frame_equal(res, exp, check_index_type=True) - msg = "a list-indexer must only include values " "that are in the categories" + msg = "a list-indexer must only include values that are in the categories" with pytest.raises(KeyError, match=msg): df.loc[["a", "x"]] @@ -431,7 +431,7 @@ def test_loc_listlike_dtypes(self): ) tm.assert_frame_equal(res, exp, check_index_type=True) - msg = "a list-indexer must only include values " "that are in the categories" + msg = "a list-indexer must only include values that are in the categories" with pytest.raises(KeyError, match=msg): df.loc[["a", "x"]] diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 7d47063623d87..702bf0b15dec9 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -307,7 +307,7 @@ def test_setting_with_copy_bug(self): ) mask = pd.isna(df.c) - msg = "A value is trying to be set on a copy of a slice from a" " DataFrame" + msg = "A value is trying to be set on a copy of a slice from a DataFrame" with pytest.raises(com.SettingWithCopyError, match=msg): df[["c"]][mask] = df[["b"]][mask] diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index a18f8380f80c1..dea1d5114f1b9 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -694,7 +694,7 @@ def test_where_index_datetime(self): assert obj.dtype == "datetime64[ns]" cond = pd.Index([True, False, True, False]) - msg = "Index\\(\\.\\.\\.\\) must be called with a collection " "of some kind" + msg = "Index\\(\\.\\.\\.\\) must be called with a collection of some kind" with pytest.raises(TypeError, match=msg): obj.where(cond, fill_val) @@ -725,7 +725,7 @@ def test_where_index_datetimetz(self): assert obj.dtype == "datetime64[ns]" cond = pd.Index([True, False, True, False]) - msg = "Index\\(\\.\\.\\.\\) must be called with a collection " "of some kind" + msg = "Index\\(\\.\\.\\.\\) must be called with a collection of some kind" with pytest.raises(TypeError, match=msg): obj.where(cond, fill_val) @@ -1031,7 +1031,7 @@ def test_replace_series(self, how, to_key, from_key): # TODO(jbrockmendel) commented out to only have a single xfail printed @pytest.mark.xfail( - reason="GH #18376, tzawareness-compat bug " "in BlockManager.replace_list" + reason="GH #18376, tzawareness-compat bug in BlockManager.replace_list" ) # @pytest.mark.parametrize('how', ['dict', 'series']) # @pytest.mark.parametrize('to_key', ['timedelta64[ns]', 'bool', 'object', diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 760d8c70b9434..60a6a509c0912 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -668,11 +668,11 @@ def test_iloc_mask(self): # GH 3631, iloc with a mask (of a series) should raise df = DataFrame(list(range(5)), index=list("ABCDE"), columns=["a"]) mask = df.a % 2 == 0 - msg = "iLocation based boolean indexing cannot use an indexable as" " a mask" + msg = "iLocation based boolean indexing cannot use an indexable as a mask" with pytest.raises(ValueError, match=msg): df.iloc[mask] mask.index = range(len(mask)) - msg = "iLocation based boolean indexing on an integer type is not" " available" + msg = "iLocation based boolean indexing on an integer type is not available" with pytest.raises(NotImplementedError, match=msg): df.iloc[mask] @@ -693,7 +693,7 @@ def test_iloc_mask(self): ("index", ""): "0b11", ("index", ".loc"): "0b11", ("index", ".iloc"): ( - "iLocation based boolean indexing " "cannot use an indexable as a mask" + "iLocation based boolean indexing cannot use an indexable as a mask" ), ("locs", ""): "Unalignable boolean Series provided as indexer " "(index of the boolean Series and of the indexed " diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index a6e1273a229dc..e6ccee684b76b 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -147,7 +147,7 @@ def test_at_to_fail(self): s = Series([1, 2, 3], index=[3, 2, 1]) result = s.at[1] assert result == 3 - msg = "At based indexing on an integer index can only have integer" " indexers" + msg = "At based indexing on an integer index can only have integer indexers" with pytest.raises(ValueError, match=msg): s.at["a"] diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 6beb847da3eb4..2d4fb87d0c6bf 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -537,7 +537,7 @@ def test_astype(self): assert tmgr.get("e").dtype.type == t # mixed - mgr = create_mgr("a,b: object; c: bool; d: datetime;" "e: f4; f: f2; g: f8") + mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8") for t in ["float16", "float32", "float64", "int32", "int64"]: t = np.dtype(t) tmgr = mgr.astype(t, errors="ignore") @@ -599,7 +599,7 @@ def _compare(old_mgr, new_mgr): assert new_mgr.get("g").dtype == np.float64 mgr = create_mgr( - "a,b,foo: object; f: i4; bool: bool; dt: datetime;" "i: i8; g: f8; h: f2" + "a,b,foo: object; f: i4; bool: bool; dt: datetime; i: i8; g: f8; h: f2" ) mgr.set("a", np.array(["1"] * N, dtype=np.object_)) mgr.set("b", np.array(["2."] * N, dtype=np.object_)) @@ -703,7 +703,7 @@ def test_reindex_index(self): def test_reindex_items(self): # mgr is not consolidated, f8 & f8-2 blocks - mgr = create_mgr("a: f8; b: i8; c: f8; d: i8; e: f8;" "f: bool; g: f8-2") + mgr = create_mgr("a: f8; b: i8; c: f8; d: i8; e: f8; f: bool; g: f8-2") reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0) assert reindexed.nblocks == 2 diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 76b27bce11b08..7ee84077a5334 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -14,7 +14,7 @@ pytest.param( "xlwt", marks=pytest.mark.xfail( - reason="xlwt does not support " "openpyxl-compatible " "style dicts" + reason="xlwt does not support openpyxl-compatible style dicts" ), ), "xlsxwriter", diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index cf26b20e5d004..0908ed885a6ca 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -172,7 +172,7 @@ def test_excel_multindex_roundtrip( with ensure_clean(ext) as pth: if c_idx_levels == 1 and c_idx_names: pytest.skip( - "Column index name cannot be " "serialized unless it's a MultiIndex" + "Column index name cannot be serialized unless it's a MultiIndex" ) # Empty name case current read in as diff --git a/pandas/tests/io/formats/test_eng_formatting.py b/pandas/tests/io/formats/test_eng_formatting.py index b122e4f6c3f33..d2a2d0a6a9706 100644 --- a/pandas/tests/io/formats/test_eng_formatting.py +++ b/pandas/tests/io/formats/test_eng_formatting.py @@ -24,16 +24,12 @@ def test_eng_float_formatter(self): fmt.set_eng_float_format(use_eng_prefix=True) result = df.to_string() - expected = ( - " A\n" "0 1.410\n" "1 141.000\n" "2 14.100k\n" "3 1.410M" - ) + expected = " A\n0 1.410\n1 141.000\n2 14.100k\n3 1.410M" assert result == expected fmt.set_eng_float_format(accuracy=0) result = df.to_string() - expected = ( - " A\n" "0 1E+00\n" "1 141E+00\n" "2 14E+03\n" "3 1E+06" - ) + expected = " A\n0 1E+00\n1 141E+00\n2 14E+03\n3 1E+06" assert result == expected tm.reset_display_options() diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index af862b11c756c..818bbc566aca8 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -374,7 +374,7 @@ def test_repr_max_columns_max_rows(self): term_width, term_height = get_terminal_size() if term_width < 10 or term_height < 10: pytest.skip( - "terminal size too small, " "{0} x {1}".format(term_width, term_height) + "terminal size too small, {0} x {1}".format(term_width, term_height) ) def mkframe(n): @@ -1409,11 +1409,11 @@ def test_to_string_no_index(self): df_s = df.to_string(index=False) # Leading space is expected for positive numbers. - expected = " x y z\n" " 11 33 AAA\n" " 22 -44 " + expected = " x y z\n 11 33 AAA\n 22 -44 " assert df_s == expected df_s = df[["y", "x", "z"]].to_string(index=False) - expected = " y x z\n" " 33 11 AAA\n" "-44 22 " + expected = " y x z\n 33 11 AAA\n-44 22 " assert df_s == expected def test_to_string_line_width_no_index(self): @@ -1475,7 +1475,7 @@ def test_to_string_float_formatting(self): df = DataFrame({"x": [3234, 0.253]}) df_s = df.to_string() - expected = " x\n" "0 3234.000\n" "1 0.253" + expected = " x\n0 3234.000\n1 0.253" assert df_s == expected tm.reset_display_options() @@ -1485,9 +1485,9 @@ def test_to_string_float_formatting(self): df_s = df.to_string() if _three_digit_exp(): - expected = " x\n" "0 1.000000e+009\n" "1 2.512000e-001" + expected = " x\n0 1.000000e+009\n1 2.512000e-001" else: - expected = " x\n" "0 1.000000e+09\n" "1 2.512000e-01" + expected = " x\n0 1.000000e+09\n1 2.512000e-01" assert df_s == expected def test_to_string_float_format_no_fixed_width(self): @@ -1526,14 +1526,14 @@ def test_to_string_small_float_values(self): # but not all exactly zero df = df * 0 result = df.to_string() - expected = " 0\n" "0 0\n" "1 0\n" "2 -0" + expected = " 0\n0 0\n1 0\n2 -0" def test_to_string_float_index(self): index = Index([1.5, 2, 3, 4, 5]) df = DataFrame(np.arange(5), index=index) result = df.to_string() - expected = " 0\n" "1.5 0\n" "2.0 1\n" "3.0 2\n" "4.0 3\n" "5.0 4" + expected = " 0\n1.5 0\n2.0 1\n3.0 2\n4.0 3\n5.0 4" assert result == expected def test_to_string_complex_float_formatting(self): @@ -1562,7 +1562,7 @@ def test_to_string_ascii_error(self): "0 ", " .gitignore ", " 5 ", - " \xe2\x80\xa2\xe2\x80\xa2\xe2\x80" "\xa2\xe2\x80\xa2\xe2\x80\xa2", + " \xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2", ) ] df = DataFrame(data) @@ -1575,7 +1575,7 @@ def test_to_string_int_formatting(self): assert issubclass(df["x"].dtype.type, np.integer) output = df.to_string() - expected = " x\n" "0 -15\n" "1 20\n" "2 25\n" "3 -35" + expected = " x\n0 -15\n1 20\n2 25\n3 -35" assert output == expected def test_to_string_index_formatter(self): @@ -1596,7 +1596,7 @@ def test_to_string_left_justify_cols(self): tm.reset_display_options() df = DataFrame({"x": [3234, 0.253]}) df_s = df.to_string(justify="left") - expected = " x \n" "0 3234.000\n" "1 0.253" + expected = " x \n0 3234.000\n1 0.253" assert df_s == expected def test_to_string_format_na(self): @@ -2077,7 +2077,7 @@ def test_to_string(self): result = cp.to_string(length=True, name=True, dtype=True) last_line = result.split("\n")[-1].strip() assert last_line == ( - "Freq: B, Name: foo, " "Length: {cp}, dtype: float64".format(cp=len(cp)) + "Freq: B, Name: foo, Length: {cp}, dtype: float64".format(cp=len(cp)) ) def test_freq_name_separation(self): @@ -2136,22 +2136,18 @@ def test_east_asian_unicode_series(self): # unicode index s = Series(["a", "bb", "CCC", "D"], index=["あ", "いい", "ううう", "ええええ"]) - expected = ( - "あ a\nいい bb\nううう CCC\n" "ええええ D\ndtype: object" - ) + expected = "あ a\nいい bb\nううう CCC\nええええ D\ndtype: object" assert repr(s) == expected # unicode values s = Series(["あ", "いい", "ううう", "ええええ"], index=["a", "bb", "c", "ddd"]) - expected = ( - "a あ\nbb いい\nc ううう\n" "ddd ええええ\ndtype: object" - ) + expected = "a あ\nbb いい\nc ううう\nddd ええええ\ndtype: object" assert repr(s) == expected # both s = Series(["あ", "いい", "ううう", "ええええ"], index=["ああ", "いいいい", "う", "えええ"]) expected = ( - "ああ あ\nいいいい いい\nう ううう\n" "えええ ええええ\ndtype: object" + "ああ あ\nいいいい いい\nう ううう\nえええ ええええ\ndtype: object" ) assert repr(s) == expected @@ -2181,7 +2177,7 @@ def test_east_asian_unicode_series(self): # object dtype, shorter than unicode repr s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"]) expected = ( - "1 1\nAB 22\nNaN 3333\n" "あああ 44444\ndtype: int64" + "1 1\nAB 22\nNaN 3333\nあああ 44444\ndtype: int64" ) assert repr(s) == expected @@ -2559,7 +2555,7 @@ def test_format_explicit(self): exp = "0 a\n1 a\n ..\n98 a\n99 a\ndtype: object" assert exp == res res = repr(test_sers["twol"]) - exp = "0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype:" " object" + exp = "0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype: object" assert exp == res res = repr(test_sers["asc"]) exp = ( diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 7bd27b2ad9be3..f2fb54796f177 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -484,12 +484,12 @@ def test_bar_align_left(self): (1, 0): [ "width: 10em", " height: 80%", - "background: linear-gradient(" "90deg,red 25.0%, transparent 25.0%)", + "background: linear-gradient(90deg,red 25.0%, transparent 25.0%)", ], (2, 0): [ "width: 10em", " height: 80%", - "background: linear-gradient(" "90deg,red 50.0%, transparent 50.0%)", + "background: linear-gradient(90deg,red 50.0%, transparent 50.0%)", ], } assert result == expected diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 7b493266144b0..c6485ff21bcfb 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -12,7 +12,7 @@ class TestToCSV: @pytest.mark.xfail( (3, 6, 5) > sys.version_info >= (3, 5), - reason=("Python csv library bug " "(see https://bugs.python.org/issue32255)"), + reason=("Python csv library bug (see https://bugs.python.org/issue32255)"), ) def test_to_csv_with_single_column(self): # see gh-18676, https://bugs.python.org/issue32255 diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 28c8837731ec1..c2753d23966c6 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -508,7 +508,7 @@ def test_convert_json_field_to_pandas_type(self, inp, exp): def test_convert_json_field_to_pandas_type_raises(self, inp): field = {"type": inp} with pytest.raises( - ValueError, match=("Unsupported or invalid field " "type: {}".format(inp)) + ValueError, match=("Unsupported or invalid field type: {}".format(inp)) ): convert_json_field_to_pandas_type(field) diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 82cd00c2d121d..412e5014c8d23 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -297,7 +297,7 @@ def test_meta_name_conflict(self): } ] - msg = r"Conflicting metadata name (foo|bar)," " need distinguishing prefix" + msg = r"Conflicting metadata name (foo|bar), need distinguishing prefix" with pytest.raises(ValueError, match=msg): json_normalize(data, "data", meta=["foo", "bar"]) @@ -491,7 +491,7 @@ def test_json_normalize_errors(self, missing_metadata): # If meta keys are not always present a new option to set # errors='ignore' has been implemented - msg = "Try running with errors='ignore' as key 'name'" " is not always present" + msg = "Try running with errors='ignore' as key 'name' is not always present" with pytest.raises(KeyError, match=msg): json_normalize( data=missing_metadata, diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index a0686b53b83a4..970fd465fd4ec 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1434,7 +1434,7 @@ def test_to_jsonl(self): def test_latin_encoding(self): # GH 13774 - pytest.skip("encoding not implemented in .to_json(), " "xref #13774") + pytest.skip("encoding not implemented in .to_json(), xref #13774") values = [ [b"E\xc9, 17", b"", b"a", b"b", b"c"], @@ -1589,7 +1589,7 @@ def test_index_false_error_to_json(self, orient): df = pd.DataFrame([[1, 2], [4, 5]], columns=["a", "b"]) - msg = "'index=False' is only valid when " "'orient' is 'split' or 'table'" + msg = "'index=False' is only valid when 'orient' is 'split' or 'table'" with pytest.raises(ValueError, match=msg): df.to_json(orient=orient, index=False) diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 7d5bf9ec850bc..d469d3c2e51de 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -1243,7 +1243,7 @@ def test_catch_too_many_names(all_parsers): 10,11,12\n""" parser = all_parsers msg = ( - "Too many columns specified: " "expected 4 and found 3" + "Too many columns specified: expected 4 and found 3" if parser.engine == "c" else "Number of passed names did not match " "number of header fields in the file" diff --git a/pandas/tests/io/parser/test_compression.py b/pandas/tests/io/parser/test_compression.py index 06ae2c0fef1b9..9d0eab0b9a907 100644 --- a/pandas/tests/io/parser/test_compression.py +++ b/pandas/tests/io/parser/test_compression.py @@ -89,7 +89,7 @@ def test_compression(parser_and_data, compression_only, buffer, filename): filename = filename if filename is None else filename.format(ext=ext) if filename and buffer: - pytest.skip("Cannot deduce compression from " "buffer of compressed data.") + pytest.skip("Cannot deduce compression from buffer of compressed data.") with tm.ensure_clean(filename=filename) as path: tm.write_to_compressed(compress_type, path, data) @@ -144,7 +144,7 @@ def test_invalid_compression(all_parsers, invalid_compression): parser = all_parsers compress_kwargs = dict(compression=invalid_compression) - msg = "Unrecognized compression " "type: {compression}".format(**compress_kwargs) + msg = "Unrecognized compression type: {compression}".format(**compress_kwargs) with pytest.raises(ValueError, match=msg): parser.read_csv("test_file.zip", **compress_kwargs) diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py index ff1dd10bdd0d9..99e0181741998 100644 --- a/pandas/tests/io/parser/test_header.py +++ b/pandas/tests/io/parser/test_header.py @@ -124,11 +124,11 @@ def test_header_multi_index(all_parsers): ), ( dict(index_col=[0, 1], names=["foo", "bar"]), - ("cannot specify names " "when specifying a " "multi-index header"), + ("cannot specify names when specifying a multi-index header"), ), ( dict(index_col=[0, 1], usecols=["foo", "bar"]), - ("cannot specify " "usecols when " "specifying a " "multi-index header"), + ("cannot specify usecols when specifying a multi-index header"), ), ], ) diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py index 8199d632223c1..4dfb8d3bd2dc8 100644 --- a/pandas/tests/io/parser/test_index_col.py +++ b/pandas/tests/io/parser/test_index_col.py @@ -62,9 +62,8 @@ def test_index_col_is_true(all_parsers): data = "a,b\n1,2" parser = all_parsers - with pytest.raises( - ValueError, match="The value of index_col " "couldn't be 'True'" - ): + msg = "The value of index_col couldn't be 'True'" + with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), index_col=True) diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 99e4e5c022ecb..5d79f6e281ef1 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -560,7 +560,7 @@ def test_multiple_date_cols_with_header(all_parsers): KORD1,19990127, 19:00:00 KORD2,19990127, 20:00:00""", [[1, 2]], - ("New date column already " "in dict date_NominalTime"), + ("New date column already in dict date_NominalTime"), ), ( """\ @@ -1272,7 +1272,7 @@ def test_parse_date_time(all_parsers, data, kwargs, expected): def test_parse_date_fields(all_parsers): parser = all_parsers - data = "year,month,day,a\n2001,01,10,10.\n" "2001,02,1,11." + data = "year,month,day,a\n2001,01,10,10.\n2001,02,1,11." result = parser.read_csv( StringIO(data), header=0, diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index 57096a2652b88..73638fe8ab7c8 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -56,7 +56,7 @@ def test_string_factorize(self): assert len(set(map(id, result[0]))) == 2 def test_skipinitialspace(self): - data = "a, b\n" "a, b\n" "a, b\n" "a, b" + data = "a, b\na, b\na, b\na, b" reader = TextReader(StringIO(data), skipinitialspace=True, header=None) result = reader.read() @@ -129,10 +129,10 @@ def test_integer_thousands_alt(self): def test_skip_bad_lines(self, capsys): # too many lines, see #2430 for why - data = "a:b:c\n" "d:e:f\n" "g:h:i\n" "j:k:l:m\n" "l:m:n\n" "o:p:q:r" + data = "a:b:c\nd:e:f\ng:h:i\nj:k:l:m\nl:m:n\no:p:q:r" reader = TextReader(StringIO(data), delimiter=":", header=None) - msg = r"Error tokenizing data\. C error: Expected 3 fields in" " line 4, saw 4" + msg = r"Error tokenizing data\. C error: Expected 3 fields in line 4, saw 4" with pytest.raises(parser.ParserError, match=msg): reader.read() @@ -165,7 +165,7 @@ def test_skip_bad_lines(self, capsys): assert "Skipping line 6" in captured.err def test_header_not_enough_lines(self): - data = "skip this\n" "skip this\n" "a,b,c\n" "1,2,3\n" "4,5,6" + data = "skip this\nskip this\na,b,c\n1,2,3\n4,5,6" reader = TextReader(StringIO(data), delimiter=",", header=2) header = reader.header diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index f135fac65f56a..8bdf53c3caf61 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -95,7 +95,7 @@ def test_python_engine(self, python_engine): 1,2,3,4,""" for default in py_unsupported: - msg = "The %r option is not supported " "with the %r engine" % ( + msg = "The %r option is not supported with the %r engine" % ( default, python_engine, ) diff --git a/pandas/tests/io/parser/test_usecols.py b/pandas/tests/io/parser/test_usecols.py index b449e848a0b5a..47c4f93fbf59c 100644 --- a/pandas/tests/io/parser/test_usecols.py +++ b/pandas/tests/io/parser/test_usecols.py @@ -18,7 +18,7 @@ "integers or a callable." ) _msg_validate_usecols_names = ( - "Usecols do not match columns, columns " "expected but not found: {0}" + "Usecols do not match columns, columns expected but not found: {0}" ) @@ -124,7 +124,7 @@ def test_usecols_name_length_conflict(all_parsers): 10,11,12""" parser = all_parsers msg = ( - "Number of passed names did not " "match number of header fields in the file" + "Number of passed names did not match number of header fields in the file" if parser.engine == "python" else "Passed header names mismatches usecols" ) @@ -501,7 +501,7 @@ def test_incomplete_first_row(all_parsers, usecols): ), # see gh-9549 ( - ("A,B,C\n1,2,3\n3,4,5\n1,2,4,5,1,6\n" "1,2,3,,,1,\n1,2,3\n5,6,7"), + ("A,B,C\n1,2,3\n3,4,5\n1,2,4,5,1,6\n1,2,3,,,1,\n1,2,3\n5,6,7"), ["A", "B", "C"], dict(), DataFrame( diff --git a/pandas/tests/io/pytables/test_pytables.py b/pandas/tests/io/pytables/test_pytables.py index fee7e1cb2ba5f..b9f4defb4edf8 100644 --- a/pandas/tests/io/pytables/test_pytables.py +++ b/pandas/tests/io/pytables/test_pytables.py @@ -1622,7 +1622,7 @@ def check_col(key, name, size): _maybe_remove(store, "df") store.append("df", df_new, data_columns=["A", "B", "string", "string2"]) result = store.select( - "df", "string='foo' and string2='foo'" " and A>0 and B<0" + "df", "string='foo' and string2='foo' and A>0 and B<0" ) expected = df_new[ (df_new.string == "foo") @@ -3726,7 +3726,7 @@ def test_append_to_multiple_dropna(self): tm.assert_index_equal(store.select("df1").index, store.select("df2").index) @pytest.mark.xfail( - run=False, reason="append_to_multiple_dropna_false " "is not raising as failed" + run=False, reason="append_to_multiple_dropna_false is not raising as failed" ) def test_append_to_multiple_dropna_false(self): df1 = tm.makeTimeDataFrame() @@ -3817,9 +3817,7 @@ def test_select_as_multiple(self): @pytest.mark.skipif( LooseVersion(tables.__version__) < LooseVersion("3.1.0"), - reason=( - "tables version does not support fix for nan selection " "bug: GH 4858" - ), + reason=("tables version does not support fix for nan selection bug: GH 4858"), ) def test_nan_selection_bug_4858(self): diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index fa63f102580ff..87a2405a10dd5 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -109,7 +109,7 @@ def test_unsupported_other(self): def test_rw_nthreads(self): df = pd.DataFrame({"A": np.arange(100000)}) expected_warning = ( - "the 'nthreads' keyword is deprecated, " "use 'use_threads' instead" + "the 'nthreads' keyword is deprecated, use 'use_threads' instead" ) # TODO: make the warning work with check_stacklevel=True with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w: diff --git a/pandas/tests/io/test_gbq.py b/pandas/tests/io/test_gbq.py index 6ca6da01a6d6f..52147f4e1afc7 100644 --- a/pandas/tests/io/test_gbq.py +++ b/pandas/tests/io/test_gbq.py @@ -33,9 +33,7 @@ def _skip_if_no_project_id(): def _skip_if_no_private_key_path(): if not _get_private_key_path(): - pytest.skip( - "Cannot run integration tests without a " "private key json file path" - ) + pytest.skip("Cannot run integration tests without a private key json file path") def _in_travis_environment(): diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index d3d05b6281d5b..9752b4c62aff7 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -220,9 +220,7 @@ def test_skiprows_ndarray(self): assert_framelist_equal(df1, df2) def test_skiprows_invalid(self): - with pytest.raises( - TypeError, match=("is not a valid type " "for skipping rows") - ): + with pytest.raises(TypeError, match=("is not a valid type for skipping rows")): self.read_html(self.spam_data, ".*Water.*", skiprows="asdf") def test_index(self): diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index f3e045be2e790..6ac2e9cd65a27 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -40,13 +40,13 @@ pytest.param( "fastparquet", marks=pytest.mark.skipif( - not _HAVE_FASTPARQUET, reason="fastparquet is " "not installed" + not _HAVE_FASTPARQUET, reason="fastparquet is not installed" ), ), pytest.param( "pyarrow", marks=pytest.mark.skipif( - not _HAVE_PYARROW, reason="pyarrow is " "not installed" + not _HAVE_PYARROW, reason="pyarrow is not installed" ), ), ] diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 4fc90ea41718d..347e280234f91 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -824,7 +824,7 @@ def test_to_sql_index_label_multiindex(self): frame = sql.read_sql_query("SELECT * FROM test_index_label", self.conn) assert frame.columns[:2].tolist() == ["C", "D"] - msg = "Length of 'index_label' should match number of levels, which" " is 2" + msg = "Length of 'index_label' should match number of levels, which is 2" with pytest.raises(ValueError, match=msg): sql.to_sql( temp_frame, @@ -1408,7 +1408,7 @@ def check(col): else: raise AssertionError( - "DateCol loaded with incorrect type " "-> {0}".format(col.dtype) + "DateCol loaded with incorrect type -> {0}".format(col.dtype) ) # GH11216 @@ -2566,7 +2566,7 @@ def clean_up(test_table_to_drop): @pytest.mark.single @pytest.mark.db @pytest.mark.skip( - reason="gh-13611: there is no support for MySQL " "if SQLAlchemy is not installed" + reason="gh-13611: there is no support for MySQL if SQLAlchemy is not installed" ) class TestXMySQL(MySQLMixIn): @pytest.fixture(autouse=True, scope="class") diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 715c7e370210f..1e7d568602656 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -915,7 +915,7 @@ def test_drop_column(self): columns = ["byte_", "byte_"] read_stata(self.dta15_117, convert_dates=True, columns=columns) - msg = "The following columns were not found in the Stata data set:" " not_found" + msg = "The following columns were not found in the Stata data set: not_found" with pytest.raises(ValueError, match=msg): columns = ["byte_", "int_", "long_", "not_found"] read_stata(self.dta15_117, convert_dates=True, columns=columns) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index ecd575020eca6..5ae29dc640dc9 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -179,7 +179,7 @@ def check_format_of_first_point(ax, expected_string): assert expected_string == ax.format_coord(first_x, first_y) except (ValueError): pytest.skip( - "skipping test because issue forming " "test comparison GH7664" + "skipping test because issue forming test comparison GH7664" ) annual = Series(1, index=date_range("2014-01-01", periods=3, freq="A-DEC")) @@ -1501,7 +1501,7 @@ def test_overlapping_datetime(self): s2.plot(ax=ax) s1.plot(ax=ax) - @pytest.mark.xfail(reason="GH9053 matplotlib does not use" " ax.xaxis.converter") + @pytest.mark.xfail(reason="GH9053 matplotlib does not use ax.xaxis.converter") def test_add_matplotlib_datetime64(self): # GH9053 - ensure that a plot with PeriodConverter still understands # datetime64 data. This still fails because matplotlib overrides the diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 0215b79cb993d..65815bcedebfc 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -547,9 +547,7 @@ def test_subplots_timeseries_y_axis(self): with pytest.raises(TypeError, match=msg): testdata.plot(y="text") - @pytest.mark.xfail( - reason="not support for period, categorical, " "datetime_mixed_tz" - ) + @pytest.mark.xfail(reason="not support for period, categorical, datetime_mixed_tz") def test_subplots_timeseries_y_axis_not_supported(self): """ This test will fail for: diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 80365e34fa87a..b6c6f967333a8 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1141,7 +1141,7 @@ def test_validation(self): validate="one_to_many", ) - msg = "Merge keys are not unique in right dataset; not a one-to-one" " merge" + msg = "Merge keys are not unique in right dataset; not a one-to-one merge" with pytest.raises(MergeError, match=msg): merge( left, @@ -1166,7 +1166,7 @@ def test_validation(self): validate="many_to_one", ) - msg = "Merge keys are not unique in left dataset; not a one-to-one" " merge" + msg = "Merge keys are not unique in left dataset; not a one-to-one merge" with pytest.raises(MergeError, match=msg): merge( left_w_dups, @@ -1182,7 +1182,7 @@ def test_validation(self): # Dups on both merge(left_w_dups, right_w_dups, on="a", validate="many_to_many") - msg = "Merge keys are not unique in right dataset; not a many-to-one" " merge" + msg = "Merge keys are not unique in right dataset; not a many-to-one merge" with pytest.raises(MergeError, match=msg): merge( left_w_dups, @@ -1192,7 +1192,7 @@ def test_validation(self): validate="many_to_one", ) - msg = "Merge keys are not unique in left dataset; not a one-to-many" " merge" + msg = "Merge keys are not unique in left dataset; not a one-to-many merge" with pytest.raises(MergeError, match=msg): merge(left_w_dups, right_w_dups, on="a", validate="one_to_many") diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index 56e83ada9eb99..1b067c08d2e40 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -121,9 +121,7 @@ def test_tuple_vars_fail_with_multiindex(self): tuple_b = ("B", "b") list_b = [tuple_b] - msg = ( - r"(id|value)_vars must be a list of tuples when columns are" " a MultiIndex" - ) + msg = r"(id|value)_vars must be a list of tuples when columns are a MultiIndex" for id_vars, value_vars in ( (tuple_a, list_b), (list_a, tuple_b), diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index b497f6c3aa9b4..d3300ffb01c3a 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -731,7 +731,7 @@ def test_pivot_with_list_like_values_nans(self, values, method): tm.assert_frame_equal(result, expected) @pytest.mark.xfail( - reason="MultiIndexed unstack with tuple names fails" "with KeyError GH#19966" + reason="MultiIndexed unstack with tuple names fails with KeyError GH#19966" ) @pytest.mark.parametrize("method", [True, False]) def test_pivot_with_multiindex(self, method): @@ -880,7 +880,7 @@ def test_margins_dtype(self): tm.assert_frame_equal(expected, result) - @pytest.mark.xfail(reason="GH#17035 (len of floats is casted back to " "floats)") + @pytest.mark.xfail(reason="GH#17035 (len of floats is casted back to floats)") def test_margins_dtype_len(self): mi_val = list(product(["bar", "foo"], ["one", "two"])) + [("All", "")] mi = MultiIndex.from_tuples(mi_val, names=("A", "B")) @@ -1575,7 +1575,7 @@ def test_pivot_table_margins_name_with_aggfunc_list(self): expected = pd.DataFrame(table.values, index=ix, columns=cols) tm.assert_frame_equal(table, expected) - @pytest.mark.xfail(reason="GH#17035 (np.mean of ints is casted back to " "ints)") + @pytest.mark.xfail(reason="GH#17035 (np.mean of ints is casted back to ints)") def test_categorical_margins(self, observed): # GH 10989 df = pd.DataFrame( @@ -1589,7 +1589,7 @@ def test_categorical_margins(self, observed): table = df.pivot_table("x", "y", "z", dropna=observed, margins=True) tm.assert_frame_equal(table, expected) - @pytest.mark.xfail(reason="GH#17035 (np.mean of ints is casted back to " "ints)") + @pytest.mark.xfail(reason="GH#17035 (np.mean of ints is casted back to ints)") def test_categorical_margins_category(self, observed): df = pd.DataFrame( {"x": np.arange(8), "y": np.arange(8) // 4, "z": np.arange(8) % 2} diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index ee0ff87e31aea..4cff061cabc40 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -31,7 +31,7 @@ def test_asfreq_near_zero_weekly(self): assert week2.asfreq("D", "S") <= per2 @pytest.mark.xfail( - reason="GH#19643 period_helper asfreq functions fail " "to check for overflows" + reason="GH#19643 period_helper asfreq functions fail to check for overflows" ) def test_to_timestamp_out_of_bounds(self): # GH#19643, currently gives Timestamp('1754-08-30 22:43:41.128654848') diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 34d2fa6a9194c..771a67dfceaa8 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -390,11 +390,11 @@ def test_period_cons_mult(self): assert result.freq == p1.freq assert result.freqstr == "3M" - msg = "Frequency must be positive, because it" " represents span: -3M" + msg = "Frequency must be positive, because it represents span: -3M" with pytest.raises(ValueError, match=msg): Period("2011-01", freq="-3M") - msg = "Frequency must be positive, because it" " represents span: 0M" + msg = "Frequency must be positive, because it represents span: 0M" with pytest.raises(ValueError, match=msg): Period("2011-01", freq="0M") @@ -445,7 +445,7 @@ def test_period_cons_combined(self): assert result.freq == p2.freq assert result.freqstr == "25H" - msg = "Frequency must be positive, because it" " represents span: -25H" + msg = "Frequency must be positive, because it represents span: -25H" with pytest.raises(ValueError, match=msg): Period("2011-01", freq="-1D1H") with pytest.raises(ValueError, match=msg): @@ -455,7 +455,7 @@ def test_period_cons_combined(self): with pytest.raises(ValueError, match=msg): Period(ordinal=1, freq="-1H1D") - msg = "Frequency must be positive, because it" " represents span: 0D" + msg = "Frequency must be positive, because it represents span: 0D" with pytest.raises(ValueError, match=msg): Period("2011-01", freq="0D0H") with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/scalar/timedelta/test_construction.py b/pandas/tests/scalar/timedelta/test_construction.py index 9917e8bc4c9ac..ae1e84576c092 100644 --- a/pandas/tests/scalar/timedelta/test_construction.py +++ b/pandas/tests/scalar/timedelta/test_construction.py @@ -239,9 +239,8 @@ def test_iso_constructor(fmt, exp): ], ) def test_iso_constructor_raises(fmt): - with pytest.raises( - ValueError, match=("Invalid ISO 8601 Duration " "format - {}".format(fmt)) - ): + msg = "Invalid ISO 8601 Duration format - {}".format(fmt) + with pytest.raises(ValueError, match=msg): Timedelta(fmt) diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py index f64cf97acf805..424b0c9abdef8 100644 --- a/pandas/tests/scalar/timestamp/test_timezones.py +++ b/pandas/tests/scalar/timestamp/test_timezones.py @@ -63,11 +63,11 @@ def test_tz_localize_ambiguous(self): ts.tz_localize("US/Eastern", ambiguous="infer") # GH#8025 - msg = "Cannot localize tz-aware Timestamp, " "use tz_convert for conversions" + msg = "Cannot localize tz-aware Timestamp, use tz_convert for conversions" with pytest.raises(TypeError, match=msg): Timestamp("2011-01-01", tz="US/Eastern").tz_localize("Asia/Tokyo") - msg = "Cannot convert tz-naive Timestamp, " "use tz_localize to localize" + msg = "Cannot convert tz-naive Timestamp, use tz_localize to localize" with pytest.raises(TypeError, match=msg): Timestamp("2011-01-01").tz_convert("Asia/Tokyo") diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index 31a1f43470f2c..c93a000f5e7ce 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -480,7 +480,7 @@ def test_rename(): @pytest.mark.parametrize( - "data, index, drop_labels," " axis, expected_data, expected_index", + "data, index, drop_labels, axis, expected_data, expected_index", [ # Unique Index ([1, 2], ["one", "two"], ["two"], 0, [1], ["one"]), @@ -503,7 +503,7 @@ def test_drop_unique_and_non_unique_index( @pytest.mark.parametrize( - "data, index, drop_labels," " axis, error_type, error_desc", + "data, index, drop_labels, axis, error_type, error_desc", [ # single string/tuple-like (range(3), list("abc"), "bc", 0, KeyError, "not found in axis"), diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index 9b76ed026e580..01b4a3c84a565 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -353,7 +353,7 @@ def test_where_setitem_invalid(): # GH 2702 # make sure correct exceptions are raised on invalid list assignment - msg = "cannot set using a {} indexer with a different length than" " the value" + msg = "cannot set using a {} indexer with a different length than the value" # slice s = Series(list("abc")) diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 89b411a284563..67373686d6728 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -229,7 +229,7 @@ def test_cummax_timedelta64(self): tm.assert_series_equal(expected, result) def test_npdiff(self): - pytest.skip("skipping due to Series no longer being an " "ndarray") + pytest.skip("skipping due to Series no longer being an ndarray") # no longer works as the return type of np.diff is now nd.array s = Series(np.arange(5)) @@ -407,9 +407,7 @@ def test_corr_invalid_method(self): # GH PR #22298 s1 = pd.Series(np.random.randn(10)) s2 = pd.Series(np.random.randn(10)) - msg = ( - "method must be either 'pearson', " "'spearman', 'kendall', or a callable, " - ) + msg = "method must be either 'pearson', 'spearman', 'kendall', or a callable, " with pytest.raises(ValueError, match=msg): s1.corr(s2, method="____") @@ -820,7 +818,7 @@ def test_ptp(self): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): tm.assert_series_equal(s.ptp(level=0, skipna=False), expected) - msg = "No axis named 1 for object type" " " + msg = "No axis named 1 for object type " with pytest.raises(ValueError, match=msg): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): s.ptp(axis=1) @@ -1295,7 +1293,7 @@ class TestNLargestNSmallest: ) def test_error(self, r): dt = r.dtype - msg = "Cannot use method 'n(larg|small)est' with " "dtype {dt}".format(dt=dt) + msg = "Cannot use method 'n(larg|small)est' with dtype {dt}".format(dt=dt) args = 2, len(r), 0, -1 methods = r.nlargest, r.nsmallest for method, arg in product(methods, args): diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 6012f3986e955..f8a44b7f5639e 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -813,7 +813,7 @@ def test_dropna_empty(self): assert len(s) == 0 # invalid axis - msg = "No axis named 1 for object type" " " + msg = "No axis named 1 for object type " with pytest.raises(ValueError, match=msg): s.dropna(axis=1) @@ -1117,9 +1117,7 @@ def test_interpolate_time_raises_for_non_timeseries(self): # When method='time' is used on a non-TimeSeries that contains a null # value, a ValueError should be raised. non_ts = Series([0, 1, 2, np.NaN]) - msg = ( - "time-weighted interpolation only works on Series.* " "with a DatetimeIndex" - ) + msg = "time-weighted interpolation only works on Series.* with a DatetimeIndex" with pytest.raises(ValueError, match=msg): non_ts.interpolate(method="time") @@ -1417,9 +1415,7 @@ def test_interp_limit_area(self): ) # raises an error even if limit type is wrong. - msg = ( - r"Invalid limit_area: expecting one of \['inside', 'outside'\]," " got abc" - ) + msg = r"Invalid limit_area: expecting one of \['inside', 'outside'\], got abc" with pytest.raises(ValueError, match=msg): s.interpolate(method="linear", limit_area="abc") @@ -1668,5 +1664,5 @@ def test_interpolate_timedelta_index(self, interp_methods_ind): assert_series_equal(result, expected) else: pytest.skip( - "This interpolation method is not supported for " "Timedelta Index yet." + "This interpolation method is not supported for Timedelta Index yet." ) diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index aada5cca9fdc7..0c25df7997469 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -194,7 +194,7 @@ def test_logical_ops_with_index(self, op): pytest.param( ops.rand_, marks=pytest.mark.xfail( - reason="GH#22092 Index " "implementation returns " "Index", + reason="GH#22092 Index implementation returns Index", raises=AssertionError, strict=True, ), @@ -202,7 +202,7 @@ def test_logical_ops_with_index(self, op): pytest.param( ops.ror_, marks=pytest.mark.xfail( - reason="Index.get_indexer " "with non unique index", + reason="Index.get_indexer with non unique index", raises=InvalidIndexError, strict=True, ), diff --git a/pandas/tests/series/test_sorting.py b/pandas/tests/series/test_sorting.py index 0ae2194543b44..125f516ab6b09 100644 --- a/pandas/tests/series/test_sorting.py +++ b/pandas/tests/series/test_sorting.py @@ -106,7 +106,7 @@ def test_sort_index(self): sorted_series = random_order.sort_index(axis=0) assert_series_equal(sorted_series, self.ts) - msg = "No axis named 1 for object type" " " + msg = "No axis named 1 for object type " with pytest.raises(ValueError, match=msg): random_order.sort_values(axis=1) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 6be1b9a9143bf..d0ca5d82c6b33 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -120,9 +120,7 @@ def test_shift(self): # incompat tz s2 = Series(date_range("2000-01-01 09:00:00", periods=5, tz="CET"), name="foo") - msg = ( - "DatetimeArray subtraction must have the same timezones or no" " timezones" - ) + msg = "DatetimeArray subtraction must have the same timezones or no timezones" with pytest.raises(TypeError, match=msg): s - s2 @@ -915,7 +913,7 @@ def test_between_time_axis(self): assert len(ts.between_time(stime, etime)) == expected_length assert len(ts.between_time(stime, etime, axis=0)) == expected_length - msg = "No axis named 1 for object type" " " + msg = "No axis named 1 for object type " with pytest.raises(ValueError, match=msg): ts.between_time(stime, etime, axis=1) diff --git a/pandas/tests/sparse/frame/test_frame.py b/pandas/tests/sparse/frame/test_frame.py index 96e3c4640d2f6..6527d41eac841 100644 --- a/pandas/tests/sparse/frame/test_frame.py +++ b/pandas/tests/sparse/frame/test_frame.py @@ -1357,9 +1357,7 @@ def test_as_blocks(self): assert list(df_blocks.keys()) == ["Sparse[float64, nan]"] tm.assert_frame_equal(df_blocks["Sparse[float64, nan]"], df) - @pytest.mark.xfail( - reason="nan column names in _init_dict problematic " "(GH#16894)" - ) + @pytest.mark.xfail(reason="nan column names in _init_dict problematic (GH#16894)") def test_nan_columnname(self): # GH 8822 nan_colname = DataFrame(Series(1.0, index=[0]), columns=[nan]) diff --git a/pandas/tests/sparse/series/test_indexing.py b/pandas/tests/sparse/series/test_indexing.py index 525b0487a9376..c75f3b2134f91 100644 --- a/pandas/tests/sparse/series/test_indexing.py +++ b/pandas/tests/sparse/series/test_indexing.py @@ -62,7 +62,7 @@ def test_where_with_numeric_data(data): ], ) @pytest.mark.parametrize("other", [True, -100, 0.1, 100.0 + 100.0j]) -@pytest.mark.skip(reason="Wrong SparseBlock initialization " "(Segfault) " "(GH 17386)") +@pytest.mark.skip(reason="Wrong SparseBlock initialization (Segfault) (GH 17386)") def test_where_with_numeric_data_and_other(data, other): # GH 17386 lower_bound = 1.5 @@ -96,7 +96,7 @@ def test_where_with_bool_data(): @pytest.mark.parametrize("other", [True, 0, 0.1, 100.0 + 100.0j]) -@pytest.mark.skip(reason="Wrong SparseBlock initialization " "(Segfault) " "(GH 17386)") +@pytest.mark.skip(reason="Wrong SparseBlock initialization (Segfault) (GH 17386)") def test_where_with_bool_data_and_other(other): # GH 17386 data = [False, False, True, True, False, False] diff --git a/pandas/tests/sparse/series/test_series.py b/pandas/tests/sparse/series/test_series.py index 5619a0a11fb11..eb217283c7a83 100644 --- a/pandas/tests/sparse/series/test_series.py +++ b/pandas/tests/sparse/series/test_series.py @@ -1194,7 +1194,7 @@ def test_to_coo_bad_ilevel(self): def test_to_coo_duplicate_index_entries(self): ss = pd.concat([self.sparse_series[0], self.sparse_series[0]]).to_sparse() - msg = "Duplicate index entries are not allowed in to_coo" " transformation" + msg = "Duplicate index entries are not allowed in to_coo transformation" with pytest.raises(ValueError, match=msg): ss.to_coo(["A", "B"], ["C", "D"]) diff --git a/pandas/tests/sparse/test_indexing.py b/pandas/tests/sparse/test_indexing.py index 5cfacaf16cffe..ea5e939b57566 100644 --- a/pandas/tests/sparse/test_indexing.py +++ b/pandas/tests/sparse/test_indexing.py @@ -441,7 +441,7 @@ def tests_indexing_with_sparse(self, kind, fill): tm.assert_sp_series_equal(s[indexer], expected) tm.assert_sp_series_equal(s.loc[indexer], expected) - msg = "iLocation based boolean indexing cannot " "use an indexable as a mask" + msg = "iLocation based boolean indexing cannot use an indexable as a mask" with pytest.raises(ValueError, match=msg): s.iloc[indexer] diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index a76f2bb04a542..c97c69c323b56 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1819,9 +1819,8 @@ def test_reset_index_multiindex_columns(self): tm.assert_frame_equal(result, df) # gh-16120: already existing column - with pytest.raises( - ValueError, match=(r"cannot insert \('A', ''\), " "already exists") - ): + msg = r"cannot insert \('A', ''\), already exists" + with pytest.raises(ValueError, match=msg): df.rename_axis("A").reset_index() # gh-16164: multiindex (tuple) full key @@ -1837,9 +1836,8 @@ def test_reset_index_multiindex_columns(self): tm.assert_frame_equal(result, expected) # with index name which is a too long tuple... - with pytest.raises( - ValueError, match=("Item must have length equal " "to number of levels.") - ): + msg = "Item must have length equal to number of levels." + with pytest.raises(ValueError, match=msg): df.rename_axis([("C", "c", "i")]).reset_index() # or too short... diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 6833757c69eaa..950d6a9595f9e 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -196,10 +196,8 @@ def test_api(self): def test_api_mi_raises(self): # GH 23679 mi = MultiIndex.from_arrays([["a", "b", "c"]]) - with pytest.raises( - AttributeError, - match="Can only use .str accessor " "with Index, not MultiIndex", - ): + msg = "Can only use .str accessor with Index, not MultiIndex" + with pytest.raises(AttributeError, match=msg): mi.str assert not hasattr(mi, "str") @@ -232,10 +230,8 @@ def test_api_per_dtype(self, box, dtype, any_skipna_inferred_dtype): assert isinstance(t.str, strings.StringMethods) else: # GH 9184, GH 23011, GH 23163 - with pytest.raises( - AttributeError, - match="Can only use .str " "accessor with string values.*", - ): + msg = "Can only use .str accessor with string values.*" + with pytest.raises(AttributeError, match=msg): t.str assert not hasattr(t, "str") @@ -1101,7 +1097,7 @@ def test_replace_literal(self): with pytest.raises(ValueError, match=msg): values.str.replace("abc", callable_repl, regex=False) - msg = "Cannot use a compiled regex as replacement pattern with" " regex=False" + msg = "Cannot use a compiled regex as replacement pattern with regex=False" with pytest.raises(ValueError, match=msg): values.str.replace(compiled_pat, "", regex=False) diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 27700d778df19..2df5460a05953 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -844,7 +844,7 @@ def test_numpy_compat(self, method): pytest.param( "ls", marks=pytest.mark.xfail( - reason="GH#16425 expanding with " "offset not supported" + reason="GH#16425 expanding with offset not supported" ), ), ], @@ -1775,9 +1775,8 @@ def test_invalid_quantile_value(self): data = np.arange(5) s = Series(data) - with pytest.raises( - ValueError, match="Interpolation 'invalid'" " is not supported" - ): + msg = "Interpolation 'invalid' is not supported" + with pytest.raises(ValueError, match=msg): s.rolling(len(data), min_periods=1).quantile(0.5, interpolation="invalid") def test_rolling_quantile_param(self): diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 822e97b21f0da..2654d83ee0c52 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -843,7 +843,7 @@ def test_apply_large_n(self): assert rs == xp def test_apply_corner(self): - msg = "Only know how to combine business day with datetime or" " timedelta" + msg = "Only know how to combine business day with datetime or timedelta" with pytest.raises(ApplyTypeError, match=msg): BDay().apply(BMonthEnd()) diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py index 700fee2d89f3c..126a1bd12ad59 100644 --- a/pandas/tests/tslibs/test_parsing.py +++ b/pandas/tests/tslibs/test_parsing.py @@ -38,11 +38,9 @@ def test_parse_time_quarter_with_dash(dashed, normal): @pytest.mark.parametrize("dashed", ["-2Q1992", "2-Q1992", "4-4Q1992"]) def test_parse_time_quarter_with_dash_error(dashed): - msg = "Unknown datetime string format, " "unable to parse: {dashed}".format( - dashed=dashed - ) + msg = "Unknown datetime string format, unable to parse: {dashed}" - with pytest.raises(parsing.DateParseError, match=msg): + with pytest.raises(parsing.DateParseError, match=msg.format(dashed=dashed)): parse_time_string(dashed) @@ -113,14 +111,12 @@ def test_parsers_quarter_invalid(date_str): if date_str == "6Q-20": msg = ( "Incorrect quarterly string is given, quarter " - "must be between 1 and 4: {date_str}".format(date_str=date_str) + "must be between 1 and 4: {date_str}" ) else: - msg = "Unknown datetime string format, unable " "to parse: {date_str}".format( - date_str=date_str - ) + msg = "Unknown datetime string format, unable to parse: {date_str}" - with pytest.raises(ValueError, match=msg): + with pytest.raises(ValueError, match=msg.format(date_str=date_str)): parsing.parse_time_string(date_str) diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py index 1583420053fde..5a677d629e72d 100644 --- a/pandas/tests/util/test_assert_almost_equal.py +++ b/pandas/tests/util/test_assert_almost_equal.py @@ -40,7 +40,7 @@ def _assert_not_almost_equal(a, b, **kwargs): try: assert_almost_equal(a, b, **kwargs) msg = ( - "{a} and {b} were approximately equal " "when they shouldn't have been" + "{a} and {b} were approximately equal when they shouldn't have been" ).format(a=a, b=b) pytest.fail(msg=msg) except AssertionError: diff --git a/pandas/tests/util/test_deprecate.py b/pandas/tests/util/test_deprecate.py index e7b38bb2b700a..8fbc8037ed7c5 100644 --- a/pandas/tests/util/test_deprecate.py +++ b/pandas/tests/util/test_deprecate.py @@ -57,9 +57,8 @@ def test_deprecate_no_docstring(): def test_deprecate_wrong_docstring(): - with pytest.raises( - AssertionError, match="deprecate needs a correctly " "formatted docstring" - ): + msg = "deprecate needs a correctly formatted docstring" + with pytest.raises(AssertionError, match=msg): deprecate( "depr_func", new_func_wrong_docstring, "1.0", msg="Use new_func instead." )