Skip to content

Commit

Permalink
Avoid crash when can not get human readable description
Browse files Browse the repository at this point in the history
Catch errors from cron-descriptor and display crontab as it is.
Apparently there are crontabs which work in Celery, but cron-descriptor
fails to format them.

Issue #647
  • Loading branch information
nijel authored and auvipy committed Apr 8, 2023
1 parent 119357a commit 2798e36
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
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"
)

0 comments on commit 2798e36

Please sign in to comment.