Skip to content

STY: use pytest.raises context syntax #24297

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
Dec 16, 2018
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
6 changes: 4 additions & 2 deletions pandas/tests/api/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ def check_deprecation(self, fold, fnew):
expected = fnew('foo')
assert result == expected
except TypeError:
pytest.raises(TypeError, lambda: fnew('foo'))
with pytest.raises(TypeError):
fnew('foo')
except AttributeError:
pytest.raises(AttributeError, lambda: fnew('foo'))
with pytest.raises(AttributeError):
fnew('foo')

def test_deprecated_from_api_types(self):

Expand Down
28 changes: 7 additions & 21 deletions pandas/tests/arrays/categorical/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,23 +157,17 @@ def test_reorder_categories(self):
# not all "old" included in "new"
cat = Categorical(["a", "b", "c", "a"], ordered=True)

def f():
with pytest.raises(ValueError):
cat.reorder_categories(["a"])

pytest.raises(ValueError, f)

# still not all "old" in "new"
def f():
with pytest.raises(ValueError):
cat.reorder_categories(["a", "b", "d"])

pytest.raises(ValueError, f)

# all "old" included in "new", but too long
def f():
with pytest.raises(ValueError):
cat.reorder_categories(["a", "b", "c", "d"])

pytest.raises(ValueError, f)

def test_add_categories(self):
cat = Categorical(["a", "b", "c", "a"], ordered=True)
old = cat.copy()
Expand All @@ -195,11 +189,9 @@ def test_add_categories(self):
assert res is None

# new is in old categories
def f():
with pytest.raises(ValueError):
cat.add_categories(["d"])

pytest.raises(ValueError, f)

# GH 9927
cat = Categorical(list("abc"), ordered=True)
expected = Categorical(
Expand Down Expand Up @@ -351,11 +343,9 @@ def test_remove_categories(self):
assert res is None

# removal is not in categories
def f():
with pytest.raises(ValueError):
cat.remove_categories(["c"])

pytest.raises(ValueError, f)

def test_remove_unused_categories(self):
c = Categorical(["a", "b", "c", "d", "a"],
categories=["a", "b", "c", "d", "e"])
Expand Down Expand Up @@ -461,20 +451,16 @@ def test_codes_immutable(self):
tm.assert_numpy_array_equal(c.codes, exp)

# Assignments to codes should raise
def f():
with pytest.raises(ValueError):
c.codes = np.array([0, 1, 2, 0, 1], dtype='int8')

pytest.raises(ValueError, f)

# changes in the codes array should raise
# np 1.6.1 raises RuntimeError rather than ValueError
codes = c.codes

def f():
with pytest.raises(ValueError):
codes[4] = 1

pytest.raises(ValueError, f)

# But even after getting the codes, the original array should still be
# writeable!
c[4] = "a"
Expand Down
32 changes: 9 additions & 23 deletions pandas/tests/arrays/categorical/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ def test_constructor_unsortable(self):
assert not factor.ordered

# this however will raise as cannot be sorted
pytest.raises(
TypeError, lambda: Categorical(arr, ordered=True))
with pytest.raises(TypeError):
Categorical(arr, ordered=True)

def test_constructor_interval(self):
result = Categorical([Interval(1, 2), Interval(2, 3), Interval(3, 6)],
Expand All @@ -99,16 +99,12 @@ def test_constructor(self):
tm.assert_numpy_array_equal(c2.__array__(), exp_arr)

# categories must be unique
def f():
with pytest.raises(ValueError):
Categorical([1, 2], [1, 2, 2])

pytest.raises(ValueError, f)

def f():
with pytest.raises(ValueError):
Categorical(["a", "b"], ["a", "b", "b"])

pytest.raises(ValueError, f)

# The default should be unordered
c1 = Categorical(["a", "b", "c", "a"])
assert not c1.ordered
Expand Down Expand Up @@ -421,35 +417,25 @@ def test_constructor_with_categorical_categories(self):
def test_from_codes(self):

# too few categories
def f():
with pytest.raises(ValueError):
Categorical.from_codes([1, 2], [1, 2])

pytest.raises(ValueError, f)

# no int codes
def f():
with pytest.raises(ValueError):
Categorical.from_codes(["a"], [1, 2])

pytest.raises(ValueError, f)

# no unique categories
def f():
with pytest.raises(ValueError):
Categorical.from_codes([0, 1, 2], ["a", "a", "b"])

pytest.raises(ValueError, f)

# NaN categories included
def f():
with pytest.raises(ValueError):
Categorical.from_codes([0, 1, 2], ["a", "b", np.nan])

pytest.raises(ValueError, f)

# too negative
def f():
with pytest.raises(ValueError):
Categorical.from_codes([-2, 1, 2], ["a", "b", "c"])

pytest.raises(ValueError, f)

exp = Categorical(["a", "b", "c"], ordered=False)
res = Categorical.from_codes([0, 1, 2], ["a", "b", "c"])
tm.assert_categorical_equal(exp, res)
Expand Down
8 changes: 2 additions & 6 deletions pandas/tests/arrays/categorical/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,13 @@ def test_categories_assigments(self):
tm.assert_index_equal(s.categories, Index([1, 2, 3]))

# lengthen
def f():
with pytest.raises(ValueError):
s.categories = [1, 2, 3, 4]

pytest.raises(ValueError, f)

# shorten
def f():
with pytest.raises(ValueError):
s.categories = [1, 2]

pytest.raises(ValueError, f)

# Combinations of sorted/unique:
@pytest.mark.parametrize("idx_values", [[1, 2, 3, 4], [1, 3, 2, 4],
[1, 3, 3, 4], [1, 2, 2, 4]])
Expand Down
22 changes: 8 additions & 14 deletions pandas/tests/arrays/categorical/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,28 +76,22 @@ def test_comparisons(self):
tm.assert_numpy_array_equal(res, exp)

# Only categories with same categories can be compared
def f():
with pytest.raises(TypeError):
cat > cat_rev

pytest.raises(TypeError, f)

cat_rev_base2 = Categorical(
["b", "b", "b"], categories=["c", "b", "a", "d"])

def f():
with pytest.raises(TypeError):
cat_rev > cat_rev_base2

pytest.raises(TypeError, f)

# Only categories with same ordering information can be compared
cat_unorderd = cat.set_ordered(False)
assert not (cat > cat).any()

def f():
with pytest.raises(TypeError):
cat > cat_unorderd

pytest.raises(TypeError, f)

# comparison (in both directions) with Series will raise
s = Series(["b", "b", "b"])
pytest.raises(TypeError, lambda: cat > s)
Expand Down Expand Up @@ -194,11 +188,9 @@ def test_comparisons(self, data, reverse, base):
tm.assert_numpy_array_equal(res_rev.values, exp_rev2)

# Only categories with same categories can be compared
def f():
with pytest.raises(TypeError):
cat > cat_rev

pytest.raises(TypeError, f)

# categorical cannot be compared to Series or numpy array, and also
# not the other way around
pytest.raises(TypeError, lambda: cat > s)
Expand Down Expand Up @@ -284,14 +276,16 @@ def test_numeric_like_ops(self):

# numpy ops
s = Series(Categorical([1, 2, 3, 4]))
pytest.raises(TypeError, lambda: np.sum(s))
with pytest.raises(TypeError):
np.sum(s)

# numeric ops on a Series
for op in ['__add__', '__sub__', '__mul__', '__truediv__']:
pytest.raises(TypeError, lambda: getattr(s, op)(2))

# invalid ufunc
pytest.raises(TypeError, lambda: np.log(s))
with pytest.raises(TypeError):
np.log(s)

def test_contains(self):
# GH21508
Expand Down
12 changes: 5 additions & 7 deletions pandas/tests/frame/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ def test_apply(self, float_frame):
# invalid axis
df = DataFrame(
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['a', 'a', 'c'])
pytest.raises(ValueError, df.apply, lambda x: x, 2)
with pytest.raises(ValueError):
df.apply(lambda x: x, 2)

# GH 9573
df = DataFrame({'c0': ['A', 'A', 'B', 'B'],
Expand Down Expand Up @@ -890,19 +891,16 @@ def test_agg_transform(self, axis, float_frame):

def test_transform_and_agg_err(self, axis, float_frame):
# cannot both transform and agg
def f():
with pytest.raises(ValueError):
float_frame.transform(['max', 'min'], axis=axis)
pytest.raises(ValueError, f)

def f():
with pytest.raises(ValueError):
with np.errstate(all='ignore'):
float_frame.agg(['max', 'sqrt'], axis=axis)
pytest.raises(ValueError, f)

def f():
with pytest.raises(ValueError):
with np.errstate(all='ignore'):
float_frame.transform(['max', 'sqrt'], axis=axis)
pytest.raises(ValueError, f)

df = pd.DataFrame({'A': range(5), 'B': 5})

Expand Down
Loading