Skip to content

Commit be26f6d

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context syntax (series) (#24812)
1 parent 17a6bc5 commit be26f6d

12 files changed

+263
-120
lines changed

pandas/tests/series/test_alter_axes.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,16 @@ class TestSeriesAlterAxes(object):
1616

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

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

2530
# works
2631
string_series.index = np.arange(len(string_series))

pandas/tests/series/test_analytics.py

+44-18
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,10 @@ def test_argsort_stable(self):
9797
check_dtype=False)
9898
tm.assert_series_equal(qindexer, Series(qexpected),
9999
check_dtype=False)
100-
pytest.raises(AssertionError, tm.assert_numpy_array_equal,
101-
qindexer, mindexer)
100+
msg = (r"ndarray Expected type <(class|type) 'numpy\.ndarray'>,"
101+
r" found <class 'pandas\.core\.series\.Series'> instead")
102+
with pytest.raises(AssertionError, match=msg):
103+
tm.assert_numpy_array_equal(qindexer, mindexer)
102104

103105
def test_cumsum(self, datetime_series):
104106
self._check_accum_op('cumsum', datetime_series)
@@ -476,8 +478,13 @@ def test_dot(self):
476478
assert_almost_equal(a.dot(b['1']), expected['1'])
477479
assert_almost_equal(a.dot(b2['1']), expected['1'])
478480

479-
pytest.raises(Exception, a.dot, a.values[:3])
480-
pytest.raises(ValueError, a.dot, b.T)
481+
msg = r"Dot product shape mismatch, \(4L?,\) vs \(3L?,\)"
482+
# exception raised is of type Exception
483+
with pytest.raises(Exception, match=msg):
484+
a.dot(a.values[:3])
485+
msg = "matrices are not aligned"
486+
with pytest.raises(ValueError, match=msg):
487+
a.dot(b.T)
481488

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

544-
pytest.raises(Exception, a.dot, a.values[:3])
545-
pytest.raises(ValueError, a.dot, b.T)
551+
msg = r"Dot product shape mismatch, \(4,\) vs \(3,\)"
552+
# exception raised is of type Exception
553+
with pytest.raises(Exception, match=msg):
554+
a.dot(a.values[:3])
555+
msg = "matrices are not aligned"
556+
with pytest.raises(ValueError, match=msg):
557+
a.dot(b.T)
546558

547559
def test_clip(self, datetime_series):
548560
val = datetime_series.median()
@@ -697,11 +709,13 @@ def test_isin(self):
697709
def test_isin_with_string_scalar(self):
698710
# GH4763
699711
s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C'])
700-
with pytest.raises(TypeError):
712+
msg = (r"only list-like objects are allowed to be passed to isin\(\),"
713+
r" you passed a \[str\]")
714+
with pytest.raises(TypeError, match=msg):
701715
s.isin('a')
702716

703-
with pytest.raises(TypeError):
704-
s = Series(['aaa', 'b', 'c'])
717+
s = Series(['aaa', 'b', 'c'])
718+
with pytest.raises(TypeError, match=msg):
705719
s.isin('aaa')
706720

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

774-
with pytest.raises(ValueError):
788+
msg = r"No axis named 1 for object type <(class|type) 'type'>"
789+
with pytest.raises(ValueError, match=msg):
775790
with tm.assert_produces_warning(FutureWarning,
776791
check_stacklevel=False):
777792
s.ptp(axis=1)
778793

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

785-
with pytest.raises(NotImplementedError):
801+
msg = r"Series\.ptp does not implement numeric_only\."
802+
with pytest.raises(NotImplementedError, match=msg):
786803
with tm.assert_produces_warning(FutureWarning,
787804
check_stacklevel=False):
788805
s.ptp(numeric_only=True)
@@ -1103,29 +1120,38 @@ def test_validate_any_all_out_keepdims_raises(self, kwargs, func):
11031120
param = list(kwargs)[0]
11041121
name = func.__name__
11051122

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

11101129
@td.skip_if_np_lt_115
11111130
def test_validate_sum_initial(self):
11121131
s = pd.Series([1, 2])
1113-
with pytest.raises(ValueError, match="the 'initial' .* sum"):
1132+
msg = (r"the 'initial' parameter is not "
1133+
r"supported in the pandas "
1134+
r"implementation of sum\(\)")
1135+
with pytest.raises(ValueError, match=msg):
11141136
np.sum(s, initial=10)
11151137

11161138
def test_validate_median_initial(self):
11171139
s = pd.Series([1, 2])
1118-
with pytest.raises(ValueError,
1119-
match="the 'overwrite_input' .* median"):
1140+
msg = (r"the 'overwrite_input' parameter is not "
1141+
r"supported in the pandas "
1142+
r"implementation of median\(\)")
1143+
with pytest.raises(ValueError, match=msg):
11201144
# It seems like np.median doesn't dispatch, so we use the
11211145
# method instead of the ufunc.
11221146
s.median(overwrite_input=True)
11231147

11241148
@td.skip_if_np_lt_115
11251149
def test_validate_stat_keepdims(self):
11261150
s = pd.Series([1, 2])
1127-
with pytest.raises(ValueError,
1128-
match="the 'keepdims'"):
1151+
msg = (r"the 'keepdims' parameter is not "
1152+
r"supported in the pandas "
1153+
r"implementation of sum\(\)")
1154+
with pytest.raises(ValueError, match=msg):
11291155
np.sum(s, keepdims=True)
11301156

11311157

pandas/tests/series/test_api.py

+19-13
Original file line numberDiff line numberDiff line change
@@ -289,8 +289,11 @@ def test_index_tab_completion(self, index):
289289
def test_not_hashable(self):
290290
s_empty = Series()
291291
s = Series([1])
292-
pytest.raises(TypeError, hash, s_empty)
293-
pytest.raises(TypeError, hash, s)
292+
msg = "'Series' objects are mutable, thus they cannot be hashed"
293+
with pytest.raises(TypeError, match=msg):
294+
hash(s_empty)
295+
with pytest.raises(TypeError, match=msg):
296+
hash(s)
294297

295298
def test_contains(self):
296299
tm.assert_contains_all(self.ts.index, self.ts)
@@ -333,7 +336,8 @@ def test_items(self):
333336

334337
def test_raise_on_info(self):
335338
s = Series(np.random.randn(10))
336-
with pytest.raises(AttributeError):
339+
msg = "'Series' object has no attribute 'info'"
340+
with pytest.raises(AttributeError, match=msg):
337341
s.info()
338342

339343
def test_copy(self):
@@ -555,15 +559,17 @@ def test_cat_accessor_updates_on_inplace(self):
555559
def test_categorical_delegations(self):
556560

557561
# invalid accessor
558-
pytest.raises(AttributeError, lambda: Series([1, 2, 3]).cat)
559-
with pytest.raises(AttributeError,
560-
match=(r"Can only use .cat accessor "
561-
r"with a 'category' dtype")):
562+
msg = r"Can only use \.cat accessor with a 'category' dtype"
563+
with pytest.raises(AttributeError, match=msg):
564+
Series([1, 2, 3]).cat
565+
with pytest.raises(AttributeError, match=msg):
562566
Series([1, 2, 3]).cat()
563-
pytest.raises(AttributeError, lambda: Series(['a', 'b', 'c']).cat)
564-
pytest.raises(AttributeError, lambda: Series(np.arange(5.)).cat)
565-
pytest.raises(AttributeError,
566-
lambda: Series([Timestamp('20130101')]).cat)
567+
with pytest.raises(AttributeError, match=msg):
568+
Series(['a', 'b', 'c']).cat
569+
with pytest.raises(AttributeError, match=msg):
570+
Series(np.arange(5.)).cat
571+
with pytest.raises(AttributeError, match=msg):
572+
Series([Timestamp('20130101')]).cat
567573

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

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

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

614620
# GH18862 (let Series.cat.rename_categories take callables)

pandas/tests/series/test_combine_concat.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@ def test_append(self, datetime_series, string_series, object_series):
2525
else:
2626
raise AssertionError("orphaned index!")
2727

28-
pytest.raises(ValueError, datetime_series.append, datetime_series,
29-
verify_integrity=True)
28+
msg = "Indexes have overlapping values:"
29+
with pytest.raises(ValueError, match=msg):
30+
datetime_series.append(datetime_series, verify_integrity=True)
3031

3132
def test_append_many(self, datetime_series):
3233
pieces = [datetime_series[:5], datetime_series[5:10],

pandas/tests/series/test_constructors.py

+32-13
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,10 @@ def test_constructor(self, datetime_series, empty_series):
6565

6666
assert not empty_series.index.is_all_dates
6767
assert not Series({}).index.is_all_dates
68-
pytest.raises(Exception, Series, np.random.randn(3, 3),
69-
index=np.arange(3))
68+
69+
# exception raised is of type Exception
70+
with pytest.raises(Exception, match="Data must be 1-dimensional"):
71+
Series(np.random.randn(3, 3), index=np.arange(3))
7072

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

7678
# raise on MultiIndex GH4187
7779
m = MultiIndex.from_arrays([[1, 2], [3, 4]])
78-
pytest.raises(NotImplementedError, Series, m)
80+
msg = "initializing a Series from a MultiIndex is not supported"
81+
with pytest.raises(NotImplementedError, match=msg):
82+
Series(m)
7983

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

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

677683
# GH3414 related
684+
# msg = (r"cannot astype a datetimelike from \[datetime64\[ns\]\] to"
685+
# r" \[int32\]")
686+
# with pytest.raises(TypeError, match=msg):
687+
# Series(Series(dates).astype('int') / 1000000, dtype='M8[ms]')
678688
pytest.raises(TypeError, lambda x: Series(
679689
Series(dates).astype('int') / 1000000, dtype='M8[ms]'))
680-
pytest.raises(TypeError,
681-
lambda x: Series(dates, dtype='datetime64'))
690+
691+
msg = (r"The 'datetime64' dtype has no unit\. Please pass in"
692+
r" 'datetime64\[ns\]' instead\.")
693+
with pytest.raises(ValueError, match=msg):
694+
Series(dates, dtype='datetime64')
682695

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

985998
def test_constructor_set(self):
986999
values = {1, 2, 3, 4, 5}
987-
pytest.raises(TypeError, Series, values)
1000+
with pytest.raises(TypeError, match="'set' type is unordered"):
1001+
Series(values)
9881002
values = frozenset(values)
989-
pytest.raises(TypeError, Series, values)
1003+
with pytest.raises(TypeError, match="'frozenset' type is unordered"):
1004+
Series(values)
9901005

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

10831098
# invalid casting
1084-
pytest.raises(TypeError, td.astype, 'int32')
1099+
msg = (r"cannot astype a timedelta from \[timedelta64\[ns\]\] to"
1100+
r" \[int32\]")
1101+
with pytest.raises(TypeError, match=msg):
1102+
td.astype('int32')
10851103

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

1090-
pytest.raises(Exception, f)
1091-
10921109
# leave as object here
10931110
td = Series([timedelta(days=i) for i in range(3)] + ['foo'])
10941111
assert td.dtype == 'object'
@@ -1134,9 +1151,11 @@ def test_constructor_name_hashable(self):
11341151
assert s.name == n
11351152

11361153
def test_constructor_name_unhashable(self):
1154+
msg = r"Series\.name must be a hashable type"
11371155
for n in [['name_list'], np.ones(2), {1: 2}]:
11381156
for data in [['name_list'], np.ones(2), {1: 2}]:
1139-
pytest.raises(TypeError, Series, data, name=n)
1157+
with pytest.raises(TypeError, match=msg):
1158+
Series(data, name=n)
11401159

11411160
def test_auto_conversion(self):
11421161
series = Series(list(date_range('1/1/2000', periods=10)))

0 commit comments

Comments
 (0)