Skip to content

Commit 145ade2

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (indexes/datetimes) (pandas-dev#24995)
1 parent dd16aa7 commit 145ade2

File tree

9 files changed

+151
-81
lines changed

9 files changed

+151
-81
lines changed

pandas/core/arrays/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2058,7 +2058,7 @@ def validate_tz_from_dtype(dtype, tz):
20582058
# tz-naive dtype (i.e. datetime64[ns])
20592059
if tz is not None and not timezones.tz_compare(tz, dtz):
20602060
raise ValueError("cannot supply both a tz and a "
2061-
"timezone-naive dtype (i.e. datetime64[ns]")
2061+
"timezone-naive dtype (i.e. datetime64[ns])")
20622062

20632063
return tz
20642064

pandas/tests/indexes/common.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,12 @@ def setup_indices(self):
3030

3131
def test_pickle_compat_construction(self):
3232
# need an object to create with
33-
pytest.raises(TypeError, self._holder)
33+
msg = (r"Index\(\.\.\.\) must be called with a collection of some"
34+
r" kind, None was passed|"
35+
r"__new__\(\) missing 1 required positional argument: 'data'|"
36+
r"__new__\(\) takes at least 2 arguments \(1 given\)")
37+
with pytest.raises(TypeError, match=msg):
38+
self._holder()
3439

3540
def test_to_series(self):
3641
# assert that we are creating a copy of the index
@@ -84,8 +89,11 @@ def test_shift(self):
8489

8590
# GH8083 test the base class for shift
8691
idx = self.create_index()
87-
pytest.raises(NotImplementedError, idx.shift, 1)
88-
pytest.raises(NotImplementedError, idx.shift, 1, 2)
92+
msg = "Not supported for type {}".format(type(idx).__name__)
93+
with pytest.raises(NotImplementedError, match=msg):
94+
idx.shift(1)
95+
with pytest.raises(NotImplementedError, match=msg):
96+
idx.shift(1, 2)
8997

9098
def test_create_index_existing_name(self):
9199

pandas/tests/indexes/datetimes/test_construction.py

+31-20
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,10 @@ def test_construction_with_alt_tz_localize(self, kwargs, tz_aware_fixture):
135135
tm.assert_index_equal(i2, expected)
136136

137137
# incompat tz/dtype
138-
pytest.raises(ValueError, lambda: DatetimeIndex(
139-
i.tz_localize(None).asi8, dtype=i.dtype, tz='US/Pacific'))
138+
msg = "cannot supply both a tz and a dtype with a tz"
139+
with pytest.raises(ValueError, match=msg):
140+
DatetimeIndex(i.tz_localize(None).asi8,
141+
dtype=i.dtype, tz='US/Pacific')
140142

141143
def test_construction_index_with_mixed_timezones(self):
142144
# gh-11488: no tz results in DatetimeIndex
@@ -439,14 +441,19 @@ def test_constructor_coverage(self):
439441
tm.assert_index_equal(from_ints, expected)
440442

441443
# non-conforming
442-
pytest.raises(ValueError, DatetimeIndex,
443-
['2000-01-01', '2000-01-02', '2000-01-04'], freq='D')
444+
msg = ("Inferred frequency None from passed values does not conform"
445+
" to passed frequency D")
446+
with pytest.raises(ValueError, match=msg):
447+
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04'], freq='D')
444448

445-
pytest.raises(ValueError, date_range, start='2011-01-01',
446-
freq='b')
447-
pytest.raises(ValueError, date_range, end='2011-01-01',
448-
freq='B')
449-
pytest.raises(ValueError, date_range, periods=10, freq='D')
449+
msg = ("Of the four parameters: start, end, periods, and freq, exactly"
450+
" three must be specified")
451+
with pytest.raises(ValueError, match=msg):
452+
date_range(start='2011-01-01', freq='b')
453+
with pytest.raises(ValueError, match=msg):
454+
date_range(end='2011-01-01', freq='B')
455+
with pytest.raises(ValueError, match=msg):
456+
date_range(periods=10, freq='D')
450457

451458
@pytest.mark.parametrize('freq', ['AS', 'W-SUN'])
452459
def test_constructor_datetime64_tzformat(self, freq):
@@ -511,18 +518,20 @@ def test_constructor_dtype(self):
511518
idx = DatetimeIndex(['2013-01-01', '2013-01-02'],
512519
dtype='datetime64[ns, US/Eastern]')
513520

514-
pytest.raises(ValueError,
515-
lambda: DatetimeIndex(idx,
516-
dtype='datetime64[ns]'))
521+
msg = ("cannot supply both a tz and a timezone-naive dtype"
522+
r" \(i\.e\. datetime64\[ns\]\)")
523+
with pytest.raises(ValueError, match=msg):
524+
DatetimeIndex(idx, dtype='datetime64[ns]')
517525

518526
# this is effectively trying to convert tz's
519-
pytest.raises(TypeError,
520-
lambda: DatetimeIndex(idx,
521-
dtype='datetime64[ns, CET]'))
522-
pytest.raises(ValueError,
523-
lambda: DatetimeIndex(
524-
idx, tz='CET',
525-
dtype='datetime64[ns, US/Eastern]'))
527+
msg = ("data is already tz-aware US/Eastern, unable to set specified"
528+
" tz: CET")
529+
with pytest.raises(TypeError, match=msg):
530+
DatetimeIndex(idx, dtype='datetime64[ns, CET]')
531+
msg = "cannot supply both a tz and a dtype with a tz"
532+
with pytest.raises(ValueError, match=msg):
533+
DatetimeIndex(idx, tz='CET', dtype='datetime64[ns, US/Eastern]')
534+
526535
result = DatetimeIndex(idx, dtype='datetime64[ns, US/Eastern]')
527536
tm.assert_index_equal(idx, result)
528537

@@ -732,7 +741,9 @@ def test_from_freq_recreate_from_data(self, freq):
732741

733742
def test_datetimeindex_constructor_misc(self):
734743
arr = ['1/1/2005', '1/2/2005', 'Jn 3, 2005', '2005-01-04']
735-
pytest.raises(Exception, DatetimeIndex, arr)
744+
msg = r"(\(u?')?Unknown string format(:', 'Jn 3, 2005'\))?"
745+
with pytest.raises(ValueError, match=msg):
746+
DatetimeIndex(arr)
736747

737748
arr = ['1/1/2005', '1/2/2005', '1/3/2005', '2005-01-04']
738749
idx1 = DatetimeIndex(arr)

pandas/tests/indexes/datetimes/test_date_range.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -346,8 +346,10 @@ def test_compat_replace(self, f):
346346
def test_catch_infinite_loop(self):
347347
offset = offsets.DateOffset(minute=5)
348348
# blow up, don't loop forever
349-
pytest.raises(Exception, date_range, datetime(2011, 11, 11),
350-
datetime(2011, 11, 12), freq=offset)
349+
msg = "Offset <DateOffset: minute=5> did not increment date"
350+
with pytest.raises(ValueError, match=msg):
351+
date_range(datetime(2011, 11, 11), datetime(2011, 11, 12),
352+
freq=offset)
351353

352354
@pytest.mark.parametrize('periods', (1, 2))
353355
def test_wom_len(self, periods):

pandas/tests/indexes/datetimes/test_misc.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,9 @@ def test_datetimeindex_accessors(self):
190190
# Ensure is_start/end accessors throw ValueError for CustomBusinessDay,
191191
bday_egypt = offsets.CustomBusinessDay(weekmask='Sun Mon Tue Wed Thu')
192192
dti = date_range(datetime(2013, 4, 30), periods=5, freq=bday_egypt)
193-
pytest.raises(ValueError, lambda: dti.is_month_start)
193+
msg = "Custom business days is not supported by is_month_start"
194+
with pytest.raises(ValueError, match=msg):
195+
dti.is_month_start
194196

195197
dti = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'])
196198

pandas/tests/indexes/datetimes/test_ops.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,19 @@ def test_ops_properties_basic(self):
3737

3838
# sanity check that the behavior didn't change
3939
# GH#7206
40+
msg = "'Series' object has no attribute '{}'"
4041
for op in ['year', 'day', 'second', 'weekday']:
41-
pytest.raises(TypeError, lambda x: getattr(self.dt_series, op))
42+
with pytest.raises(AttributeError, match=msg.format(op)):
43+
getattr(self.dt_series, op)
4244

4345
# attribute access should still work!
4446
s = Series(dict(year=2000, month=1, day=10))
4547
assert s.year == 2000
4648
assert s.month == 1
4749
assert s.day == 10
48-
pytest.raises(AttributeError, lambda: s.weekday)
50+
msg = "'Series' object has no attribute 'weekday'"
51+
with pytest.raises(AttributeError, match=msg):
52+
s.weekday
4953

5054
def test_repeat_range(self, tz_naive_fixture):
5155
tz = tz_naive_fixture

pandas/tests/indexes/datetimes/test_partial_slicing.py

+21-11
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,8 @@ def test_partial_slice(self):
170170
result = s['2005-1-1']
171171
assert result == s.iloc[0]
172172

173-
pytest.raises(Exception, s.__getitem__, '2004-12-31')
173+
with pytest.raises(KeyError, match=r"^'2004-12-31'$"):
174+
s['2004-12-31']
174175

175176
def test_partial_slice_daily(self):
176177
rng = date_range(freq='H', start=datetime(2005, 1, 31), periods=500)
@@ -179,7 +180,8 @@ def test_partial_slice_daily(self):
179180
result = s['2005-1-31']
180181
tm.assert_series_equal(result, s.iloc[:24])
181182

182-
pytest.raises(Exception, s.__getitem__, '2004-12-31 00')
183+
with pytest.raises(KeyError, match=r"^'2004-12-31 00'$"):
184+
s['2004-12-31 00']
183185

184186
def test_partial_slice_hourly(self):
185187
rng = date_range(freq='T', start=datetime(2005, 1, 1, 20, 0, 0),
@@ -193,7 +195,8 @@ def test_partial_slice_hourly(self):
193195
tm.assert_series_equal(result, s.iloc[:60])
194196

195197
assert s['2005-1-1 20:00'] == s.iloc[0]
196-
pytest.raises(Exception, s.__getitem__, '2004-12-31 00:15')
198+
with pytest.raises(KeyError, match=r"^'2004-12-31 00:15'$"):
199+
s['2004-12-31 00:15']
197200

198201
def test_partial_slice_minutely(self):
199202
rng = date_range(freq='S', start=datetime(2005, 1, 1, 23, 59, 0),
@@ -207,7 +210,8 @@ def test_partial_slice_minutely(self):
207210
tm.assert_series_equal(result, s.iloc[:60])
208211

209212
assert s[Timestamp('2005-1-1 23:59:00')] == s.iloc[0]
210-
pytest.raises(Exception, s.__getitem__, '2004-12-31 00:00:00')
213+
with pytest.raises(KeyError, match=r"^'2004-12-31 00:00:00'$"):
214+
s['2004-12-31 00:00:00']
211215

212216
def test_partial_slice_second_precision(self):
213217
rng = date_range(start=datetime(2005, 1, 1, 0, 0, 59,
@@ -255,7 +259,9 @@ def test_partial_slicing_dataframe(self):
255259
result = df['a'][ts_string]
256260
assert isinstance(result, np.int64)
257261
assert result == expected
258-
pytest.raises(KeyError, df.__getitem__, ts_string)
262+
msg = r"^'{}'$".format(ts_string)
263+
with pytest.raises(KeyError, match=msg):
264+
df[ts_string]
259265

260266
# Timestamp with resolution less precise than index
261267
for fmt in formats[:rnum]:
@@ -282,15 +288,20 @@ def test_partial_slicing_dataframe(self):
282288
result = df['a'][ts_string]
283289
assert isinstance(result, np.int64)
284290
assert result == 2
285-
pytest.raises(KeyError, df.__getitem__, ts_string)
291+
msg = r"^'{}'$".format(ts_string)
292+
with pytest.raises(KeyError, match=msg):
293+
df[ts_string]
286294

287295
# Not compatible with existing key
288296
# Should raise KeyError
289297
for fmt, res in list(zip(formats, resolutions))[rnum + 1:]:
290298
ts = index[1] + Timedelta("1 " + res)
291299
ts_string = ts.strftime(fmt)
292-
pytest.raises(KeyError, df['a'].__getitem__, ts_string)
293-
pytest.raises(KeyError, df.__getitem__, ts_string)
300+
msg = r"^'{}'$".format(ts_string)
301+
with pytest.raises(KeyError, match=msg):
302+
df['a'][ts_string]
303+
with pytest.raises(KeyError, match=msg):
304+
df[ts_string]
294305

295306
def test_partial_slicing_with_multiindex(self):
296307

@@ -316,11 +327,10 @@ def test_partial_slicing_with_multiindex(self):
316327

317328
# this is an IndexingError as we don't do partial string selection on
318329
# multi-levels.
319-
def f():
330+
msg = "Too many indexers"
331+
with pytest.raises(IndexingError, match=msg):
320332
df_multi.loc[('2013-06-19', 'ACCT1', 'ABC')]
321333

322-
pytest.raises(IndexingError, f)
323-
324334
# GH 4294
325335
# partial slice on a series mi
326336
s = pd.DataFrame(np.random.rand(1000, 1000), index=pd.date_range(

pandas/tests/indexes/datetimes/test_scalar_compat.py

+18-6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import numpy as np
88
import pytest
99

10+
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
11+
1012
import pandas as pd
1113
from pandas import DatetimeIndex, Timestamp, date_range
1214
import pandas.util.testing as tm
@@ -27,10 +29,14 @@ def test_dti_date(self):
2729
expected = [t.date() for t in rng]
2830
assert (result == expected).all()
2931

30-
def test_dti_date_out_of_range(self):
32+
@pytest.mark.parametrize('data', [
33+
['1400-01-01'],
34+
[datetime(1400, 1, 1)]])
35+
def test_dti_date_out_of_range(self, data):
3136
# GH#1475
32-
pytest.raises(ValueError, DatetimeIndex, ['1400-01-01'])
33-
pytest.raises(ValueError, DatetimeIndex, [datetime(1400, 1, 1)])
37+
msg = "Out of bounds nanosecond timestamp: 1400-01-01 00:00:00"
38+
with pytest.raises(OutOfBoundsDatetime, match=msg):
39+
DatetimeIndex(data)
3440

3541
@pytest.mark.parametrize('field', [
3642
'dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter',
@@ -74,9 +80,15 @@ def test_round_daily(self):
7480
result = dti.round('s')
7581
tm.assert_index_equal(result, dti)
7682

77-
# invalid
78-
for freq in ['Y', 'M', 'foobar']:
79-
pytest.raises(ValueError, lambda: dti.round(freq))
83+
@pytest.mark.parametrize('freq, error_msg', [
84+
('Y', '<YearEnd: month=12> is a non-fixed frequency'),
85+
('M', '<MonthEnd> is a non-fixed frequency'),
86+
('foobar', 'Invalid frequency: foobar')])
87+
def test_round_invalid(self, freq, error_msg):
88+
dti = date_range('20130101 09:10:11', periods=5)
89+
dti = dti.tz_localize('UTC').tz_convert('US/Eastern')
90+
with pytest.raises(ValueError, match=error_msg):
91+
dti.round(freq)
8092

8193
def test_round(self, tz_naive_fixture):
8294
tz = tz_naive_fixture

0 commit comments

Comments
 (0)