Skip to content
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

STY: use pytest.raises context manager (arithmetic, arrays, computati… #25504

Merged
merged 2 commits into from
Mar 3, 2019
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
66 changes: 49 additions & 17 deletions pandas/tests/arithmetic/test_timedelta64.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,10 +205,20 @@ def test_subtraction_ops(self):
td = Timedelta('1 days')
dt = Timestamp('20130101')

pytest.raises(TypeError, lambda: tdi - dt)
pytest.raises(TypeError, lambda: tdi - dti)
pytest.raises(TypeError, lambda: td - dt)
pytest.raises(TypeError, lambda: td - dti)
msg = "cannot subtract a datelike from a TimedeltaArray"
with pytest.raises(TypeError, match=msg):
tdi - dt
with pytest.raises(TypeError, match=msg):
tdi - dti

msg = (r"descriptor '__sub__' requires a 'datetime\.datetime' object"
" but received a 'Timedelta'")
with pytest.raises(TypeError, match=msg):
td - dt

msg = "bad operand type for unary -: 'DatetimeArray'"
with pytest.raises(TypeError, match=msg):
td - dti

result = dt - dti
expected = TimedeltaIndex(['0 days', '-1 days', '-2 days'], name='bar')
Expand Down Expand Up @@ -265,19 +275,38 @@ def _check(result, expected):
_check(result, expected)

# tz mismatches
pytest.raises(TypeError, lambda: dt_tz - ts)
pytest.raises(TypeError, lambda: dt_tz - dt)
pytest.raises(TypeError, lambda: dt_tz - ts_tz2)
pytest.raises(TypeError, lambda: dt - dt_tz)
pytest.raises(TypeError, lambda: ts - dt_tz)
pytest.raises(TypeError, lambda: ts_tz2 - ts)
pytest.raises(TypeError, lambda: ts_tz2 - dt)
pytest.raises(TypeError, lambda: ts_tz - ts_tz2)
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")
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")
with pytest.raises(TypeError, match=msg):
ts - dt_tz
with pytest.raises(TypeError, match=msg):
ts_tz2 - ts
with pytest.raises(TypeError, match=msg):
ts_tz2 - dt
with pytest.raises(TypeError, match=msg):
ts_tz - ts_tz2

# with dti
pytest.raises(TypeError, lambda: dti - ts_tz)
pytest.raises(TypeError, lambda: dti_tz - ts)
pytest.raises(TypeError, lambda: dti_tz - ts_tz2)
with pytest.raises(TypeError, match=msg):
dti - ts_tz
with pytest.raises(TypeError, match=msg):
dti_tz - ts
with pytest.raises(TypeError, match=msg):
dti_tz - ts_tz2

result = dti_tz - dt_tz
expected = TimedeltaIndex(['0 days', '1 days', '2 days'])
Expand Down Expand Up @@ -349,8 +378,11 @@ def test_addition_ops(self):
tm.assert_index_equal(result, expected)

# unequal length
pytest.raises(ValueError, lambda: tdi + dti[0:1])
pytest.raises(ValueError, lambda: tdi[0:1] + dti)
msg = "cannot add indices of unequal length"
with pytest.raises(ValueError, match=msg):
tdi + dti[0:1]
with pytest.raises(ValueError, match=msg):
tdi[0:1] + dti

# random indexes
with pytest.raises(NullFrequencyError):
Expand Down
29 changes: 19 additions & 10 deletions pandas/tests/arrays/categorical/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ def test_min_max(self):

# unordered cats have no min/max
cat = Categorical(["a", "b", "c", "d"], ordered=False)
pytest.raises(TypeError, lambda: cat.min())
pytest.raises(TypeError, lambda: cat.max())
msg = "Categorical is not ordered for operation {}"
with pytest.raises(TypeError, match=msg.format('min')):
cat.min()
with pytest.raises(TypeError, match=msg.format('max')):
cat.max()

cat = Categorical(["a", "b", "c", "d"], ordered=True)
_min = cat.min()
Expand Down Expand Up @@ -108,18 +111,24 @@ def test_searchsorted(self):
tm.assert_numpy_array_equal(res_ser, exp)

# Searching for a single value that is not from the Categorical
pytest.raises(KeyError, lambda: c1.searchsorted('cucumber'))
pytest.raises(KeyError, lambda: s1.searchsorted('cucumber'))
msg = r"Value\(s\) to be inserted must be in categories"
with pytest.raises(KeyError, match=msg):
c1.searchsorted('cucumber')
with pytest.raises(KeyError, match=msg):
s1.searchsorted('cucumber')

# Searching for multiple values one of each is not from the Categorical
pytest.raises(KeyError,
lambda: c1.searchsorted(['bread', 'cucumber']))
pytest.raises(KeyError,
lambda: s1.searchsorted(['bread', 'cucumber']))
with pytest.raises(KeyError, match=msg):
c1.searchsorted(['bread', 'cucumber'])
with pytest.raises(KeyError, match=msg):
s1.searchsorted(['bread', 'cucumber'])

# searchsorted call for unordered Categorical
pytest.raises(ValueError, lambda: c2.searchsorted('apple'))
pytest.raises(ValueError, lambda: s2.searchsorted('apple'))
msg = "Categorical not ordered"
with pytest.raises(ValueError, match=msg):
c2.searchsorted('apple')
with pytest.raises(ValueError, match=msg):
s2.searchsorted('apple')

def test_unique(self):
# categories are reordered based on value when ordered=False
Expand Down
88 changes: 63 additions & 25 deletions pandas/tests/arrays/categorical/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import numpy as np
import pytest

from pandas.compat import PY2

import pandas as pd
from pandas import Categorical, DataFrame, Series, date_range
from pandas.tests.arrays.categorical.common import TestCategorical
Expand All @@ -17,6 +19,7 @@ def test_categories_none_comparisons(self):
'a', 'c', 'c', 'c'], ordered=True)
tm.assert_categorical_equal(factor, self.factor)

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_comparisons(self):

result = self.factor[self.factor == 'a']
Expand Down Expand Up @@ -95,16 +98,24 @@ def test_comparisons(self):

# comparison (in both directions) with Series will raise
s = Series(["b", "b", "b"])
pytest.raises(TypeError, lambda: cat > s)
pytest.raises(TypeError, lambda: cat_rev > s)
pytest.raises(TypeError, lambda: s < cat)
pytest.raises(TypeError, lambda: s < cat_rev)
msg = ("Cannot compare a Categorical for op __gt__ with type"
r" <class 'numpy\.ndarray'>")
with pytest.raises(TypeError, match=msg):
cat > s
with pytest.raises(TypeError, match=msg):
cat_rev > s
with pytest.raises(TypeError, match=msg):
s < cat
with pytest.raises(TypeError, match=msg):
s < cat_rev

# comparison with numpy.array will raise in both direction, but only on
# newer numpy versions
a = np.array(["b", "b", "b"])
pytest.raises(TypeError, lambda: cat > a)
pytest.raises(TypeError, lambda: cat_rev > a)
with pytest.raises(TypeError, match=msg):
cat > a
with pytest.raises(TypeError, match=msg):
cat_rev > a

# Make sure that unequal comparison take the categories order in
# account
Expand Down Expand Up @@ -163,16 +174,23 @@ def test_comparison_with_unknown_scalars(self):
# for unequal comps, but not for equal/not equal
cat = Categorical([1, 2, 3], ordered=True)

pytest.raises(TypeError, lambda: cat < 4)
pytest.raises(TypeError, lambda: cat > 4)
pytest.raises(TypeError, lambda: 4 < cat)
pytest.raises(TypeError, lambda: 4 > cat)
msg = ("Cannot compare a Categorical for op __{}__ with a scalar,"
" which is not a category")
with pytest.raises(TypeError, match=msg.format('lt')):
cat < 4
with pytest.raises(TypeError, match=msg.format('gt')):
cat > 4
with pytest.raises(TypeError, match=msg.format('gt')):
4 < cat
with pytest.raises(TypeError, match=msg.format('lt')):
4 > cat

tm.assert_numpy_array_equal(cat == 4,
np.array([False, False, False]))
tm.assert_numpy_array_equal(cat != 4,
np.array([True, True, True]))

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
@pytest.mark.parametrize('data,reverse,base', [
(list("abc"), list("cba"), list("bbb")),
([1, 2, 3], [3, 2, 1], [2, 2, 2])]
Expand Down Expand Up @@ -219,16 +237,26 @@ def test_comparisons(self, data, reverse, base):

# categorical cannot be compared to Series or numpy array, and also
# not the other way around
pytest.raises(TypeError, lambda: cat > s)
pytest.raises(TypeError, lambda: cat_rev > s)
pytest.raises(TypeError, lambda: cat > a)
pytest.raises(TypeError, lambda: cat_rev > a)
msg = ("Cannot compare a Categorical for op __gt__ with type"
r" <class 'numpy\.ndarray'>")
with pytest.raises(TypeError, match=msg):
cat > s
with pytest.raises(TypeError, match=msg):
cat_rev > s
with pytest.raises(TypeError, match=msg):
cat > a
with pytest.raises(TypeError, match=msg):
cat_rev > a

pytest.raises(TypeError, lambda: s < cat)
pytest.raises(TypeError, lambda: s < cat_rev)
with pytest.raises(TypeError, match=msg):
s < cat
with pytest.raises(TypeError, match=msg):
s < cat_rev

pytest.raises(TypeError, lambda: a < cat)
pytest.raises(TypeError, lambda: a < cat_rev)
with pytest.raises(TypeError, match=msg):
a < cat
with pytest.raises(TypeError, match=msg):
a < cat_rev

@pytest.mark.parametrize('ctor', [
lambda *args, **kwargs: Categorical(*args, **kwargs),
Expand Down Expand Up @@ -287,16 +315,21 @@ def test_numeric_like_ops(self):
right=False, labels=cat_labels)

# numeric ops should not succeed
for op in ['__add__', '__sub__', '__mul__', '__truediv__']:
pytest.raises(TypeError,
lambda: getattr(df, op)(df))
for op, str_rep in [('__add__', r'\+'),
('__sub__', '-'),
('__mul__', r'\*'),
('__truediv__', '/')]:
msg = r"Series cannot perform the operation {}".format(str_rep)
with pytest.raises(TypeError, match=msg):
getattr(df, op)(df)
Copy link
Member

Choose a reason for hiding this comment

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

Looks parametrizable but can always do in follow-up


# reduction ops should not succeed (unless specifically defined, e.g.
# min/max)
s = df['value_group']
for op in ['kurt', 'skew', 'var', 'std', 'mean', 'sum', 'median']:
pytest.raises(TypeError,
lambda: getattr(s, op)(numeric_only=False))
msg = "Categorical cannot perform the operation {}".format(op)
with pytest.raises(TypeError, match=msg):
getattr(s, op)(numeric_only=False)

# mad technically works because it takes always the numeric data

Expand All @@ -306,8 +339,13 @@ def test_numeric_like_ops(self):
np.sum(s)

# numeric ops on a Series
for op in ['__add__', '__sub__', '__mul__', '__truediv__']:
pytest.raises(TypeError, lambda: getattr(s, op)(2))
for op, str_rep in [('__add__', r'\+'),
('__sub__', '-'),
('__mul__', r'\*'),
('__truediv__', '/')]:
msg = r"Series cannot perform the operation {}".format(str_rep)
with pytest.raises(TypeError, match=msg):
getattr(s, op)(2)

# invalid ufunc
with pytest.raises(TypeError):
Expand Down
10 changes: 6 additions & 4 deletions pandas/tests/arrays/sparse/test_libsparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,11 +449,13 @@ def test_check_integrity(self):
# also OK even though empty
index = BlockIndex(1, locs, lengths) # noqa

# block extend beyond end
pytest.raises(Exception, BlockIndex, 10, [5], [10])
msg = "Block 0 extends beyond end"
with pytest.raises(ValueError, match=msg):
BlockIndex(10, [5], [10])

# block overlap
pytest.raises(Exception, BlockIndex, 10, [2, 5], [5, 3])
msg = "Block 0 overlaps"
with pytest.raises(ValueError, match=msg):
BlockIndex(10, [2, 5], [5, 3])

def test_to_int_index(self):
locs = [0, 10]
Expand Down
Loading