Skip to content

Commit 69905c5

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (generic) (#25603)
1 parent cc4a7e5 commit 69905c5

File tree

2 files changed

+61
-30
lines changed

2 files changed

+61
-30
lines changed

pandas/tests/generic/test_generic.py

+44-24
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import numpy as np
88
import pytest
99

10-
from pandas.compat import PY3, range, zip
10+
from pandas.compat import PY2, PY3, range, zip
1111

1212
from pandas.core.dtypes.common import is_scalar
1313

@@ -16,8 +16,6 @@
1616
import pandas.util.testing as tm
1717
from pandas.util.testing import assert_frame_equal, assert_series_equal
1818

19-
import pandas.io.formats.printing as printing
20-
2119
# ----------------------------------------------------------------------
2220
# Generic types test cases
2321

@@ -135,37 +133,51 @@ def test_nonzero(self):
135133
# GH 4633
136134
# look at the boolean/nonzero behavior for objects
137135
obj = self._construct(shape=4)
138-
pytest.raises(ValueError, lambda: bool(obj == 0))
139-
pytest.raises(ValueError, lambda: bool(obj == 1))
140-
pytest.raises(ValueError, lambda: bool(obj))
136+
msg = "The truth value of a {} is ambiguous".format(
137+
self._typ.__name__)
138+
with pytest.raises(ValueError, match=msg):
139+
bool(obj == 0)
140+
with pytest.raises(ValueError, match=msg):
141+
bool(obj == 1)
142+
with pytest.raises(ValueError, match=msg):
143+
bool(obj)
141144

142145
obj = self._construct(shape=4, value=1)
143-
pytest.raises(ValueError, lambda: bool(obj == 0))
144-
pytest.raises(ValueError, lambda: bool(obj == 1))
145-
pytest.raises(ValueError, lambda: bool(obj))
146+
with pytest.raises(ValueError, match=msg):
147+
bool(obj == 0)
148+
with pytest.raises(ValueError, match=msg):
149+
bool(obj == 1)
150+
with pytest.raises(ValueError, match=msg):
151+
bool(obj)
146152

147153
obj = self._construct(shape=4, value=np.nan)
148-
pytest.raises(ValueError, lambda: bool(obj == 0))
149-
pytest.raises(ValueError, lambda: bool(obj == 1))
150-
pytest.raises(ValueError, lambda: bool(obj))
154+
with pytest.raises(ValueError, match=msg):
155+
bool(obj == 0)
156+
with pytest.raises(ValueError, match=msg):
157+
bool(obj == 1)
158+
with pytest.raises(ValueError, match=msg):
159+
bool(obj)
151160

152161
# empty
153162
obj = self._construct(shape=0)
154-
pytest.raises(ValueError, lambda: bool(obj))
163+
with pytest.raises(ValueError, match=msg):
164+
bool(obj)
155165

156166
# invalid behaviors
157167

158168
obj1 = self._construct(shape=4, value=1)
159169
obj2 = self._construct(shape=4, value=1)
160170

161-
def f():
171+
with pytest.raises(ValueError, match=msg):
162172
if obj1:
163-
printing.pprint_thing("this works and shouldn't")
173+
pass
164174

165-
pytest.raises(ValueError, f)
166-
pytest.raises(ValueError, lambda: obj1 and obj2)
167-
pytest.raises(ValueError, lambda: obj1 or obj2)
168-
pytest.raises(ValueError, lambda: not obj1)
175+
with pytest.raises(ValueError, match=msg):
176+
obj1 and obj2
177+
with pytest.raises(ValueError, match=msg):
178+
obj1 or obj2
179+
with pytest.raises(ValueError, match=msg):
180+
not obj1
169181

170182
def test_downcast(self):
171183
# test close downcasting
@@ -200,9 +212,10 @@ def test_constructor_compound_dtypes(self):
200212
def f(dtype):
201213
return self._construct(shape=3, value=1, dtype=dtype)
202214

203-
pytest.raises(NotImplementedError, f, [("A", "datetime64[h]"),
204-
("B", "str"),
205-
("C", "int32")])
215+
msg = ("compound dtypes are not implemented in the {} constructor"
216+
.format(self._typ.__name__))
217+
with pytest.raises(NotImplementedError, match=msg):
218+
f([("A", "datetime64[h]"), ("B", "str"), ("C", "int32")])
206219

207220
# these work (though results may be unexpected)
208221
f('int64')
@@ -725,6 +738,7 @@ def test_sample(sel):
725738
with pytest.raises(ValueError):
726739
df.sample(1, weights=s4)
727740

741+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
728742
def test_squeeze(self):
729743
# noop
730744
for s in [tm.makeFloatSeries(), tm.makeStringSeries(),
@@ -755,8 +769,14 @@ def test_squeeze(self):
755769
tm.assert_series_equal(df.squeeze(axis=1), df.iloc[:, 0])
756770
tm.assert_series_equal(df.squeeze(axis='columns'), df.iloc[:, 0])
757771
assert df.squeeze() == df.iloc[0, 0]
758-
pytest.raises(ValueError, df.squeeze, axis=2)
759-
pytest.raises(ValueError, df.squeeze, axis='x')
772+
msg = ("No axis named 2 for object type <class"
773+
" 'pandas.core.frame.DataFrame'>")
774+
with pytest.raises(ValueError, match=msg):
775+
df.squeeze(axis=2)
776+
msg = ("No axis named x for object type <class"
777+
" 'pandas.core.frame.DataFrame'>")
778+
with pytest.raises(ValueError, match=msg):
779+
df.squeeze(axis='x')
760780

761781
df = tm.makeTimeDataFrame(3)
762782
tm.assert_frame_equal(df.squeeze(axis=0), df)

pandas/tests/generic/test_series.py

+17-6
Original file line numberDiff line numberDiff line change
@@ -102,23 +102,34 @@ def test_nonzero_single_element(self):
102102
s = Series([False])
103103
assert not s.bool()
104104

105+
msg = "The truth value of a Series is ambiguous"
105106
# single item nan to raise
106107
for s in [Series([np.nan]), Series([pd.NaT]), Series([True]),
107108
Series([False])]:
108-
pytest.raises(ValueError, lambda: bool(s))
109+
with pytest.raises(ValueError, match=msg):
110+
bool(s)
109111

112+
msg = "bool cannot act on a non-boolean single element Series"
110113
for s in [Series([np.nan]), Series([pd.NaT])]:
111-
pytest.raises(ValueError, lambda: s.bool())
114+
with pytest.raises(ValueError, match=msg):
115+
s.bool()
112116

113117
# multiple bool are still an error
118+
msg = "The truth value of a Series is ambiguous"
114119
for s in [Series([True, True]), Series([False, False])]:
115-
pytest.raises(ValueError, lambda: bool(s))
116-
pytest.raises(ValueError, lambda: s.bool())
120+
with pytest.raises(ValueError, match=msg):
121+
bool(s)
122+
with pytest.raises(ValueError, match=msg):
123+
s.bool()
117124

118125
# single non-bool are an error
119126
for s in [Series([1]), Series([0]), Series(['a']), Series([0.0])]:
120-
pytest.raises(ValueError, lambda: bool(s))
121-
pytest.raises(ValueError, lambda: s.bool())
127+
msg = "The truth value of a Series is ambiguous"
128+
with pytest.raises(ValueError, match=msg):
129+
bool(s)
130+
msg = "bool cannot act on a non-boolean single element Series"
131+
with pytest.raises(ValueError, match=msg):
132+
s.bool()
122133

123134
def test_metadata_propagation_indiv(self):
124135
# check that the metadata matches up on the resulting ops

0 commit comments

Comments
 (0)