Debian Codegraph @

tests/test_cron.py

raw
1 from contextlib import suppress
2 from io import StringIO
3 from unittest import skipIf
4 from unittest.mock import patch
5
6 from django.contrib.auth.models import User
7 from django.core.management import call_command
8 from django.core.paginator import Paginator
9 from django.test import TestCase, override_settings
10 from django.test.client import Client
11 from django.urls import reverse
12 from rq.cron import CronJob
13
14 from django_rq import get_connection
15 from django_rq.cron import (
16 CRON_JOB_HISTORY_SUPPORTED,
17 DjangoCronScheduler,
18 get_cron_job_history,
19 get_cron_job_history_count,
20 )
21 from django_rq.cron_views import ITEMS_PER_PAGE
22 from tests.fixtures import say_hello
23
24 # `CronJob.name`, `job_history_key` and `get_job_ids()` were added in RQ 2.11, but django-rq
25 # still supports older versions and degrades gracefully
26 requires_job_history = skipIf(not CRON_JOB_HISTORY_SUPPORTED, 'requires RQ >= 2.11')
27
28
29 class CronTest(TestCase):
30 def test_django_cron_scheduler_init(self):
31 """Test DjangoCronScheduler can be initialized without connection."""
32 scheduler = DjangoCronScheduler()
33
34 # Should not have connection until first register() call
35 self.assertIsNone(scheduler.connection)
36 self.assertIsNone(scheduler._connection_config)
37 self.assertEqual(scheduler._cron_jobs, [])
38
39 def test_first_register_initializes_connection(self):
40 """Test that first register() call initializes the scheduler with queue's connection."""
41 scheduler = DjangoCronScheduler()
42
43 # Register a job with cron expression (run every minute)
44 cron_job = scheduler.register(say_hello, "default", cron="* * * * *")
45
46 # Should now have connection set
47 self.assertIsNotNone(scheduler.connection)
48 self.assertIsNotNone(scheduler._connection_config)
49 self.assertIsInstance(cron_job, CronJob)
50 self.assertEqual(len(scheduler.get_jobs()), 1)
51
52 # Verify cron expression is set correctly
53 self.assertEqual(cron_job.cron, "* * * * *")
54 self.assertIsNone(cron_job.interval)
55 # self.assertIsNotNone(cron_job.next_run_time)
56
57 def test_register_with_webhooks(self):
58 """webhooks passed to register() are forwarded to the underlying CronJob."""
59 from rq.webhook import Webhook
60
61 webhook = Webhook('https://example.com/hook', 'finished')
62 scheduler = DjangoCronScheduler()
63 cron_job = scheduler.register(say_hello, 'default', interval=60, webhooks=[webhook])
64 self.assertEqual(cron_job.job_options['webhooks'], [webhook])
65
66 @requires_job_history
67 def test_register_with_name(self):
68 """A cron job's name defaults to the function's import path and can be overridden."""
69 scheduler = DjangoCronScheduler()
70 default_name = scheduler.register(say_hello, 'default', interval=60)
71 named = scheduler.register(say_hello, 'default', interval=60, name='nightly-report')
72
73 self.assertEqual(default_name.name, 'tests.fixtures.say_hello')
74 self.assertEqual(named.name, 'nightly-report')
75
76 @requires_job_history
77 def test_cron_job_history(self):
78 """Job history returns (job_id, enqueued_at) pairs, newest first."""
79 scheduler = DjangoCronScheduler()
80 cron_job = scheduler.register(say_hello, 'default', interval=60, name='history-test')
81 connection = scheduler.connection
82 self.addCleanup(connection.delete, cron_job.job_history_key)
83
84 # A cron job that hasn't run yet has no history
85 self.assertEqual(get_cron_job_history(cron_job, connection), [])
86
87 first = cron_job.enqueue(connection)
88 second = cron_job.enqueue(connection)
89 self.addCleanup(second.delete)
90 self.addCleanup(first.delete)
91
92 history = get_cron_job_history(cron_job, connection)
93 self.assertEqual([job_id for job_id, _ in history], [second.id, first.id])
94 self.assertEqual(get_cron_job_history_count(cron_job, connection), 2)
95
96 # Timestamps come from the sorted set score, which is the job's enqueue time
97 self.assertAlmostEqual(history[0][1].timestamp(), second.enqueued_at.timestamp(), places=3)
98
99 # start/end are inclusive indexes into the newest first ordering, which is what paginates
100 self.assertEqual([job_id for job_id, _ in get_cron_job_history(cron_job, connection, 1, 1)], [first.id])
101
102 def test_connection_validation(self):
103 """Test connection validation for same, compatible, and incompatible queues."""
104 # Start with test3 queue (secondary Redis DB configured for tests)
105 scheduler = DjangoCronScheduler()
106
107 # Same queue multiple times should work
108 job1 = scheduler.register(say_hello, "test3", interval=60)
109 job2 = scheduler.register(say_hello, "test3", interval=120)
110
111 self.assertEqual(len(scheduler.get_jobs()), 2)
112 self.assertEqual(job1.queue_name, "test3")
113 self.assertEqual(job2.queue_name, "test3")
114
115 # Compatible queues (same Redis connection) should work
116 # Both 'test3' and 'async' share the same Redis connection settings
117 job3 = scheduler.register(say_hello, "async", interval=180)
118 self.assertEqual(len(scheduler.get_jobs()), 3)
119 self.assertEqual(job3.queue_name, "async")
120
121 # Queues having different Redis connections should fail
122 with self.assertRaises(ValueError):
123 scheduler.register(say_hello, "default", interval=240)
124
125 # Undefined queue_name should fail
126 scheduler = DjangoCronScheduler()
127 with self.assertRaises(KeyError):
128 scheduler.register(say_hello, "nonexistent_queue", interval=300)
129
130 def test_connection_index_property(self):
131 """Test connection_index property returns correct index or raises appropriate exceptions."""
132
133 scheduler = DjangoCronScheduler()
134
135 # Before any registration, connection_index should raise ValueError
136 with self.assertRaises(ValueError):
137 _ = scheduler.connection_index
138
139 # Register a job with 'test3' queue (secondary Redis DB configured for tests)
140 scheduler.register(say_hello, "test3", interval=60)
141
142 # Now connection_index should return a valid index
143 connection_index = scheduler.connection_index
144 self.assertGreaterEqual(connection_index, 0)
145
146 # Test with a queue using a different connection
147 scheduler2 = DjangoCronScheduler()
148 scheduler2.register(say_hello, "default", interval=60) # Uses DB=0
149
150 # Should have a different connection_index
151 self.assertNotEqual(scheduler2.connection_index, scheduler.connection_index)
152
153
154 class CronCommandTest(TestCase):
155 @patch('django_rq.cron.DjangoCronScheduler.start')
156 def test_rqcron_command(self, mock_start):
157 """Test rqcron command execution: success and import errors from load_config_from_file."""
158 mock_start.return_value = None
159
160 # Test 1: Successful execution
161 out = StringIO()
162 config_path = "tests.cron_config1"
163
164 call_command("rqcron", config_path, stdout=out)
165
166 output = out.getvalue()
167 self.assertIn(f"Loading cron configuration from {config_path}", output)
168 self.assertIn("Starting cron scheduler with 2 jobs...", output)
169 mock_start.assert_called_once()
170
171 # Test 2: File not found - should raise ImportError from RQ
172 with self.assertRaises(ImportError) as cm:
173 call_command("rqcron", "nonexistent_file.py")
174
175 self.assertIn("No module named 'nonexistent_file'", str(cm.exception))
176
177 # Test 3: Import error
178 with self.assertRaises(ImportError) as cm:
179 call_command("rqcron", "nonexistent.module.path")
180
181 self.assertIn("No module named 'nonexistent'", str(cm.exception))
182
183 @patch("django_rq.cron.DjangoCronScheduler.start")
184 @patch("django_rq.cron.DjangoCronScheduler.load_config_from_file")
185 def test_rqcron_command_exceptions(self, mock_load_config, mock_start):
186 """Test rqcron command exception handling."""
187 mock_load_config.return_value = None
188
189 # Test KeyboardInterrupt handling
190 mock_start.side_effect = KeyboardInterrupt()
191 with self.assertRaises(SystemExit):
192 call_command("rqcron", "tests.cron_config2")
193
194 # Test general exception handling - should bubble up as raw exception
195 mock_load_config.side_effect = Exception("Test error")
196 with self.assertRaises(Exception) as cm:
197 call_command("rqcron", "tests.cron_config2")
198
199 self.assertEqual(str(cm.exception), "Test error")
200
201 def test_rqcron_command_successful_run(self):
202 """Test successful rqcron command execution without mocking."""
203 out = StringIO()
204 config_path = "tests.cron_config1"
205
206 # Use a very short timeout to test actual execution
207 import signal
208
209 def timeout_handler(signum, frame):
210 raise KeyboardInterrupt()
211
212 # Set up a timeout to stop the command after a short time
213 old_handler = signal.signal(signal.SIGALRM, timeout_handler)
214 signal.alarm(1) # Stop after 1 second
215
216 try:
217 # The command will be interrupted and may or may not raise SystemExit depending on Django version
218 with suppress(SystemExit):
219 call_command("rqcron", config_path, stdout=out)
220 finally:
221 signal.alarm(0) # Cancel the alarm
222 signal.signal(signal.SIGALRM, old_handler)
223
224 output = out.getvalue()
225 self.assertIn(f"Loading cron configuration from {config_path}", output)
226 self.assertIn("Starting cron scheduler with 2 jobs...", output)
227
228
229 @override_settings(ROOT_URLCONF='tests.default_with_custom_mount_urls')
230 class CronViewTest(TestCase):
231 def setUp(self):
232 """Set up test user and client."""
233 self.user = User.objects.create_user('foo', password='pass', is_staff=True, is_active=True)
234 self.client = Client()
235 self.client.login(username=self.user.username, password='pass')
236
237 def test_cron_scheduler_detail_view(self):
238 """Test cron scheduler detail view with various scenarios."""
239 # Create a real scheduler and register it
240 scheduler = DjangoCronScheduler(name='test-scheduler')
241 scheduler.register(
242 say_hello,
243 "default",
244 interval=60,
245 args=("hello",),
246 kwargs={"target": "world"},
247 meta={"source": "test"},
248 job_timeout=20,
249 result_ttl=500,
250 ttl=60,
251 failure_ttl=120,
252 )
253 from rq.webhook import Webhook
254
255 webhook = Webhook('https://example.com/hook', 'failed')
256 scheduler.register(say_hello, "default", cron="*/5 * * * *", webhooks=[webhook])
257 scheduler.register_birth()
258
259 for prefix in ('admin:django_rq_', 'django_rq:'):
260 # Test 1: Successful view of existing scheduler
261 connection_index = scheduler.connection_index
262 url = reverse(f'{prefix}cron_scheduler_detail', args=[connection_index, 'test-scheduler'])
263 response = self.client.get(url)
264 self.assertEqual(response.status_code, 200)
265 self.assertEqual(response.context['scheduler'].name, 'test-scheduler')
266 self.assertEqual(len(response.context['cron_jobs']), 2)
267 first_cron_job = response.context['cron_jobs'][0]
268 self.assertEqual(first_cron_job['func_name'], 'tests.fixtures.say_hello')
269 self.assertEqual(first_cron_job['queue_name'], 'default')
270 self.assertEqual(first_cron_job['schedule'], 'Every 60 seconds')
271 self.assertContains(response, 'test-scheduler')
272 self.assertContains(response, 'Cron Jobs')
273 self.assertContains(response, 'tests.fixtures.say_hello')
274 self.assertContains(response, 'default')
275 self.assertContains(response, 'Every 60 seconds')
276 self.assertContains(response, 'Cron: */5 * * * *')
277
278 # Each cron job's name links to its job history, where RQ provides one
279 if CRON_JOB_HISTORY_SUPPORTED:
280 self.assertContains(
281 response,
282 reverse(
283 f'{prefix}cron_job_detail',
284 args=[connection_index, 'test-scheduler', 'tests.fixtures.say_hello'],
285 ),
286 )
287
288 # Webhooks: first job has none, second job's webhook is exposed in the context
289 self.assertEqual(first_cron_job['webhooks'], [])
290 self.assertEqual(response.context['cron_jobs'][1]['webhooks'], [webhook])
291
292 # Test 2: Non-existent scheduler returns 404
293 url = reverse(f'{prefix}cron_scheduler_detail', args=[connection_index, 'nonexistent-scheduler'])
294 response = self.client.get(url)
295 self.assertEqual(response.status_code, 404)
296
297 # Test 3: Invalid connection index returns 404
298 url = reverse(f'{prefix}cron_scheduler_detail', args=[999, 'test-scheduler'])
299 response = self.client.get(url)
300 self.assertEqual(response.status_code, 404)
301
302 # Clean up
303 scheduler.register_death()
304
305 def test_cron_scheduler_detail_view_with_no_jobs(self):
306 """Test cron scheduler detail view gracefully handles schedulers with no jobs."""
307 scheduler = DjangoCronScheduler(connection=get_connection("default"), name='empty-scheduler')
308 scheduler.register_birth()
309
310 for prefix in ('admin:django_rq_', 'django_rq:'):
311 url = reverse(f'{prefix}cron_scheduler_detail', args=[scheduler.connection_index, 'empty-scheduler'])
312 response = self.client.get(url)
313 self.assertEqual(response.status_code, 200)
314 self.assertEqual(response.context['scheduler'].name, 'empty-scheduler')
315 self.assertEqual(response.context['cron_jobs'], [])
316 self.assertContains(response, 'No persisted cron jobs found')
317
318 scheduler.register_death()
319
320 @requires_job_history
321 def test_cron_job_detail_view(self):
322 """Cron job detail lists spawned jobs, including those whose job data is gone."""
323 scheduler = DjangoCronScheduler(name='job-history-scheduler')
324 cron_job = scheduler.register(say_hello, 'default', interval=60, name='history-view-test')
325 scheduler.register_birth()
326 self.addCleanup(scheduler.register_death)
327
328 connection = scheduler.connection
329 self.addCleanup(connection.delete, cron_job.job_history_key)
330
331 kept = cron_job.enqueue(connection)
332 self.addCleanup(kept.delete)
333 # A job's data is deleted long before its history entry expires
334 deleted = cron_job.enqueue(connection)
335 deleted.delete()
336
337 for prefix in ('admin:django_rq_', 'django_rq:'):
338 url = reverse(
339 f'{prefix}cron_job_detail',
340 args=[scheduler.connection_index, 'job-history-scheduler', 'history-view-test'],
341 )
342 response = self.client.get(url)
343 self.assertEqual(response.status_code, 200)
344 self.assertEqual(response.context['cron_job']['name'], 'history-view-test')
345
346 # Both entries are listed newest first, even though one job no longer exists
347 history = response.context['history']
348 self.assertEqual([entry['job_id'] for entry in history], [deleted.id, kept.id])
349 self.assertEqual(response.context['num_jobs'], 2)
350 self.assertIsNone(history[0]['job'])
351 self.assertEqual(history[1]['job'].id, kept.id)
352
353 # The deleted job is still shown, with the enqueue time recorded in the history
354 self.assertContains(response, deleted.id)
355 self.assertContains(response, 'expired or deleted')
356
357 # Only the job that still exists links to its job detail page
358 queue_index = response.context['queue_index']
359 self.assertContains(response, reverse(f'{prefix}job_detail', args=[queue_index, kept.id]))
360 self.assertNotContains(response, reverse(f'{prefix}job_detail', args=[queue_index, deleted.id]))
361
362 def test_cron_job_detail_view_404s(self):
363 """Cron job detail 404s on unknown cron jobs, schedulers and connection indexes."""
364 scheduler = DjangoCronScheduler(name='job-history-404-scheduler')
365 scheduler.register(say_hello, 'default', interval=60)
366 scheduler.register_birth()
367 self.addCleanup(scheduler.register_death)
368 connection_index = scheduler.connection_index
369 known = 'tests.fixtures.say_hello'
370
371 for prefix in ('admin:django_rq_', 'django_rq:'):
372 for args in (
373 [connection_index, 'job-history-404-scheduler', 'unknown-cron-job'],
374 [connection_index, 'nonexistent-scheduler', known],
375 [999, 'job-history-404-scheduler', known],
376 ):
377 response = self.client.get(reverse(f'{prefix}cron_job_detail', args=args))
378 self.assertEqual(response.status_code, 404)
379
380 @requires_job_history
381 def test_cron_job_detail_view_pagination(self):
382 """An unusable page number shows a valid page, not the wrong end of the history."""
383 scheduler = DjangoCronScheduler(name='paginated-scheduler')
384 cron_job = scheduler.register(say_hello, 'default', interval=60, name='paginated-history')
385 scheduler.register_birth()
386 self.addCleanup(scheduler.register_death)
387
388 connection = scheduler.connection
389 self.addCleanup(connection.delete, cron_job.job_history_key)
390
391 # Enough entries to span 13 pages, so the page range is elided. History entries outlive
392 # the jobs themselves, so recording IDs scored by enqueue time is all
393 # `CronJob.enqueue()` leaves behind.
394 last_page = 13
395 num_entries = ITEMS_PER_PAGE * (last_page - 1) + 5
396 connection.zadd(cron_job.job_history_key, {f'job-{i:03}': float(i) for i in range(num_entries)})
397 newest_job_id = f'job-{num_entries - 1:03}'
398
399 url = reverse(
400 'django_rq:cron_job_detail',
401 args=[scheduler.connection_index, 'paginated-scheduler', 'paginated-history'],
402 )
403
404 # `?page=0` used to slice from the end of the history and quietly render the oldest jobs
405 for page in ('0', '-1', 'abc', ''):
406 response = self.client.get(url, {'page': page})
407 self.assertEqual(response.status_code, 200)
408 self.assertEqual(response.context['page'], 1)
409 history = response.context['history']
410 self.assertEqual(len(history), ITEMS_PER_PAGE)
411 self.assertEqual(history[0]['job_id'], newest_job_id)
412
413 # Only a handful of the 13 pages are linked, and the gap marker isn't itself a link
414 page_range = response.context['page_range']
415 self.assertIn(Paginator.ELLIPSIS, page_range)
416 self.assertLess(len(page_range), last_page)
417 self.assertNotContains(response, f'?page={Paginator.ELLIPSIS}')
418
419 # A page past the end, including one too large for a Redis index, shows the last page
420 for page in ('999', '9' * 30):
421 response = self.client.get(url, {'page': page})
422 self.assertEqual(response.status_code, 200)
423 self.assertEqual(response.context['page'], last_page)
424 self.assertEqual(response.context['history'][-1]['job_id'], 'job-000')
425
426 @requires_job_history
427 def test_cron_job_detail_view_with_no_jobs(self):
428 """Cron job detail gracefully handles a cron job that hasn't run yet."""
429 scheduler = DjangoCronScheduler(name='no-history-scheduler')
430 scheduler.register(say_hello, 'default', interval=60, name='never-run')
431 scheduler.register_birth()
432 self.addCleanup(scheduler.register_death)
433
434 for prefix in ('admin:django_rq_', 'django_rq:'):
435 url = reverse(
436 f'{prefix}cron_job_detail',
437 args=[scheduler.connection_index, 'no-history-scheduler', 'never-run'],
438 )
439 response = self.client.get(url)
440 self.assertEqual(response.status_code, 200)
441 self.assertEqual(response.context['history'], [])
442 self.assertContains(response, 'No jobs recorded for this cron job')