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 (frame) #25516

Merged
merged 5 commits into from
Mar 4, 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
3 changes: 2 additions & 1 deletion pandas/tests/frame/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,8 @@ def test_rename(self, float_frame):
tm.assert_index_equal(renamed.index, Index(['BAR', 'FOO']))

# have to pass something
pytest.raises(TypeError, float_frame.rename)
with pytest.raises(TypeError, match="must pass an index to rename"):
float_frame.rename()

# partial columns
renamed = float_frame.rename(columns={'C': 'foo', 'D': 'bar'})
Expand Down
25 changes: 18 additions & 7 deletions pandas/tests/frame/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,7 @@ def test_var_std(self, datetime_frame):
result = nanops.nanvar(arr, axis=0)
assert not (result < 0).any()

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
@pytest.mark.parametrize(
"meth", ['sem', 'var', 'std'])
def test_numeric_only_flag(self, meth):
Expand All @@ -919,10 +920,12 @@ def test_numeric_only_flag(self, meth):
tm.assert_series_equal(expected, result)

# df1 has all numbers, df2 has a letter inside
pytest.raises(TypeError, lambda: getattr(df1, meth)(
axis=1, numeric_only=False))
pytest.raises(TypeError, lambda: getattr(df2, meth)(
axis=1, numeric_only=False))
msg = r"unsupported operand type\(s\) for -: 'float' and 'str'"
with pytest.raises(TypeError, match=msg):
getattr(df1, meth)(axis=1, numeric_only=False)
msg = "could not convert string to float: 'a'"
with pytest.raises(TypeError, match=msg):
getattr(df2, meth)(axis=1, numeric_only=False)

def test_sem(self, datetime_frame):
result = datetime_frame.sem(ddof=4)
Expand Down Expand Up @@ -1367,6 +1370,7 @@ def test_pct_change(self):
# ----------------------------------------------------------------------
# Index of max / min

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_idxmin(self, float_frame, int_frame):
frame = float_frame
frame.loc[5:10] = np.nan
Expand All @@ -1379,8 +1383,11 @@ def test_idxmin(self, float_frame, int_frame):
skipna=skipna)
tm.assert_series_equal(result, expected)

pytest.raises(ValueError, frame.idxmin, axis=2)
msg = "No axis named 2 for object type <class 'type'>"
with pytest.raises(ValueError, match=msg):
frame.idxmin(axis=2)

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_idxmax(self, float_frame, int_frame):
frame = float_frame
frame.loc[5:10] = np.nan
Expand All @@ -1393,7 +1400,9 @@ def test_idxmax(self, float_frame, int_frame):
skipna=skipna)
tm.assert_series_equal(result, expected)

pytest.raises(ValueError, frame.idxmax, axis=2)
msg = "No axis named 2 for object type <class 'type'>"
with pytest.raises(ValueError, match=msg):
frame.idxmax(axis=2)

# ----------------------------------------------------------------------
# Logical reductions
Expand Down Expand Up @@ -1879,7 +1888,9 @@ def test_round_issue(self):
tm.assert_index_equal(rounded.index, dfs.index)

decimals = pd.Series([1, 0, 2], index=['A', 'B', 'A'])
pytest.raises(ValueError, df.round, decimals)
msg = "Index of decimals must be unique"
with pytest.raises(ValueError, match=msg):
df.round(decimals)

def test_built_in_round(self):
if not compat.PY3:
Expand Down
19 changes: 14 additions & 5 deletions pandas/tests/frame/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import numpy as np
import pytest

from pandas.compat import long, lrange, range
from pandas.compat import PY2, long, lrange, range

import pandas as pd
from pandas import (
Expand Down Expand Up @@ -144,8 +144,12 @@ def test_tab_completion(self):

def test_not_hashable(self, empty_frame):
df = self.klass([1])
pytest.raises(TypeError, hash, df)
pytest.raises(TypeError, hash, empty_frame)
msg = ("'(Sparse)?DataFrame' objects are mutable, thus they cannot be"
" hashed")
with pytest.raises(TypeError, match=msg):
hash(df)
with pytest.raises(TypeError, match=msg):
hash(empty_frame)

def test_new_empty_index(self):
df1 = self.klass(np.random.randn(0, 3))
Expand All @@ -169,7 +173,9 @@ def test_get_agg_axis(self, float_frame):
idx = float_frame._get_agg_axis(1)
assert idx is float_frame.index

pytest.raises(ValueError, float_frame._get_agg_axis, 2)
msg = r"Axis must be 0 or 1 \(got 2\)"
with pytest.raises(ValueError, match=msg):
float_frame._get_agg_axis(2)

def test_nonzero(self, float_frame, float_string_frame, empty_frame):
assert empty_frame.empty
Expand Down Expand Up @@ -351,12 +357,15 @@ def test_transpose(self, float_frame):
for col, s in compat.iteritems(mixed_T):
assert s.dtype == np.object_

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_swapaxes(self):
df = self.klass(np.random.randn(10, 5))
self._assert_frame_equal(df.T, df.swapaxes(0, 1))
self._assert_frame_equal(df.T, df.swapaxes(1, 0))
self._assert_frame_equal(df, df.swapaxes(0, 0))
pytest.raises(ValueError, df.swapaxes, 2, 5)
msg = "No axis named 2 for object type <class 'type'>"
with pytest.raises(ValueError, match=msg):
df.swapaxes(2, 5)

def test_axis_aliases(self, float_frame):
f = float_frame
Expand Down
43 changes: 30 additions & 13 deletions pandas/tests/frame/test_axis_select_reindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import numpy as np
import pytest

from pandas.compat import lrange, lzip, u
from pandas.compat import PY2, lrange, lzip, u
from pandas.errors import PerformanceWarning

import pandas as pd
Expand Down Expand Up @@ -38,8 +38,11 @@ def test_drop_names(self):
assert obj.columns.name == 'second'
assert list(df.columns) == ['d', 'e', 'f']

pytest.raises(KeyError, df.drop, ['g'])
pytest.raises(KeyError, df.drop, ['g'], 1)
msg = r"\['g'\] not found in axis"
with pytest.raises(KeyError, match=msg):
df.drop(['g'])
with pytest.raises(KeyError, match=msg):
df.drop(['g'], 1)

# errors = 'ignore'
dropped = df.drop(['g'], errors='ignore')
Expand Down Expand Up @@ -84,10 +87,14 @@ def test_drop(self):
assert_frame_equal(simple.drop(
[0, 3], axis='index'), simple.loc[[1, 2], :])

pytest.raises(KeyError, simple.drop, 5)
pytest.raises(KeyError, simple.drop, 'C', 1)
pytest.raises(KeyError, simple.drop, [1, 5])
pytest.raises(KeyError, simple.drop, ['A', 'C'], 1)
with pytest.raises(KeyError, match=r"\[5\] not found in axis"):
simple.drop(5)
with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):
simple.drop('C', 1)
with pytest.raises(KeyError, match=r"\[5\] not found in axis"):
simple.drop([1, 5])
with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):
simple.drop(['A', 'C'], 1)

# errors = 'ignore'
assert_frame_equal(simple.drop(5, errors='ignore'), simple)
Expand Down Expand Up @@ -444,7 +451,9 @@ def test_reindex_dups(self):
assert_frame_equal(result, expected)

# reindex fails
pytest.raises(ValueError, df.reindex, index=list(range(len(df))))
msg = "cannot reindex from a duplicate axis"
with pytest.raises(ValueError, match=msg):
df.reindex(index=list(range(len(df))))

def test_reindex_axis_style(self):
# https://github.com/pandas-dev/pandas/issues/12392
Expand Down Expand Up @@ -963,10 +972,15 @@ def test_take(self):
assert_frame_equal(result, expected, check_names=False)

# illegal indices
pytest.raises(IndexError, df.take, [3, 1, 2, 30], axis=0)
pytest.raises(IndexError, df.take, [3, 1, 2, -31], axis=0)
pytest.raises(IndexError, df.take, [3, 1, 2, 5], axis=1)
pytest.raises(IndexError, df.take, [3, 1, 2, -5], axis=1)
msg = "indices are out-of-bounds"
with pytest.raises(IndexError, match=msg):
df.take([3, 1, 2, 30], axis=0)
with pytest.raises(IndexError, match=msg):
df.take([3, 1, 2, -31], axis=0)
with pytest.raises(IndexError, match=msg):
df.take([3, 1, 2, 5], axis=1)
with pytest.raises(IndexError, match=msg):
df.take([3, 1, 2, -5], axis=1)

# mixed-dtype
order = [4, 1, 2, 0, 3]
Expand Down Expand Up @@ -1037,6 +1051,7 @@ def test_reindex_corner(self):
smaller = self.intframe.reindex(columns=['A', 'B', 'E'])
assert smaller['E'].dtype == np.float64

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_reindex_axis(self):
cols = ['A', 'B', 'E']
with tm.assert_produces_warning(FutureWarning) as m:
Expand All @@ -1052,7 +1067,9 @@ def test_reindex_axis(self):
reindexed2 = self.intframe.reindex(index=rows)
assert_frame_equal(reindexed1, reindexed2)

pytest.raises(ValueError, self.intframe.reindex_axis, rows, axis=2)
msg = "No axis named 2 for object type <class 'type'>"
with pytest.raises(ValueError, match=msg):
self.intframe.reindex_axis(rows, axis=2)

# no-op case
cols = self.frame.columns.copy()
Expand Down
10 changes: 6 additions & 4 deletions pandas/tests/frame/test_block_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,12 @@ def f(dtype):
columns=["A", "B", "C"],
dtype=dtype)

pytest.raises(NotImplementedError, f,
[("A", "datetime64[h]"),
("B", "str"),
("C", "int32")])
msg = ("compound dtypes are not implemented in the DataFrame"
" constructor")
with pytest.raises(NotImplementedError, match=msg):
f([("A", "datetime64[h]"),
("B", "str"),
("C", "int32")])

# these work (though results may be unexpected)
f('int64')
Expand Down
51 changes: 34 additions & 17 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
import pytest

from pandas.compat import (
PY3, PY36, is_platform_little_endian, lmap, long, lrange, lzip, range, zip)
PY2, PY3, PY36, is_platform_little_endian, lmap, long, lrange, lzip, range,
zip)

from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
from pandas.core.dtypes.common import is_integer_dtype
Expand Down Expand Up @@ -58,8 +59,9 @@ def test_constructor_cast_failure(self):
df['foo'] = np.ones((4, 2)).tolist()

# this is not ok
pytest.raises(ValueError, df.__setitem__, tuple(['test']),
np.ones((4, 2)))
msg = "Wrong number of items passed 2, placement implies 1"
with pytest.raises(ValueError, match=msg):
df['test'] = np.ones((4, 2))

# this is ok
df['foo2'] = np.ones((4, 2)).tolist()
Expand Down Expand Up @@ -1259,7 +1261,9 @@ def test_constructor_Series_named(self):
expected = DataFrame({0: s})
tm.assert_frame_equal(df, expected)

pytest.raises(ValueError, DataFrame, s, columns=[1, 2])
msg = r"Shape of passed values is \(10, 1\), indices imply \(10, 2\)"
with pytest.raises(ValueError, match=msg):
DataFrame(s, columns=[1, 2])

# #2234
a = Series([], name='x')
Expand Down Expand Up @@ -1433,8 +1437,10 @@ def test_constructor_column_duplicates(self):

tm.assert_frame_equal(idf, edf)

pytest.raises(ValueError, DataFrame.from_dict,
OrderedDict([('b', 8), ('a', 5), ('a', 6)]))
msg = "If using all scalar values, you must pass an index"
with pytest.raises(ValueError, match=msg):
DataFrame.from_dict(
OrderedDict([('b', 8), ('a', 5), ('a', 6)]))

def test_constructor_empty_with_string_dtype(self):
# GH 9428
Expand Down Expand Up @@ -1465,8 +1471,11 @@ def test_constructor_single_value(self):
dtype=object),
index=[1, 2], columns=['a', 'c']))

pytest.raises(ValueError, DataFrame, 'a', [1, 2])
pytest.raises(ValueError, DataFrame, 'a', columns=['a', 'c'])
msg = "DataFrame constructor not properly called!"
with pytest.raises(ValueError, match=msg):
DataFrame('a', [1, 2])
with pytest.raises(ValueError, match=msg):
DataFrame('a', columns=['a', 'c'])

msg = 'incompatible data and dtype'
with pytest.raises(TypeError, match=msg):
Expand Down Expand Up @@ -1692,6 +1701,7 @@ def test_constructor_series_copy(self):

assert not (series['A'] == 5).all()

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_constructor_with_nas(self):
# GH 5016
# na's in indices
Expand All @@ -1704,9 +1714,11 @@ def check(df):

# No NaN found -> error
if len(indexer) == 0:
def f():
msg = ("cannot do label indexing on"
r" <class 'pandas\.core\.indexes\.range\.RangeIndex'>"
r" with these indexers \[nan\] of <class 'float'>")
with pytest.raises(TypeError, match=msg):
df.loc[:, np.nan]
pytest.raises(TypeError, f)
# single nan should result in Series
elif len(indexer) == 1:
tm.assert_series_equal(df.iloc[:, indexer[0]],
Expand Down Expand Up @@ -1782,13 +1794,15 @@ def test_constructor_categorical(self):
tm.assert_frame_equal(df, expected)

# invalid (shape)
pytest.raises(ValueError,
lambda: DataFrame([Categorical(list('abc')),
Categorical(list('abdefg'))]))
msg = r"Shape of passed values is \(6, 2\), indices imply \(3, 2\)"
with pytest.raises(ValueError, match=msg):
DataFrame([Categorical(list('abc')),
Categorical(list('abdefg'))])

# ndim > 1
pytest.raises(NotImplementedError,
lambda: Categorical(np.array([list('abcd')])))
msg = "> 1 ndim Categorical are not supported at this time"
with pytest.raises(NotImplementedError, match=msg):
Categorical(np.array([list('abcd')]))

def test_constructor_categorical_series(self):

Expand Down Expand Up @@ -2164,8 +2178,11 @@ def test_from_records_bad_index_column(self):
tm.assert_index_equal(df1.index, Index(df.C))

# should fail
pytest.raises(ValueError, DataFrame.from_records, df, index=[2])
pytest.raises(KeyError, DataFrame.from_records, df, index=2)
msg = r"Shape of passed values is \(10, 3\), indices imply \(1, 3\)"
with pytest.raises(ValueError, match=msg):
DataFrame.from_records(df, index=[2])
with pytest.raises(KeyError, match=r"^2$"):
DataFrame.from_records(df, index=2)

def test_from_records_non_tuple(self):
class Record(object):
Expand Down
8 changes: 6 additions & 2 deletions pandas/tests/frame/test_convert_to.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,15 @@ def test_to_dict_index_not_unique_with_index_orient(self):
# GH22801
# Data loss when indexes are not unique. Raise ValueError.
df = DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
pytest.raises(ValueError, df.to_dict, orient='index')
msg = "DataFrame index must be unique for orient='index'"
with pytest.raises(ValueError, match=msg):
df.to_dict(orient='index')

def test_to_dict_invalid_orient(self):
df = DataFrame({'A': [0, 1]})
pytest.raises(ValueError, df.to_dict, orient='xinvalid')
msg = "orient 'xinvalid' not understood"
with pytest.raises(ValueError, match=msg):
df.to_dict(orient='xinvalid')

def test_to_records_dt64(self):
df = DataFrame([["one", "two", "three"],
Expand Down
Loading