mirror of https://github.com/peter4431/rq.git
Merge branch 'selwin-decorator'
commit
4057ae768b
@ -0,0 +1,34 @@
|
||||
from functools import wraps
|
||||
from .queue import Queue
|
||||
from .connections import resolve_connection
|
||||
|
||||
|
||||
class job(object):
|
||||
|
||||
def __init__(self, queue, connection=None, timeout=None):
|
||||
"""A decorator that adds a ``delay`` method to the decorated function,
|
||||
which in turn creates a RQ job when called. Accepts a required
|
||||
``queue`` argument that can be either a ``Queue`` instance or a string
|
||||
denoting the queue name. For example:
|
||||
|
||||
@job(queue='default')
|
||||
def simple_add(x, y):
|
||||
return x + y
|
||||
|
||||
simple_add.delay(1, 2) # Puts simple_add function into queue
|
||||
"""
|
||||
self.queue = queue
|
||||
self.connection = resolve_connection(connection)
|
||||
self.timeout = timeout
|
||||
|
||||
def __call__(self, f):
|
||||
@wraps(f)
|
||||
def delay(*args, **kwargs):
|
||||
if isinstance(self.queue, basestring):
|
||||
queue = Queue(name=self.queue, connection=self.connection)
|
||||
else:
|
||||
queue = self.queue
|
||||
return queue.enqueue_call(f, args=args, kwargs=kwargs,
|
||||
timeout=self.timeout)
|
||||
f.delay = delay
|
||||
return f
|
@ -0,0 +1,36 @@
|
||||
from tests import RQTestCase
|
||||
from tests.fixtures import decorated_job
|
||||
|
||||
from rq.decorators import job
|
||||
from rq.job import Job
|
||||
|
||||
|
||||
class TestDecorator(RQTestCase):
|
||||
|
||||
def setUp(self):
|
||||
super(TestDecorator, self).setUp()
|
||||
|
||||
def test_decorator_preserves_functionality(self):
|
||||
"""Ensure that a decorated function's functionality is still preserved.
|
||||
"""
|
||||
self.assertEqual(decorated_job(1, 2), 3)
|
||||
|
||||
def test_decorator_adds_delay_attr(self):
|
||||
"""Ensure that decorator adds a delay attribute to function that returns
|
||||
a Job instance when called.
|
||||
"""
|
||||
self.assertTrue(hasattr(decorated_job, 'delay'))
|
||||
result = decorated_job.delay(1, 2)
|
||||
self.assertTrue(isinstance(result, Job))
|
||||
# Ensure that job returns the right result when performed
|
||||
self.assertEqual(result.perform(), 3)
|
||||
|
||||
def test_decorator_accepts_queue_name_as_argument(self):
|
||||
"""Ensure that passing in queue name to the decorator puts the job in
|
||||
the right queue.
|
||||
"""
|
||||
@job(queue='queue_name')
|
||||
def hello():
|
||||
return 'Hi'
|
||||
result = hello.delay()
|
||||
self.assertEqual(result.origin, 'queue_name')
|
Loading…
Reference in New Issue