Skip to content

Commit d708461

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (arithmetic, arrays, computati… (#25504)
1 parent 3e3c901 commit d708461

File tree

7 files changed

+205
-95
lines changed

7 files changed

+205
-95
lines changed

pandas/tests/arithmetic/test_timedelta64.py

+49-17
Original file line numberDiff line numberDiff line change
@@ -205,10 +205,20 @@ def test_subtraction_ops(self):
205205
td = Timedelta('1 days')
206206
dt = Timestamp('20130101')
207207

208-
pytest.raises(TypeError, lambda: tdi - dt)
209-
pytest.raises(TypeError, lambda: tdi - dti)
210-
pytest.raises(TypeError, lambda: td - dt)
211-
pytest.raises(TypeError, lambda: td - dti)
208+
msg = "cannot subtract a datelike from a TimedeltaArray"
209+
with pytest.raises(TypeError, match=msg):
210+
tdi - dt
211+
with pytest.raises(TypeError, match=msg):
212+
tdi - dti
213+
214+
msg = (r"descriptor '__sub__' requires a 'datetime\.datetime' object"
215+
" but received a 'Timedelta'")
216+
with pytest.raises(TypeError, match=msg):
217+
td - dt
218+
219+
msg = "bad operand type for unary -: 'DatetimeArray'"
220+
with pytest.raises(TypeError, match=msg):
221+
td - dti
212222

213223
result = dt - dti
214224
expected = TimedeltaIndex(['0 days', '-1 days', '-2 days'], name='bar')
@@ -265,19 +275,38 @@ def _check(result, expected):
265275
_check(result, expected)
266276

267277
# tz mismatches
268-
pytest.raises(TypeError, lambda: dt_tz - ts)
269-
pytest.raises(TypeError, lambda: dt_tz - dt)
270-
pytest.raises(TypeError, lambda: dt_tz - ts_tz2)
271-
pytest.raises(TypeError, lambda: dt - dt_tz)
272-
pytest.raises(TypeError, lambda: ts - dt_tz)
273-
pytest.raises(TypeError, lambda: ts_tz2 - ts)
274-
pytest.raises(TypeError, lambda: ts_tz2 - dt)
275-
pytest.raises(TypeError, lambda: ts_tz - ts_tz2)
278+
msg = ("Timestamp subtraction must have the same timezones or no"
279+
" timezones")
280+
with pytest.raises(TypeError, match=msg):
281+
dt_tz - ts
282+
msg = "can't subtract offset-naive and offset-aware datetimes"
283+
with pytest.raises(TypeError, match=msg):
284+
dt_tz - dt
285+
msg = ("Timestamp subtraction must have the same timezones or no"
286+
" timezones")
287+
with pytest.raises(TypeError, match=msg):
288+
dt_tz - ts_tz2
289+
msg = "can't subtract offset-naive and offset-aware datetimes"
290+
with pytest.raises(TypeError, match=msg):
291+
dt - dt_tz
292+
msg = ("Timestamp subtraction must have the same timezones or no"
293+
" timezones")
294+
with pytest.raises(TypeError, match=msg):
295+
ts - dt_tz
296+
with pytest.raises(TypeError, match=msg):
297+
ts_tz2 - ts
298+
with pytest.raises(TypeError, match=msg):
299+
ts_tz2 - dt
300+
with pytest.raises(TypeError, match=msg):
301+
ts_tz - ts_tz2
276302

277303
# with dti
278-
pytest.raises(TypeError, lambda: dti - ts_tz)
279-
pytest.raises(TypeError, lambda: dti_tz - ts)
280-
pytest.raises(TypeError, lambda: dti_tz - ts_tz2)
304+
with pytest.raises(TypeError, match=msg):
305+
dti - ts_tz
306+
with pytest.raises(TypeError, match=msg):
307+
dti_tz - ts
308+
with pytest.raises(TypeError, match=msg):
309+
dti_tz - ts_tz2
281310

282311
result = dti_tz - dt_tz
283312
expected = TimedeltaIndex(['0 days', '1 days', '2 days'])
@@ -349,8 +378,11 @@ def test_addition_ops(self):
349378
tm.assert_index_equal(result, expected)
350379

351380
# unequal length
352-
pytest.raises(ValueError, lambda: tdi + dti[0:1])
353-
pytest.raises(ValueError, lambda: tdi[0:1] + dti)
381+
msg = "cannot add indices of unequal length"
382+
with pytest.raises(ValueError, match=msg):
383+
tdi + dti[0:1]
384+
with pytest.raises(ValueError, match=msg):
385+
tdi[0:1] + dti
354386

355387
# random indexes
356388
with pytest.raises(NullFrequencyError):

pandas/tests/arrays/categorical/test_analytics.py

+19-10
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,11 @@ def test_min_max(self):
1818

1919
# unordered cats have no min/max
2020
cat = Categorical(["a", "b", "c", "d"], ordered=False)
21-
pytest.raises(TypeError, lambda: cat.min())
22-
pytest.raises(TypeError, lambda: cat.max())
21+
msg = "Categorical is not ordered for operation {}"
22+
with pytest.raises(TypeError, match=msg.format('min')):
23+
cat.min()
24+
with pytest.raises(TypeError, match=msg.format('max')):
25+
cat.max()
2326

2427
cat = Categorical(["a", "b", "c", "d"], ordered=True)
2528
_min = cat.min()
@@ -108,18 +111,24 @@ def test_searchsorted(self):
108111
tm.assert_numpy_array_equal(res_ser, exp)
109112

110113
# Searching for a single value that is not from the Categorical
111-
pytest.raises(KeyError, lambda: c1.searchsorted('cucumber'))
112-
pytest.raises(KeyError, lambda: s1.searchsorted('cucumber'))
114+
msg = r"Value\(s\) to be inserted must be in categories"
115+
with pytest.raises(KeyError, match=msg):
116+
c1.searchsorted('cucumber')
117+
with pytest.raises(KeyError, match=msg):
118+
s1.searchsorted('cucumber')
113119

114120
# Searching for multiple values one of each is not from the Categorical
115-
pytest.raises(KeyError,
116-
lambda: c1.searchsorted(['bread', 'cucumber']))
117-
pytest.raises(KeyError,
118-
lambda: s1.searchsorted(['bread', 'cucumber']))
121+
with pytest.raises(KeyError, match=msg):
122+
c1.searchsorted(['bread', 'cucumber'])
123+
with pytest.raises(KeyError, match=msg):
124+
s1.searchsorted(['bread', 'cucumber'])
119125

120126
# searchsorted call for unordered Categorical
121-
pytest.raises(ValueError, lambda: c2.searchsorted('apple'))
122-
pytest.raises(ValueError, lambda: s2.searchsorted('apple'))
127+
msg = "Categorical not ordered"
128+
with pytest.raises(ValueError, match=msg):
129+
c2.searchsorted('apple')
130+
with pytest.raises(ValueError, match=msg):
131+
s2.searchsorted('apple')
123132

124133
def test_unique(self):
125134
# categories are reordered based on value when ordered=False

pandas/tests/arrays/categorical/test_operators.py

+63-25
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import numpy as np
55
import pytest
66

7+
from pandas.compat import PY2
8+
79
import pandas as pd
810
from pandas import Categorical, DataFrame, Series, date_range
911
from pandas.tests.arrays.categorical.common import TestCategorical
@@ -17,6 +19,7 @@ def test_categories_none_comparisons(self):
1719
'a', 'c', 'c', 'c'], ordered=True)
1820
tm.assert_categorical_equal(factor, self.factor)
1921

22+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
2023
def test_comparisons(self):
2124

2225
result = self.factor[self.factor == 'a']
@@ -95,16 +98,24 @@ def test_comparisons(self):
9598

9699
# comparison (in both directions) with Series will raise
97100
s = Series(["b", "b", "b"])
98-
pytest.raises(TypeError, lambda: cat > s)
99-
pytest.raises(TypeError, lambda: cat_rev > s)
100-
pytest.raises(TypeError, lambda: s < cat)
101-
pytest.raises(TypeError, lambda: s < cat_rev)
101+
msg = ("Cannot compare a Categorical for op __gt__ with type"
102+
r" <class 'numpy\.ndarray'>")
103+
with pytest.raises(TypeError, match=msg):
104+
cat > s
105+
with pytest.raises(TypeError, match=msg):
106+
cat_rev > s
107+
with pytest.raises(TypeError, match=msg):
108+
s < cat
109+
with pytest.raises(TypeError, match=msg):
110+
s < cat_rev
102111

103112
# comparison with numpy.array will raise in both direction, but only on
104113
# newer numpy versions
105114
a = np.array(["b", "b", "b"])
106-
pytest.raises(TypeError, lambda: cat > a)
107-
pytest.raises(TypeError, lambda: cat_rev > a)
115+
with pytest.raises(TypeError, match=msg):
116+
cat > a
117+
with pytest.raises(TypeError, match=msg):
118+
cat_rev > a
108119

109120
# Make sure that unequal comparison take the categories order in
110121
# account
@@ -163,16 +174,23 @@ def test_comparison_with_unknown_scalars(self):
163174
# for unequal comps, but not for equal/not equal
164175
cat = Categorical([1, 2, 3], ordered=True)
165176

166-
pytest.raises(TypeError, lambda: cat < 4)
167-
pytest.raises(TypeError, lambda: cat > 4)
168-
pytest.raises(TypeError, lambda: 4 < cat)
169-
pytest.raises(TypeError, lambda: 4 > cat)
177+
msg = ("Cannot compare a Categorical for op __{}__ with a scalar,"
178+
" which is not a category")
179+
with pytest.raises(TypeError, match=msg.format('lt')):
180+
cat < 4
181+
with pytest.raises(TypeError, match=msg.format('gt')):
182+
cat > 4
183+
with pytest.raises(TypeError, match=msg.format('gt')):
184+
4 < cat
185+
with pytest.raises(TypeError, match=msg.format('lt')):
186+
4 > cat
170187

171188
tm.assert_numpy_array_equal(cat == 4,
172189
np.array([False, False, False]))
173190
tm.assert_numpy_array_equal(cat != 4,
174191
np.array([True, True, True]))
175192

193+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
176194
@pytest.mark.parametrize('data,reverse,base', [
177195
(list("abc"), list("cba"), list("bbb")),
178196
([1, 2, 3], [3, 2, 1], [2, 2, 2])]
@@ -219,16 +237,26 @@ def test_comparisons(self, data, reverse, base):
219237

220238
# categorical cannot be compared to Series or numpy array, and also
221239
# not the other way around
222-
pytest.raises(TypeError, lambda: cat > s)
223-
pytest.raises(TypeError, lambda: cat_rev > s)
224-
pytest.raises(TypeError, lambda: cat > a)
225-
pytest.raises(TypeError, lambda: cat_rev > a)
240+
msg = ("Cannot compare a Categorical for op __gt__ with type"
241+
r" <class 'numpy\.ndarray'>")
242+
with pytest.raises(TypeError, match=msg):
243+
cat > s
244+
with pytest.raises(TypeError, match=msg):
245+
cat_rev > s
246+
with pytest.raises(TypeError, match=msg):
247+
cat > a
248+
with pytest.raises(TypeError, match=msg):
249+
cat_rev > a
226250

227-
pytest.raises(TypeError, lambda: s < cat)
228-
pytest.raises(TypeError, lambda: s < cat_rev)
251+
with pytest.raises(TypeError, match=msg):
252+
s < cat
253+
with pytest.raises(TypeError, match=msg):
254+
s < cat_rev
229255

230-
pytest.raises(TypeError, lambda: a < cat)
231-
pytest.raises(TypeError, lambda: a < cat_rev)
256+
with pytest.raises(TypeError, match=msg):
257+
a < cat
258+
with pytest.raises(TypeError, match=msg):
259+
a < cat_rev
232260

233261
@pytest.mark.parametrize('ctor', [
234262
lambda *args, **kwargs: Categorical(*args, **kwargs),
@@ -287,16 +315,21 @@ def test_numeric_like_ops(self):
287315
right=False, labels=cat_labels)
288316

289317
# numeric ops should not succeed
290-
for op in ['__add__', '__sub__', '__mul__', '__truediv__']:
291-
pytest.raises(TypeError,
292-
lambda: getattr(df, op)(df))
318+
for op, str_rep in [('__add__', r'\+'),
319+
('__sub__', '-'),
320+
('__mul__', r'\*'),
321+
('__truediv__', '/')]:
322+
msg = r"Series cannot perform the operation {}".format(str_rep)
323+
with pytest.raises(TypeError, match=msg):
324+
getattr(df, op)(df)
293325

294326
# reduction ops should not succeed (unless specifically defined, e.g.
295327
# min/max)
296328
s = df['value_group']
297329
for op in ['kurt', 'skew', 'var', 'std', 'mean', 'sum', 'median']:
298-
pytest.raises(TypeError,
299-
lambda: getattr(s, op)(numeric_only=False))
330+
msg = "Categorical cannot perform the operation {}".format(op)
331+
with pytest.raises(TypeError, match=msg):
332+
getattr(s, op)(numeric_only=False)
300333

301334
# mad technically works because it takes always the numeric data
302335

@@ -306,8 +339,13 @@ def test_numeric_like_ops(self):
306339
np.sum(s)
307340

308341
# numeric ops on a Series
309-
for op in ['__add__', '__sub__', '__mul__', '__truediv__']:
310-
pytest.raises(TypeError, lambda: getattr(s, op)(2))
342+
for op, str_rep in [('__add__', r'\+'),
343+
('__sub__', '-'),
344+
('__mul__', r'\*'),
345+
('__truediv__', '/')]:
346+
msg = r"Series cannot perform the operation {}".format(str_rep)
347+
with pytest.raises(TypeError, match=msg):
348+
getattr(s, op)(2)
311349

312350
# invalid ufunc
313351
with pytest.raises(TypeError):

pandas/tests/arrays/sparse/test_libsparse.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -449,11 +449,13 @@ def test_check_integrity(self):
449449
# also OK even though empty
450450
index = BlockIndex(1, locs, lengths) # noqa
451451

452-
# block extend beyond end
453-
pytest.raises(Exception, BlockIndex, 10, [5], [10])
452+
msg = "Block 0 extends beyond end"
453+
with pytest.raises(ValueError, match=msg):
454+
BlockIndex(10, [5], [10])
454455

455-
# block overlap
456-
pytest.raises(Exception, BlockIndex, 10, [2, 5], [5, 3])
456+
msg = "Block 0 overlaps"
457+
with pytest.raises(ValueError, match=msg):
458+
BlockIndex(10, [2, 5], [5, 3])
457459

458460
def test_to_int_index(self):
459461
locs = [0, 10]

0 commit comments

Comments
 (0)