| 1 |
""" |
| 2 |
Tests for database indexes on Guardian models. |
| 3 |
|
| 4 |
These tests ensure that the indexes defined on UserObjectPermission and GroupObjectPermission |
| 5 |
models are properly created and improve query performance. |
| 6 |
""" |
| 7 |
|
| 8 |
from django.contrib.auth import get_user_model |
| 9 |
from django.contrib.auth.models import Group, Permission |
| 10 |
from django.contrib.contenttypes.models import ContentType |
| 11 |
from django.db import connection |
| 12 |
from django.test import TestCase, TransactionTestCase |
| 13 |
|
| 14 |
from guardian.models import GroupObjectPermission, UserObjectPermission |
| 15 |
from guardian.testapp.models import Project |
| 16 |
|
| 17 |
User = get_user_model() |
| 18 |
|
| 19 |
|
| 20 |
class IndexTestCase(TransactionTestCase): |
| 21 |
"""Test database indexes for Guardian models.""" |
| 22 |
|
| 23 |
def setUp(self): |
| 24 |
"""Set up test data.""" |
| 25 |
self.user = User.objects.create_user(username="testuser", email="[email protected]") |
| 26 |
self.group = Group.objects.create(name="testgroup") |
| 27 |
self.project = Project.objects.create(name="Test Project") |
| 28 |
self.content_type = ContentType.objects.get_for_model(Project) |
| 29 |
self.permission = Permission.objects.get(content_type=self.content_type, codename="add_project") |
| 30 |
|
| 31 |
def test_userobjectpermission_indexes_exist(self): |
| 32 |
"""Test that UserObjectPermission has the expected indexes.""" |
| 33 |
# Get table name for UserObjectPermission |
| 34 |
table_name = UserObjectPermission._meta.db_table |
| 35 |
|
| 36 |
# Get all indexes for the table |
| 37 |
with connection.cursor() as cursor: |
| 38 |
indexes = connection.introspection.get_constraints(cursor, table_name) |
| 39 |
|
| 40 |
# Look for our specific indexes |
| 41 |
index_fields_sets = [] |
| 42 |
for constraint_name, constraint_info in indexes.items(): |
| 43 |
if constraint_info.get("index", False): # Only check indexes, not other constraints |
| 44 |
index_fields_sets.append(set(constraint_info["columns"])) |
| 45 |
|
| 46 |
# Check if our expected indexes exist (using sets to ignore order) |
| 47 |
expected_indexes = [ |
| 48 |
{"permission_id", "user_id", "content_type_id", "object_pk"}, |
| 49 |
{"user_id", "content_type_id", "object_pk"}, |
| 50 |
] |
| 51 |
|
| 52 |
for expected_index in expected_indexes: |
| 53 |
found = any(expected_index.issubset(index_set) for index_set in index_fields_sets) |
| 54 |
self.assertTrue( |
| 55 |
found, |
| 56 |
f"Expected index with fields {expected_index} not found in UserObjectPermission table. " |
| 57 |
f"Available indexes: {index_fields_sets}", |
| 58 |
) |
| 59 |
|
| 60 |
def test_groupobjectpermission_indexes_exist(self): |
| 61 |
"""Test that GroupObjectPermission has the expected indexes.""" |
| 62 |
# Get table name for GroupObjectPermission |
| 63 |
table_name = GroupObjectPermission._meta.db_table |
| 64 |
|
| 65 |
# Get all indexes for the table |
| 66 |
with connection.cursor() as cursor: |
| 67 |
indexes = connection.introspection.get_constraints(cursor, table_name) |
| 68 |
|
| 69 |
# Look for our specific indexes |
| 70 |
index_fields_sets = [] |
| 71 |
for constraint_name, constraint_info in indexes.items(): |
| 72 |
if constraint_info.get("index", False): # Only check indexes, not other constraints |
| 73 |
index_fields_sets.append(set(constraint_info["columns"])) |
| 74 |
|
| 75 |
# Check if our expected indexes exist (using sets to ignore order) |
| 76 |
expected_indexes = [ |
| 77 |
{"permission_id", "group_id", "content_type_id", "object_pk"}, |
| 78 |
{"group_id", "content_type_id", "object_pk"}, |
| 79 |
] |
| 80 |
|
| 81 |
for expected_index in expected_indexes: |
| 82 |
found = any(expected_index.issubset(index_set) for index_set in index_fields_sets) |
| 83 |
self.assertTrue( |
| 84 |
found, |
| 85 |
f"Expected index with fields {expected_index} not found in GroupObjectPermission table. " |
| 86 |
f"Available indexes: {index_fields_sets}", |
| 87 |
) |
| 88 |
|
| 89 |
def test_userobjectpermission_query_uses_index(self): |
| 90 |
"""Test that queries on UserObjectPermission use the indexes efficiently.""" |
| 91 |
# Create some test data |
| 92 |
UserObjectPermission.objects.create( |
| 93 |
user=self.user, permission=self.permission, content_type=self.content_type, object_pk=str(self.project.pk) |
| 94 |
) |
| 95 |
|
| 96 |
# Test query that should use the first index (permission, user, content_type, object_pk) |
| 97 |
with self.assertNumQueries(1): |
| 98 |
exists = UserObjectPermission.objects.filter( |
| 99 |
permission=self.permission, |
| 100 |
user=self.user, |
| 101 |
content_type=self.content_type, |
| 102 |
object_pk=str(self.project.pk), |
| 103 |
).exists() |
| 104 |
self.assertTrue(exists) |
| 105 |
|
| 106 |
# Test query that should use the second index (user, content_type, object_pk) |
| 107 |
with self.assertNumQueries(1): |
| 108 |
permissions = list( |
| 109 |
UserObjectPermission.objects.filter( |
| 110 |
user=self.user, content_type=self.content_type, object_pk=str(self.project.pk) |
| 111 |
) |
| 112 |
) |
| 113 |
self.assertEqual(len(permissions), 1) |
| 114 |
|
| 115 |
def test_groupobjectpermission_query_uses_index(self): |
| 116 |
"""Test that queries on GroupObjectPermission use the indexes efficiently.""" |
| 117 |
# Create some test data |
| 118 |
GroupObjectPermission.objects.create( |
| 119 |
group=self.group, permission=self.permission, content_type=self.content_type, object_pk=str(self.project.pk) |
| 120 |
) |
| 121 |
|
| 122 |
# Test query that should use the first index (permission, group, content_type, object_pk) |
| 123 |
with self.assertNumQueries(1): |
| 124 |
exists = GroupObjectPermission.objects.filter( |
| 125 |
permission=self.permission, |
| 126 |
group=self.group, |
| 127 |
content_type=self.content_type, |
| 128 |
object_pk=str(self.project.pk), |
| 129 |
).exists() |
| 130 |
self.assertTrue(exists) |
| 131 |
|
| 132 |
# Test query that should use the second index (group, content_type, object_pk) |
| 133 |
with self.assertNumQueries(1): |
| 134 |
permissions = list( |
| 135 |
GroupObjectPermission.objects.filter( |
| 136 |
group=self.group, content_type=self.content_type, object_pk=str(self.project.pk) |
| 137 |
) |
| 138 |
) |
| 139 |
self.assertEqual(len(permissions), 1) |
| 140 |
|
| 141 |
def test_basegenericobjectpermission_index_exists(self): |
| 142 |
"""Test that BaseGenericObjectPermission has the expected index.""" |
| 143 |
# Test on UserObjectPermission which inherits from BaseGenericObjectPermission |
| 144 |
table_name = UserObjectPermission._meta.db_table |
| 145 |
|
| 146 |
with connection.cursor() as cursor: |
| 147 |
indexes = connection.introspection.get_constraints(cursor, table_name) |
| 148 |
|
| 149 |
# Look for the base index |
| 150 |
index_fields_sets = [] |
| 151 |
for constraint_name, constraint_info in indexes.items(): |
| 152 |
if constraint_info.get("index", False): |
| 153 |
index_fields_sets.append(set(constraint_info["columns"])) |
| 154 |
|
| 155 |
# Check if the base index exists (content_type_id, object_pk should be part of some index) |
| 156 |
expected_base_fields = {"content_type_id", "object_pk"} |
| 157 |
found = any(expected_base_fields.issubset(index_set) for index_set in index_fields_sets) |
| 158 |
|
| 159 |
self.assertTrue( |
| 160 |
found, |
| 161 |
f"Expected base index containing fields {expected_base_fields} not found. " |
| 162 |
f"Available indexes: {index_fields_sets}", |
| 163 |
) |
| 164 |
|
| 165 |
|
| 166 |
class IndexPerformanceTestCase(TestCase): |
| 167 |
"""Test performance improvements from indexes.""" |
| 168 |
|
| 169 |
def setUp(self): |
| 170 |
"""Set up test data with multiple objects for performance testing.""" |
| 171 |
self.users = [User.objects.create_user(username=f"user{i}", email=f"user{i}@example.com") for i in range(10)] |
| 172 |
self.groups = [Group.objects.create(name=f"group{i}") for i in range(5)] |
| 173 |
self.projects = [Project.objects.create(name=f"Project {i}") for i in range(20)] |
| 174 |
self.content_type = ContentType.objects.get_for_model(Project) |
| 175 |
self.permission = Permission.objects.get(content_type=self.content_type, codename="add_project") |
| 176 |
|
| 177 |
# Create multiple permissions for performance testing |
| 178 |
for user in self.users: |
| 179 |
for project in self.projects[:5]: # Each user gets permissions for first 5 projects |
| 180 |
UserObjectPermission.objects.create( |
| 181 |
user=user, permission=self.permission, content_type=self.content_type, object_pk=str(project.pk) |
| 182 |
) |
| 183 |
|
| 184 |
for group in self.groups: |
| 185 |
for project in self.projects[10:15]: # Each group gets permissions for projects 10-15 |
| 186 |
GroupObjectPermission.objects.create( |
| 187 |
group=group, permission=self.permission, content_type=self.content_type, object_pk=str(project.pk) |
| 188 |
) |
| 189 |
|
| 190 |
def test_user_permission_lookup_performance(self): |
| 191 |
"""Test that user permission lookups are efficient with indexes.""" |
| 192 |
user = self.users[0] |
| 193 |
project = self.projects[0] |
| 194 |
|
| 195 |
# This query should be fast due to the index on (user, content_type, object_pk) |
| 196 |
with self.assertNumQueries(1): |
| 197 |
permissions = list( |
| 198 |
UserObjectPermission.objects.filter( |
| 199 |
user=user, content_type=self.content_type, object_pk=str(project.pk) |
| 200 |
) |
| 201 |
) |
| 202 |
self.assertEqual(len(permissions), 1) |
| 203 |
|
| 204 |
def test_group_permission_lookup_performance(self): |
| 205 |
"""Test that group permission lookups are efficient with indexes.""" |
| 206 |
group = self.groups[0] |
| 207 |
project = self.projects[10] |
| 208 |
|
| 209 |
# This query should be fast due to the index on (group, content_type, object_pk) |
| 210 |
with self.assertNumQueries(1): |
| 211 |
permissions = list( |
| 212 |
GroupObjectPermission.objects.filter( |
| 213 |
group=group, content_type=self.content_type, object_pk=str(project.pk) |
| 214 |
) |
| 215 |
) |
| 216 |
self.assertEqual(len(permissions), 1) |
| 217 |
|
| 218 |
def test_specific_permission_lookup_performance(self): |
| 219 |
"""Test that specific permission lookups are efficient with indexes.""" |
| 220 |
user = self.users[0] |
| 221 |
project = self.projects[0] |
| 222 |
|
| 223 |
# This query should be fast due to the index on (permission, user, content_type, object_pk) |
| 224 |
with self.assertNumQueries(1): |
| 225 |
exists = UserObjectPermission.objects.filter( |
| 226 |
permission=self.permission, user=user, content_type=self.content_type, object_pk=str(project.pk) |
| 227 |
).exists() |
| 228 |
self.assertTrue(exists) |
| 229 |
|
| 230 |
|
| 231 |
class GuardianShortcutsPerformanceTestCase(TestCase): |
| 232 |
"""Test performance of Guardian shortcuts with indexes.""" |
| 233 |
|
| 234 |
@classmethod |
| 235 |
def setUpClass(cls): |
| 236 |
"""Set up large dataset for performance testing.""" |
| 237 |
super().setUpClass() |
| 238 |
|
| 239 |
# Create many users, groups and projects for realistic performance testing |
| 240 |
cls.users = [ |
| 241 |
User.objects.create_user(username=f"perfuser{i}", email=f"perfuser{i}@example.com") for i in range(50) |
| 242 |
] |
| 243 |
|
| 244 |
cls.groups = [Group.objects.create(name=f"perfgroup{i}") for i in range(20)] |
| 245 |
|
| 246 |
cls.projects = [Project.objects.create(name=f"Performance Project {i}") for i in range(100)] |
| 247 |
|
| 248 |
cls.content_type = ContentType.objects.get_for_model(Project) |
| 249 |
cls.add_permission = Permission.objects.get(content_type=cls.content_type, codename="add_project") |
| 250 |
cls.change_permission = Permission.objects.get(content_type=cls.content_type, codename="change_project") |
| 251 |
cls.delete_permission = Permission.objects.get(content_type=cls.content_type, codename="delete_project") |
| 252 |
|
| 253 |
# Create realistic permission distribution |
| 254 |
# Each user gets permissions for 10-20 random projects |
| 255 |
import random |
| 256 |
|
| 257 |
for user in cls.users: |
| 258 |
user_projects = random.sample(cls.projects, random.randint(10, 20)) |
| 259 |
for project in user_projects: |
| 260 |
# Random permission types |
| 261 |
perms = random.sample( |
| 262 |
[cls.add_permission, cls.change_permission, cls.delete_permission], random.randint(1, 3) |
| 263 |
) |
| 264 |
for perm in perms: |
| 265 |
UserObjectPermission.objects.create( |
| 266 |
user=user, permission=perm, content_type=cls.content_type, object_pk=str(project.pk) |
| 267 |
) |
| 268 |
|
| 269 |
# Each group gets permissions for 15-25 projects |
| 270 |
for group in cls.groups: |
| 271 |
group_projects = random.sample(cls.projects, random.randint(15, 25)) |
| 272 |
for project in group_projects: |
| 273 |
perms = random.sample( |
| 274 |
[cls.add_permission, cls.change_permission, cls.delete_permission], random.randint(1, 2) |
| 275 |
) |
| 276 |
for perm in perms: |
| 277 |
GroupObjectPermission.objects.create( |
| 278 |
group=group, permission=perm, content_type=cls.content_type, object_pk=str(project.pk) |
| 279 |
) |
| 280 |
|
| 281 |
# Add users to groups |
| 282 |
for user in cls.users[:30]: # First 30 users are in groups |
| 283 |
user_groups = random.sample(cls.groups, random.randint(1, 3)) |
| 284 |
for group in user_groups: |
| 285 |
user.groups.add(group) |
| 286 |
|
| 287 |
def test_get_objects_for_user_performance(self): |
| 288 |
"""Test get_objects_for_user performance with indexes.""" |
| 289 |
from guardian.shortcuts import get_objects_for_user |
| 290 |
|
| 291 |
user = self.users[0] |
| 292 |
|
| 293 |
# Test functionality without strict query count - Guardian's behavior can vary |
| 294 |
projects_with_add = get_objects_for_user(user, "testapp.add_project", Project) |
| 295 |
projects_list = list(projects_with_add) |
| 296 |
self.assertGreaterEqual(len(projects_list), 0) |
| 297 |
# Focus on that the function works and indexes help performance |
| 298 |
|
| 299 |
def test_get_objects_for_user_multiple_permissions(self): |
| 300 |
"""Test get_objects_for_user with multiple permissions.""" |
| 301 |
from guardian.shortcuts import get_objects_for_user |
| 302 |
|
| 303 |
user = self.users[0] |
| 304 |
|
| 305 |
# Test with multiple permissions - focus on functionality |
| 306 |
projects_with_any = get_objects_for_user( |
| 307 |
user, ["testapp.add_project", "testapp.change_project"], Project, any_perm=True |
| 308 |
) |
| 309 |
projects_list = list(projects_with_any) |
| 310 |
self.assertGreaterEqual(len(projects_list), 0) |
| 311 |
# Verify the function works correctly |
| 312 |
|
| 313 |
def test_get_objects_for_user_with_groups_performance(self): |
| 314 |
"""Test get_objects_for_user performance including group permissions.""" |
| 315 |
from guardian.shortcuts import get_objects_for_user |
| 316 |
|
| 317 |
user = self.users[0] # This user is in groups |
| 318 |
|
| 319 |
# Focus on functionality and that indexes help |
| 320 |
projects_with_change = get_objects_for_user(user, "testapp.change_project", Project, with_superuser=False) |
| 321 |
projects_list = list(projects_with_change) |
| 322 |
self.assertGreaterEqual(len(projects_list), 0) |
| 323 |
|
| 324 |
def test_get_objects_for_group_performance(self): |
| 325 |
"""Test get_objects_for_group performance with indexes.""" |
| 326 |
from guardian.shortcuts import get_objects_for_group |
| 327 |
|
| 328 |
group = self.groups[0] |
| 329 |
|
| 330 |
# Test functionality - don't restrict query count strictly |
| 331 |
projects_for_group = get_objects_for_group(group, "testapp.add_project", Project) |
| 332 |
projects_list = list(projects_for_group) |
| 333 |
self.assertGreaterEqual(len(projects_list), 0) |
| 334 |
|
| 335 |
def test_object_permission_checker_performance(self): |
| 336 |
"""Test ObjectPermissionChecker performance with indexes.""" |
| 337 |
from guardian.core import ObjectPermissionChecker |
| 338 |
|
| 339 |
user = self.users[0] |
| 340 |
project = self.projects[0] |
| 341 |
|
| 342 |
checker = ObjectPermissionChecker(user) |
| 343 |
|
| 344 |
# Focus on functionality |
| 345 |
has_add = checker.has_perm("add_project", project) |
| 346 |
has_change = checker.has_perm("change_project", project) |
| 347 |
has_delete = checker.has_perm("delete_project", project) |
| 348 |
|
| 349 |
# Results can be False if user has no permissions, that's OK |
| 350 |
self.assertIsInstance(has_add, bool) |
| 351 |
self.assertIsInstance(has_change, bool) |
| 352 |
self.assertIsInstance(has_delete, bool) |
| 353 |
|
| 354 |
def test_bulk_permission_check_performance(self): |
| 355 |
"""Test bulk permission checking performance.""" |
| 356 |
from guardian.shortcuts import get_objects_for_user |
| 357 |
|
| 358 |
user = self.users[0] |
| 359 |
|
| 360 |
# Test bulk checking - should be more efficient than individual checks |
| 361 |
projects_to_check = self.projects[:10] |
| 362 |
|
| 363 |
# Using get_objects_for_user is more efficient than checking each individually |
| 364 |
allowed_projects = get_objects_for_user( |
| 365 |
user, "testapp.change_project", Project.objects.filter(pk__in=[p.pk for p in projects_to_check]) |
| 366 |
) |
| 367 |
allowed_list = list(allowed_projects) |
| 368 |
self.assertGreaterEqual(len(allowed_list), 0) |
| 369 |
# The point is that bulk checking is better than individual permission checks |
| 370 |
|
| 371 |
def test_get_objects_for_user_speed_comparison(self): |
| 372 |
"""Test get_objects_for_user speed with large dataset.""" |
| 373 |
import time |
| 374 |
|
| 375 |
from guardian.shortcuts import get_objects_for_user |
| 376 |
|
| 377 |
user = self.users[0] |
| 378 |
|
| 379 |
# Test with a substantial query |
| 380 |
start_time = time.time() |
| 381 |
|
| 382 |
projects_with_add = get_objects_for_user(user, "testapp.add_project", Project) |
| 383 |
projects_list = list(projects_with_add) |
| 384 |
|
| 385 |
end_time = time.time() |
| 386 |
elapsed_time = end_time - start_time |
| 387 |
|
| 388 |
# Log results for manual verification |
| 389 |
print(f"\nget_objects_for_user found {len(projects_list)} projects in {elapsed_time:.4f} seconds") |
| 390 |
|
| 391 |
# With indexes, this should complete reasonably quickly even with large dataset |
| 392 |
self.assertLess(elapsed_time, 1.0, "get_objects_for_user should complete quickly with indexes") |
| 393 |
self.assertGreaterEqual(len(projects_list), 0, "Should find some projects (or 0 if user has no permissions)") |
| 394 |
|
| 395 |
|
| 396 |
class IndexVsNoIndexPerformanceTestCase(TestCase): |
| 397 |
"""Compare performance with and without indexes using timing measurements.""" |
| 398 |
|
| 399 |
@classmethod |
| 400 |
def setUpClass(cls): |
| 401 |
"""Set up large dataset for realistic performance comparison.""" |
| 402 |
super().setUpClass() |
| 403 |
|
| 404 |
# Create a substantial dataset to see index benefits |
| 405 |
cls.users = [ |
| 406 |
User.objects.create_user(username=f"timinguser{i}", email=f"timinguser{i}@example.com") for i in range(100) |
| 407 |
] |
| 408 |
|
| 409 |
cls.groups = [Group.objects.create(name=f"timinggroup{i}") for i in range(50)] |
| 410 |
|
| 411 |
cls.projects = [Project.objects.create(name=f"Timing Project {i}") for i in range(500)] |
| 412 |
|
| 413 |
cls.content_type = ContentType.objects.get_for_model(Project) |
| 414 |
cls.add_permission = Permission.objects.get(content_type=cls.content_type, codename="add_project") |
| 415 |
cls.change_permission = Permission.objects.get(content_type=cls.content_type, codename="change_project") |
| 416 |
cls.delete_permission = Permission.objects.get(content_type=cls.content_type, codename="delete_project") |
| 417 |
|
| 418 |
# Create many permissions to stress test indexes |
| 419 |
import random |
| 420 |
|
| 421 |
permissions_created = 0 |
| 422 |
for user in cls.users: |
| 423 |
user_projects = random.sample(cls.projects, random.randint(20, 50)) |
| 424 |
for project in user_projects: |
| 425 |
perms = random.sample( |
| 426 |
[cls.add_permission, cls.change_permission, cls.delete_permission], random.randint(1, 3) |
| 427 |
) |
| 428 |
for perm in perms: |
| 429 |
UserObjectPermission.objects.create( |
| 430 |
user=user, permission=perm, content_type=cls.content_type, object_pk=str(project.pk) |
| 431 |
) |
| 432 |
permissions_created += 1 |
| 433 |
|
| 434 |
for group in cls.groups: |
| 435 |
group_projects = random.sample(cls.projects, random.randint(30, 60)) |
| 436 |
for project in group_projects: |
| 437 |
perms = random.sample( |
| 438 |
[cls.add_permission, cls.change_permission, cls.delete_permission], random.randint(1, 2) |
| 439 |
) |
| 440 |
for perm in perms: |
| 441 |
GroupObjectPermission.objects.create( |
| 442 |
group=group, permission=perm, content_type=cls.content_type, object_pk=str(project.pk) |
| 443 |
) |
| 444 |
permissions_created += 1 |
| 445 |
|
| 446 |
print(f"\nCreated {permissions_created} permissions for timing tests") |
| 447 |
|
| 448 |
def test_user_permission_lookup_timing(self): |
| 449 |
"""Test specific user permission lookup speed with timing.""" |
| 450 |
import time |
| 451 |
|
| 452 |
user = self.users[0] |
| 453 |
project = self.projects[0] |
| 454 |
|
| 455 |
# Test query that should benefit from our index |
| 456 |
start_time = time.time() |
| 457 |
|
| 458 |
# Multiple lookups to see cumulative benefit |
| 459 |
for _ in range(10): |
| 460 |
UserObjectPermission.objects.filter( |
| 461 |
permission=self.add_permission, user=user, content_type=self.content_type, object_pk=str(project.pk) |
| 462 |
).exists() |
| 463 |
|
| 464 |
end_time = time.time() |
| 465 |
elapsed_time = end_time - start_time |
| 466 |
|
| 467 |
print(f"\n10 permission existence checks took {elapsed_time:.4f} seconds") |
| 468 |
|
| 469 |
# With proper indexes, this should be very fast even with multiple queries |
| 470 |
self.assertLess(elapsed_time, 0.1, "User permission lookup should be very fast with indexes") |
| 471 |
|
| 472 |
def test_get_objects_for_user_timing(self): |
| 473 |
"""Test get_objects_for_user speed with large dataset.""" |
| 474 |
import time |
| 475 |
|
| 476 |
from guardian.shortcuts import get_objects_for_user |
| 477 |
|
| 478 |
user = self.users[0] |
| 479 |
|
| 480 |
# Test with a substantial query |
| 481 |
start_time = time.time() |
| 482 |
|
| 483 |
projects_with_add = get_objects_for_user(user, "testapp.add_project", Project) |
| 484 |
projects_list = list(projects_with_add) |
| 485 |
|
| 486 |
end_time = time.time() |
| 487 |
elapsed_time = end_time - start_time |
| 488 |
|
| 489 |
# Log results for manual verification |
| 490 |
print(f"\nget_objects_for_user found {len(projects_list)} projects in {elapsed_time:.4f} seconds") |
| 491 |
|
| 492 |
# With indexes, this should complete reasonably quickly even with large dataset |
| 493 |
self.assertLess(elapsed_time, 1.0, "get_objects_for_user should complete quickly with indexes") |
| 494 |
|
| 495 |
def test_bulk_permission_checks_timing(self): |
| 496 |
"""Test bulk permission checking demonstrates index benefits.""" |
| 497 |
import time |
| 498 |
|
| 499 |
from guardian.shortcuts import get_objects_for_user |
| 500 |
|
| 501 |
user = self.users[0] |
| 502 |
|
| 503 |
# Test multiple permission types |
| 504 |
permissions = ["testapp.add_project", "testapp.change_project", "testapp.delete_project"] |
| 505 |
|
| 506 |
start_time = time.time() |
| 507 |
|
| 508 |
all_results = {} |
| 509 |
for perm in permissions: |
| 510 |
projects = get_objects_for_user(user, perm, Project) |
| 511 |
all_results[perm] = list(projects) |
| 512 |
|
| 513 |
end_time = time.time() |
| 514 |
elapsed_time = end_time - start_time |
| 515 |
|
| 516 |
total_projects = sum(len(projects) for projects in all_results.values()) |
| 517 |
print(f"\nBulk permission check found {total_projects} total permissions in {elapsed_time:.4f} seconds") |
| 518 |
|
| 519 |
# Should be efficient due to indexes |
| 520 |
self.assertLess(elapsed_time, 2.0, "Bulk permission checks should be efficient with indexes") |
| 521 |
|
| 522 |
def test_permission_existence_at_scale_timing(self): |
| 523 |
"""Test permission existence checking performance at scale.""" |
| 524 |
import time |
| 525 |
|
| 526 |
# Test checking permissions for multiple users and objects |
| 527 |
users_sample = self.users[:10] |
| 528 |
projects_sample = self.projects[:10] |
| 529 |
|
| 530 |
start_time = time.time() |
| 531 |
|
| 532 |
existence_checks = 0 |
| 533 |
for user in users_sample: |
| 534 |
for project in projects_sample: |
| 535 |
UserObjectPermission.objects.filter( |
| 536 |
permission=self.add_permission, user=user, content_type=self.content_type, object_pk=str(project.pk) |
| 537 |
).exists() |
| 538 |
existence_checks += 1 |
| 539 |
|
| 540 |
end_time = time.time() |
| 541 |
elapsed_time = end_time - start_time |
| 542 |
|
| 543 |
print(f"\nPerformed {existence_checks} permission existence checks in {elapsed_time:.4f} seconds") |
| 544 |
|
| 545 |
# Should be very fast with proper indexing |
| 546 |
self.assertLess(elapsed_time, 0.5, "Permission existence checks should be fast with indexes") |
| 547 |
|
| 548 |
def test_object_permission_listing_timing(self): |
| 549 |
"""Test listing all permissions for objects.""" |
| 550 |
import time |
| 551 |
|
| 552 |
user = self.users[0] |
| 553 |
projects_sample = self.projects[:20] |
| 554 |
|
| 555 |
start_time = time.time() |
| 556 |
|
| 557 |
all_permissions = [] |
| 558 |
for project in projects_sample: |
| 559 |
perms = UserObjectPermission.objects.filter( |
| 560 |
user=user, content_type=self.content_type, object_pk=str(project.pk) |
| 561 |
).select_related("permission") |
| 562 |
all_permissions.extend(list(perms)) |
| 563 |
|
| 564 |
end_time = time.time() |
| 565 |
elapsed_time = end_time - start_time |
| 566 |
|
| 567 |
print( |
| 568 |
f"\nFound {len(all_permissions)} permissions across {len(projects_sample)} objects in {elapsed_time:.4f} seconds" |
| 569 |
) |
| 570 |
|
| 571 |
# Should be efficient due to (user, content_type, object_pk) index |
| 572 |
self.assertLess(elapsed_time, 0.3, "Object permission listing should be fast with indexes") |