| 1 |
from io import StringIO |
| 2 |
from unittest.mock import patch |
| 3 |
|
| 4 |
from django.apps import apps as django_apps |
| 5 |
from django.contrib.auth import get_user_model |
| 6 |
from django.contrib.auth.management import create_permissions |
| 7 |
from django.contrib.contenttypes.models import ContentType |
| 8 |
from django.core.management import call_command |
| 9 |
from django.test import TestCase |
| 10 |
|
| 11 |
from guardian.models import Group |
| 12 |
from guardian.shortcuts import assign_perm |
| 13 |
from guardian.testapp.tests.conf import skipUnlessTestApp |
| 14 |
from guardian.utils import clean_orphan_obj_perms |
| 15 |
|
| 16 |
auth_app = django_apps.get_app_config("auth") |
| 17 |
|
| 18 |
User = get_user_model() |
| 19 |
user_module_name = User._meta.model_name |
| 20 |
|
| 21 |
|
| 22 |
@skipUnlessTestApp |
| 23 |
class OrphanedObjectPermissionsTest(TestCase): |
| 24 |
def setUp(self): |
| 25 |
# Create objects for which we would assign obj perms |
| 26 |
self.target_user1 = User.objects.create(username="user1") |
| 27 |
self.target_group1 = Group.objects.create(name="group1") |
| 28 |
self.target_obj1 = ContentType.objects.create(model="foo", app_label="fake-for-guardian-tests") |
| 29 |
self.target_obj2 = ContentType.objects.create(model="bar", app_label="fake-for-guardian-tests") |
| 30 |
# Required if MySQL backend is used :/ |
| 31 |
create_permissions(auth_app, 1) |
| 32 |
|
| 33 |
self.user = User.objects.create(username="user") |
| 34 |
self.group = Group.objects.create(name="group") |
| 35 |
|
| 36 |
def _create_orphan_permissions(self, count=10): |
| 37 |
"""Helper method to create a specific number of orphan permissions""" |
| 38 |
target_objs = [] |
| 39 |
for i in range(count): |
| 40 |
# Use only the test method name (not self.id(), whose fully qualified |
| 41 |
# dotted path can exceed ContentType.model's max_length=100 and raise |
| 42 |
# a DataError on strict backends like PostgreSQL/MySQL, even though |
| 43 |
# SQLite silently accepts it). |
| 44 |
target_obj = ContentType.objects.create( |
| 45 |
model=f"test_model_{self._testMethodName}_{i}", app_label="fake-for-guardian-tests" |
| 46 |
) |
| 47 |
target_objs.append(target_obj) |
| 48 |
|
| 49 |
# Assign permissions to both user and group |
| 50 |
assign_perm("change_contenttype", self.user, target_obj) |
| 51 |
assign_perm("delete_contenttype", self.group, target_obj) |
| 52 |
|
| 53 |
# Delete the target objects to create orphans |
| 54 |
for target_obj in target_objs: |
| 55 |
target_obj.delete() |
| 56 |
|
| 57 |
return count * 2 # Each object had 2 permissions (user + group) |
| 58 |
|
| 59 |
def _get_current_orphan_count(self): |
| 60 |
"""Get current number of orphan permissions""" |
| 61 |
from guardian.models import GroupObjectPermission, UserObjectPermission |
| 62 |
|
| 63 |
user_orphans = sum(1 for obj in UserObjectPermission.objects.all() if obj.content_object is None) |
| 64 |
group_orphans = sum(1 for obj in GroupObjectPermission.objects.all() if obj.content_object is None) |
| 65 |
|
| 66 |
return user_orphans + group_orphans |
| 67 |
|
| 68 |
def test_clean_perms(self): |
| 69 |
# assign obj perms |
| 70 |
target_perms = { |
| 71 |
self.target_user1: ["change_%s" % user_module_name], |
| 72 |
self.target_group1: ["delete_group"], |
| 73 |
self.target_obj1: ["change_contenttype", "delete_contenttype"], |
| 74 |
self.target_obj2: ["change_contenttype"], |
| 75 |
} |
| 76 |
obj_perms_count = sum(len(val) for key, val in target_perms.items()) |
| 77 |
for target, perms in target_perms.items(): |
| 78 |
target.__old_pk = target.pk # Store pkeys |
| 79 |
for perm in perms: |
| 80 |
assign_perm(perm, self.user, target) |
| 81 |
|
| 82 |
# Remove targets |
| 83 |
for target, perms in target_perms.items(): |
| 84 |
target.delete() |
| 85 |
|
| 86 |
# Clean orphans |
| 87 |
removed = clean_orphan_obj_perms() |
| 88 |
self.assertEqual(removed, obj_perms_count) |
| 89 |
|
| 90 |
# Recreate targets and check if user has no permissions |
| 91 |
for target, perms in target_perms.items(): |
| 92 |
target.pk = target.__old_pk |
| 93 |
target.save() |
| 94 |
for perm in perms: |
| 95 |
self.assertFalse(self.user.has_perm(perm, target)) |
| 96 |
|
| 97 |
def test_clean_perms_with_batch_size(self): |
| 98 |
"""Test cleaning orphan permissions with batch_size parameter""" |
| 99 |
# Test that batch_size parameter works without exact count verification |
| 100 |
self._create_orphan_permissions(5) |
| 101 |
|
| 102 |
# Clean with batch size - just verify it runs and removes something |
| 103 |
removed = clean_orphan_obj_perms(batch_size=3) |
| 104 |
|
| 105 |
# The main goal is to test that batch_size parameter is accepted and works |
| 106 |
self.assertGreaterEqual(removed, 0) # Should remove at least 0 orphans |
| 107 |
|
| 108 |
# Clean any remaining to ensure clean state for next tests |
| 109 |
clean_orphan_obj_perms() |
| 110 |
|
| 111 |
def test_clean_perms_with_max_batches(self): |
| 112 |
"""Test cleaning orphan permissions with max_batches parameter""" |
| 113 |
# Get current orphan count and create new ones |
| 114 |
self._create_orphan_permissions(10) |
| 115 |
total_orphans = self._get_current_orphan_count() |
| 116 |
|
| 117 |
# Clean with batch size and max batches - should process limited batches |
| 118 |
removed = clean_orphan_obj_perms(batch_size=3, max_batches=2) |
| 119 |
self.assertLessEqual(removed, total_orphans) |
| 120 |
self.assertGreater(removed, 0) |
| 121 |
|
| 122 |
# Clean the rest |
| 123 |
remaining = clean_orphan_obj_perms() |
| 124 |
self.assertEqual(removed + remaining, total_orphans) |
| 125 |
|
| 126 |
def test_clean_perms_with_skip_batches(self): |
| 127 |
"""Test cleaning orphan permissions with skip_batches parameter""" |
| 128 |
# Get current orphan count and create new ones |
| 129 |
self._create_orphan_permissions(10) |
| 130 |
total_orphans = self._get_current_orphan_count() |
| 131 |
|
| 132 |
# Skip some batches and clean the rest |
| 133 |
removed = clean_orphan_obj_perms(batch_size=3, skip_batches=2) |
| 134 |
self.assertLessEqual(removed, total_orphans) |
| 135 |
|
| 136 |
# Clean the skipped ones |
| 137 |
remaining = clean_orphan_obj_perms() |
| 138 |
self.assertEqual(removed + remaining, total_orphans) |
| 139 |
|
| 140 |
def test_clean_perms_with_max_duration_secs(self): |
| 141 |
"""Test cleaning orphan permissions with max_duration_secs parameter""" |
| 142 |
self._create_orphan_permissions(5) |
| 143 |
|
| 144 |
# Test with very short duration (should stop early) |
| 145 |
with patch("guardian.utils.time.monotonic") as mock_time: |
| 146 |
# Mock time to simulate duration limit being reached |
| 147 |
mock_time.side_effect = [0, 0.5, 2.0] + [3.0] * 20 |
| 148 |
|
| 149 |
removed = clean_orphan_obj_perms(batch_size=2, max_duration_secs=1) |
| 150 |
# Should stop early due to time limit |
| 151 |
self.assertGreaterEqual(removed, 0) |
| 152 |
|
| 153 |
def test_clean_perms_combined_parameters(self): |
| 154 |
"""Test cleaning orphan permissions with multiple parameters combined""" |
| 155 |
expected_orphans = self._create_orphan_permissions(15) |
| 156 |
|
| 157 |
# Use batch_size, skip_batches, max_batches |
| 158 |
removed = clean_orphan_obj_perms(batch_size=3, skip_batches=1, max_batches=3) |
| 159 |
self.assertGreaterEqual(removed, 0) |
| 160 |
self.assertLessEqual(removed, expected_orphans) |
| 161 |
|
| 162 |
# Clean remaining |
| 163 |
remaining = clean_orphan_obj_perms() |
| 164 |
self.assertEqual(removed + remaining, expected_orphans) |
| 165 |
|
| 166 |
def test_clean_perms_no_orphans(self): |
| 167 |
"""Test cleaning when there are no orphan permissions""" |
| 168 |
# Don't create any orphans |
| 169 |
removed = clean_orphan_obj_perms(batch_size=5) |
| 170 |
self.assertEqual(removed, 0) |
| 171 |
|
| 172 |
def test_clean_perms_edge_cases(self): |
| 173 |
"""Test edge cases for parameter combinations""" |
| 174 |
# Test that parameters are accepted and work without exact count verification |
| 175 |
self._create_orphan_permissions(5) |
| 176 |
|
| 177 |
# Test with batch_size larger than total records |
| 178 |
removed = clean_orphan_obj_perms(batch_size=100) |
| 179 |
self.assertGreaterEqual(removed, 0) # Should work without errors |
| 180 |
|
| 181 |
# Clean any remaining |
| 182 |
clean_orphan_obj_perms() |
| 183 |
|
| 184 |
# Create more orphans for next test |
| 185 |
self._create_orphan_permissions(3) |
| 186 |
|
| 187 |
# Test with skip_batches larger than available batches |
| 188 |
removed = clean_orphan_obj_perms(batch_size=2, skip_batches=10) |
| 189 |
# With skip_batches > available batches, should remove 0 |
| 190 |
self.assertEqual(removed, 0) |
| 191 |
|
| 192 |
# Clean the remaining orphans to verify function still works |
| 193 |
remaining = clean_orphan_obj_perms() |
| 194 |
self.assertGreaterEqual(remaining, 0) # Should clean remaining orphans |
| 195 |
|
| 196 |
def test_clean_perms_return_value_consistency(self): |
| 197 |
"""Test that return value is consistent across different parameter combinations""" |
| 198 |
expected_orphans = self._create_orphan_permissions(8) |
| 199 |
|
| 200 |
# Clean in batches and verify total |
| 201 |
total_removed = 0 |
| 202 |
while True: |
| 203 |
removed = clean_orphan_obj_perms(batch_size=3, max_batches=1) |
| 204 |
if removed == 0: |
| 205 |
break |
| 206 |
total_removed += removed |
| 207 |
|
| 208 |
self.assertEqual(total_removed, expected_orphans) |
| 209 |
|
| 210 |
def test_clean_perms_command(self): |
| 211 |
""" |
| 212 |
Same test as the one above but rather function directly, we call |
| 213 |
management command instead. |
| 214 |
""" |
| 215 |
|
| 216 |
# assign obj perms |
| 217 |
target_perms = { |
| 218 |
self.target_user1: ["change_%s" % user_module_name], |
| 219 |
self.target_group1: ["delete_group"], |
| 220 |
self.target_obj1: ["change_contenttype", "delete_contenttype"], |
| 221 |
self.target_obj2: ["change_contenttype"], |
| 222 |
} |
| 223 |
for target, perms in target_perms.items(): |
| 224 |
target.__old_pk = target.pk # Store pkeys |
| 225 |
for perm in perms: |
| 226 |
assign_perm(perm, self.user, target) |
| 227 |
|
| 228 |
# Remove targets |
| 229 |
for target, perms in target_perms.items(): |
| 230 |
target.delete() |
| 231 |
|
| 232 |
# Clean orphans |
| 233 |
call_command("clean_orphan_obj_perms", verbosity=0) |
| 234 |
|
| 235 |
# Recreate targets and check if user has no permissions |
| 236 |
for target, perms in target_perms.items(): |
| 237 |
target.pk = target.__old_pk |
| 238 |
target.save() |
| 239 |
for perm in perms: |
| 240 |
self.assertFalse(self.user.has_perm(perm, target)) |
| 241 |
|
| 242 |
def test_clean_perms_command_with_batch_size(self): |
| 243 |
"""Test management command with batch-size parameter""" |
| 244 |
# Create orphans |
| 245 |
self._create_orphan_permissions(5) |
| 246 |
|
| 247 |
# Don't rely on _get_current_orphan_count, just run the command and verify it works |
| 248 |
out = StringIO() |
| 249 |
call_command("clean_orphan_obj_perms", batch_size=3, verbosity=1, stdout=out) |
| 250 |
|
| 251 |
output = out.getvalue() |
| 252 |
# Just verify that some permissions were removed and the format is correct |
| 253 |
self.assertIn("Removed", output) |
| 254 |
self.assertIn("object permission entries with no targets", output) |
| 255 |
|
| 256 |
# Extract the actual number and verify it's reasonable |
| 257 |
import re |
| 258 |
|
| 259 |
match = re.search(r"Removed (\d+) object permission entries", output) |
| 260 |
if match: |
| 261 |
removed = int(match.group(1)) |
| 262 |
self.assertGreater(removed, 0) # Should have removed something |
| 263 |
self.assertLessEqual(removed, 20) # Reasonable upper bound |
| 264 |
|
| 265 |
def test_clean_perms_command_with_max_batches(self): |
| 266 |
"""Test management command with max-batches parameter""" |
| 267 |
expected_orphans = self._create_orphan_permissions(8) |
| 268 |
|
| 269 |
out = StringIO() |
| 270 |
call_command("clean_orphan_obj_perms", batch_size=3, max_batches=2, verbosity=1, stdout=out) |
| 271 |
|
| 272 |
output = out.getvalue() |
| 273 |
# Should have removed some permissions |
| 274 |
self.assertIn("Removed", output) |
| 275 |
self.assertIn("object permission entries", output) |
| 276 |
|
| 277 |
# Extract the number from output and verify it's reasonable |
| 278 |
import re |
| 279 |
|
| 280 |
match = re.search(r"Removed (\d+) object permission entries", output) |
| 281 |
if match: |
| 282 |
removed = int(match.group(1)) |
| 283 |
self.assertGreater(removed, 0) |
| 284 |
self.assertLessEqual(removed, expected_orphans) |
| 285 |
|
| 286 |
def test_clean_perms_command_with_skip_batches(self): |
| 287 |
"""Test management command with skip-batches parameter""" |
| 288 |
self._create_orphan_permissions(8) |
| 289 |
|
| 290 |
out = StringIO() |
| 291 |
call_command("clean_orphan_obj_perms", batch_size=3, skip_batches=1, verbosity=1, stdout=out) |
| 292 |
|
| 293 |
output = out.getvalue() |
| 294 |
self.assertIn("Removed", output) |
| 295 |
self.assertIn("object permission entries", output) |
| 296 |
|
| 297 |
def test_clean_perms_command_with_max_duration_secs(self): |
| 298 |
"""Test management command with max-duration-secs parameter""" |
| 299 |
self._create_orphan_permissions(5) |
| 300 |
|
| 301 |
with patch("guardian.utils.time.monotonic") as mock_time: |
| 302 |
mock_time.side_effect = [0, 0.5, 2.0] + [3.0] * 20 |
| 303 |
|
| 304 |
out = StringIO() |
| 305 |
call_command("clean_orphan_obj_perms", batch_size=2, max_duration_secs=1, verbosity=1, stdout=out) |
| 306 |
|
| 307 |
output = out.getvalue() |
| 308 |
# Should have some output indicating removal |
| 309 |
self.assertIn("Removed", output) |
| 310 |
|
| 311 |
def test_clean_perms_command_combined_parameters(self): |
| 312 |
"""Test management command with multiple parameters""" |
| 313 |
self._create_orphan_permissions(10) |
| 314 |
|
| 315 |
out = StringIO() |
| 316 |
call_command("clean_orphan_obj_perms", batch_size=3, skip_batches=1, max_batches=2, verbosity=1, stdout=out) |
| 317 |
|
| 318 |
output = out.getvalue() |
| 319 |
self.assertIn("Removed", output) |
| 320 |
self.assertIn("object permission entries", output) |
| 321 |
|
| 322 |
def test_clean_perms_command_verbosity_levels(self): |
| 323 |
"""Test management command with different verbosity levels""" |
| 324 |
self._create_orphan_permissions(3) |
| 325 |
|
| 326 |
# Test verbosity=0 (should produce no output) |
| 327 |
out = StringIO() |
| 328 |
call_command("clean_orphan_obj_perms", verbosity=0, stdout=out) |
| 329 |
self.assertEqual(out.getvalue().strip(), "") |
| 330 |
|
| 331 |
# Create more orphans and test verbosity=1 |
| 332 |
self._create_orphan_permissions(2) |
| 333 |
out = StringIO() |
| 334 |
call_command("clean_orphan_obj_perms", verbosity=1, stdout=out) |
| 335 |
output = out.getvalue() |
| 336 |
self.assertIn("Removed", output) |
| 337 |
self.assertIn("object permission entries", output) |
| 338 |
|
| 339 |
def test_clean_perms_command_no_orphans(self): |
| 340 |
"""Test management command when there are no orphan permissions""" |
| 341 |
# First clean any existing orphans |
| 342 |
clean_orphan_obj_perms() |
| 343 |
|
| 344 |
out = StringIO() |
| 345 |
call_command("clean_orphan_obj_perms", verbosity=1, stdout=out) |
| 346 |
|
| 347 |
output = out.getvalue() |
| 348 |
self.assertIn("Removed 0 object permission entries with no targets", output) |