| 1 |
from unittest.mock import MagicMock, patch |
| 2 |
|
| 3 |
from django.contrib.auth import get_user_model |
| 4 |
from django.contrib.auth.models import AnonymousUser, Group |
| 5 |
from django.contrib.contenttypes.models import ContentType |
| 6 |
from django.db import models |
| 7 |
from django.test import TestCase, override_settings |
| 8 |
|
| 9 |
from guardian.exceptions import NotUserNorGroup |
| 10 |
from guardian.models import GroupObjectPermission, UserObjectPermission, UserObjectPermissionBase |
| 11 |
from guardian.testapp.models import Project, ProjectGroupObjectPermission, ProjectUserObjectPermission |
| 12 |
from guardian.testapp.tests.conf import skipUnlessTestApp |
| 13 |
from guardian.testapp.tests.test_core import ObjectPermissionTestCase |
| 14 |
from guardian.utils import ( |
| 15 |
_get_anonymous_user_cached, |
| 16 |
_get_anonymous_user_uncached, |
| 17 |
get_anonymous_user, |
| 18 |
get_group_obj_perms_model, |
| 19 |
get_identity, |
| 20 |
get_obj_perms_model, |
| 21 |
get_user_obj_perms_model, |
| 22 |
) |
| 23 |
|
| 24 |
User = get_user_model() |
| 25 |
|
| 26 |
|
| 27 |
class GetAnonymousUserTest(TestCase): |
| 28 |
def test(self): |
| 29 |
anon = get_anonymous_user() |
| 30 |
self.assertTrue(isinstance(anon, User)) |
| 31 |
|
| 32 |
|
| 33 |
class GetIdentityTest(ObjectPermissionTestCase): |
| 34 |
def test_user(self): |
| 35 |
user, group = get_identity(self.user) |
| 36 |
self.assertTrue(isinstance(user, User)) |
| 37 |
self.assertEqual(group, None) |
| 38 |
|
| 39 |
def test_anonymous_user(self): |
| 40 |
anon = AnonymousUser() |
| 41 |
user, group = get_identity(anon) |
| 42 |
self.assertTrue(isinstance(user, User)) |
| 43 |
self.assertEqual(group, None) |
| 44 |
|
| 45 |
def test_group(self): |
| 46 |
user, group = get_identity(self.group) |
| 47 |
self.assertTrue(isinstance(group, Group)) |
| 48 |
self.assertEqual(user, None) |
| 49 |
|
| 50 |
def test_not_user_nor_group(self): |
| 51 |
self.assertRaises(NotUserNorGroup, get_identity, 1) |
| 52 |
self.assertRaises(NotUserNorGroup, get_identity, "User") |
| 53 |
self.assertRaises(NotUserNorGroup, get_identity, User) |
| 54 |
|
| 55 |
def test_multiple_user_qs(self): |
| 56 |
user, group = get_identity(User.objects.all()) |
| 57 |
self.assertIsInstance(user, models.QuerySet) |
| 58 |
self.assertIsNone(group) |
| 59 |
|
| 60 |
def test_multiple_user_list(self): |
| 61 |
user, group = get_identity([self.user]) |
| 62 |
self.assertIsInstance(user, list) |
| 63 |
self.assertIsNone(group) |
| 64 |
|
| 65 |
def test_multiple_group_qs(self): |
| 66 |
user, group = get_identity(Group.objects.all()) |
| 67 |
self.assertIsInstance(group, models.QuerySet) |
| 68 |
self.assertIsNone(user) |
| 69 |
|
| 70 |
def test_multiple_group_list(self): |
| 71 |
user, group = get_identity([self.group]) |
| 72 |
self.assertIsInstance(group, list) |
| 73 |
self.assertIsNone(user) |
| 74 |
|
| 75 |
def test_group_subclass_queryset(self): |
| 76 |
"""Test that Group subclasses work with QuerySet identity resolution.""" |
| 77 |
|
| 78 |
# Create a Group subclass to test the issubclass fix |
| 79 |
class TestTeam(Group): |
| 80 |
class Meta: |
| 81 |
proxy = True |
| 82 |
|
| 83 |
# Create a TestTeam instance |
| 84 |
team = TestTeam.objects.create(name="Test Team Subclass") |
| 85 |
|
| 86 |
# Test with QuerySet of Group subclass |
| 87 |
team_qs = TestTeam.objects.filter(pk=team.pk) |
| 88 |
user, group = get_identity(team_qs) |
| 89 |
self.assertIsInstance(group, models.QuerySet) |
| 90 |
self.assertIsNone(user) |
| 91 |
self.assertEqual(group.model, TestTeam) |
| 92 |
|
| 93 |
# Test with all TestTeams QuerySet |
| 94 |
all_teams_qs = TestTeam.objects.all() |
| 95 |
user, group = get_identity(all_teams_qs) |
| 96 |
self.assertIsInstance(group, models.QuerySet) |
| 97 |
self.assertIsNone(user) |
| 98 |
self.assertEqual(group.model, TestTeam) |
| 99 |
|
| 100 |
# Clean up |
| 101 |
team.delete() |
| 102 |
|
| 103 |
def test_user_subclass_queryset(self): |
| 104 |
"""Test that User subclasses work with QuerySet identity resolution.""" |
| 105 |
|
| 106 |
# Create a User subclass to test the issubclass fix |
| 107 |
class TestCustomUser(User): |
| 108 |
class Meta: |
| 109 |
proxy = True |
| 110 |
|
| 111 |
# Create a TestCustomUser instance |
| 112 |
custom_user = TestCustomUser.objects.create(username="testcustomuser_subclass") |
| 113 |
|
| 114 |
# Test with QuerySet of User subclass |
| 115 |
custom_user_qs = TestCustomUser.objects.filter(pk=custom_user.pk) |
| 116 |
user, group = get_identity(custom_user_qs) |
| 117 |
self.assertIsInstance(user, models.QuerySet) |
| 118 |
self.assertIsNone(group) |
| 119 |
self.assertEqual(user.model, TestCustomUser) |
| 120 |
|
| 121 |
# Test with all TestCustomUsers QuerySet |
| 122 |
all_custom_users_qs = TestCustomUser.objects.all() |
| 123 |
user, group = get_identity(all_custom_users_qs) |
| 124 |
self.assertIsInstance(user, models.QuerySet) |
| 125 |
self.assertIsNone(group) |
| 126 |
self.assertEqual(user.model, TestCustomUser) |
| 127 |
|
| 128 |
# Clean up |
| 129 |
custom_user.delete() |
| 130 |
|
| 131 |
|
| 132 |
@skipUnlessTestApp |
| 133 |
class GetUserObjPermsModelTest(TestCase): |
| 134 |
def test_for_instance(self): |
| 135 |
project = Project(name="Foobar") |
| 136 |
self.assertEqual(get_user_obj_perms_model(project), ProjectUserObjectPermission) |
| 137 |
|
| 138 |
def test_for_class(self): |
| 139 |
self.assertEqual(get_user_obj_perms_model(Project), ProjectUserObjectPermission) |
| 140 |
|
| 141 |
def test_default(self): |
| 142 |
self.assertEqual(get_user_obj_perms_model(ContentType), UserObjectPermission) |
| 143 |
|
| 144 |
def test_user_model(self): |
| 145 |
# this test assumes that there were no direct obj perms model to User |
| 146 |
# model defined (i.e. while testing guardian app in some custom |
| 147 |
# project) |
| 148 |
self.assertEqual(get_user_obj_perms_model(User), UserObjectPermission) |
| 149 |
|
| 150 |
|
| 151 |
@skipUnlessTestApp |
| 152 |
class GetGroupObjPermsModelTest(TestCase): |
| 153 |
def test_for_instance(self): |
| 154 |
project = Project(name="Foobar") |
| 155 |
self.assertEqual(get_group_obj_perms_model(project), ProjectGroupObjectPermission) |
| 156 |
|
| 157 |
def test_for_class(self): |
| 158 |
self.assertEqual(get_group_obj_perms_model(Project), ProjectGroupObjectPermission) |
| 159 |
|
| 160 |
def test_default(self): |
| 161 |
self.assertEqual(get_group_obj_perms_model(ContentType), GroupObjectPermission) |
| 162 |
|
| 163 |
def test_group_model(self): |
| 164 |
# this test assumes that there were no direct obj perms model to Group |
| 165 |
# model defined (i.e. while testing guardian app in some custom |
| 166 |
# project) |
| 167 |
self.assertEqual(get_group_obj_perms_model(Group), GroupObjectPermission) |
| 168 |
|
| 169 |
|
| 170 |
class GetObjPermsModelTest(TestCase): |
| 171 |
def test_image_field(self): |
| 172 |
class SomeModel(models.Model): |
| 173 |
image = models.FileField(upload_to="images/") |
| 174 |
|
| 175 |
obj = SomeModel() |
| 176 |
perm_model = get_obj_perms_model(obj, UserObjectPermissionBase, UserObjectPermission) |
| 177 |
self.assertEqual(perm_model, UserObjectPermission) |
| 178 |
|
| 179 |
def test_file_field(self): |
| 180 |
class SomeModel2(models.Model): |
| 181 |
file = models.FileField(upload_to="images/") |
| 182 |
|
| 183 |
obj = SomeModel2() |
| 184 |
perm_model = get_obj_perms_model(obj, UserObjectPermissionBase, UserObjectPermission) |
| 185 |
self.assertEqual(perm_model, UserObjectPermission) |
| 186 |
|
| 187 |
|
| 188 |
class GetAnonymousUserCacheTest(TestCase): |
| 189 |
"""Test cases for get_anonymous_user caching functionality.""" |
| 190 |
|
| 191 |
def setUp(self): |
| 192 |
# Clear any existing cache before each test |
| 193 |
if hasattr(_get_anonymous_user_cached, "cache_clear"): |
| 194 |
_get_anonymous_user_cached.cache_clear() |
| 195 |
|
| 196 |
def tearDown(self): |
| 197 |
# Clear cache after each test |
| 198 |
if hasattr(_get_anonymous_user_cached, "cache_clear"): |
| 199 |
_get_anonymous_user_cached.cache_clear() |
| 200 |
|
| 201 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=0) |
| 202 |
def test_cache_disabled_by_default(self): |
| 203 |
"""Test that caching is disabled by default.""" |
| 204 |
with ( |
| 205 |
patch("guardian.utils._get_anonymous_user_uncached") as mock_uncached, |
| 206 |
patch("guardian.utils._get_anonymous_user_cached") as mock_cached, |
| 207 |
): |
| 208 |
mock_user = MagicMock() |
| 209 |
mock_uncached.return_value = mock_user |
| 210 |
|
| 211 |
# Call function multiple times |
| 212 |
result1 = get_anonymous_user() |
| 213 |
result2 = get_anonymous_user() |
| 214 |
|
| 215 |
# Should call uncached version each time |
| 216 |
self.assertEqual(mock_uncached.call_count, 2) |
| 217 |
self.assertEqual(mock_cached.call_count, 0) |
| 218 |
self.assertEqual(result1, mock_user) |
| 219 |
self.assertEqual(result2, mock_user) |
| 220 |
|
| 221 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=300) |
| 222 |
def test_cache_enabled(self): |
| 223 |
"""Test that caching works when enabled.""" |
| 224 |
# Reload the settings module to pick up the override |
| 225 |
from importlib import reload |
| 226 |
|
| 227 |
from guardian.conf import settings as guardian_settings_module |
| 228 |
|
| 229 |
reload(guardian_settings_module) |
| 230 |
|
| 231 |
with ( |
| 232 |
patch("guardian.utils._get_anonymous_user_cached") as mock_cached, |
| 233 |
patch("guardian.utils._get_anonymous_user_uncached") as mock_uncached, |
| 234 |
): |
| 235 |
mock_user = MagicMock() |
| 236 |
mock_cached.return_value = mock_user |
| 237 |
|
| 238 |
# Call function multiple times |
| 239 |
result1 = get_anonymous_user() |
| 240 |
result2 = get_anonymous_user() |
| 241 |
result3 = get_anonymous_user() |
| 242 |
|
| 243 |
# Should call cached version each time |
| 244 |
self.assertEqual(mock_cached.call_count, 3) |
| 245 |
self.assertEqual(mock_uncached.call_count, 0) |
| 246 |
self.assertEqual(result1, mock_user) |
| 247 |
self.assertEqual(result2, mock_user) |
| 248 |
self.assertEqual(result3, mock_user) |
| 249 |
|
| 250 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=0) |
| 251 |
def test_uncached_function_calls_database_each_time(self): |
| 252 |
"""Test that uncached version calls database each time.""" |
| 253 |
with ( |
| 254 |
patch("guardian.utils.get_user_model") as mock_get_user_model, |
| 255 |
patch("guardian.conf.settings.ANONYMOUS_USER_NAME", "TestAnonymousUser"), |
| 256 |
): |
| 257 |
mock_user_model = MagicMock() |
| 258 |
mock_user_model.USERNAME_FIELD = "username" |
| 259 |
mock_user_instance = MagicMock() |
| 260 |
mock_user_model.objects.get.return_value = mock_user_instance |
| 261 |
mock_get_user_model.return_value = mock_user_model |
| 262 |
|
| 263 |
# Call uncached function multiple times |
| 264 |
result1 = _get_anonymous_user_uncached() |
| 265 |
result2 = _get_anonymous_user_uncached() |
| 266 |
|
| 267 |
# Should call database each time |
| 268 |
self.assertEqual(mock_user_model.objects.get.call_count, 2) |
| 269 |
self.assertEqual(result1, mock_user_instance) |
| 270 |
self.assertEqual(result2, mock_user_instance) |
| 271 |
|
| 272 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=300) |
| 273 |
def test_cached_function_calls_database_once(self): |
| 274 |
"""Test that cached version calls database only once.""" |
| 275 |
with ( |
| 276 |
patch("guardian.utils.get_user_model") as mock_get_user_model, |
| 277 |
patch("guardian.conf.settings.ANONYMOUS_USER_NAME", "TestAnonymousUser"), |
| 278 |
patch("guardian.utils.cache") as mock_cache, |
| 279 |
): |
| 280 |
mock_user_model = MagicMock() |
| 281 |
mock_user_model.USERNAME_FIELD = "username" |
| 282 |
mock_user_instance = MagicMock() |
| 283 |
mock_user_model.objects.get.return_value = mock_user_instance |
| 284 |
mock_get_user_model.return_value = mock_user_model |
| 285 |
|
| 286 |
# Mock cache behavior - first call returns None (cache miss), subsequent calls return cached value |
| 287 |
call_count = 0 |
| 288 |
|
| 289 |
def cache_get_side_effect(key): |
| 290 |
nonlocal call_count |
| 291 |
call_count += 1 |
| 292 |
if call_count == 1: |
| 293 |
return None # Cache miss on first call |
| 294 |
return mock_user_instance # Cache hit on subsequent calls |
| 295 |
|
| 296 |
mock_cache.get.side_effect = cache_get_side_effect |
| 297 |
mock_cache.set.return_value = None |
| 298 |
|
| 299 |
# Call cached function multiple times |
| 300 |
result1 = _get_anonymous_user_cached() |
| 301 |
result2 = _get_anonymous_user_cached() |
| 302 |
result3 = _get_anonymous_user_cached() |
| 303 |
|
| 304 |
# Should call database only once due to caching |
| 305 |
self.assertEqual(mock_user_model.objects.get.call_count, 1) |
| 306 |
self.assertEqual(result1, mock_user_instance) |
| 307 |
self.assertEqual(result2, mock_user_instance) |
| 308 |
self.assertEqual(result3, mock_user_instance) |
| 309 |
|
| 310 |
# Cache should be called for get operations |
| 311 |
self.assertEqual(mock_cache.get.call_count, 3) |
| 312 |
# Cache should be set once (on first call) |
| 313 |
self.assertEqual(mock_cache.set.call_count, 1) |
| 314 |
|
| 315 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=300) |
| 316 |
def test_cache_info_available(self): |
| 317 |
"""Test that Django cache is working correctly.""" |
| 318 |
with ( |
| 319 |
patch("guardian.utils.get_user_model") as mock_get_user_model, |
| 320 |
patch("guardian.conf.settings.ANONYMOUS_USER_NAME", "TestAnonymousUser"), |
| 321 |
patch("guardian.utils.cache") as mock_cache, |
| 322 |
): |
| 323 |
mock_user_model = MagicMock() |
| 324 |
mock_user_model.USERNAME_FIELD = "username" |
| 325 |
mock_user_instance = MagicMock() |
| 326 |
mock_user_model.objects.get.return_value = mock_user_instance |
| 327 |
mock_get_user_model.return_value = mock_user_model |
| 328 |
|
| 329 |
# Mock cache behavior |
| 330 |
mock_cache.get.side_effect = [None, mock_user_instance] # First miss, then hit |
| 331 |
mock_cache.set.return_value = None |
| 332 |
|
| 333 |
# First call should hit database |
| 334 |
result1 = _get_anonymous_user_cached() |
| 335 |
self.assertEqual(mock_user_model.objects.get.call_count, 1) |
| 336 |
|
| 337 |
# Second call should use cache |
| 338 |
result2 = _get_anonymous_user_cached() |
| 339 |
self.assertEqual(mock_user_model.objects.get.call_count, 1) # Still 1, no additional DB calls |
| 340 |
|
| 341 |
self.assertEqual(result1, result2) |
| 342 |
|
| 343 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=300) |
| 344 |
def test_cache_clear_functionality(self): |
| 345 |
"""Test that cache can be cleared.""" |
| 346 |
with ( |
| 347 |
patch("guardian.utils.get_user_model") as mock_get_user_model, |
| 348 |
patch("guardian.conf.settings.ANONYMOUS_USER_NAME", "TestAnonymousUser"), |
| 349 |
patch("guardian.utils.cache") as mock_cache, |
| 350 |
): |
| 351 |
mock_user_model = MagicMock() |
| 352 |
mock_user_model.USERNAME_FIELD = "username" |
| 353 |
mock_user_instance = MagicMock() |
| 354 |
mock_user_model.objects.get.return_value = mock_user_instance |
| 355 |
mock_get_user_model.return_value = mock_user_model |
| 356 |
|
| 357 |
# Mock cache behavior - simulate cache miss, hit, then miss again after clear |
| 358 |
mock_cache.get.side_effect = [None, mock_user_instance, None] |
| 359 |
mock_cache.set.return_value = None |
| 360 |
mock_cache.clear.return_value = None |
| 361 |
|
| 362 |
# Call function (cache miss - should hit DB) |
| 363 |
_get_anonymous_user_cached() |
| 364 |
self.assertEqual(mock_user_model.objects.get.call_count, 1) |
| 365 |
|
| 366 |
# Call again (cache hit - should not hit DB) |
| 367 |
_get_anonymous_user_cached() |
| 368 |
self.assertEqual(mock_user_model.objects.get.call_count, 1) |
| 369 |
|
| 370 |
# Clear cache and call again (cache miss - should hit DB again) |
| 371 |
mock_cache.clear() |
| 372 |
_get_anonymous_user_cached() |
| 373 |
self.assertEqual(mock_user_model.objects.get.call_count, 2) |
| 374 |
|
| 375 |
def test_both_functions_return_same_user(self): |
| 376 |
"""Test that cached and uncached functions return the same user.""" |
| 377 |
# Clear cache first |
| 378 |
if hasattr(_get_anonymous_user_cached, "cache_clear"): |
| 379 |
_get_anonymous_user_cached.cache_clear() |
| 380 |
|
| 381 |
cached_result = _get_anonymous_user_cached() |
| 382 |
uncached_result = _get_anonymous_user_uncached() |
| 383 |
|
| 384 |
# Both should return the same user |
| 385 |
self.assertEqual(cached_result.pk, uncached_result.pk) |
| 386 |
self.assertEqual(str(cached_result), str(uncached_result)) |
| 387 |
self.assertTrue(isinstance(cached_result, User)) |
| 388 |
self.assertTrue(isinstance(uncached_result, User)) |
| 389 |
|
| 390 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=300) |
| 391 |
def test_integration_with_get_identity(self): |
| 392 |
"""Test that cached anonymous user works with get_identity function.""" |
| 393 |
anon = AnonymousUser() |
| 394 |
|
| 395 |
# This test should use the actual implementation to ensure integration works |
| 396 |
user, group = get_identity(anon) |
| 397 |
|
| 398 |
# Should return a real user instance and None for group |
| 399 |
self.assertTrue(isinstance(user, User)) |
| 400 |
self.assertIsNone(group) |
| 401 |
|
| 402 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=0) |
| 403 |
def test_integration_with_get_identity_uncached(self): |
| 404 |
"""Test that uncached anonymous user works with get_identity function.""" |
| 405 |
anon = AnonymousUser() |
| 406 |
|
| 407 |
# This test should use the actual implementation to ensure integration works |
| 408 |
user, group = get_identity(anon) |
| 409 |
|
| 410 |
# Should return a real user instance and None for group |
| 411 |
self.assertTrue(isinstance(user, User)) |
| 412 |
self.assertIsNone(group) |
| 413 |
|
| 414 |
@override_settings(GUARDIAN_ANONYMOUS_USER_CACHE_TTL=-1) |
| 415 |
def test_indefinite_cache(self): |
| 416 |
"""Test that TTL=-1 enables indefinite caching.""" |
| 417 |
with patch("guardian.utils.guardian_settings") as mock_settings: |
| 418 |
mock_settings.ANONYMOUS_USER_CACHE_TTL = -1 |
| 419 |
with ( |
| 420 |
patch("guardian.utils._get_anonymous_user_cached") as mock_cached, |
| 421 |
patch("guardian.utils._get_anonymous_user_uncached") as mock_uncached, |
| 422 |
): |
| 423 |
mock_user = MagicMock() |
| 424 |
mock_cached.return_value = mock_user |
| 425 |
|
| 426 |
# Call function - should use cached version |
| 427 |
result = get_anonymous_user() |
| 428 |
|
| 429 |
mock_cached.assert_called_once() |
| 430 |
mock_uncached.assert_not_called() |
| 431 |
self.assertEqual(result, mock_user) |