|
1 | 1 | from datetime import timedelta |
| 2 | +from typing import TYPE_CHECKING |
2 | 3 |
|
3 | 4 | from django.utils import timezone |
4 | 5 | import pytest |
|
7 | 8 | from hope.contrib.aurora.celery_tasks import clean_old_record_files_task |
8 | 9 | from hope.contrib.aurora.models import Record |
9 | 10 |
|
| 11 | +if TYPE_CHECKING: |
| 12 | + from pytest_mock import MockerFixture |
| 13 | + |
10 | 14 | pytestmark = pytest.mark.django_db |
11 | 15 |
|
12 | 16 |
|
@@ -50,3 +54,45 @@ def test_clean_old_record_files_task(record_set: dict[str, Record]) -> None: |
50 | 54 | assert record_set["recent_imported"].id in remaining_ids |
51 | 55 | assert record_set["old_error"].id in remaining_ids |
52 | 56 | assert record_set["old_to_import"].id in remaining_ids |
| 57 | + |
| 58 | + |
| 59 | +def test_clean_old_record_files_task_empty() -> None: |
| 60 | + # No records at all |
| 61 | + clean_old_record_files_task() |
| 62 | + assert Record.objects.count() == 0 |
| 63 | + |
| 64 | + |
| 65 | +def test_clean_old_record_files_task_batching(mocker: "MockerFixture") -> None: |
| 66 | + now = timezone.now() |
| 67 | + # Create 5 records that should be deleted |
| 68 | + RecordFactory.create_batch(5, status=Record.STATUS_IMPORTED, timestamp=now - timedelta(days=100)) |
| 69 | + |
| 70 | + # Run with batch_size=2, should take 3 batches (2+2+1) |
| 71 | + clean_old_record_files_task(batch_size=2) |
| 72 | + |
| 73 | + assert Record.objects.count() == 0 |
| 74 | + |
| 75 | + |
| 76 | +def test_clean_old_record_files_task_logging(mocker: "MockerFixture") -> None: |
| 77 | + now = timezone.now() |
| 78 | + RecordFactory.create_batch(3, status=Record.STATUS_IMPORTED, timestamp=now - timedelta(days=100)) |
| 79 | + mock_logger = mocker.patch("hope.contrib.aurora.celery_tasks.logger") |
| 80 | + |
| 81 | + clean_old_record_files_task(batch_size=2) |
| 82 | + |
| 83 | + # Should log 2 batches and one final message |
| 84 | + assert mock_logger.info.call_count == 3 |
| 85 | + mock_logger.info.assert_any_call("Batch 1/2 (2 deleted, total: 2/3)") |
| 86 | + mock_logger.info.assert_any_call("Batch 2/2 (1 deleted, total: 3/3)") |
| 87 | + mock_logger.info.assert_any_call("Record files have been successfully cleared") |
| 88 | + |
| 89 | + |
| 90 | +def test_clean_old_record_files_task_error_handling(mocker: "MockerFixture") -> None: |
| 91 | + mock_logger = mocker.patch("hope.contrib.aurora.celery_tasks.logger") |
| 92 | + # Force an exception by mocking timezone.now to raise something |
| 93 | + mocker.patch("hope.contrib.aurora.celery_tasks.timezone.now", side_effect=Exception("Database error")) |
| 94 | + |
| 95 | + with pytest.raises(Exception, match="Database error"): |
| 96 | + clean_old_record_files_task() |
| 97 | + |
| 98 | + mock_logger.exception.assert_called_once_with("Error cleaning old record files") |
0 commit comments