Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix next_occurrence function #1893

Merged
8 changes: 5 additions & 3 deletions data_safe_haven/functions/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ def next_occurrence(
microsecond=0,
)
utc_dt = local_dt.astimezone(pytz.utc)
# Add one day until this datetime is in the future
utc_now = datetime.datetime.now(pytz.utc) + datetime.timedelta(minutes=1)
while utc_dt < utc_now:
# Add one day until this datetime is at least 1 hour in the future.
# This ensures that any Azure functions which depend on this datetime being in
# the future should treat it as valid.
utc_near_future = datetime.datetime.now(pytz.utc) + datetime.timedelta(hours=1)
while utc_dt < utc_near_future:
utc_dt += datetime.timedelta(days=1)
JimMadge marked this conversation as resolved.
Show resolved Hide resolved
if time_format == "iso":
return utc_dt.isoformat()
Expand Down
16 changes: 14 additions & 2 deletions tests/functions/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,22 @@
from data_safe_haven.functions import next_occurrence, sanitise_sre_name


def test_next_occurrence_is_within_next_day():
def test_next_occurrence_will_occur_soon():
dt_utc_now = datetime.datetime.now(datetime.UTC)
next_time = next_occurrence(5, 13, "Australia/Perth")
dt_utc_tomorrow = dt_utc_now + datetime.timedelta(days=1, minutes=5)
dt_utc_tomorrow = dt_utc_now + datetime.timedelta(days=1, hours=2)
jemrobinson marked this conversation as resolved.
Show resolved Hide resolved
dt_next_time = datetime.datetime.fromisoformat(next_time)
assert dt_next_time > dt_utc_now
assert dt_next_time < dt_utc_tomorrow


def test_next_occurrence_day_shift():
dt_utc_now = datetime.datetime.now(datetime.UTC)
dt_perth_now = dt_utc_now.astimezone(pytz.timezone("Australia/Perth"))
next_time = next_occurrence(
dt_perth_now.hour, dt_perth_now.minute, "Australia/Perth"
)
dt_utc_tomorrow = dt_utc_now + datetime.timedelta(days=1, hours=2)
dt_next_time = datetime.datetime.fromisoformat(next_time)
assert dt_next_time > dt_utc_now
assert dt_next_time < dt_utc_tomorrow
Expand Down
Loading