Skip to content

STY: use pytest.raises context syntax (series) #24812

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 17, 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
11 changes: 8 additions & 3 deletions pandas/tests/series/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,16 @@ class TestSeriesAlterAxes(object):

def test_setindex(self, string_series):
# wrong type
pytest.raises(TypeError, setattr, string_series, 'index', None)
msg = (r"Index\(\.\.\.\) must be called with a collection of some"
r" kind, None was passed")
with pytest.raises(TypeError, match=msg):
string_series.index = None

# wrong length
pytest.raises(Exception, setattr, string_series, 'index',
np.arange(len(string_series) - 1))
msg = (r"Length mismatch: Expected axis has (30|100) elements, new"
r" values have (29|99) elements")
with pytest.raises(ValueError, match=msg):
string_series.index = np.arange(len(string_series) - 1)

# works
string_series.index = np.arange(len(string_series))
Expand Down
62 changes: 44 additions & 18 deletions pandas/tests/series/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,10 @@ def test_argsort_stable(self):
check_dtype=False)
tm.assert_series_equal(qindexer, Series(qexpected),
check_dtype=False)
pytest.raises(AssertionError, tm.assert_numpy_array_equal,
qindexer, mindexer)
msg = (r"ndarray Expected type <(class|type) 'numpy\.ndarray'>,"
r" found <class 'pandas\.core\.series\.Series'> instead")
with pytest.raises(AssertionError, match=msg):
tm.assert_numpy_array_equal(qindexer, mindexer)

def test_cumsum(self, datetime_series):
self._check_accum_op('cumsum', datetime_series)
Expand Down Expand Up @@ -476,8 +478,13 @@ def test_dot(self):
assert_almost_equal(a.dot(b['1']), expected['1'])
assert_almost_equal(a.dot(b2['1']), expected['1'])

pytest.raises(Exception, a.dot, a.values[:3])
pytest.raises(ValueError, a.dot, b.T)
msg = r"Dot product shape mismatch, \(4L?,\) vs \(3L?,\)"
# exception raised is of type Exception
with pytest.raises(Exception, match=msg):
a.dot(a.values[:3])
msg = "matrices are not aligned"
with pytest.raises(ValueError, match=msg):
a.dot(b.T)

@pytest.mark.skipif(not PY35,
reason='matmul supported for Python>=3.5')
Expand Down Expand Up @@ -541,8 +548,13 @@ def test_matmul(self):
index=['1', '2', '3'])
assert_series_equal(result, expected)

pytest.raises(Exception, a.dot, a.values[:3])
pytest.raises(ValueError, a.dot, b.T)
msg = r"Dot product shape mismatch, \(4,\) vs \(3,\)"
# exception raised is of type Exception
with pytest.raises(Exception, match=msg):
a.dot(a.values[:3])
msg = "matrices are not aligned"
with pytest.raises(ValueError, match=msg):
a.dot(b.T)

def test_clip(self, datetime_series):
val = datetime_series.median()
Expand Down Expand Up @@ -697,11 +709,13 @@ def test_isin(self):
def test_isin_with_string_scalar(self):
# GH4763
s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C'])
with pytest.raises(TypeError):
msg = (r"only list-like objects are allowed to be passed to isin\(\),"
r" you passed a \[str\]")
with pytest.raises(TypeError, match=msg):
s.isin('a')

with pytest.raises(TypeError):
s = Series(['aaa', 'b', 'c'])
s = Series(['aaa', 'b', 'c'])
with pytest.raises(TypeError, match=msg):
s.isin('aaa')

def test_isin_with_i8(self):
Expand Down Expand Up @@ -771,18 +785,21 @@ def test_ptp(self):
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
tm.assert_series_equal(s.ptp(level=0, skipna=False), expected)

with pytest.raises(ValueError):
msg = r"No axis named 1 for object type <(class|type) 'type'>"
with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
s.ptp(axis=1)

s = pd.Series(['a', 'b', 'c', 'd', 'e'])
with pytest.raises(TypeError):
msg = r"unsupported operand type\(s\) for -: 'str' and 'str'"
with pytest.raises(TypeError, match=msg):
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
s.ptp()

with pytest.raises(NotImplementedError):
msg = r"Series\.ptp does not implement numeric_only\."
with pytest.raises(NotImplementedError, match=msg):
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
s.ptp(numeric_only=True)
Expand Down Expand Up @@ -1103,29 +1120,38 @@ def test_validate_any_all_out_keepdims_raises(self, kwargs, func):
param = list(kwargs)[0]
name = func.__name__

msg = "the '{}' parameter .* {}".format(param, name)
msg = (r"the '{arg}' parameter is not "
r"supported in the pandas "
r"implementation of {fname}\(\)").format(arg=param, fname=name)
with pytest.raises(ValueError, match=msg):
func(s, **kwargs)

@td.skip_if_np_lt_115
def test_validate_sum_initial(self):
s = pd.Series([1, 2])
with pytest.raises(ValueError, match="the 'initial' .* sum"):
msg = (r"the 'initial' parameter is not "
r"supported in the pandas "
r"implementation of sum\(\)")
with pytest.raises(ValueError, match=msg):
np.sum(s, initial=10)

def test_validate_median_initial(self):
s = pd.Series([1, 2])
with pytest.raises(ValueError,
match="the 'overwrite_input' .* median"):
msg = (r"the 'overwrite_input' parameter is not "
r"supported in the pandas "
r"implementation of median\(\)")
with pytest.raises(ValueError, match=msg):
# It seems like np.median doesn't dispatch, so we use the
# method instead of the ufunc.
s.median(overwrite_input=True)

@td.skip_if_np_lt_115
def test_validate_stat_keepdims(self):
s = pd.Series([1, 2])
with pytest.raises(ValueError,
match="the 'keepdims'"):
msg = (r"the 'keepdims' parameter is not "
r"supported in the pandas "
r"implementation of sum\(\)")
with pytest.raises(ValueError, match=msg):
np.sum(s, keepdims=True)


Expand Down
32 changes: 19 additions & 13 deletions pandas/tests/series/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,11 @@ def test_index_tab_completion(self, index):
def test_not_hashable(self):
s_empty = Series()
s = Series([1])
pytest.raises(TypeError, hash, s_empty)
pytest.raises(TypeError, hash, s)
msg = "'Series' objects are mutable, thus they cannot be hashed"
with pytest.raises(TypeError, match=msg):
hash(s_empty)
with pytest.raises(TypeError, match=msg):
hash(s)

def test_contains(self):
tm.assert_contains_all(self.ts.index, self.ts)
Expand Down Expand Up @@ -333,7 +336,8 @@ def test_items(self):

def test_raise_on_info(self):
s = Series(np.random.randn(10))
with pytest.raises(AttributeError):
msg = "'Series' object has no attribute 'info'"
with pytest.raises(AttributeError, match=msg):
s.info()

def test_copy(self):
Expand Down Expand Up @@ -555,15 +559,17 @@ def test_cat_accessor_updates_on_inplace(self):
def test_categorical_delegations(self):

# invalid accessor
pytest.raises(AttributeError, lambda: Series([1, 2, 3]).cat)
with pytest.raises(AttributeError,
match=(r"Can only use .cat accessor "
r"with a 'category' dtype")):
msg = r"Can only use \.cat accessor with a 'category' dtype"
with pytest.raises(AttributeError, match=msg):
Series([1, 2, 3]).cat
with pytest.raises(AttributeError, match=msg):
Series([1, 2, 3]).cat()
pytest.raises(AttributeError, lambda: Series(['a', 'b', 'c']).cat)
pytest.raises(AttributeError, lambda: Series(np.arange(5.)).cat)
pytest.raises(AttributeError,
lambda: Series([Timestamp('20130101')]).cat)
with pytest.raises(AttributeError, match=msg):
Series(['a', 'b', 'c']).cat
with pytest.raises(AttributeError, match=msg):
Series(np.arange(5.)).cat
with pytest.raises(AttributeError, match=msg):
Series([Timestamp('20130101')]).cat

# Series should delegate calls to '.categories', '.codes', '.ordered'
# and the methods '.set_categories()' 'drop_unused_categories()' to the
Expand Down Expand Up @@ -605,10 +611,10 @@ def test_categorical_delegations(self):

# This method is likely to be confused, so test that it raises an error
# on wrong inputs:
def f():
msg = "'Series' object has no attribute 'set_categories'"
with pytest.raises(AttributeError, match=msg):
s.set_categories([4, 3, 2, 1])

pytest.raises(Exception, f)
# right: s.cat.set_categories([4,3,2,1])

# GH18862 (let Series.cat.rename_categories take callables)
Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/series/test_combine_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ def test_append(self, datetime_series, string_series, object_series):
else:
raise AssertionError("orphaned index!")

pytest.raises(ValueError, datetime_series.append, datetime_series,
verify_integrity=True)
msg = "Indexes have overlapping values:"
with pytest.raises(ValueError, match=msg):
datetime_series.append(datetime_series, verify_integrity=True)

def test_append_many(self, datetime_series):
pieces = [datetime_series[:5], datetime_series[5:10],
Expand Down
45 changes: 32 additions & 13 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ def test_constructor(self, datetime_series, empty_series):

assert not empty_series.index.is_all_dates
assert not Series({}).index.is_all_dates
pytest.raises(Exception, Series, np.random.randn(3, 3),
index=np.arange(3))

# exception raised is of type Exception
with pytest.raises(Exception, match="Data must be 1-dimensional"):
Series(np.random.randn(3, 3), index=np.arange(3))

mixed.name = 'Series'
rs = Series(mixed).name
Expand All @@ -75,7 +77,9 @@ def test_constructor(self, datetime_series, empty_series):

# raise on MultiIndex GH4187
m = MultiIndex.from_arrays([[1, 2], [3, 4]])
pytest.raises(NotImplementedError, Series, m)
msg = "initializing a Series from a MultiIndex is not supported"
with pytest.raises(NotImplementedError, match=msg):
Series(m)

@pytest.mark.parametrize('input_class', [list, dict, OrderedDict])
def test_constructor_empty(self, input_class):
Expand Down Expand Up @@ -495,7 +499,9 @@ def test_constructor_broadcast_list(self):
# GH 19342
# construction with single-element container and index
# should raise
pytest.raises(ValueError, Series, ['foo'], index=['a', 'b', 'c'])
msg = "Length of passed values is 1, index implies 3"
with pytest.raises(ValueError, match=msg):
Series(['foo'], index=['a', 'b', 'c'])

def test_constructor_corner(self):
df = tm.makeTimeDataFrame()
Expand Down Expand Up @@ -675,10 +681,17 @@ def test_constructor_dtype_datetime64(self):
assert s.dtype == 'M8[ns]'

# GH3414 related
# msg = (r"cannot astype a datetimelike from \[datetime64\[ns\]\] to"
# r" \[int32\]")
# with pytest.raises(TypeError, match=msg):
# Series(Series(dates).astype('int') / 1000000, dtype='M8[ms]')
pytest.raises(TypeError, lambda x: Series(
Copy link
Member Author

Choose a reason for hiding this comment

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

this is raising missing 1 required positional argument: 'x' because of the lambda and not failing as intended. correcting this with the conversion to context manger is only failing on windows and again from the error message is probably not failing as intended

Copy link
Contributor

Choose a reason for hiding this comment

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

this should be raising TypeError, what happens when you use the context manager

Copy link
Member Author

Choose a reason for hiding this comment

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

it is raising TypeError in master because of the lambda. this is a bad test.

correcting it with the context manager raises TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32] but only on the windows tests (see ci failures)

i've reverted the changes to the test, but the ci is failing on an unrelated conda error at the moment.

with the changes in this PR there will still be 823 uses of pytest.raises without the cm. so i don't want to get bogged down with bad tests at the moment.

Copy link
Contributor

Choose a reason for hiding this comment

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

k that's fine (though happy to take your change, though it should raise on windows as well). can you create an issue about this.

Series(dates).astype('int') / 1000000, dtype='M8[ms]'))
pytest.raises(TypeError,
lambda x: Series(dates, dtype='datetime64'))

msg = (r"The 'datetime64' dtype has no unit\. Please pass in"
r" 'datetime64\[ns\]' instead\.")
with pytest.raises(ValueError, match=msg):
Series(dates, dtype='datetime64')
Copy link
Member Author

Choose a reason for hiding this comment

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

i think this test is also not failing as intended and was masked by another lambda error. will do a follow-up PR to address theses cases.


# invalid dates can be help as object
result = Series([datetime(2, 1, 1)])
Expand Down Expand Up @@ -984,9 +997,11 @@ def test_constructor_dict_of_tuples(self):

def test_constructor_set(self):
values = {1, 2, 3, 4, 5}
pytest.raises(TypeError, Series, values)
with pytest.raises(TypeError, match="'set' type is unordered"):
Series(values)
values = frozenset(values)
pytest.raises(TypeError, Series, values)
with pytest.raises(TypeError, match="'frozenset' type is unordered"):
Series(values)

# https://github.com/pandas-dev/pandas/issues/22698
@pytest.mark.filterwarnings("ignore:elementwise comparison:FutureWarning")
Expand Down Expand Up @@ -1081,14 +1096,16 @@ def test_constructor_dtype_timedelta64(self):
td.astype('int64')

# invalid casting
pytest.raises(TypeError, td.astype, 'int32')
msg = (r"cannot astype a timedelta from \[timedelta64\[ns\]\] to"
r" \[int32\]")
with pytest.raises(TypeError, match=msg):
td.astype('int32')

# this is an invalid casting
def f():
msg = "Could not convert object to NumPy timedelta"
with pytest.raises(ValueError, match=msg):
Series([timedelta(days=1), 'foo'], dtype='m8[ns]')

pytest.raises(Exception, f)

# leave as object here
td = Series([timedelta(days=i) for i in range(3)] + ['foo'])
assert td.dtype == 'object'
Expand Down Expand Up @@ -1134,9 +1151,11 @@ def test_constructor_name_hashable(self):
assert s.name == n

def test_constructor_name_unhashable(self):
msg = r"Series\.name must be a hashable type"
for n in [['name_list'], np.ones(2), {1: 2}]:
for data in [['name_list'], np.ones(2), {1: 2}]:
pytest.raises(TypeError, Series, data, name=n)
with pytest.raises(TypeError, match=msg):
Series(data, name=n)

def test_auto_conversion(self):
series = Series(list(date_range('1/1/2000', periods=10)))
Expand Down
Loading