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

Avoid crash when can not get human readable description #648

Merged
merged 1 commit into from
Apr 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 12 additions & 3 deletions django_celery_beat/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

import timezone_field
from celery import current_app, schedules
from cron_descriptor import get_description
from cron_descriptor import (FormatException, MissingFieldException,
WrongArgumentException, get_description)
from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned, ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
Expand Down Expand Up @@ -316,11 +317,19 @@ class Meta:

@property
def human_readable(self):
human_readable = get_description('{} {} {} {} {}'.format(
cron_expression = '{} {} {} {} {}'.format(
cronexp(self.minute), cronexp(self.hour),
cronexp(self.day_of_month), cronexp(self.month_of_year),
cronexp(self.day_of_week)
))
)
try:
human_readable = get_description(cron_expression)
except (
MissingFieldException,
FormatException,
WrongArgumentException
):
return f'{cron_expression} {str(self.timezone)}'
return f'{human_readable} {str(self.timezone)}'

def __str__(self):
Expand Down
37 changes: 37 additions & 0 deletions t/unit/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,40 @@ def test_trigger_update_when_deleted(self):
'The `PeriodicTasks.last_update` has not be update.'
)
# Check the `PeriodicTasks` does be updated.


class HumanReadableTestCase(TestCase):
def test_good(self):
"""Valid crontab display."""
cron = CrontabSchedule.objects.create(
hour="2",
minute="0",
day_of_week="mon",
)
self.assertNotEqual(
cron.human_readable, "0 2 * * mon UTC"
)

def test_invalid(self):
"""Invalid crontab display."""
cron = CrontabSchedule.objects.create(
hour="2",
minute="0",
day_of_week="monxxx",
)
self.assertEqual(
cron.human_readable, "0 2 * * monxxx UTC"
)

def test_long_name(self):
"""Long day name display."""
# TODO: this should eventually work, but probably needs conversion
# before passing data to cron_description
cron = CrontabSchedule.objects.create(
hour="2",
minute="0",
day_of_week="monday",
)
self.assertEqual(
cron.human_readable, "0 2 * * monday UTC"
)