from contextlib import suppress from io import StringIO from unittest import skipIf from unittest.mock import patch from django.contrib.auth.models import User from django.core.management import call_command from django.core.paginator import Paginator from django.test import TestCase, override_settings from django.test.client import Client from django.urls import reverse from rq.cron import CronJob from django_rq import get_connection from django_rq.cron import ( CRON_JOB_HISTORY_SUPPORTED, DjangoCronScheduler, get_cron_job_history, get_cron_job_history_count, ) from django_rq.cron_views import ITEMS_PER_PAGE from tests.fixtures import say_hello # `CronJob.name`, `job_history_key` and `get_job_ids()` were added in RQ 2.11, but django-rq # still supports older versions and degrades gracefully requires_job_history = skipIf(not CRON_JOB_HISTORY_SUPPORTED, 'requires RQ >= 2.11') class CronTest(TestCase): def test_django_cron_scheduler_init(self): """Test DjangoCronScheduler can be initialized without connection.""" scheduler = DjangoCronScheduler() # Should not have connection until first register() call self.assertIsNone(scheduler.connection) self.assertIsNone(scheduler._connection_config) self.assertEqual(scheduler._cron_jobs, []) def test_first_register_initializes_connection(self): """Test that first register() call initializes the scheduler with queue's connection.""" scheduler = DjangoCronScheduler() # Register a job with cron expression (run every minute) cron_job = scheduler.register(say_hello, "default", cron="* * * * *") # Should now have connection set self.assertIsNotNone(scheduler.connection) self.assertIsNotNone(scheduler._connection_config) self.assertIsInstance(cron_job, CronJob) self.assertEqual(len(scheduler.get_jobs()), 1) # Verify cron expression is set correctly self.assertEqual(cron_job.cron, "* * * * *") self.assertIsNone(cron_job.interval) # self.assertIsNotNone(cron_job.next_run_time) def test_register_with_webhooks(self): """webhooks passed to register() are forwarded to the underlying CronJob.""" from rq.webhook import Webhook webhook = Webhook('https://example.com/hook', 'finished') scheduler = DjangoCronScheduler() cron_job = scheduler.register(say_hello, 'default', interval=60, webhooks=[webhook]) self.assertEqual(cron_job.job_options['webhooks'], [webhook]) @requires_job_history def test_register_with_name(self): """A cron job's name defaults to the function's import path and can be overridden.""" scheduler = DjangoCronScheduler() default_name = scheduler.register(say_hello, 'default', interval=60) named = scheduler.register(say_hello, 'default', interval=60, name='nightly-report') self.assertEqual(default_name.name, 'tests.fixtures.say_hello') self.assertEqual(named.name, 'nightly-report') @requires_job_history def test_cron_job_history(self): """Job history returns (job_id, enqueued_at) pairs, newest first.""" scheduler = DjangoCronScheduler() cron_job = scheduler.register(say_hello, 'default', interval=60, name='history-test') connection = scheduler.connection self.addCleanup(connection.delete, cron_job.job_history_key) # A cron job that hasn't run yet has no history self.assertEqual(get_cron_job_history(cron_job, connection), []) first = cron_job.enqueue(connection) second = cron_job.enqueue(connection) self.addCleanup(second.delete) self.addCleanup(first.delete) history = get_cron_job_history(cron_job, connection) self.assertEqual([job_id for job_id, _ in history], [second.id, first.id]) self.assertEqual(get_cron_job_history_count(cron_job, connection), 2) # Timestamps come from the sorted set score, which is the job's enqueue time self.assertAlmostEqual(history[0][1].timestamp(), second.enqueued_at.timestamp(), places=3) # start/end are inclusive indexes into the newest first ordering, which is what paginates self.assertEqual([job_id for job_id, _ in get_cron_job_history(cron_job, connection, 1, 1)], [first.id]) def test_connection_validation(self): """Test connection validation for same, compatible, and incompatible queues.""" # Start with test3 queue (secondary Redis DB configured for tests) scheduler = DjangoCronScheduler() # Same queue multiple times should work job1 = scheduler.register(say_hello, "test3", interval=60) job2 = scheduler.register(say_hello, "test3", interval=120) self.assertEqual(len(scheduler.get_jobs()), 2) self.assertEqual(job1.queue_name, "test3") self.assertEqual(job2.queue_name, "test3") # Compatible queues (same Redis connection) should work # Both 'test3' and 'async' share the same Redis connection settings job3 = scheduler.register(say_hello, "async", interval=180) self.assertEqual(len(scheduler.get_jobs()), 3) self.assertEqual(job3.queue_name, "async") # Queues having different Redis connections should fail with self.assertRaises(ValueError): scheduler.register(say_hello, "default", interval=240) # Undefined queue_name should fail scheduler = DjangoCronScheduler() with self.assertRaises(KeyError): scheduler.register(say_hello, "nonexistent_queue", interval=300) def test_connection_index_property(self): """Test connection_index property returns correct index or raises appropriate exceptions.""" scheduler = DjangoCronScheduler() # Before any registration, connection_index should raise ValueError with self.assertRaises(ValueError): _ = scheduler.connection_index # Register a job with 'test3' queue (secondary Redis DB configured for tests) scheduler.register(say_hello, "test3", interval=60) # Now connection_index should return a valid index connection_index = scheduler.connection_index self.assertGreaterEqual(connection_index, 0) # Test with a queue using a different connection scheduler2 = DjangoCronScheduler() scheduler2.register(say_hello, "default", interval=60) # Uses DB=0 # Should have a different connection_index self.assertNotEqual(scheduler2.connection_index, scheduler.connection_index) class CronCommandTest(TestCase): @patch('django_rq.cron.DjangoCronScheduler.start') def test_rqcron_command(self, mock_start): """Test rqcron command execution: success and import errors from load_config_from_file.""" mock_start.return_value = None # Test 1: Successful execution out = StringIO() config_path = "tests.cron_config1" call_command("rqcron", config_path, stdout=out) output = out.getvalue() self.assertIn(f"Loading cron configuration from {config_path}", output) self.assertIn("Starting cron scheduler with 2 jobs...", output) mock_start.assert_called_once() # Test 2: File not found - should raise ImportError from RQ with self.assertRaises(ImportError) as cm: call_command("rqcron", "nonexistent_file.py") self.assertIn("No module named 'nonexistent_file'", str(cm.exception)) # Test 3: Import error with self.assertRaises(ImportError) as cm: call_command("rqcron", "nonexistent.module.path") self.assertIn("No module named 'nonexistent'", str(cm.exception)) @patch("django_rq.cron.DjangoCronScheduler.start") @patch("django_rq.cron.DjangoCronScheduler.load_config_from_file") def test_rqcron_command_exceptions(self, mock_load_config, mock_start): """Test rqcron command exception handling.""" mock_load_config.return_value = None # Test KeyboardInterrupt handling mock_start.side_effect = KeyboardInterrupt() with self.assertRaises(SystemExit): call_command("rqcron", "tests.cron_config2") # Test general exception handling - should bubble up as raw exception mock_load_config.side_effect = Exception("Test error") with self.assertRaises(Exception) as cm: call_command("rqcron", "tests.cron_config2") self.assertEqual(str(cm.exception), "Test error") def test_rqcron_command_successful_run(self): """Test successful rqcron command execution without mocking.""" out = StringIO() config_path = "tests.cron_config1" # Use a very short timeout to test actual execution import signal def timeout_handler(signum, frame): raise KeyboardInterrupt() # Set up a timeout to stop the command after a short time old_handler = signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(1) # Stop after 1 second try: # The command will be interrupted and may or may not raise SystemExit depending on Django version with suppress(SystemExit): call_command("rqcron", config_path, stdout=out) finally: signal.alarm(0) # Cancel the alarm signal.signal(signal.SIGALRM, old_handler) output = out.getvalue() self.assertIn(f"Loading cron configuration from {config_path}", output) self.assertIn("Starting cron scheduler with 2 jobs...", output) @override_settings(ROOT_URLCONF='tests.default_with_custom_mount_urls') class CronViewTest(TestCase): def setUp(self): """Set up test user and client.""" self.user = User.objects.create_user('foo', password='pass', is_staff=True, is_active=True) self.client = Client() self.client.login(username=self.user.username, password='pass') def test_cron_scheduler_detail_view(self): """Test cron scheduler detail view with various scenarios.""" # Create a real scheduler and register it scheduler = DjangoCronScheduler(name='test-scheduler') scheduler.register( say_hello, "default", interval=60, args=("hello",), kwargs={"target": "world"}, meta={"source": "test"}, job_timeout=20, result_ttl=500, ttl=60, failure_ttl=120, ) from rq.webhook import Webhook webhook = Webhook('https://example.com/hook', 'failed') scheduler.register(say_hello, "default", cron="*/5 * * * *", webhooks=[webhook]) scheduler.register_birth() for prefix in ('admin:django_rq_', 'django_rq:'): # Test 1: Successful view of existing scheduler connection_index = scheduler.connection_index url = reverse(f'{prefix}cron_scheduler_detail', args=[connection_index, 'test-scheduler']) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['scheduler'].name, 'test-scheduler') self.assertEqual(len(response.context['cron_jobs']), 2) first_cron_job = response.context['cron_jobs'][0] self.assertEqual(first_cron_job['func_name'], 'tests.fixtures.say_hello') self.assertEqual(first_cron_job['queue_name'], 'default') self.assertEqual(first_cron_job['schedule'], 'Every 60 seconds') self.assertContains(response, 'test-scheduler') self.assertContains(response, 'Cron Jobs') self.assertContains(response, 'tests.fixtures.say_hello') self.assertContains(response, 'default') self.assertContains(response, 'Every 60 seconds') self.assertContains(response, 'Cron: */5 * * * *') # Each cron job's name links to its job history, where RQ provides one if CRON_JOB_HISTORY_SUPPORTED: self.assertContains( response, reverse( f'{prefix}cron_job_detail', args=[connection_index, 'test-scheduler', 'tests.fixtures.say_hello'], ), ) # Webhooks: first job has none, second job's webhook is exposed in the context self.assertEqual(first_cron_job['webhooks'], []) self.assertEqual(response.context['cron_jobs'][1]['webhooks'], [webhook]) # Test 2: Non-existent scheduler returns 404 url = reverse(f'{prefix}cron_scheduler_detail', args=[connection_index, 'nonexistent-scheduler']) response = self.client.get(url) self.assertEqual(response.status_code, 404) # Test 3: Invalid connection index returns 404 url = reverse(f'{prefix}cron_scheduler_detail', args=[999, 'test-scheduler']) response = self.client.get(url) self.assertEqual(response.status_code, 404) # Clean up scheduler.register_death() def test_cron_scheduler_detail_view_with_no_jobs(self): """Test cron scheduler detail view gracefully handles schedulers with no jobs.""" scheduler = DjangoCronScheduler(connection=get_connection("default"), name='empty-scheduler') scheduler.register_birth() for prefix in ('admin:django_rq_', 'django_rq:'): url = reverse(f'{prefix}cron_scheduler_detail', args=[scheduler.connection_index, 'empty-scheduler']) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['scheduler'].name, 'empty-scheduler') self.assertEqual(response.context['cron_jobs'], []) self.assertContains(response, 'No persisted cron jobs found') scheduler.register_death() @requires_job_history def test_cron_job_detail_view(self): """Cron job detail lists spawned jobs, including those whose job data is gone.""" scheduler = DjangoCronScheduler(name='job-history-scheduler') cron_job = scheduler.register(say_hello, 'default', interval=60, name='history-view-test') scheduler.register_birth() self.addCleanup(scheduler.register_death) connection = scheduler.connection self.addCleanup(connection.delete, cron_job.job_history_key) kept = cron_job.enqueue(connection) self.addCleanup(kept.delete) # A job's data is deleted long before its history entry expires deleted = cron_job.enqueue(connection) deleted.delete() for prefix in ('admin:django_rq_', 'django_rq:'): url = reverse( f'{prefix}cron_job_detail', args=[scheduler.connection_index, 'job-history-scheduler', 'history-view-test'], ) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['cron_job']['name'], 'history-view-test') # Both entries are listed newest first, even though one job no longer exists history = response.context['history'] self.assertEqual([entry['job_id'] for entry in history], [deleted.id, kept.id]) self.assertEqual(response.context['num_jobs'], 2) self.assertIsNone(history[0]['job']) self.assertEqual(history[1]['job'].id, kept.id) # The deleted job is still shown, with the enqueue time recorded in the history self.assertContains(response, deleted.id) self.assertContains(response, 'expired or deleted') # Only the job that still exists links to its job detail page queue_index = response.context['queue_index'] self.assertContains(response, reverse(f'{prefix}job_detail', args=[queue_index, kept.id])) self.assertNotContains(response, reverse(f'{prefix}job_detail', args=[queue_index, deleted.id])) def test_cron_job_detail_view_404s(self): """Cron job detail 404s on unknown cron jobs, schedulers and connection indexes.""" scheduler = DjangoCronScheduler(name='job-history-404-scheduler') scheduler.register(say_hello, 'default', interval=60) scheduler.register_birth() self.addCleanup(scheduler.register_death) connection_index = scheduler.connection_index known = 'tests.fixtures.say_hello' for prefix in ('admin:django_rq_', 'django_rq:'): for args in ( [connection_index, 'job-history-404-scheduler', 'unknown-cron-job'], [connection_index, 'nonexistent-scheduler', known], [999, 'job-history-404-scheduler', known], ): response = self.client.get(reverse(f'{prefix}cron_job_detail', args=args)) self.assertEqual(response.status_code, 404) @requires_job_history def test_cron_job_detail_view_pagination(self): """An unusable page number shows a valid page, not the wrong end of the history.""" scheduler = DjangoCronScheduler(name='paginated-scheduler') cron_job = scheduler.register(say_hello, 'default', interval=60, name='paginated-history') scheduler.register_birth() self.addCleanup(scheduler.register_death) connection = scheduler.connection self.addCleanup(connection.delete, cron_job.job_history_key) # Enough entries to span 13 pages, so the page range is elided. History entries outlive # the jobs themselves, so recording IDs scored by enqueue time is all # `CronJob.enqueue()` leaves behind. last_page = 13 num_entries = ITEMS_PER_PAGE * (last_page - 1) + 5 connection.zadd(cron_job.job_history_key, {f'job-{i:03}': float(i) for i in range(num_entries)}) newest_job_id = f'job-{num_entries - 1:03}' url = reverse( 'django_rq:cron_job_detail', args=[scheduler.connection_index, 'paginated-scheduler', 'paginated-history'], ) # `?page=0` used to slice from the end of the history and quietly render the oldest jobs for page in ('0', '-1', 'abc', ''): response = self.client.get(url, {'page': page}) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['page'], 1) history = response.context['history'] self.assertEqual(len(history), ITEMS_PER_PAGE) self.assertEqual(history[0]['job_id'], newest_job_id) # Only a handful of the 13 pages are linked, and the gap marker isn't itself a link page_range = response.context['page_range'] self.assertIn(Paginator.ELLIPSIS, page_range) self.assertLess(len(page_range), last_page) self.assertNotContains(response, f'?page={Paginator.ELLIPSIS}') # A page past the end, including one too large for a Redis index, shows the last page for page in ('999', '9' * 30): response = self.client.get(url, {'page': page}) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['page'], last_page) self.assertEqual(response.context['history'][-1]['job_id'], 'job-000') @requires_job_history def test_cron_job_detail_view_with_no_jobs(self): """Cron job detail gracefully handles a cron job that hasn't run yet.""" scheduler = DjangoCronScheduler(name='no-history-scheduler') scheduler.register(say_hello, 'default', interval=60, name='never-run') scheduler.register_birth() self.addCleanup(scheduler.register_death) for prefix in ('admin:django_rq_', 'django_rq:'): url = reverse( f'{prefix}cron_job_detail', args=[scheduler.connection_index, 'no-history-scheduler', 'never-run'], ) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['history'], []) self.assertContains(response, 'No jobs recorded for this cron job')