From 1253d6aeaac3133ff9aed7d600a93d4d2f24d9dd Mon Sep 17 00:00:00 2001 From: tlebrize Date: Sat, 6 Jul 2019 00:37:21 +0200 Subject: [PATCH] added delete_access_logs management commands as well as tests for it #455 --- .../commands/axes_delete_access_logs.py | 18 +++++++++++++ axes/tests/test_management.py | 27 ++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 axes/management/commands/axes_delete_access_logs.py diff --git a/axes/management/commands/axes_delete_access_logs.py b/axes/management/commands/axes_delete_access_logs.py new file mode 100644 index 0000000..a0b49b6 --- /dev/null +++ b/axes/management/commands/axes_delete_access_logs.py @@ -0,0 +1,18 @@ +from django.core.management.base import BaseCommand +from django.utils import timezone + +from axes.models import AccessLog + +class Command(BaseCommand): + help = 'Deletes all logs that are older than `age` days old.' + + def add_arguments(self, parser): + parser.add_argument('age', type=int, help='In days.') + + def handle(self, *args, **options): + limit_date = timezone.now().date() - timezone.timedelta(days=options['age']) + to_be_deleted = AccessLog.objects.filter(attempt_time__gt=limit_date) + + self.stdout.write(f'{to_be_deleted.count()} logs will be deleted.') + + to_be_deleted.delete() diff --git a/axes/tests/test_management.py b/axes/tests/test_management.py index 976e028..b67b7f4 100644 --- a/axes/tests/test_management.py +++ b/axes/tests/test_management.py @@ -1,10 +1,35 @@ from io import StringIO +from unittest.mock import patch, Mock from django.core.management import call_command +from django.utils import timezone -from axes.models import AccessAttempt +from axes.models import AccessAttempt, AccessLog from axes.tests.base import AxesTestCase +class DeleteAccessLogsManagementCommandTestCase(AxesTestCase): + def setUp(self): + yesterday = timezone.now() - timezone.timedelta(days=1) + with patch('django.utils.timezone.now', Mock(return_value=yesterday)): + AccessLog.objects.create() + + ten_days_ago = timezone.now() - timezone.timedelta(days=10) + with patch('django.utils.timezone.now', Mock(return_value=ten_days_ago)): + AccessLog.objects.create() + + def test_axes_delete_access_logs(self): + expected = '1 logs will be deleted.\n' + + out = StringIO() + call_command('axes_delete_access_logs', 5, stdout=out) + + self.assertEqual(expected, out.getvalue()) + + out = StringIO() + call_command('axes_delete_access_logs', 15, stdout=out) + + self.assertEqual(expected, out.getvalue()) + class ManagementCommandTestCase(AxesTestCase): def setUp(self):