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: 7 additions & 1 deletion data_safe_haven/functions/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,14 @@ def next_occurrence(
minute=minute,
second=0,
microsecond=0,
) + datetime.timedelta(days=1)
)
utc_dt = local_dt.astimezone(pytz.utc)
# 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)
if time_format == "iso":
return utc_dt.isoformat()
elif time_format == "iso_minute":
Expand Down
17 changes: 15 additions & 2 deletions tests/functions/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,25 @@
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, hours=2)
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_now + datetime.timedelta(days=1)
assert dt_next_time < dt_utc_tomorrow


def test_next_occurrence_has_correct_time():
Expand Down
Loading