test and fix year step and december handling in date_range, fixes #319

This commit is contained in:
Mahmoud Hashemi 2022-12-07 18:22:36 -08:00
parent 6c7fa3e056
commit 8ba3a7fa0d
2 changed files with 20 additions and 4 deletions

View File

@ -377,6 +377,8 @@ def daterange(start, stop, step=1, inclusive=False):
else: else:
raise ValueError('step expected int, timedelta, or tuple' raise ValueError('step expected int, timedelta, or tuple'
' (year, month, day), not: %r' % step) ' (year, month, day), not: %r' % step)
m_step += y_step * 12
if stop is None: if stop is None:
finished = lambda now, stop: False finished = lambda now, stop: False
@ -388,10 +390,10 @@ def daterange(start, stop, step=1, inclusive=False):
while not finished(now, stop): while not finished(now, stop):
yield now yield now
if y_step or m_step: if m_step:
m_y_step, cur_month = divmod(now.month + m_step, 12) m_y_step, cur_month = divmod((now.month - 1) + m_step, 12)
now = now.replace(year=now.year + y_step + m_y_step, now = now.replace(year=now.year + m_y_step,
month=cur_month or 12) month=(cur_month + 1))
now = now + d_step now = now + d_step
return return

View File

@ -48,6 +48,20 @@ def test_daterange_years():
assert years_from_2025[0] == date(2025, 1, 1) assert years_from_2025[0] == date(2025, 1, 1)
assert years_from_2025[-1] == date(2017, 1, 1) assert years_from_2025[-1] == date(2017, 1, 1)
def test_daterange_years_step():
start_day = date(year=2012, month=12, day=25)
end_day = date(year=2016, month=1, day=1)
dates = list(daterange(start_day, end_day, step=(1, 0, 0), inclusive=False))
expected = [date(year=2012, month=12, day=25), date(year=2013, month=12, day=25), date(year=2014, month=12, day=25), date(year=2015, month=12, day=25)]
assert dates == expected
dates = list(daterange(start_day, end_day, step=(0, 13, 0), inclusive=False))
expected = [date(year=2012, month=12, day=25), date(year=2014, month=1, day=25), date(year=2015, month=2, day=25)]
assert dates == expected
def test_daterange_infinite(): def test_daterange_infinite():
today = date.today() today = date.today()
infinite_dates = daterange(today, None) infinite_dates = daterange(today, None)