Skip to content

STY: use pytest.raises context syntax (series/indexing/*) #24750

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 5 commits into from
Jan 13, 2019
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 4 additions & 1 deletion pandas/tests/series/indexing/test_alter_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,10 @@ def test_reindex_corner(test_data):

# bad fill method
ts = test_data.ts[::2]
pytest.raises(Exception, ts.reindex, test_data.ts.index, method='foo')
msg = (r"Invalid fill method\. Expecting pad \(ffill\), backfill"
r" \(bfill\) or nearest\. Got foo")
with pytest.raises(ValueError, match=msg):
ts.reindex(test_data.ts.index, method='foo')


def test_reindex_pad():
Expand Down
78 changes: 50 additions & 28 deletions pandas/tests/series/indexing/test_boolean.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@ def test_getitem_boolean_empty():

# invalid because of the boolean indexer
# that's empty or not-aligned
with pytest.raises(IndexingError):
msg = (r"Unalignable boolean Series provided as indexer \(index of"
r" the boolean Series and of the indexed object do not match")
with pytest.raises(IndexingError, match=msg):
s[Series([], dtype=bool)]

with pytest.raises(IndexingError):
with pytest.raises(IndexingError, match=msg):
s[Series([True], dtype=bool)]


Expand All @@ -77,8 +79,11 @@ def test_getitem_boolean_object(test_data):

# nans raise exception
omask[5:10] = np.nan
pytest.raises(Exception, s.__getitem__, omask)
pytest.raises(Exception, s.__setitem__, omask, 5)
msg = "cannot index with vector containing NA / NaN values"
with pytest.raises(ValueError, match=msg):
s[omask]
with pytest.raises(ValueError, match=msg):
s[omask] = 5


def test_getitem_setitem_boolean_corner(test_data):
Expand All @@ -87,15 +92,17 @@ def test_getitem_setitem_boolean_corner(test_data):

# these used to raise...??

pytest.raises(Exception, ts.__getitem__, mask_shifted)
pytest.raises(Exception, ts.__setitem__, mask_shifted, 1)
# ts[mask_shifted]
# ts[mask_shifted] = 1
msg = (r"Unalignable boolean Series provided as indexer \(index of"
r" the boolean Series and of the indexed object do not match")
with pytest.raises(IndexingError, match=msg):
ts[mask_shifted]
with pytest.raises(IndexingError, match=msg):
ts[mask_shifted] = 1

pytest.raises(Exception, ts.loc.__getitem__, mask_shifted)
pytest.raises(Exception, ts.loc.__setitem__, mask_shifted, 1)
# ts.loc[mask_shifted]
# ts.loc[mask_shifted] = 2
with pytest.raises(IndexingError, match=msg):
ts.loc[mask_shifted]
with pytest.raises(IndexingError, match=msg):
ts.loc[mask_shifted] = 1


def test_setitem_boolean(test_data):
Expand Down Expand Up @@ -165,6 +172,7 @@ def test_where_unsafe_upcast(dtype):
assert_series_equal(s, expected)


@pytest.mark.xfail(reason="Failed: DID NOT RAISE <class 'Exception'>")
@pytest.mark.parametrize("dtype", [
np.int8, np.int16, np.int32, np.float32
])
Expand All @@ -175,7 +183,8 @@ def test_where_unsafe_itemsize_fail(dtype):
mask = s < 5

values = [2.5, 3.5, 4.5, 5.5, 6.5]
pytest.raises(Exception, s.__setitem__, tuple(mask), values)
with pytest.raises(Exception):
s[mask] = values
Copy link
Member Author

@simonjayhawkins simonjayhawkins Jan 13, 2019

Choose a reason for hiding this comment

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

does not raise using python index operator instead of setitem with tuple

Copy link
Contributor

Choose a reason for hiding this comment

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

not clear what you mean here?

Copy link
Member Author

Choose a reason for hiding this comment

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

@jreback

@pytest.mark.parametrize("dtype", [np.int64, np.float64])
def test_where_unsafe_upcast(dtype):
s = Series(np.arange(10), dtype=dtype)
values = [2.5, 3.5, 4.5, 5.5, 6.5]
mask = s < 5
expected = Series(values + lrange(5, 10), dtype="float64")
s[mask] = values
assert_series_equal(s, expected)
@pytest.mark.xfail
@pytest.mark.parametrize("dtype", [
np.int8, np.int16, np.int32, np.float32
])
def test_where_unsafe_itemsize_fail(dtype):
# Can't do these, as we are forced to change the
# item size of the input to something we cannot.
s = Series(np.arange(10), dtype=dtype)
mask = s < 5
values = [2.5, 3.5, 4.5, 5.5, 6.5]
with pytest.raises(Exception):
s[mask] = values

looking at test above test_where_unsafe_upcast i'm assuming that it should be

s[mask] = values

whereas the current test, tests

s[tuple(mask)] = values

which gives KeyError: "None of [Index([True, True, True, True, True, False, False, False, False, False], dtype='object')] are in the [index]"

which does not appear to be the intended tested behaviour whereas the test is not raising an exception with the change.

Copy link
Contributor

Choose a reason for hiding this comment

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

can you match the expection more specifically with an error message, would make it more informative

Copy link
Member Author

Choose a reason for hiding this comment

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

test originally added in #3292 so i'm guessing that the expected error message was originally:

https://github.com/jreback/pandas/blob/b379772359a06d2fe9a646ad60bc7c4c125bfd6a/pandas/core/common.py#L780-L783

Copy link
Member Author

Choose a reason for hiding this comment

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

maybe fixed by #9743. this is where the error message was removed from core/common.py



def test_where_unsafe():
Expand Down Expand Up @@ -206,10 +215,11 @@ def test_where_unsafe():
s = Series(np.arange(10))
mask = s > 5

with pytest.raises(ValueError):
msg = "cannot assign mismatch length to masked array"
with pytest.raises(ValueError, match=msg):
s[mask] = [5, 4, 3, 2, 1]

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg):
s[mask] = [0] * 5

# dtype changes
Expand Down Expand Up @@ -276,8 +286,11 @@ def test_where_error():
s = Series(np.random.randn(5))
cond = s > 0

pytest.raises(ValueError, s.where, 1)
pytest.raises(ValueError, s.where, cond[:3].values, -s)
msg = "Array conditional must be same shape as self"
with pytest.raises(ValueError, match=msg):
s.where(1)
with pytest.raises(ValueError, match=msg):
s.where(cond[:3].values, -s)

# GH 2745
s = Series([1, 2])
Expand All @@ -286,10 +299,13 @@ def test_where_error():
assert_series_equal(s, expected)

# failures
pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]),
[0, 2, 3])
pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]),
[])
msg = "cannot assign mismatch length to masked array"
with pytest.raises(ValueError, match=msg):
s[[True, False]] = [0, 2, 3]
msg = ("NumPy boolean array indexing assignment cannot assign 0 input"
" values to the 1 output values where the mask is true")
with pytest.raises(ValueError, match=msg):
s[[True, False]] = []


@pytest.mark.parametrize('klass', [list, tuple, np.array, Series])
Expand Down Expand Up @@ -349,10 +365,13 @@ 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")

# slice
s = Series(list('abc'))

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg.format('slice')):
s[0:3] = list(range(27))

s[0:3] = list(range(3))
Expand All @@ -362,7 +381,7 @@ def test_where_setitem_invalid():
# slice with step
s = Series(list('abcdef'))

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg.format('slice')):
s[0:4:2] = list(range(27))

s = Series(list('abcdef'))
Expand All @@ -373,7 +392,7 @@ def test_where_setitem_invalid():
# neg slices
s = Series(list('abcdef'))

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg.format('slice')):
s[:-1] = list(range(27))

s[-3:-1] = list(range(2))
Expand All @@ -383,12 +402,12 @@ def test_where_setitem_invalid():
# list
s = Series(list('abc'))

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg.format('list-like')):
s[[0, 1, 2]] = list(range(27))

s = Series(list('abc'))

with pytest.raises(ValueError):
with pytest.raises(ValueError, match=msg.format('list-like')):
s[[0, 1, 2]] = list(range(2))

# scalar
Expand Down Expand Up @@ -590,8 +609,11 @@ def test_mask():
rs2 = s2.mask(cond[:3], -s2)
assert_series_equal(rs, rs2)

pytest.raises(ValueError, s.mask, 1)
pytest.raises(ValueError, s.mask, cond[:3].values, -s)
msg = "Array conditional must be same shape as self"
with pytest.raises(ValueError, match=msg):
s.mask(1)
with pytest.raises(ValueError, match=msg):
s.mask(cond[:3].values, -s)

# dtype changes
s = Series([1, 2, 3, 4])
Expand Down
23 changes: 15 additions & 8 deletions pandas/tests/series/indexing/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ def test_fancy_getitem():
assert s['2009-1-2'] == 48
assert s[datetime(2009, 1, 2)] == 48
assert s[Timestamp(datetime(2009, 1, 2))] == 48
pytest.raises(KeyError, s.__getitem__, '2009-1-3')

with pytest.raises(KeyError, match=r"^'2009-1-3'$"):
s['2009-1-3']
assert_series_equal(s['3/6/2009':'2009-06-05'],
s[datetime(2009, 3, 6):datetime(2009, 6, 5)])

Expand Down Expand Up @@ -298,7 +298,8 @@ def test_getitem_setitem_datetimeindex():

lb = datetime(1990, 1, 1, 4)
rb = datetime(1990, 1, 1, 7)
with pytest.raises(TypeError):
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
# tznaive vs tzaware comparison is invalid
# see GH#18376, GH#18162
ts[(ts.index >= lb) & (ts.index <= rb)]
Expand Down Expand Up @@ -400,15 +401,17 @@ def test_datetime_indexing():
s = Series(len(index), index=index)
stamp = Timestamp('1/8/2000')

pytest.raises(KeyError, s.__getitem__, stamp)
with pytest.raises(KeyError, match=r"^947289600000000000L?$"):
s[stamp]
s[stamp] = 0
assert s[stamp] == 0

# not monotonic
s = Series(len(index), index=index)
s = s[::-1]

pytest.raises(KeyError, s.__getitem__, stamp)
with pytest.raises(KeyError, match=r"^947289600000000000L?$"):
s[stamp]
s[stamp] = 0
assert s[stamp] == 0

Expand Down Expand Up @@ -499,7 +502,8 @@ def test_duplicate_dates_indexing(dups):
expected = Series(np.where(mask, 0, ts), index=ts.index)
assert_series_equal(cp, expected)

pytest.raises(KeyError, ts.__getitem__, datetime(2000, 1, 6))
with pytest.raises(KeyError, match=r"^947116800000000000L?$"):
ts[datetime(2000, 1, 6)]

# new index
ts[datetime(2000, 1, 6)] = 0
Expand Down Expand Up @@ -664,8 +668,11 @@ def test_indexing():
expected = df.loc[[df.index[2]]]

# this is a single date, so will raise
pytest.raises(KeyError, df.__getitem__, '2012-01-02 18:01:02', )
pytest.raises(KeyError, df.__getitem__, df.index[2], )
with pytest.raises(KeyError, match=r"^'2012-01-02 18:01:02'$"):
df['2012-01-02 18:01:02']
msg = r"Timestamp\('2012-01-02 18:01:02-0600', tz='US/Central', freq='S'\)"
with pytest.raises(KeyError, match=msg):
df[df.index[2]]


"""
Expand Down
Loading