Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eeb2a47

Browse files
oscargusandrew-fennell
authored andcommitted
Add tests for date module
1 parent 9f6d467 commit eeb2a47

File tree

2 files changed

+64
-34
lines changed

2 files changed

+64
-34
lines changed

lib/matplotlib/dates.py

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -332,11 +332,7 @@ def _dt64_to_ordinalf(d):
332332

333333
NaT_int = np.datetime64('NaT').astype(np.int64)
334334
d_int = d.astype(np.int64)
335-
try:
336-
dt[d_int == NaT_int] = np.nan
337-
except TypeError:
338-
if d_int == NaT_int:
339-
dt = np.nan
335+
dt[d_int == NaT_int] = np.nan
340336
return dt
341337

342338

@@ -592,7 +588,8 @@ def drange(dstart, dend, delta):
592588

593589
# ensure, that an half open interval will be generated [dstart, dend)
594590
if dinterval_end >= dend:
595-
# if the endpoint is greater than dend, just subtract one delta
591+
# if the endpoint is greater than or equal to dend,
592+
# just subtract one delta
596593
dinterval_end -= delta
597594
num -= 1
598595

@@ -1534,11 +1531,6 @@ def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
15341531
"""
15351532
if bymonth is None:
15361533
bymonth = range(1, 13)
1537-
elif isinstance(bymonth, np.ndarray):
1538-
# This fixes a bug in dateutil <= 2.3 which prevents the use of
1539-
# numpy arrays in (among other things) the bymonthday, byweekday
1540-
# and bymonth parameters.
1541-
bymonth = [x.item() for x in bymonth.astype(int)]
15421534

15431535
rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
15441536
interval=interval, **self.hms0d)
@@ -1562,12 +1554,6 @@ def __init__(self, byweekday=1, interval=1, tz=None):
15621554
*interval* specifies the number of weeks to skip. For example,
15631555
``interval=2`` plots every second week.
15641556
"""
1565-
if isinstance(byweekday, np.ndarray):
1566-
# This fixes a bug in dateutil <= 2.3 which prevents the use of
1567-
# numpy arrays in (among other things) the bymonthday, byweekday
1568-
# and bymonth parameters.
1569-
[x.item() for x in byweekday.astype(int)]
1570-
15711557
rule = rrulewrapper(DAILY, byweekday=byweekday,
15721558
interval=interval, **self.hms0d)
15731559
super().__init__(rule, tz=tz)
@@ -1588,11 +1574,6 @@ def __init__(self, bymonthday=None, interval=1, tz=None):
15881574
raise ValueError("interval must be an integer greater than 0")
15891575
if bymonthday is None:
15901576
bymonthday = range(1, 32)
1591-
elif isinstance(bymonthday, np.ndarray):
1592-
# This fixes a bug in dateutil <= 2.3 which prevents the use of
1593-
# numpy arrays in (among other things) the bymonthday, byweekday
1594-
# and bymonth parameters.
1595-
bymonthday = [x.item() for x in bymonthday.astype(int)]
15961577

15971578
rule = rrulewrapper(DAILY, bymonthday=bymonthday,
15981579
interval=interval, **self.hms0d)

lib/matplotlib/tests/test_dates.py

Lines changed: 61 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -357,9 +357,13 @@ def test_drange():
357357
# dates from an half open interval [start, end)
358358
assert len(mdates.drange(start, end, delta)) == 24
359359

360+
# Same if interval ends slightly earlier
361+
end = end - datetime.timedelta(microseconds=1)
362+
assert len(mdates.drange(start, end, delta)) == 24
363+
360364
# if end is a little bit later, we expect the range to contain one element
361365
# more
362-
end = end + datetime.timedelta(microseconds=1)
366+
end = end + datetime.timedelta(microseconds=2)
363367
assert len(mdates.drange(start, end, delta)) == 25
364368

365369
# reset end
@@ -1012,6 +1016,20 @@ def attach_tz(dt, zi):
10121016

10131017
_test_rrulewrapper(attach_tz, dateutil.tz.gettz)
10141018

1019+
SYD = dateutil.tz.gettz('Australia/Sydney')
1020+
dtstart = datetime.datetime(2017, 4, 1, 0)
1021+
dtend = datetime.datetime(2017, 4, 4, 0)
1022+
rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart,
1023+
tzinfo=SYD, until=dtend)
1024+
assert rule.after(dtstart) == datetime.datetime(2017, 4, 2, 0, 0,
1025+
tzinfo=SYD)
1026+
assert rule.before(dtend) == datetime.datetime(2017, 4, 3, 0, 0,
1027+
tzinfo=SYD)
1028+
1029+
# Test parts of __getattr__
1030+
assert rule._base_tzinfo == SYD
1031+
assert rule._interval == 1
1032+
10151033

10161034
@pytest.mark.pytz
10171035
def test_rrulewrapper_pytz():
@@ -1046,6 +1064,15 @@ def test_yearlocator_pytz():
10461064
'2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00']
10471065
st = list(map(str, mdates.num2date(locator(), tz=tz)))
10481066
assert st == expected
1067+
assert np.allclose(locator.tick_values(x[0], x[1]), np.array(
1068+
[14610.20833333, 14610.33333333, 14610.45833333, 14610.58333333,
1069+
14610.70833333, 14610.83333333, 14610.95833333, 14611.08333333,
1070+
14611.20833333]))
1071+
assert np.allclose(locator.get_locator(x[1], x[0]).tick_values(x[0], x[1]),
1072+
np.array(
1073+
[14610.20833333, 14610.33333333, 14610.45833333, 14610.58333333,
1074+
14610.70833333, 14610.83333333, 14610.95833333, 14611.08333333,
1075+
14611.20833333]))
10491076

10501077

10511078
def test_YearLocator():
@@ -1290,18 +1317,14 @@ def test_datestr2num():
12901317
month=1, day=10)).size == 0
12911318

12921319

1293-
def test_concise_formatter_exceptions():
1320+
@pytest.mark.parametrize('kwarg',
1321+
('formats', 'zero_formats', 'offset_formats'))
1322+
def test_concise_formatter_exceptions(kwarg):
12941323
locator = mdates.AutoDateLocator()
1295-
with pytest.raises(ValueError, match="formats argument must be a list"):
1296-
mdates.ConciseDateFormatter(locator, formats=['', '%Y'])
1297-
1298-
with pytest.raises(ValueError,
1299-
match="zero_formats argument must be a list"):
1300-
mdates.ConciseDateFormatter(locator, zero_formats=['', '%Y'])
1301-
1302-
with pytest.raises(ValueError,
1303-
match="offset_formats argument must be a list"):
1304-
mdates.ConciseDateFormatter(locator, offset_formats=['', '%Y'])
1324+
kwargs = {kwarg: ['', '%Y']}
1325+
match = f"{kwarg} argument must be a list"
1326+
with pytest.raises(ValueError, match=match):
1327+
mdates.ConciseDateFormatter(locator, **kwargs)
13051328

13061329

13071330
def test_concise_formatter_call():
@@ -1340,3 +1363,29 @@ def test_datetime_masked():
13401363
fig, ax = plt.subplots()
13411364
ax.plot(x, m)
13421365
assert ax.get_xlim() == (0, 1)
1366+
1367+
1368+
@pytest.mark.parametrize('val', (-1000000, 10000000))
1369+
def test_num2date_error(val):
1370+
with pytest.raises(ValueError, match=f"Date ordinal {val} converts"):
1371+
mdates.num2date(val)
1372+
1373+
1374+
def test_num2date_roundoff():
1375+
assert mdates.num2date(100000.0000578702) == datetime.datetime(
1376+
2243, 10, 17, 0, 0, 4, 999980, tzinfo=datetime.timezone.utc)
1377+
# Slightly larger, steps of 20 microseconds
1378+
assert mdates.num2date(100000.0000578703) == datetime.datetime(
1379+
2243, 10, 17, 0, 0, 5, tzinfo=datetime.timezone.utc)
1380+
1381+
1382+
def test_DateFormatter_settz():
1383+
time = mdates.date2num(datetime.datetime(2011, 1, 1, 0, 0,
1384+
tzinfo=mdates.UTC))
1385+
formatter = mdates.DateFormatter('%Y-%b-%d %H:%M')
1386+
# Default UTC
1387+
assert formatter(time) == '2011-Jan-01 00:00'
1388+
1389+
# Set tzinfo
1390+
formatter.set_tzinfo('Pacific/Kiritimati')
1391+
assert formatter(time) == '2011-Jan-01 14:00'

0 commit comments

Comments
 (0)