Skip to content

add match message for pytest.raises() #33144

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 6 commits into from
Apr 19, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion pandas/tests/groupby/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,8 @@ def test_bins_unequal_len():
bins = pd.cut(series.dropna().values, 4)

# len(bins) != len(series) here
with pytest.raises(ValueError):
msg = r"Length of grouper \(8\) and axis \(10\) must be same length"
with pytest.raises(ValueError, match=msg):
series.groupby(bins).mean()


Expand Down
32 changes: 23 additions & 9 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ def test_take(self, indices):

if not isinstance(indices, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
# GH 10791
with pytest.raises(AttributeError):
msg = r"'(.*Index)' object has no attribute 'freq'"
with pytest.raises(AttributeError, match=msg):
indices.freq

def test_take_invalid_kwargs(self):
Expand Down Expand Up @@ -537,9 +538,10 @@ def test_delete_base(self, indices):
assert result.equals(expected)
assert result.name == expected.name

with pytest.raises((IndexError, ValueError)):
# either depending on numpy version
indices.delete(len(indices))
length = len(indices)
msg = f"index {length} is out of bounds for axis 0 with size {length}"
with pytest.raises(IndexError, match=msg):
indices.delete(length)
Copy link
Member

Choose a reason for hiding this comment

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

are we testing the missing-argument case somewhere else?

i think the "either depending..." comment is obsolete


def test_equals(self, indices):
if isinstance(indices, IntervalIndex):
Expand Down Expand Up @@ -787,13 +789,14 @@ def test_putmask_with_wrong_mask(self):
# GH18368
index = self.create_index()

with pytest.raises(ValueError):
msg = "putmask: mask and data must be the same size"
with pytest.raises(ValueError, match=msg):
index.putmask(np.ones(len(index) + 1, np.bool), 1)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
index.putmask(np.ones(len(index) - 1, np.bool), 1)

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
index.putmask("foo", 1)

@pytest.mark.parametrize("copy", [True, False])
Expand Down Expand Up @@ -861,10 +864,21 @@ def test_getitem_2d_deprecated(self):

def test_contains_requires_hashable_raises(self):
idx = self.create_index()
with pytest.raises(TypeError, match="unhashable type"):

msg = "unhashable type: 'list'"
with pytest.raises(TypeError, match=msg):
[] in idx

with pytest.raises(TypeError):
msg = "|".join(
[
r"unhashable type: 'dict'",
r"must be real number, not dict",
r"an integer is required",
r"\{\}",
r"pandas\._libs\.interval\.IntervalTree' is not iterable",
]
)
with pytest.raises(TypeError, match=msg):
{} in idx._engine

def test_copy_copies_cache(self):
Expand Down
9 changes: 5 additions & 4 deletions pandas/tests/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
class DatetimeLike(Base):
def test_argmax_axis_invalid(self):
# GH#23081
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
rng = self.create_index()
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
rng.argmax(axis=1)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
rng.argmin(axis=2)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
rng.min(axis=-2)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
rng.max(axis=-3)

def test_can_hold_identifiers(self):
Expand Down
6 changes: 5 additions & 1 deletion pandas/tests/indexes/multi/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,11 @@ def test_boolean_context_compat2():
i2 = MultiIndex.from_tuples([("A", 1), ("A", 3)])
common = i1.intersection(i2)

with pytest.raises(ValueError):
msg = (
r"The truth value of a MultiIndex is ambiguous\. "
r"Use a\.empty, a\.bool\(\), a\.item\(\), a\.any\(\) or a\.all\(\)\."
)
with pytest.raises(ValueError, match=msg):
bool(common)


Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexes/multi/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,6 @@ def test_delete_base(idx):
assert result.equals(expected)
assert result.name == expected.name

with pytest.raises((IndexError, ValueError)):
# Exception raised depends on NumPy version.
msg = "index 6 is out of bounds for axis 0 with size 6"
with pytest.raises(IndexError, match=msg):
idx.delete(len(idx))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Member

Choose a reason for hiding this comment

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

@sathyz Thank you for looking into this!

9 changes: 7 additions & 2 deletions pandas/tests/indexes/multi/test_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,11 @@ def test_unsortedindex():
expected = df.iloc[0]
tm.assert_series_equal(result, expected)

with pytest.raises(UnsortedIndexError):
msg = (
"MultiIndex slicing requires the index to be lexsorted: "
r"slicing on levels \[1\], lexsort depth 0"
)
with pytest.raises(UnsortedIndexError, match=msg):
df.loc(axis=0)["z", slice("a")]
df.sort_index(inplace=True)
assert len(df.loc(axis=0)["z", :]) == 2
Expand All @@ -124,7 +128,8 @@ def test_unsortedindex_doc_examples():
with tm.assert_produces_warning(PerformanceWarning):
dfm.loc[(1, "z")]

with pytest.raises(UnsortedIndexError):
msg = r"Key length \(2\) was greater than MultiIndex lexsort depth \(1\)"
with pytest.raises(UnsortedIndexError, match=msg):
dfm.loc[(0, "y"):(1, "z")]

assert not dfm.index.is_lexsorted()
Expand Down