From 25cf9842c28abc5c475146a56cf50affe6abf3eb Mon Sep 17 00:00:00 2001 From: Kunal Mehta Date: Tue, 30 Apr 2024 15:01:31 -0400 Subject: [PATCH] loaddata: Fix random_datetime() edge case Instead of generating month and day separately, generate them at the same time by randomly selecting a day in the year, and then calculating the month and date based on that. This should avoid randomly generating invalid dates like February 30th. Fixes #7155. --- securedrop/loaddata.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/securedrop/loaddata.py b/securedrop/loaddata.py index ad4f6946e3..3edeee4a1c 100755 --- a/securedrop/loaddata.py +++ b/securedrop/loaddata.py @@ -5,6 +5,7 @@ """ import argparse +import calendar import datetime import io import math @@ -83,10 +84,17 @@ def random_datetime(nullable: bool) -> Optional[datetime.datetime]: return None now = datetime.datetime.now() + year = random.randint(2013, now.year) + max_day = 366 if calendar.isleap(year) else 365 + day = random.randint(1, max_day) + + # Calculate the month/day given the year + date = datetime.date(year, 1, 1) + datetime.timedelta(days=day - 1) + return datetime.datetime( - year=random.randint(2013, now.year), - month=random.randint(1, now.month), - day=random.randint(1, now.day), + year=year, + month=date.month, + day=date.day, hour=random.randint(0, 23), minute=random.randint(0, 59), second=random.randint(0, 59),