Skip to content

TST: Avoid bare pytest.raises in multiple files #32816

New issue

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

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

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
1786b2d
Adding message check to pytest.raises for test_dtypes.py
Mar 11, 2020
98110e5
Merge branch 'master' of https://github.com/pandas-dev/pandas
Mar 11, 2020
bf777e8
Readding message check to pytest.raises for test_dtypes.py
Mar 11, 2020
dce255e
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 13, 2020
912b03d
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 18, 2020
20094d9
Fixed bare pytest raises in test_indexing.py.
Mar 18, 2020
617f03c
Fixed bare pytest raises in test_replace.py
Mar 18, 2020
1991131
Fixed bare pytest raises in test_apply.py
Mar 18, 2020
f88064f
Fixed bare pytest raises in test_arithmetic.py
Mar 18, 2020
74476ae
Fixed bare pytest raises in test_axis_select_reindex.py
Mar 18, 2020
fa46b4a
Fixed bare pytest raises in test_axis_select_reindex.py
Mar 18, 2020
cf714b0
Fixed bare pytest raises in test_constructors.py
Mar 18, 2020
ec2223e
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 18, 2020
9443bce
Fixed bare pytest raises in test_dtypes.py.py
Mar 18, 2020
5a06dd1
Fixed bare pytest raises in test_operators.py
Mar 19, 2020
058404b
Fixed bare pytest raises in test_reshape.py
Mar 19, 2020
9db72da
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 19, 2020
2faa42a
Blacked the files before creating pull request
Mar 19, 2020
44185dd
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 19, 2020
f0d6e58
Revert "Fixed bare pytest raises in test_indexing.py."
Mar 19, 2020
5546949
Fixed the issues with Black that were brought up by the linter test.
Mar 19, 2020
e9645fe
Update pandas/tests/frame/test_operators.py
Vlek Mar 19, 2020
d90454a
Made error messages more human readable based on feedback received on…
Mar 20, 2020
d0e1df6
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 20, 2020
d6db6d3
Merge remote-tracking branch 'origin/30999_disallow_bare_pytest_raise…
Mar 20, 2020
4830092
Fixed the assertions in other tests that relied on the previous wordi…
Mar 20, 2020
531ae1c
Removed error message check for test_categorical_replace_with_dict in
Mar 21, 2020
241a025
Merge branch 'master' of https://github.com/pandas-dev/pandas into 30…
Mar 21, 2020
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
3 changes: 2 additions & 1 deletion pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1308,7 +1308,8 @@ def test_categorical_replace_with_dict(self, replace_dict, final_data):
expected["b"] = expected["b"].cat.set_categories([1, 2, 3])
result = df.replace(replace_dict, 3)
tm.assert_frame_equal(result, expected)
with pytest.raises(AssertionError):
msg = 'Attributes of DataFrame.iloc[:, 0] (column name="a") are different'
with pytest.raises(AssertionError, match=re.escape(msg)):
# ensure non-inplace call does not affect original
tm.assert_frame_equal(df, expected)
df.replace(replace_dict, 3, inplace=True)
Expand Down
28 changes: 19 additions & 9 deletions pandas/tests/frame/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def test_apply(self, float_frame):

# invalid axis
df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"])
with pytest.raises(ValueError):
msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>"
with pytest.raises(ValueError, match=msg):
df.apply(lambda x: x, 2)

# GH 9573
Expand Down Expand Up @@ -221,18 +222,20 @@ def test_apply_broadcast_error(self, int_frame_const_col):
df = int_frame_const_col

# > 1 ndim
with pytest.raises(ValueError):
msg = "too many dims to broadcast"
with pytest.raises(ValueError, match=msg):
df.apply(
lambda x: np.array([1, 2]).reshape(-1, 2),
axis=1,
result_type="broadcast",
)

# cannot broadcast
with pytest.raises(ValueError):
msg = "cannot broadcast result"
with pytest.raises(ValueError, match=msg):
df.apply(lambda x: [1, 2], axis=1, result_type="broadcast")

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.apply(lambda x: Series([1, 2]), axis=1, result_type="broadcast")

def test_apply_raw(self, float_frame, mixed_type_frame):
Expand Down Expand Up @@ -950,7 +953,11 @@ def test_result_type_error(self, result_type, int_frame_const_col):
# allowed result_type
df = int_frame_const_col

with pytest.raises(ValueError):
msg = (
"invalid value for result_type, must be one of "
"{None, 'reduce', 'broadcast', 'expand'}"
)
with pytest.raises(ValueError, match=msg):
df.apply(lambda x: [1, 2, 3], axis=1, result_type=result_type)

@pytest.mark.parametrize(
Expand Down Expand Up @@ -1046,14 +1053,16 @@ def test_agg_transform(self, axis, float_frame):

def test_transform_and_agg_err(self, axis, float_frame):
# cannot both transform and agg
with pytest.raises(ValueError):
msg = "transforms cannot produce aggregated results"
with pytest.raises(ValueError, match=msg):
float_frame.transform(["max", "min"], axis=axis)

with pytest.raises(ValueError):
msg = "cannot combine transform and aggregation operations"
with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
float_frame.agg(["max", "sqrt"], axis=axis)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
float_frame.transform(["max", "sqrt"], axis=axis)

Expand Down Expand Up @@ -1387,7 +1396,8 @@ def test_agg_cython_table_transform(self, df, func, expected, axis):
)
def test_agg_cython_table_raises(self, df, func, expected, axis):
# GH 21224
with pytest.raises(expected):
msg = "can't multiply sequence by non-int of type 'str'"
with pytest.raises(expected, match=msg):
df.agg(func, axis=axis)

@pytest.mark.parametrize("num_cols", [2, 3, 5])
Expand Down
20 changes: 14 additions & 6 deletions pandas/tests/frame/test_arithmetic.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from collections import deque
from datetime import datetime
import operator
import re

import numpy as np
import pytest
Expand Down Expand Up @@ -46,13 +47,16 @@ def check(df, df2):
)
tm.assert_frame_equal(result, expected)

with pytest.raises(TypeError):
msg = re.escape(
"Invalid comparison between dtype=datetime64[ns] and ndarray"
)
with pytest.raises(TypeError, match=msg):
x >= y
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
x > y
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
x < y
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
x <= y

# GH4968
Expand Down Expand Up @@ -98,9 +102,13 @@ def test_timestamp_compare(self):
result = right_f(pd.Timestamp("20010109"), df)
tm.assert_frame_equal(result, expected)
else:
with pytest.raises(TypeError):
msg = (
"'(<|>)=?' not supported between "
"instances of 'Timestamp' and 'float'"
)
with pytest.raises(TypeError, match=msg):
left_f(df, pd.Timestamp("20010109"))
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
right_f(pd.Timestamp("20010109"), df)
# nats
expected = left_f(df, pd.Timestamp("nat"))
Expand Down
11 changes: 7 additions & 4 deletions pandas/tests/frame/test_axis_select_reindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,15 @@ def test_drop_api_equivalence(self):
res2 = df.drop(index=["a"], columns=["d"])
tm.assert_frame_equal(res1, res2)

with pytest.raises(ValueError):
msg = "Cannot specify both 'labels' and 'index'/'columns'"
with pytest.raises(ValueError, match=msg):
df.drop(labels="a", index="b")

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.drop(labels="a", columns="b")

with pytest.raises(ValueError):
msg = "Need to specify at least one of 'labels', 'index' or 'columns'"
with pytest.raises(ValueError, match=msg):
df.drop(axis=1)

def test_merge_join_different_levels(self):
Expand Down Expand Up @@ -616,7 +618,8 @@ def test_align_float(self, float_frame):
tm.assert_index_equal(bf.index, Index([]))

# Try to align DataFrame to Series along bad axis
with pytest.raises(ValueError):
msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>"
with pytest.raises(ValueError, match=msg):
float_frame.align(af.iloc[0, :3], join="inner", axis=2)

# align dataframe to series with broadcast or not
Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from datetime import date, datetime, timedelta
import functools
import itertools
import re

import numpy as np
import numpy.ma as ma
Expand Down Expand Up @@ -1401,7 +1402,8 @@ def test_constructor_list_of_dataclasses_error_thrown(self):
Point = make_dataclass("Point", [("x", int), ("y", int)])

# expect TypeError
with pytest.raises(TypeError):
msg = "asdict() should be called on dataclass instances"
with pytest.raises(TypeError, match=re.escape(msg)):
DataFrame([Point(0, 0), {"x": 1, "y": 0}])

def test_constructor_list_of_dict_order(self):
Expand Down
7 changes: 6 additions & 1 deletion pandas/tests/frame/test_dtypes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import OrderedDict
from datetime import timedelta
import re

import numpy as np
import pytest
Expand Down Expand Up @@ -636,7 +637,11 @@ def test_arg_for_errors_in_astype(self):

df = DataFrame([1, 2, 3])

with pytest.raises(ValueError):
msg = (
"Expected value of kwarg 'errors' to be one of "
"['raise', 'ignore']. Supplied value is 'True'"
)
with pytest.raises(ValueError, match=re.escape(msg)):
df.astype(np.float64, errors=True)

df.astype(np.int8, errors="ignore")
Expand Down
31 changes: 22 additions & 9 deletions pandas/tests/frame/test_operators.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from decimal import Decimal
import operator
import re

import numpy as np
import pytest
Expand Down Expand Up @@ -51,9 +52,14 @@ def test_neg_object(self, df, expected):
],
)
def test_neg_raises(self, df):
with pytest.raises(TypeError):
msg = (
"bad operand type for unary -: 'str'|"
+ "Unary negative expects numeric "
+ re.escape("dtype, not datetime64[ns]")
)
with pytest.raises(TypeError, match=msg):
(-df)
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
(-df["a"])

def test_invert(self, float_frame):
Expand Down Expand Up @@ -116,9 +122,10 @@ def test_pos_object(self, df):
"df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})]
)
def test_pos_raises(self, df):
with pytest.raises(TypeError):
msg = re.escape("Unary plus expects numeric dtype, not datetime64[ns]")
with pytest.raises(TypeError, match=msg):
(+df)
with pytest.raises(TypeError):
with pytest.raises(TypeError, match=msg):
(+df["a"])


Expand Down Expand Up @@ -173,12 +180,14 @@ def test_logical_ops_invalid(self):

df1 = DataFrame(1.0, index=[1], columns=["A"])
df2 = DataFrame(True, index=[1], columns=["A"])
with pytest.raises(TypeError):
msg = re.escape("unsupported operand type(s) for |: 'float' and 'bool'")
with pytest.raises(TypeError, match=msg):
df1 | df2

df1 = DataFrame("foo", index=[1], columns=["A"])
df2 = DataFrame(True, index=[1], columns=["A"])
with pytest.raises(TypeError):
msg = re.escape("unsupported operand type(s) for |: 'str' and 'bool'")
with pytest.raises(TypeError, match=msg):
df1 | df2

def test_logical_operators(self):
Expand Down Expand Up @@ -594,7 +603,8 @@ def test_strings_to_numbers_comparisons_raises(self, compare_operators_no_eq_ne)
)

f = getattr(operator, compare_operators_no_eq_ne)
with pytest.raises(TypeError):
msg = "'[<>]=?' not supported between instances of 'str' and 'int'"
with pytest.raises(TypeError, match=msg):
f(df, 0)

def test_comparison_protected_from_errstate(self):
Expand Down Expand Up @@ -881,9 +891,12 @@ def test_alignment_non_pandas(self):
align(df, val, "columns")

val = np.zeros((3, 3, 3))
with pytest.raises(ValueError):
msg = re.escape(
"Unable to coerce to Series/DataFrame, dim must be <= 2: (3, 3, 3)"
)
with pytest.raises(ValueError, match=msg):
align(df, val, "index")
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
align(df, val, "columns")

def test_no_warning(self, all_arithmetic_operators):
Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/frame/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,10 +695,11 @@ def test_unstack_dtypes(self):
def test_unstack_non_unique_index_names(self):
idx = MultiIndex.from_tuples([("a", "b"), ("c", "d")], names=["c1", "c1"])
df = DataFrame([1, 2], index=idx)
with pytest.raises(ValueError):
msg = "The name c1 occurs multiple times, use a level number"
with pytest.raises(ValueError, match=msg):
df.unstack("c1")

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
df.T.stack("c1")

def test_unstack_unused_levels(self):
Expand Down