From d39868534594488492bf0aa61ea7bca727dd6d0d Mon Sep 17 00:00:00 2001 From: Ilan Steemers Date: Thu, 19 Nov 2015 17:57:31 +0100 Subject: [PATCH] Adds a check for duplicate schedule names. This should prevent the accidental repeated creation of schedules. --- django_q/tasks.py | 6 ++++++ django_q/tests/test_scheduler.py | 16 ++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/django_q/tasks.py b/django_q/tasks.py index f933bc3..4af1788 100644 --- a/django_q/tasks.py +++ b/django_q/tasks.py @@ -2,6 +2,7 @@ from multiprocessing import Queue, Value # django +from django.db import IntegrityError from django.utils import timezone # local @@ -75,6 +76,11 @@ def schedule(func, *args, **kwargs): repeats = kwargs.pop('repeats', -1) next_run = kwargs.pop('next_run', timezone.now()) + # check for name duplicates instead of am unique constraint + if name and Schedule.objects.filter(name=name).exists(): + raise IntegrityError("A schedule with the same name already exists.") + + # create and return the schedule return Schedule.objects.create(name=name, func=func, hook=hook, diff --git a/django_q/tests/test_scheduler.py b/django_q/tests/test_scheduler.py index a8e5abc..167da4a 100644 --- a/django_q/tests/test_scheduler.py +++ b/django_q/tests/test_scheduler.py @@ -1,15 +1,15 @@ from datetime import timedelta from multiprocessing import Queue, Event, Value -import pytest import arrow - +import pytest +from django.db import IntegrityError from django.utils import timezone from django_q.brokers import get_broker -from django_q.conf import Conf from django_q.cluster import pusher, worker, monitor, scheduler -from django_q.tasks import Schedule, fetch, schedule as create_schedule, queue_size +from django_q.conf import Conf +from django_q.tasks import Schedule, fetch, schedule as create_schedule @pytest.fixture @@ -33,6 +33,14 @@ def test_scheduler(broker): schedule_type=Schedule.HOURLY, repeats=1) assert schedule.last_run() is None + # check duplicate constraint + with pytest.raises(IntegrityError): + schedule = create_schedule('math.copysign', + 1, -1, + name='test math', + hook='django_q.tests.tasks.result', + schedule_type=Schedule.HOURLY, + repeats=1) # run scheduler scheduler(broker=broker) # set up the workflow