Skip to content

Commit 5c901de

Browse files
authored
fix bare pytest raises in indexes/datetimes (#32884)
1 parent 3681157 commit 5c901de

File tree

5 files changed

+65
-42
lines changed

5 files changed

+65
-42
lines changed

pandas/tests/indexes/datetimes/test_constructors.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,8 @@ def test_construction_dti_with_mixed_timezones(self):
415415

416416
# tz mismatch affecting to tz-aware raises TypeError/ValueError
417417

418-
with pytest.raises(ValueError):
418+
msg = "cannot be converted to datetime64"
419+
with pytest.raises(ValueError, match=msg):
419420
DatetimeIndex(
420421
[
421422
Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"),
@@ -424,7 +425,6 @@ def test_construction_dti_with_mixed_timezones(self):
424425
name="idx",
425426
)
426427

427-
msg = "cannot be converted to datetime64"
428428
with pytest.raises(ValueError, match=msg):
429429
DatetimeIndex(
430430
[
@@ -435,7 +435,7 @@ def test_construction_dti_with_mixed_timezones(self):
435435
name="idx",
436436
)
437437

438-
with pytest.raises(ValueError):
438+
with pytest.raises(ValueError, match=msg):
439439
DatetimeIndex(
440440
[
441441
Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"),
@@ -480,7 +480,8 @@ def test_construction_outofbounds(self):
480480
# coerces to object
481481
tm.assert_index_equal(Index(dates), exp)
482482

483-
with pytest.raises(OutOfBoundsDatetime):
483+
msg = "Out of bounds nanosecond timestamp"
484+
with pytest.raises(OutOfBoundsDatetime, match=msg):
484485
# can't create DatetimeIndex
485486
DatetimeIndex(dates)
486487

@@ -516,7 +517,8 @@ def test_constructor_coverage(self):
516517
with pytest.raises(TypeError, match=msg):
517518
date_range(start="1/1/2000", periods="foo", freq="D")
518519

519-
with pytest.raises(TypeError):
520+
msg = "DatetimeIndex\\(\\) must be called with a collection"
521+
with pytest.raises(TypeError, match=msg):
520522
DatetimeIndex("1/1/2000")
521523

522524
# generator expression
@@ -664,7 +666,8 @@ def test_constructor_dtype(self):
664666
@pytest.mark.parametrize("dtype", [object, np.int32, np.int64])
665667
def test_constructor_invalid_dtype_raises(self, dtype):
666668
# GH 23986
667-
with pytest.raises(ValueError):
669+
msg = "Unexpected value for 'dtype'"
670+
with pytest.raises(ValueError, match=msg):
668671
DatetimeIndex([1, 2], dtype=dtype)
669672

670673
def test_constructor_name(self):
@@ -681,7 +684,8 @@ def test_000constructor_resolution(self):
681684
def test_disallow_setting_tz(self):
682685
# GH 3746
683686
dti = DatetimeIndex(["2010"], tz="UTC")
684-
with pytest.raises(AttributeError):
687+
msg = "Cannot directly set timezone"
688+
with pytest.raises(AttributeError, match=msg):
685689
dti.tz = pytz.timezone("US/Pacific")
686690

687691
@pytest.mark.parametrize(
@@ -770,7 +774,8 @@ def test_construction_from_replaced_timestamps_with_dst(self):
770774
def test_construction_with_tz_and_tz_aware_dti(self):
771775
# GH 23579
772776
dti = date_range("2016-01-01", periods=3, tz="US/Central")
773-
with pytest.raises(TypeError):
777+
msg = "data is already tz-aware US/Central, unable to set specified tz"
778+
with pytest.raises(TypeError, match=msg):
774779
DatetimeIndex(dti, tz="Asia/Tokyo")
775780

776781
def test_construction_with_nat_and_tzlocal(self):
@@ -790,7 +795,8 @@ def test_constructor_no_precision_raises(self):
790795
pd.Index(["2000"], dtype="datetime64")
791796

792797
def test_constructor_wrong_precision_raises(self):
793-
with pytest.raises(ValueError):
798+
msg = "Unexpected value for 'dtype': 'datetime64\\[us\\]'"
799+
with pytest.raises(ValueError, match=msg):
794800
pd.DatetimeIndex(["2000"], dtype="datetime64[us]")
795801

796802
def test_index_constructor_with_numpy_object_array_and_timestamp_tz_with_nan(self):

pandas/tests/indexes/datetimes/test_date_range.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,10 @@ def test_date_range_int64_overflow_stride_endpoint_different_signs(self):
153153

154154
def test_date_range_out_of_bounds(self):
155155
# GH#14187
156-
with pytest.raises(OutOfBoundsDatetime):
156+
msg = "Cannot generate range"
157+
with pytest.raises(OutOfBoundsDatetime, match=msg):
157158
date_range("2016-01-01", periods=100000, freq="D")
158-
with pytest.raises(OutOfBoundsDatetime):
159+
with pytest.raises(OutOfBoundsDatetime, match=msg):
159160
date_range(end="1763-10-12", periods=100000, freq="D")
160161

161162
def test_date_range_gen_error(self):
@@ -736,9 +737,10 @@ def test_precision_finer_than_offset(self):
736737
)
737738
def test_mismatching_tz_raises_err(self, start, end):
738739
# issue 18488
739-
with pytest.raises(TypeError):
740+
msg = "Start and end cannot both be tz-aware with different timezones"
741+
with pytest.raises(TypeError, match=msg):
740742
pd.date_range(start, end)
741-
with pytest.raises(TypeError):
743+
with pytest.raises(TypeError, match=msg):
742744
pd.date_range(start, end, freq=BDay())
743745

744746

@@ -771,16 +773,17 @@ def test_misc(self):
771773
def test_date_parse_failure(self):
772774
badly_formed_date = "2007/100/1"
773775

774-
with pytest.raises(ValueError):
776+
msg = "could not convert string to Timestamp"
777+
with pytest.raises(ValueError, match=msg):
775778
Timestamp(badly_formed_date)
776779

777-
with pytest.raises(ValueError):
780+
with pytest.raises(ValueError, match=msg):
778781
bdate_range(start=badly_formed_date, periods=10)
779782

780-
with pytest.raises(ValueError):
783+
with pytest.raises(ValueError, match=msg):
781784
bdate_range(end=badly_formed_date, periods=10)
782785

783-
with pytest.raises(ValueError):
786+
with pytest.raises(ValueError, match=msg):
784787
bdate_range(badly_formed_date, badly_formed_date)
785788

786789
def test_daterange_bug_456(self):
@@ -813,8 +816,9 @@ def test_bday_near_overflow(self):
813816

814817
def test_bday_overflow_error(self):
815818
# GH#24252 check that we get OutOfBoundsDatetime and not OverflowError
819+
msg = "Out of bounds nanosecond timestamp"
816820
start = pd.Timestamp.max.floor("D").to_pydatetime()
817-
with pytest.raises(OutOfBoundsDatetime):
821+
with pytest.raises(OutOfBoundsDatetime, match=msg):
818822
pd.date_range(start, periods=2, freq="B")
819823

820824

pandas/tests/indexes/datetimes/test_indexing.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,8 @@ def test_take_fill_value(self):
312312
with pytest.raises(ValueError, match=msg):
313313
idx.take(np.array([1, 0, -5]), fill_value=True)
314314

315-
with pytest.raises(IndexError):
315+
msg = "out of bounds"
316+
with pytest.raises(IndexError, match=msg):
316317
idx.take(np.array([1, -5]))
317318

318319
def test_take_fill_value_with_timezone(self):
@@ -348,7 +349,8 @@ def test_take_fill_value_with_timezone(self):
348349
with pytest.raises(ValueError, match=msg):
349350
idx.take(np.array([1, 0, -5]), fill_value=True)
350351

351-
with pytest.raises(IndexError):
352+
msg = "out of bounds"
353+
with pytest.raises(IndexError, match=msg):
352354
idx.take(np.array([1, -5]))
353355

354356

@@ -428,7 +430,8 @@ def test_get_loc(self):
428430
tm.assert_numpy_array_equal(
429431
idx.get_loc(time(12, 30)), np.array([]), check_dtype=False
430432
)
431-
with pytest.raises(NotImplementedError):
433+
msg = "cannot yet lookup inexact labels when key is a time object"
434+
with pytest.raises(NotImplementedError, match=msg):
432435
idx.get_loc(time(12, 30), method="pad")
433436

434437
def test_get_loc_tz_aware(self):
@@ -462,7 +465,8 @@ def test_get_loc_nat(self):
462465
def test_get_loc_timedelta_invalid_key(self, key):
463466
# GH#20464
464467
dti = pd.date_range("1970-01-01", periods=10)
465-
with pytest.raises(TypeError):
468+
msg = "Cannot index DatetimeIndex with [Tt]imedelta"
469+
with pytest.raises(TypeError, match=msg):
466470
dti.get_loc(key)
467471

468472
def test_get_loc_reasonable_key_error(self):
@@ -571,9 +575,9 @@ def test_insert(self):
571575
idx.insert(3, pd.Timestamp("2000-01-04"))
572576
with pytest.raises(TypeError, match="Cannot compare tz-naive and tz-aware"):
573577
idx.insert(3, datetime(2000, 1, 4))
574-
with pytest.raises(ValueError):
578+
with pytest.raises(ValueError, match="Timezones don't match"):
575579
idx.insert(3, pd.Timestamp("2000-01-04", tz="US/Eastern"))
576-
with pytest.raises(ValueError):
580+
with pytest.raises(ValueError, match="Timezones don't match"):
577581
idx.insert(3, datetime(2000, 1, 4, tzinfo=pytz.timezone("US/Eastern")))
578582

579583
for tz in ["US/Pacific", "Asia/Singapore"]:
@@ -645,7 +649,7 @@ def test_delete(self):
645649
assert result.name == expected.name
646650
assert result.freq == expected.freq
647651

648-
with pytest.raises((IndexError, ValueError)):
652+
with pytest.raises((IndexError, ValueError), match="out of bounds"):
649653
# either depending on numpy version
650654
idx.delete(5)
651655

@@ -804,5 +808,5 @@ def test_get_indexer(self):
804808
]
805809
with pytest.raises(ValueError, match="abbreviation w/o a number"):
806810
idx.get_indexer(target, "nearest", tolerance=tol_bad)
807-
with pytest.raises(ValueError):
811+
with pytest.raises(ValueError, match="abbreviation w/o a number"):
808812
idx.get_indexer(idx[[0]], method="nearest", tolerance="foo")

pandas/tests/indexes/datetimes/test_shift.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def test_dti_shift_int(self):
8080
def test_dti_shift_no_freq(self):
8181
# GH#19147
8282
dti = pd.DatetimeIndex(["2011-01-01 10:00", "2011-01-01"], freq=None)
83-
with pytest.raises(NullFrequencyError):
83+
with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"):
8484
dti.shift(2)
8585

8686
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])

pandas/tests/indexes/datetimes/test_timezones.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -319,10 +319,10 @@ def test_dti_tz_localize_nonexistent_raise_coerce(self):
319319
times = ["2015-03-08 01:00", "2015-03-08 02:00", "2015-03-08 03:00"]
320320
index = DatetimeIndex(times)
321321
tz = "US/Eastern"
322-
with pytest.raises(pytz.NonExistentTimeError):
322+
with pytest.raises(pytz.NonExistentTimeError, match="|".join(times)):
323323
index.tz_localize(tz=tz)
324324

325-
with pytest.raises(pytz.NonExistentTimeError):
325+
with pytest.raises(pytz.NonExistentTimeError, match="|".join(times)):
326326
index.tz_localize(tz=tz, nonexistent="raise")
327327

328328
result = index.tz_localize(tz=tz, nonexistent="NaT")
@@ -336,7 +336,7 @@ def test_dti_tz_localize_ambiguous_infer(self, tz):
336336
# November 6, 2011, fall back, repeat 2 AM hour
337337
# With no repeated hours, we cannot infer the transition
338338
dr = date_range(datetime(2011, 11, 6, 0), periods=5, freq=pd.offsets.Hour())
339-
with pytest.raises(pytz.AmbiguousTimeError):
339+
with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):
340340
dr.tz_localize(tz)
341341

342342
# With repeated hours, we can infer the transition
@@ -365,7 +365,7 @@ def test_dti_tz_localize_ambiguous_infer(self, tz):
365365
def test_dti_tz_localize_ambiguous_times(self, tz):
366366
# March 13, 2011, spring forward, skip from 2 AM to 3 AM
367367
dr = date_range(datetime(2011, 3, 13, 1, 30), periods=3, freq=pd.offsets.Hour())
368-
with pytest.raises(pytz.NonExistentTimeError):
368+
with pytest.raises(pytz.NonExistentTimeError, match="2011-03-13 02:30:00"):
369369
dr.tz_localize(tz)
370370

371371
# after dst transition, it works
@@ -375,7 +375,7 @@ def test_dti_tz_localize_ambiguous_times(self, tz):
375375

376376
# November 6, 2011, fall back, repeat 2 AM hour
377377
dr = date_range(datetime(2011, 11, 6, 1, 30), periods=3, freq=pd.offsets.Hour())
378-
with pytest.raises(pytz.AmbiguousTimeError):
378+
with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):
379379
dr.tz_localize(tz)
380380

381381
# UTC is OK
@@ -411,11 +411,11 @@ def test_dti_tz_localize(self, prefix):
411411
tm.assert_numpy_array_equal(dti3.values, dti_utc.values)
412412

413413
dti = pd.date_range(start="11/6/2011 1:59", end="11/6/2011 2:00", freq="L")
414-
with pytest.raises(pytz.AmbiguousTimeError):
414+
with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):
415415
dti.tz_localize(tzstr)
416416

417417
dti = pd.date_range(start="3/13/2011 1:59", end="3/13/2011 2:00", freq="L")
418-
with pytest.raises(pytz.NonExistentTimeError):
418+
with pytest.raises(pytz.NonExistentTimeError, match="2011-03-13 02:00:00"):
419419
dti.tz_localize(tzstr)
420420

421421
@pytest.mark.parametrize(
@@ -441,7 +441,7 @@ def test_dti_tz_localize_utc_conversion(self, tz):
441441
# DST ambiguity, this should fail
442442
rng = date_range("3/11/2012", "3/12/2012", freq="30T")
443443
# Is this really how it should fail??
444-
with pytest.raises(pytz.NonExistentTimeError):
444+
with pytest.raises(pytz.NonExistentTimeError, match="2012-03-11 02:00:00"):
445445
rng.tz_localize(tz)
446446

447447
def test_dti_tz_localize_roundtrip(self, tz_aware_fixture):
@@ -452,7 +452,9 @@ def test_dti_tz_localize_roundtrip(self, tz_aware_fixture):
452452
tz = tz_aware_fixture
453453
localized = idx.tz_localize(tz)
454454
# cant localize a tz-aware object
455-
with pytest.raises(TypeError):
455+
with pytest.raises(
456+
TypeError, match="Already tz-aware, use tz_convert to convert"
457+
):
456458
localized.tz_localize(tz)
457459
reset = localized.tz_localize(None)
458460
assert reset.tzinfo is None
@@ -542,7 +544,8 @@ def test_dti_tz_localize_ambiguous_flags(self, tz):
542544
di = DatetimeIndex(times)
543545

544546
# When the sizes are incompatible, make sure error is raised
545-
with pytest.raises(Exception):
547+
msg = "Length of ambiguous bool-array must be the same size as vals"
548+
with pytest.raises(Exception, match=msg):
546549
di.tz_localize(tz, ambiguous=is_dst)
547550

548551
# When sizes are compatible and there are repeats ('infer' won't work)
@@ -564,7 +567,7 @@ def test_dti_construction_ambiguous_endpoint(self, tz):
564567
# construction with an ambiguous end-point
565568
# GH#11626
566569

567-
with pytest.raises(pytz.AmbiguousTimeError):
570+
with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):
568571
date_range(
569572
"2013-10-26 23:00", "2013-10-27 01:00", tz="Europe/London", freq="H"
570573
)
@@ -588,7 +591,7 @@ def test_dti_construction_ambiguous_endpoint(self, tz):
588591
def test_dti_construction_nonexistent_endpoint(self, tz, option, expected):
589592
# construction with an nonexistent end-point
590593

591-
with pytest.raises(pytz.NonExistentTimeError):
594+
with pytest.raises(pytz.NonExistentTimeError, match="2019-03-10 02:00:00"):
592595
date_range(
593596
"2019-03-10 00:00", "2019-03-10 02:00", tz="US/Pacific", freq="H"
594597
)
@@ -613,10 +616,15 @@ def test_dti_tz_localize_nonexistent(self, tz, method, exp):
613616
n = 60
614617
dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min")
615618
if method == "raise":
616-
with pytest.raises(pytz.NonExistentTimeError):
619+
with pytest.raises(pytz.NonExistentTimeError, match="2015-03-29 02:00:00"):
617620
dti.tz_localize(tz, nonexistent=method)
618621
elif exp == "invalid":
619-
with pytest.raises(ValueError):
622+
msg = (
623+
"The nonexistent argument must be one of "
624+
"'raise', 'NaT', 'shift_forward', 'shift_backward' "
625+
"or a timedelta object"
626+
)
627+
with pytest.raises(ValueError, match=msg):
620628
dti.tz_localize(tz, nonexistent=method)
621629
else:
622630
result = dti.tz_localize(tz, nonexistent=method)
@@ -1082,7 +1090,8 @@ def test_with_tz(self, tz):
10821090
dr = bdate_range(
10831091
datetime(2005, 1, 1, tzinfo=pytz.utc), datetime(2009, 1, 1, tzinfo=pytz.utc)
10841092
)
1085-
with pytest.raises(Exception):
1093+
msg = "Start and end cannot both be tz-aware with different timezones"
1094+
with pytest.raises(Exception, match=msg):
10861095
bdate_range(datetime(2005, 1, 1, tzinfo=pytz.utc), "1/1/2009", tz=tz)
10871096

10881097
@pytest.mark.parametrize("prefix", ["", "dateutil/"])

0 commit comments

Comments
 (0)