Browse Source

croniter.is_valid() throws exceptions for some bad inputs, so must use try ... except

pull/211/head
Pēteris Caune 6 years ago
parent
commit
25e48f1b9f
No known key found for this signature in database GPG Key ID: E28D7679E9A9EDE2
4 changed files with 36 additions and 24 deletions
  1. +8
    -1
      hc/front/tests/test_cron_preview.py
  2. +12
    -9
      hc/front/tests/test_update_timeout.py
  3. +3
    -1
      hc/front/validators.py
  4. +13
    -13
      hc/front/views.py

+ 8
- 1
hc/front/tests/test_cron_preview.py View File

@ -16,7 +16,14 @@ class CronPreviewTestCase(BaseTestCase):
self.assertContains(r, "cron-preview-title", status_code=200)
def test_it_rejects_invalid_cron_expression(self):
for schedule in [None, "", "*", "100 100 100 100 100", "* * * * * *"]:
samples = [None,
"",
"*",
"100 100 100 100 100",
"* * * * * *",
"1,2 3,* * * *"]
for schedule in samples:
payload = {"schedule": schedule, "tz": "UTC"}
r = self.client.post("/checks/cron_preview/", payload)
self.assertContains(r, "Invalid cron expression", status_code=200)


+ 12
- 9
hc/front/tests/test_update_timeout.py View File

@ -67,16 +67,19 @@ class UpdateTimeoutTestCase(BaseTestCase):
self.assertEqual(self.check.schedule, "5 * * * *")
def test_it_validates_cron_expression(self):
payload = {
"kind": "cron",
"schedule": "* invalid *",
"tz": "UTC",
"grace": 60
}
self.client.login(username="[email protected]", password="password")
r = self.client.post(self.url, data=payload)
self.assertEqual(r.status_code, 400)
samples = ["* invalid *", "1,2 3,* * * *"]
for sample in samples:
payload = {
"kind": "cron",
"schedule": sample,
"tz": "UTC",
"grace": 60
}
r = self.client.post(self.url, data=payload)
self.assertEqual(r.status_code, 400)
# Check should still have its original data:
self.check.refresh_from_db()


+ 3
- 1
hc/front/validators.py View File

@ -24,7 +24,9 @@ class CronExpressionValidator(object):
if len(value.split()) != 5:
raise ValidationError(message=self.message)
if not croniter.is_valid(value):
try:
croniter(value)
except:
raise ValidationError(message=self.message)


+ 13
- 13
hc/front/views.py View File

@ -325,21 +325,21 @@ def cron_preview(request):
tz = request.POST.get("tz")
ctx = {"tz": tz, "dates": []}
if len(schedule.split()) != 5:
ctx["bad_schedule"] = True
elif not croniter.is_valid(schedule):
try:
zone = pytz.timezone(tz)
now_local = timezone.localtime(timezone.now(), zone)
if len(schedule.split()) != 5:
raise ValueError()
it = croniter(schedule, now_local)
for i in range(0, 6):
ctx["dates"].append(it.get_next(datetime))
except UnknownTimeZoneError:
ctx["bad_tz"] = True
except:
ctx["bad_schedule"] = True
if "bad_schedule" not in ctx:
try:
zone = pytz.timezone(tz)
now_local = timezone.localtime(timezone.now(), zone)
it = croniter(schedule, now_local)
for i in range(0, 6):
ctx["dates"].append(it.get_next(datetime))
except UnknownTimeZoneError:
ctx["bad_tz"] = True
return render(request, "front/cron_preview.html", ctx)


Loading…
Cancel
Save