Skip to content

Commit

Permalink
[#2623] Validate rescheduled date/time to not be in past
Browse files Browse the repository at this point in the history
  • Loading branch information
pbanaszkiewicz committed Apr 17, 2024
1 parent 5f0a4aa commit 07bcd6a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
10 changes: 10 additions & 0 deletions amy/emails/forms.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import UTC, datetime

from django import forms
from markdownx.fields import MarkdownxFormField

Expand Down Expand Up @@ -87,6 +89,14 @@ class ScheduledEmailRescheduleForm(forms.Form):

helper = BootstrapHelper(submit_label="Update")

def clean_scheduled_at(self):
scheduled_at = self.cleaned_data["scheduled_at"]

if scheduled_at < datetime.now(tz=UTC):
raise forms.ValidationError("Scheduled time cannot be in the past.")

return scheduled_at


class ScheduledEmailCancelForm(forms.Form):
confirm = forms.CharField(required=False)
Expand Down
44 changes: 44 additions & 0 deletions amy/emails/tests/test_forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from datetime import UTC, datetime
from unittest.mock import MagicMock, patch

from django.test import TestCase

from emails.forms import ScheduledEmailRescheduleForm


class TestScheduledEmailRescheduleForm(TestCase):
@patch("emails.forms.datetime", wraps=datetime)
def test_clean_scheduled_at_success(self, mock_datetime: MagicMock) -> None:
# Arrange
mock_datetime.now.return_value = datetime(2023, 1, 1, 0, 0, 0, tzinfo=UTC)
data = {
"scheduled_at_0": "2024-01-01",
"scheduled_at_1": "00:00",
}
form = ScheduledEmailRescheduleForm(data=data)

# Act
result = form.is_valid()

# Assert
self.assertTrue(result)

@patch("emails.forms.datetime", wraps=datetime)
def test_clean_scheduled_at_failure(self, mock_datetime: MagicMock) -> None:
# Arrange
mock_datetime.now.return_value = datetime(2024, 1, 1, 0, 0, 0, tzinfo=UTC)
data = {
"scheduled_at_0": "2023-01-01",
"scheduled_at_1": "00:00",
}
form = ScheduledEmailRescheduleForm(data=data)

# Act
result = form.is_valid()

# Assert
self.assertFalse(result)
self.assertEqual(
form.errors["scheduled_at"],
["Scheduled time cannot be in the past."],
)

0 comments on commit 07bcd6a

Please sign in to comment.