Skip to content

Disallow bare pytest.raises #31029

New issue

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

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

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions pandas/tests/io/test_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,14 +276,14 @@ def test_file_like(self):

@tm.network
def test_bad_url_protocol(self):
with pytest.raises(URLError):
with pytest.raises(URLError, match=msg):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where is msg defined?

self.read_html("git://github.com", match=".*Water.*")

@tm.network
@pytest.mark.slow
def test_invalid_url(self):
try:
with pytest.raises(URLError):
with pytest.raises(URLError, match=msg):
self.read_html("http://www.a23950sdfa908sd.com", match=".*Water.*")
except ValueError as e:
assert "No tables found" in str(e)
Expand Down Expand Up @@ -964,7 +964,7 @@ def test_decimal_rows(self):
def test_bool_header_arg(self):
# GH 6114
for arg in [True, False]:
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
self.read_html(self.spam_data, header=arg)

def test_converters(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/io/test_parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def compare(repeat):


def test_invalid_engine(df_compat):
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
check_round_trip(df_compat, "foo", "bar")


Expand Down Expand Up @@ -667,7 +667,7 @@ def test_error_on_using_partition_cols_and_partition_on(self, fp, df_full):
# GH #23283
partition_cols = ["bool", "int"]
df = df_full
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
with tm.ensure_clean_dir() as path:
df.to_parquet(
path,
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/io/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -2417,7 +2417,7 @@ def test_execute_fail(self):
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)', self.conn)

with pytest.raises(Exception):
with pytest.raises(Exception, match=msg):
sql.execute('INSERT INTO test VALUES("foo", "bar", 7)', self.conn)

def test_execute_closed_connection(self):
Expand All @@ -2436,7 +2436,7 @@ def test_execute_closed_connection(self):
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
self.conn.close()

with pytest.raises(Exception):
with pytest.raises(Exception, match=msg):
tquery("select * from test", con=self.conn)

def test_na_roundtrip(self):
Expand Down Expand Up @@ -2700,7 +2700,7 @@ def test_execute_fail(self):
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)', self.conn)

with pytest.raises(Exception):
with pytest.raises(Exception, match=msg):
sql.execute('INSERT INTO test VALUES("foo", "bar", 7)', self.conn)

def test_execute_closed_connection(self, request, datapath):
Expand All @@ -2721,7 +2721,7 @@ def test_execute_closed_connection(self, request, datapath):
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
self.conn.close()

with pytest.raises(Exception):
with pytest.raises(Exception, match=msg):
tquery("select * from test", con=self.conn)

# Initialize connection again (needed for tearDown)
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/test_stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -1374,7 +1374,7 @@ def test_unsupported_datetype(self):
"dates": dates,
}
)
with pytest.raises(NotImplementedError):
with pytest.raises(NotImplementedError, match=msg):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
with pytest.raises(NotImplementedError, match=msg):
with pytest.raises(
NotImplementedError,
match=re.escape("Data type datetime64[ns, Asia/Hong_Kong] not supported."),
):

also re needs to be imported.

with tm.ensure_clean() as path:
original.to_stata(path)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/plotting/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def test_setting_backend_without_plot_raises():

@td.skip_if_mpl
def test_no_matplotlib_ok():
with pytest.raises(ImportError):
with pytest.raises(ImportError, match=msg):
pandas.plotting._core._get_plot_backend("matplotlib")


Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/plotting/test_boxplot_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def test_boxplot_return_type_legacy(self):
index=list(string.ascii_letters[:6]),
columns=["one", "two", "three", "four"],
)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.boxplot(return_type="NOTATYPE")

result = df.boxplot()
Expand Down Expand Up @@ -429,7 +429,7 @@ def test_grouped_box_multiple_axes(self):
tm.assert_numpy_array_equal(returned, axes[1])
assert returned[0].figure is fig

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
fig, axes = self.plt.subplots(2, 3)
# pass different number of axes from required
with tm.assert_produces_warning(UserWarning):
Expand Down
54 changes: 27 additions & 27 deletions pandas/tests/plotting/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def test_rgb_tuple_color(self):

def test_color_empty_string(self):
df = DataFrame(randn(10, 2))
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(color="")

def test_color_and_style_arguments(self):
Expand All @@ -203,7 +203,7 @@ def test_color_and_style_arguments(self):
assert color == ["red", "black"]
# passing both 'color' and 'style' arguments should not be allowed
# if there is a color symbol in the style strings:
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(color=["red", "black"], style=["k-", "r--"])

def test_nonnumeric_exclude(self):
Expand Down Expand Up @@ -628,9 +628,9 @@ def test_subplots_layout(self):
self._check_axes_shape(axes, axes_num=3, layout=(4, 1))
assert axes.shape == (4, 1)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(subplots=True, layout=(1, 1))
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(subplots=True, layout=(-1, -1))

# single column
Expand Down Expand Up @@ -673,7 +673,7 @@ def test_subplots_multiple_axes(self):
self._check_axes_shape(axes, axes_num=6, layout=(2, 3))
tm.close()

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
fig, axes = self.plt.subplots(2, 3)
# pass different number of axes from required
df.plot(subplots=True, ax=axes)
Expand Down Expand Up @@ -784,9 +784,9 @@ def test_negative_log(self):
columns=["x", "y", "z", "four"],
)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot.area(logy=True)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot.area(loglog=True)

def _compare_stacked_y_cood(self, normal_lines, stacked_lines):
Expand Down Expand Up @@ -826,7 +826,7 @@ def test_line_area_stacked(self):
self._compare_stacked_y_cood(ax1.lines[2:], ax2.lines[2:])

_check_plot_works(mixed_df.plot, stacked=False)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
mixed_df.plot(stacked=True)

# Use an index with strictly positive values, preventing
Expand Down Expand Up @@ -1153,9 +1153,9 @@ def test_plot_scatter(self):
_check_plot_works(df.plot.scatter, x="x", y="y")
_check_plot_works(df.plot.scatter, x=1, y=2)

with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
df.plot.scatter(x="x")
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
df.plot.scatter(y="y")

# GH 6951
Expand Down Expand Up @@ -1310,7 +1310,7 @@ def test_plot_scatter_with_c(self):

def test_scatter_colors(self):
df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3]})
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
df.plot.scatter(x="a", y="b", c="c", color="green")

default_colors = self._unpack_cycler(self.plt.rcParams)
Expand Down Expand Up @@ -1580,7 +1580,7 @@ def test_boxplot_return_type(self):
index=list(string.ascii_letters[:6]),
columns=["one", "two", "three", "four"],
)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot.box(return_type="NOTATYPE")

result = df.plot.box(return_type="dict")
Expand Down Expand Up @@ -2036,7 +2036,7 @@ def test_line_colors(self):
self._check_colors(ax.get_lines(), linecolors=custom_colors)
tm.close()

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
# Color contains shorthand hex value results in ValueError
custom_colors = ["#F00", "#00F", "#FF0", "#000", "#FFF"]
# Forced show plot
Expand Down Expand Up @@ -2093,7 +2093,7 @@ def test_line_colors_and_styles_subplots(self):
self._check_colors(ax.get_lines(), linecolors=[c])
tm.close()

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
# Color contains shorthand hex value results in ValueError
custom_colors = ["#F00", "#00F", "#FF0", "#000", "#FFF"]
# Forced show plot
Expand Down Expand Up @@ -2348,7 +2348,7 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None):
bp = df.plot.box(color=(0, 1, 0), sym="#123456", return_type="dict")
_check_colors(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), "#123456")

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
# Color contains invalid key results in ValueError
df.plot.box(color=dict(boxes="red", xxxx="blue"))

Expand Down Expand Up @@ -2413,12 +2413,12 @@ def test_partially_invalid_plot_data(self):
df = DataFrame(rand(10, 2), dtype=object)
df[np.random.rand(df.shape[0]) > 0.5] = "a"
for kind in kinds:
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
df.plot(kind=kind)

def test_invalid_kind(self):
df = DataFrame(randn(10, 2))
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(kind="aasdf")

@pytest.mark.parametrize(
Expand All @@ -2432,14 +2432,14 @@ def test_invalid_kind(self):
def test_invalid_xy_args(self, x, y, lbl):
# GH 18671, 19699 allows y to be list-like but not x
df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(x=x, y=y, label=lbl)

@pytest.mark.parametrize("x,y", [("A", "B"), (["A"], "B")])
def test_invalid_xy_args_dup_cols(self, x, y):
# GH 18671, 19699 allows y to be list-like but not x
df = DataFrame([[1, 3, 5], [2, 4, 6]], columns=list("AAB"))
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(x=x, y=y)

@pytest.mark.parametrize(
Expand Down Expand Up @@ -2518,7 +2518,7 @@ def test_allow_cmap(self):
ax = df.plot.hexbin(x="A", y="B", cmap="YlGn")
assert ax.collections[0].cmap.name == "YlGn"

with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
df.plot.hexbin(x="A", y="B", cmap="YlGn", colormap="BuGn")

@pytest.mark.slow
Expand All @@ -2528,7 +2528,7 @@ def test_pie_df(self):
columns=["X", "Y", "Z"],
index=["a", "b", "c", "d", "e"],
)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot.pie()

ax = _check_plot_works(df.plot.pie, y="Y")
Expand Down Expand Up @@ -2635,11 +2635,11 @@ def test_errorbar_plot(self):
ax = _check_plot_works(s_df.plot, y="y", x="x", yerr=yerr)
self._check_has_errorbars(ax, xerr=0, yerr=1)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(yerr=np.random.randn(11))

df_err = DataFrame({"x": ["zzz"] * 12, "y": ["zzz"] * 12})
with pytest.raises((ValueError, TypeError)):
with pytest.raises((ValueError, TypeError), match=msg):
df.plot(yerr=df_err)

@pytest.mark.xfail(reason="Iterator is consumed", raises=ValueError)
Expand Down Expand Up @@ -2731,7 +2731,7 @@ def test_errorbar_asymmetrical(self):
expected_0_0 = err[0, :, 0] * np.array([-1, 1])
tm.assert_almost_equal(yerr_0_0, expected_0_0)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(yerr=err.T)

tm.close()
Expand Down Expand Up @@ -2923,7 +2923,7 @@ def test_memory_leak(self):
gc.collect()
for key in results:
# check that every plot was collected
with pytest.raises(ReferenceError):
with pytest.raises(ReferenceError, match=msg):
# need to actually access something to get an error
results[key].lines

Expand Down Expand Up @@ -3102,7 +3102,7 @@ def test_df_grid_settings(self):
def test_invalid_colormap(self):
df = DataFrame(randn(3, 2), columns=["A", "B"])

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.plot(colormap="invalid_colormap")

def test_plain_axes(self):
Expand Down Expand Up @@ -3268,7 +3268,7 @@ def test_plot_no_rows(self):

def test_plot_no_numeric_data(self):
df = pd.DataFrame(["a", "b", "c"])
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
df.plot()

def test_missing_markers_legend(self):
Expand Down
Loading