Skip to content

Commit

Permalink
loaddata: Fix random_datetime() edge case
Browse files Browse the repository at this point in the history
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 freedomofpress#7155.
  • Loading branch information
legoktm authored and cfm committed May 1, 2024
1 parent 33cb6eb commit 25cf984
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions securedrop/loaddata.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""

import argparse
import calendar
import datetime
import io
import math
Expand Down Expand Up @@ -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),
Expand Down

0 comments on commit 25cf984

Please sign in to comment.