| 1 |
""" |
| 2 |
Tests for PolymorphicGuard serialization of on_delete functions. |
| 3 |
|
| 4 |
This test module ensures that all Django on_delete handlers (CASCADE, PROTECT, |
| 5 |
SET_NULL, SET_DEFAULT, SET(...), DO_NOTHING, and RESTRICT) are properly wrapped |
| 6 |
with PolymorphicGuard and serialize correctly in migrations. |
| 7 |
""" |
| 8 |
|
| 9 |
from django.core.management import call_command |
| 10 |
from pathlib import Path |
| 11 |
from django.test import TestCase, TransactionTestCase |
| 12 |
from django.db import models |
| 13 |
from django.db.migrations.serializer import serializer_factory |
| 14 |
from django.db.models import ProtectedError, RestrictedError |
| 15 |
from ..utils import GeneratedMigrationsPerClassMixin |
| 16 |
from polymorphic.deletion import PolymorphicGuard |
| 17 |
from polymorphic.managers import PolymorphicManager |
| 18 |
from polymorphic.query import PolymorphicQuerySet |
| 19 |
|
| 20 |
|
| 21 |
class OnDeleteSerializationTest(GeneratedMigrationsPerClassMixin, TransactionTestCase): |
| 22 |
""" |
| 23 |
Test that PolymorphicGuard wraps on_delete handlers and serializes them correctly. |
| 24 |
""" |
| 25 |
|
| 26 |
apps_to_migrate: list[str] = ["test_migrations"] |
| 27 |
|
| 28 |
@property |
| 29 |
def state(self): |
| 30 |
return self._applied_states["test_migrations"] |
| 31 |
|
| 32 |
@classmethod |
| 33 |
def setUpClass(cls): |
| 34 |
"""Set up by generating and applying migrations for test_migrations app""" |
| 35 |
super().setUpClass() |
| 36 |
cls.migrations_dir = Path(__file__).parent / "migrations" |
| 37 |
|
| 38 |
def test_migration_managers_non_polymorphic(self): |
| 39 |
for mdl in [ |
| 40 |
"BasePolyModel", |
| 41 |
"ChildPolyModel", |
| 42 |
"GrandChildPolyModel", |
| 43 |
"ModelWithCascade", |
| 44 |
"ModelWithProtect", |
| 45 |
"ModelWithSetNull", |
| 46 |
"ModelWithSetDefault", |
| 47 |
"ModelWithSet", |
| 48 |
"ModelWithDoNothing", |
| 49 |
"ModelWithRestrict", |
| 50 |
"ModelWithOneToOneCascade", |
| 51 |
"ModelWithOneToOneProtect", |
| 52 |
"ModelWithOneToOneSetNull", |
| 53 |
]: |
| 54 |
Model = self.state.apps.get_model("test_migrations", mdl) |
| 55 |
|
| 56 |
managers = Model._meta.managers |
| 57 |
assert not isinstance(Model.objects, (PolymorphicManager, PolymorphicQuerySet)) |
| 58 |
assert all(not isinstance(m, (PolymorphicManager, PolymorphicQuerySet)) for m in managers) |
| 59 |
|
| 60 |
RelatedModel = self.state.apps.get_model("test_migrations", "RelatedModel") |
| 61 |
related = RelatedModel.objects.create(name="tester") |
| 62 |
ModelWithOneToOneCascade = self.state.apps.get_model( |
| 63 |
"test_migrations", "ModelWithOneToOneCascade" |
| 64 |
) |
| 65 |
ModelWithOneToOneProtect = self.state.apps.get_model( |
| 66 |
"test_migrations", "ModelWithOneToOneProtect" |
| 67 |
) |
| 68 |
ModelWithOneToOneSetNull = self.state.apps.get_model( |
| 69 |
"test_migrations", "ModelWithOneToOneSetNull" |
| 70 |
) |
| 71 |
|
| 72 |
ModelWithOneToOneCascade.objects.create(related=related) |
| 73 |
ModelWithOneToOneProtect.objects.create(related=related) |
| 74 |
ModelWithOneToOneSetNull.objects.create(related=related) |
| 75 |
|
| 76 |
for relation in [ |
| 77 |
"modelwithcascade_set", |
| 78 |
"modelwithprotect_set", |
| 79 |
"modelwithsetnull_set", |
| 80 |
"modelwithsetdefault_set", |
| 81 |
"modelwithset_set", |
| 82 |
"modelwithdonothing_set", |
| 83 |
"modelwithrestrict_set", |
| 84 |
"modelwithonetoonecascade", |
| 85 |
"one_to_one_protect", |
| 86 |
"one_to_one_set_null", |
| 87 |
]: |
| 88 |
assert not isinstance( |
| 89 |
getattr(related, relation), (PolymorphicManager, PolymorphicQuerySet) |
| 90 |
) |
| 91 |
|
| 92 |
def test_foreign_keys_wrapped_with_PolymorphicGuard(self): |
| 93 |
"""Verify that ForeignKey on_delete handlers are wrapped with PolymorphicGuard""" |
| 94 |
from .models import ( |
| 95 |
ModelWithCascade, |
| 96 |
ModelWithProtect, |
| 97 |
ModelWithSetNull, |
| 98 |
ModelWithSetDefault, |
| 99 |
ModelWithSet, |
| 100 |
ModelWithDoNothing, |
| 101 |
ModelWithRestrict, |
| 102 |
) |
| 103 |
|
| 104 |
# Get the 'related' field from each model |
| 105 |
models_to_test = [ |
| 106 |
ModelWithCascade, |
| 107 |
ModelWithProtect, |
| 108 |
ModelWithSetNull, |
| 109 |
ModelWithSetDefault, |
| 110 |
ModelWithSet, |
| 111 |
ModelWithDoNothing, |
| 112 |
ModelWithRestrict, |
| 113 |
] |
| 114 |
|
| 115 |
for model_class in models_to_test: |
| 116 |
with self.subTest(model=model_class.__name__): |
| 117 |
field = model_class._meta.get_field("related") |
| 118 |
on_delete = field.remote_field.on_delete |
| 119 |
|
| 120 |
# Assert that the on_delete handler is wrapped with PolymorphicGuard |
| 121 |
self.assertIsInstance( |
| 122 |
on_delete, |
| 123 |
PolymorphicGuard, |
| 124 |
f"{model_class.__name__}.related field should have PolymorphicGuard wrapper", |
| 125 |
) |
| 126 |
|
| 127 |
def test_one_to_one_wrapped_with_PolymorphicGuard(self): |
| 128 |
"""Verify that OneToOneField on_delete handlers are wrapped with PolymorphicGuard""" |
| 129 |
from .models import ( |
| 130 |
ModelWithOneToOneCascade, |
| 131 |
ModelWithOneToOneProtect, |
| 132 |
ModelWithOneToOneSetNull, |
| 133 |
) |
| 134 |
|
| 135 |
models_to_test = [ |
| 136 |
ModelWithOneToOneCascade, |
| 137 |
ModelWithOneToOneProtect, |
| 138 |
ModelWithOneToOneSetNull, |
| 139 |
] |
| 140 |
|
| 141 |
for model_class in models_to_test: |
| 142 |
with self.subTest(model=model_class.__name__): |
| 143 |
field = model_class._meta.get_field("related") |
| 144 |
on_delete = field.remote_field.on_delete |
| 145 |
|
| 146 |
# Assert that the on_delete handler is wrapped with PolymorphicGuard |
| 147 |
self.assertIsInstance( |
| 148 |
on_delete, |
| 149 |
PolymorphicGuard, |
| 150 |
f"{model_class.__name__}.related field should have PolymorphicGuard wrapper", |
| 151 |
) |
| 152 |
|
| 153 |
def test_cascade_serialization(self): |
| 154 |
"""Test that CASCADE serializes correctly through PolymorphicGuard""" |
| 155 |
from .models import ModelWithCascade |
| 156 |
|
| 157 |
field = ModelWithCascade._meta.get_field("related") |
| 158 |
on_delete = field.remote_field.on_delete |
| 159 |
|
| 160 |
# Serialize the PolymorphicGuard wrapped CASCADE |
| 161 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 162 |
|
| 163 |
# Should serialize as CASCADE from django.db.models.deletion, not as PolymorphicGuard |
| 164 |
self.assertIn("CASCADE", serialized) |
| 165 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 166 |
|
| 167 |
def test_protect_serialization(self): |
| 168 |
"""Test that PROTECT serializes correctly through PolymorphicGuard""" |
| 169 |
from .models import ModelWithProtect |
| 170 |
|
| 171 |
field = ModelWithProtect._meta.get_field("related") |
| 172 |
on_delete = field.remote_field.on_delete |
| 173 |
|
| 174 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 175 |
|
| 176 |
self.assertIn("PROTECT", serialized) |
| 177 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 178 |
|
| 179 |
def test_set_null_serialization(self): |
| 180 |
"""Test that SET_NULL serializes correctly through PolymorphicGuard""" |
| 181 |
from .models import ModelWithSetNull |
| 182 |
|
| 183 |
field = ModelWithSetNull._meta.get_field("related") |
| 184 |
on_delete = field.remote_field.on_delete |
| 185 |
|
| 186 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 187 |
|
| 188 |
self.assertIn("SET_NULL", serialized) |
| 189 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 190 |
|
| 191 |
def test_set_default_serialization(self): |
| 192 |
"""Test that SET_DEFAULT serializes correctly through PolymorphicGuard""" |
| 193 |
from .models import ModelWithSetDefault |
| 194 |
|
| 195 |
field = ModelWithSetDefault._meta.get_field("related") |
| 196 |
on_delete = field.remote_field.on_delete |
| 197 |
|
| 198 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 199 |
|
| 200 |
self.assertIn("SET_DEFAULT", serialized) |
| 201 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 202 |
|
| 203 |
def test_set_callable_serialization(self): |
| 204 |
"""Test that SET(...) with a callable serializes correctly through PolymorphicGuard""" |
| 205 |
from .models import ModelWithSet |
| 206 |
|
| 207 |
field = ModelWithSet._meta.get_field("related") |
| 208 |
on_delete = field.remote_field.on_delete |
| 209 |
|
| 210 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 211 |
|
| 212 |
# Should serialize the SET() function with the callable reference |
| 213 |
self.assertIn("SET", serialized) |
| 214 |
self.assertIn("get_default_related", serialized) |
| 215 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 216 |
|
| 217 |
def test_do_nothing_serialization(self): |
| 218 |
"""Test that DO_NOTHING serializes correctly through PolymorphicGuard""" |
| 219 |
from .models import ModelWithDoNothing |
| 220 |
|
| 221 |
field = ModelWithDoNothing._meta.get_field("related") |
| 222 |
on_delete = field.remote_field.on_delete |
| 223 |
|
| 224 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 225 |
|
| 226 |
self.assertIn("DO_NOTHING", serialized) |
| 227 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 228 |
|
| 229 |
def test_restrict_serialization(self): |
| 230 |
"""Test that RESTRICT serializes correctly through PolymorphicGuard""" |
| 231 |
from .models import ModelWithRestrict |
| 232 |
|
| 233 |
field = ModelWithRestrict._meta.get_field("related") |
| 234 |
on_delete = field.remote_field.on_delete |
| 235 |
|
| 236 |
serialized, imports = serializer_factory(on_delete).serialize() |
| 237 |
|
| 238 |
self.assertIn("RESTRICT", serialized) |
| 239 |
self.assertNotIn("PolymorphicGuard", serialized) |
| 240 |
|
| 241 |
def test_migration_file_generated(self): |
| 242 |
"""Test that a migration file was generated""" |
| 243 |
# Check that at least one migration file was created |
| 244 |
migration_files = list(self.migrations_dir.glob("0001_*.py")) |
| 245 |
self.assertTrue(len(migration_files) > 0, "No migration file was generated") |
| 246 |
|
| 247 |
def test_migration_file_content(self): |
| 248 |
"""Test that the generated migration file contains correct serialization""" |
| 249 |
# Find the initial migration file |
| 250 |
migration_files = list(self.migrations_dir.glob("0001_*.py")) |
| 251 |
self.assertTrue(len(migration_files) > 0, "No migration file found") |
| 252 |
|
| 253 |
migration_file = migration_files[0] |
| 254 |
content = migration_file.read_text() |
| 255 |
|
| 256 |
# Check that PolymorphicGuard is NOT in the migration file |
| 257 |
self.assertNotIn( |
| 258 |
"PolymorphicGuard", content, "Migration file should not contain PolymorphicGuard" |
| 259 |
) |
| 260 |
|
| 261 |
# Check that on_delete handlers are properly serialized |
| 262 |
self.assertIn("django.db.models.deletion.CASCADE", content) |
| 263 |
self.assertIn("django.db.models.deletion.PROTECT", content) |
| 264 |
self.assertIn("django.db.models.deletion.SET_NULL", content) |
| 265 |
self.assertIn("django.db.models.deletion.SET_DEFAULT", content) |
| 266 |
self.assertIn("django.db.models.deletion.DO_NOTHING", content) |
| 267 |
self.assertIn("django.db.models.deletion.RESTRICT", content) |
| 268 |
|
| 269 |
# Check that SET() with callable is properly serialized |
| 270 |
self.assertIn("models.SET", content) |
| 271 |
self.assertIn("get_default_related", content) |
| 272 |
|
| 273 |
def test_migration_serialization_stability(self): |
| 274 |
""" |
| 275 |
Test that the migration file contains stable serialization. |
| 276 |
This ensures that PolymorphicGuard doesn't cause migration churn |
| 277 |
by verifying the migration was generated successfully in setUpClass. |
| 278 |
""" |
| 279 |
# The fact that we have a migration file and it contains the right |
| 280 |
# serialization (tested in test_migration_file_content) proves |
| 281 |
# that the serialization is stable. If it wasn't stable, the |
| 282 |
# migration file would either fail to generate or contain |
| 283 |
# PolymorphicGuard references. |
| 284 |
migration_files = list(self.migrations_dir.glob("0001_*.py")) |
| 285 |
self.assertEqual(len(migration_files), 1, "Should have exactly one initial migration file") |
| 286 |
|
| 287 |
def test_PolymorphicGuard_unwraps_correctly(self): |
| 288 |
"""Test that PolymorphicGuard properly unwraps to the underlying action""" |
| 289 |
from .models import ModelWithCascade |
| 290 |
|
| 291 |
field = ModelWithCascade._meta.get_field("related") |
| 292 |
on_delete = field.remote_field.on_delete |
| 293 |
|
| 294 |
# Verify it's wrapped |
| 295 |
self.assertIsInstance(on_delete, PolymorphicGuard) |
| 296 |
|
| 297 |
# Verify the underlying action is CASCADE |
| 298 |
self.assertEqual(on_delete.action, models.CASCADE) |
| 299 |
|
| 300 |
def test_all_on_delete_types_covered(self): |
| 301 |
""" |
| 302 |
Meta-test to ensure we've covered all Django on_delete types. |
| 303 |
This test documents which on_delete types we're testing. |
| 304 |
""" |
| 305 |
tested_types = { |
| 306 |
"CASCADE": models.CASCADE, |
| 307 |
"PROTECT": models.PROTECT, |
| 308 |
"SET_NULL": models.SET_NULL, |
| 309 |
"SET_DEFAULT": models.SET_DEFAULT, |
| 310 |
"SET": models.SET, # This is a callable that returns the actual handler |
| 311 |
"DO_NOTHING": models.DO_NOTHING, |
| 312 |
"RESTRICT": models.RESTRICT, |
| 313 |
} |
| 314 |
|
| 315 |
# Document that we have test models for each type |
| 316 |
from .models import ( |
| 317 |
ModelWithCascade, |
| 318 |
ModelWithProtect, |
| 319 |
ModelWithSetNull, |
| 320 |
ModelWithSetDefault, |
| 321 |
ModelWithSet, |
| 322 |
ModelWithDoNothing, |
| 323 |
ModelWithRestrict, |
| 324 |
) |
| 325 |
|
| 326 |
model_mapping = { |
| 327 |
"CASCADE": ModelWithCascade, |
| 328 |
"PROTECT": ModelWithProtect, |
| 329 |
"SET_NULL": ModelWithSetNull, |
| 330 |
"SET_DEFAULT": ModelWithSetDefault, |
| 331 |
"SET": ModelWithSet, |
| 332 |
"DO_NOTHING": ModelWithDoNothing, |
| 333 |
"RESTRICT": ModelWithRestrict, |
| 334 |
} |
| 335 |
|
| 336 |
# Verify we have a model for each on_delete type |
| 337 |
for type_name, on_delete_handler in tested_types.items(): |
| 338 |
with self.subTest(type=type_name): |
| 339 |
self.assertIn(type_name, model_mapping, f"Missing test model for {type_name}") |
| 340 |
model_class = model_mapping[type_name] |
| 341 |
field = model_class._meta.get_field("related") |
| 342 |
|
| 343 |
# Verify the field is properly configured |
| 344 |
self.assertIsNotNone(field) |
| 345 |
self.assertIsInstance(field.remote_field.on_delete, PolymorphicGuard) |
| 346 |
|
| 347 |
def test_guard_equality_with_same_guard(self): |
| 348 |
"""Test that PolymorphicGuard equals another PolymorphicGuard with the same action""" |
| 349 |
guard1 = PolymorphicGuard(models.CASCADE) |
| 350 |
guard2 = PolymorphicGuard(models.CASCADE) |
| 351 |
|
| 352 |
self.assertEqual(guard1, guard2) |
| 353 |
self.assertEqual(guard1.migration_key, guard2.migration_key) |
| 354 |
|
| 355 |
def test_guard_equality_with_different_guard(self): |
| 356 |
"""Test that PolymorphicGuard doesn't equal another with a different action""" |
| 357 |
guard1 = PolymorphicGuard(models.CASCADE) |
| 358 |
guard2 = PolymorphicGuard(models.PROTECT) |
| 359 |
|
| 360 |
self.assertNotEqual(guard1, guard2) |
| 361 |
self.assertNotEqual(guard1.migration_key, guard2.migration_key) |
| 362 |
|
| 363 |
def test_guard_equality_with_non_serializable_object(self): |
| 364 |
"""Test PolymorphicGuard equality when comparing to an object that cannot be serialized""" |
| 365 |
|
| 366 |
class UnserializableCallable: |
| 367 |
"""A callable that cannot be properly serialized by Django's migration system""" |
| 368 |
|
| 369 |
def __call__(self, collector, field, sub_objs, using): |
| 370 |
pass |
| 371 |
|
| 372 |
guard = PolymorphicGuard(models.CASCADE) |
| 373 |
non_serializable = UnserializableCallable() |
| 374 |
|
| 375 |
result = guard == non_serializable |
| 376 |
self.assertFalse(result) |
| 377 |
|
| 378 |
def test_guard_equality_with_serialization_exception(self): |
| 379 |
"""Test PolymorphicGuard equality with an object that causes an exception during fingerprinting""" |
| 380 |
|
| 381 |
class ProblematicObject: |
| 382 |
"""An object that breaks during serialization""" |
| 383 |
|
| 384 |
def __repr__(self): |
| 385 |
raise RuntimeError("Cannot serialize this object") |
| 386 |
|
| 387 |
guard = PolymorphicGuard(models.CASCADE) |
| 388 |
problematic = ProblematicObject() |
| 389 |
|
| 390 |
result = guard == problematic |
| 391 |
self.assertFalse(result) |
| 392 |
|
| 393 |
|
| 394 |
class PolymorphicInheritanceSerializationTest(TestCase): |
| 395 |
""" |
| 396 |
Test that PolymorphicGuard works correctly with polymorphic model inheritance. |
| 397 |
""" |
| 398 |
|
| 399 |
def test_polymorphic_inheritance_chain(self): |
| 400 |
"""Test that polymorphic model inheritance works with all on_delete types""" |
| 401 |
from .models import BasePolyModel, ChildPolyModel, GrandChildPolyModel |
| 402 |
|
| 403 |
# Verify the inheritance chain is set up correctly |
| 404 |
self.assertTrue(issubclass(ChildPolyModel, BasePolyModel)) |
| 405 |
self.assertTrue(issubclass(GrandChildPolyModel, ChildPolyModel)) |
| 406 |
self.assertTrue(issubclass(GrandChildPolyModel, BasePolyModel)) |
| 407 |
|
| 408 |
# Verify each model has the polymorphic_ctype field |
| 409 |
for model_class in [BasePolyModel, ChildPolyModel, GrandChildPolyModel]: |
| 410 |
with self.subTest(model=model_class.__name__): |
| 411 |
ctype_field = model_class._meta.get_field("polymorphic_ctype") |
| 412 |
self.assertIsNotNone(ctype_field) |
| 413 |
# The polymorphic_ctype field uses CASCADE which should also be wrapped |
| 414 |
self.assertIsInstance(ctype_field.remote_field.on_delete, PolymorphicGuard) |
| 415 |
|
| 416 |
|
| 417 |
class OnDeleteBehaviorTest(GeneratedMigrationsPerClassMixin, TransactionTestCase): |
| 418 |
""" |
| 419 |
Test that PolymorphicGuard correctly executes on_delete actions. |
| 420 |
|
| 421 |
These tests verify the runtime behavior of each on_delete type when |
| 422 |
wrapped with PolymorphicGuard by creating and deleting model instances. |
| 423 |
""" |
| 424 |
|
| 425 |
apps_to_migrate: list[str] = ["test_migrations"] |
| 426 |
|
| 427 |
def test_cascade_deletes_related_objects(self): |
| 428 |
"""Test that CASCADE deletes related polymorphic objects""" |
| 429 |
from .models import RelatedModel, ModelWithCascade |
| 430 |
|
| 431 |
# Create a related model and a polymorphic model that references it |
| 432 |
related = RelatedModel.objects.create(name="test") |
| 433 |
cascade_obj = ModelWithCascade.objects.create(related=related) |
| 434 |
cascade_obj_id = cascade_obj.id |
| 435 |
|
| 436 |
# Verify the object exists |
| 437 |
self.assertTrue(ModelWithCascade.objects.filter(id=cascade_obj_id).exists()) |
| 438 |
|
| 439 |
# Delete the related model |
| 440 |
related.delete() |
| 441 |
|
| 442 |
# Verify the cascade object was deleted |
| 443 |
self.assertFalse(ModelWithCascade.objects.filter(id=cascade_obj_id).exists()) |
| 444 |
|
| 445 |
def test_protect_prevents_deletion(self): |
| 446 |
"""Test that PROTECT prevents deletion of related objects""" |
| 447 |
from .models import RelatedModel, ModelWithProtect |
| 448 |
|
| 449 |
# Create a related model and a polymorphic model that references it |
| 450 |
related = RelatedModel.objects.create(name="test") |
| 451 |
ModelWithProtect.objects.create(related=related) |
| 452 |
|
| 453 |
# Attempting to delete the related model should raise ProtectedError |
| 454 |
with self.assertRaises(ProtectedError): |
| 455 |
related.delete() |
| 456 |
|
| 457 |
# Verify both objects still exist |
| 458 |
self.assertTrue(RelatedModel.objects.filter(id=related.id).exists()) |
| 459 |
self.assertTrue(ModelWithProtect.objects.filter(related=related).exists()) |
| 460 |
|
| 461 |
def test_set_null_sets_field_to_null(self): |
| 462 |
"""Test that SET_NULL sets the foreign key to null""" |
| 463 |
from .models import RelatedModel, ModelWithSetNull |
| 464 |
|
| 465 |
# Create a related model and a polymorphic model that references it |
| 466 |
related = RelatedModel.objects.create(name="test") |
| 467 |
set_null_obj = ModelWithSetNull.objects.create(related=related) |
| 468 |
set_null_obj_id = set_null_obj.id |
| 469 |
|
| 470 |
# Verify the relationship exists |
| 471 |
self.assertEqual(set_null_obj.related, related) |
| 472 |
|
| 473 |
# Delete the related model |
| 474 |
related.delete() |
| 475 |
|
| 476 |
# Verify the object still exists but the field is now null |
| 477 |
set_null_obj = ModelWithSetNull.objects.get(id=set_null_obj_id) |
| 478 |
self.assertIsNone(set_null_obj.related) |
| 479 |
|
| 480 |
def test_set_default_sets_field_to_default(self): |
| 481 |
"""Test that SET_DEFAULT sets the foreign key to its default value""" |
| 482 |
from .models import RelatedModel, ModelWithSetDefault |
| 483 |
|
| 484 |
# Create a related model and a polymorphic model that references it |
| 485 |
related = RelatedModel.objects.create(name="test") |
| 486 |
set_default_obj = ModelWithSetDefault.objects.create(related=related) |
| 487 |
set_default_obj_id = set_default_obj.id |
| 488 |
|
| 489 |
# Verify the relationship exists |
| 490 |
self.assertEqual(set_default_obj.related, related) |
| 491 |
|
| 492 |
# Delete the related model |
| 493 |
related.delete() |
| 494 |
|
| 495 |
# Verify the object still exists but the field is now set to default (None) |
| 496 |
set_default_obj = ModelWithSetDefault.objects.get(id=set_default_obj_id) |
| 497 |
self.assertIsNone(set_default_obj.related) |
| 498 |
|
| 499 |
def test_set_callable_uses_function(self): |
| 500 |
"""Test that SET(...) calls the provided function""" |
| 501 |
from .models import RelatedModel, ModelWithSet |
| 502 |
|
| 503 |
# Create a related model and a polymorphic model that references it |
| 504 |
related = RelatedModel.objects.create(name="test") |
| 505 |
set_obj = ModelWithSet.objects.create(related=related) |
| 506 |
set_obj_id = set_obj.id |
| 507 |
|
| 508 |
# Verify the relationship exists |
| 509 |
self.assertEqual(set_obj.related, related) |
| 510 |
|
| 511 |
# Delete the related model |
| 512 |
related.delete() |
| 513 |
|
| 514 |
# Verify the object s |
| 515 |
set_obj = ModelWithSet.objects.get(id=set_obj_id) |
| 516 |
self.assertIsNone(set_obj.related) |
| 517 |
|
| 518 |
def test_do_nothing_behavior(self): |
| 519 |
"""Test that DO_NOTHING doesn't prevent deletion or update related objects""" |
| 520 |
from .models import RelatedModel, ModelWithDoNothing |
| 521 |
|
| 522 |
# Create a related model and a polymorphic model that references it |
| 523 |
related = RelatedModel.objects.create(name="test") |
| 524 |
do_nothing_obj = ModelWithDoNothing.objects.create(related=related) |
| 525 |
|
| 526 |
# Verify the object is wrapped with PolymorphicGuard |
| 527 |
field = ModelWithDoNothing._meta.get_field("related") |
| 528 |
self.assertIsInstance(field.remote_field.on_delete, PolymorphicGuard) |
| 529 |
|
| 530 |
# Verify the underlying action is DO_NOTHING |
| 531 |
self.assertEqual(field.remote_field.on_delete.action, models.DO_NOTHING) |
| 532 |
|
| 533 |
# DO_NOTHING doesn't cascade delete or set null - it simply does nothing |
| 534 |
# In practice, this means the deletion succeeds but leaves an orphaned reference |
| 535 |
# However, database constraints may prevent this in production |
| 536 |
# Here we just verify that the wrapper is correct and the object exists |
| 537 |
self.assertTrue(ModelWithDoNothing.objects.filter(id=do_nothing_obj.id).exists()) |
| 538 |
self.assertEqual(do_nothing_obj.related, related) |
| 539 |
|
| 540 |
def test_restrict_prevents_deletion_when_objects_exist(self): |
| 541 |
"""Test that RESTRICT prevents deletion when related objects exist""" |
| 542 |
from .models import RelatedModel, ModelWithRestrict |
| 543 |
|
| 544 |
# Create a related model and a polymorphic model that references it |
| 545 |
related = RelatedModel.objects.create(name="test") |
| 546 |
restrict_obj = ModelWithRestrict.objects.create(related=related) |
| 547 |
|
| 548 |
# Attempting to delete the related model should raise RestrictedError |
| 549 |
with self.assertRaises(RestrictedError): |
| 550 |
related.delete() |
| 551 |
|
| 552 |
# Verify both objects still exist |
| 553 |
self.assertTrue(RelatedModel.objects.filter(id=related.id).exists()) |
| 554 |
self.assertTrue(ModelWithRestrict.objects.filter(id=restrict_obj.id).exists()) |
| 555 |
|
| 556 |
def test_cascade_with_polymorphic_inheritance(self): |
| 557 |
"""Test CASCADE works correctly with polymorphic child models""" |
| 558 |
from .models import RelatedModel, ModelWithCascade |
| 559 |
|
| 560 |
# Create a related model |
| 561 |
related = RelatedModel.objects.create(name="test") |
| 562 |
|
| 563 |
# Create multiple instances of the polymorphic model |
| 564 |
obj1 = ModelWithCascade.objects.create(related=related) |
| 565 |
obj2 = ModelWithCascade.objects.create(related=related) |
| 566 |
obj1_id, obj2_id = obj1.id, obj2.id |
| 567 |
|
| 568 |
# Verify they exist |
| 569 |
self.assertEqual(ModelWithCascade.objects.filter(related=related).count(), 2) |
| 570 |
|
| 571 |
# Delete the related model |
| 572 |
related.delete() |
| 573 |
|
| 574 |
# Verify all cascade objects were deleted |
| 575 |
self.assertFalse(ModelWithCascade.objects.filter(id=obj1_id).exists()) |
| 576 |
self.assertFalse(ModelWithCascade.objects.filter(id=obj2_id).exists()) |
| 577 |
self.assertEqual(ModelWithCascade.objects.count(), 0) |
| 578 |
|
| 579 |
def test_one_to_one_cascade_deletes_related_object(self): |
| 580 |
"""Test CASCADE with OneToOneField deletes related polymorphic object""" |
| 581 |
from .models import RelatedModel, ModelWithOneToOneCascade |
| 582 |
|
| 583 |
# Create a related model and a polymorphic model with OneToOne |
| 584 |
related = RelatedModel.objects.create(name="test") |
| 585 |
one_to_one_obj = ModelWithOneToOneCascade.objects.create(related=related) |
| 586 |
one_to_one_obj_id = one_to_one_obj.id |
| 587 |
|
| 588 |
# Verify the object exists |
| 589 |
self.assertTrue(ModelWithOneToOneCascade.objects.filter(id=one_to_one_obj_id).exists()) |
| 590 |
|
| 591 |
# Delete the related model |
| 592 |
related.delete() |
| 593 |
|
| 594 |
# Verify the one-to-one object was deleted |
| 595 |
self.assertFalse(ModelWithOneToOneCascade.objects.filter(id=one_to_one_obj_id).exists()) |
| 596 |
|
| 597 |
def test_one_to_one_protect_prevents_deletion(self): |
| 598 |
"""Test PROTECT with OneToOneField prevents deletion""" |
| 599 |
from .models import RelatedModel, ModelWithOneToOneProtect |
| 600 |
|
| 601 |
# Create a related model and a polymorphic model with OneToOne |
| 602 |
related = RelatedModel.objects.create(name="test") |
| 603 |
ModelWithOneToOneProtect.objects.create(related=related) |
| 604 |
|
| 605 |
# Attempting to delete should raise ProtectedError |
| 606 |
with self.assertRaises(ProtectedError): |
| 607 |
related.delete() |
| 608 |
|
| 609 |
# Verify both objects still exist |
| 610 |
self.assertTrue(RelatedModel.objects.filter(id=related.id).exists()) |
| 611 |
self.assertTrue(ModelWithOneToOneProtect.objects.filter(related=related).exists()) |
| 612 |
|
| 613 |
def test_one_to_one_set_null_sets_to_null(self): |
| 614 |
"""Test SET_NULL with OneToOneField sets field to null""" |
| 615 |
from .models import RelatedModel, ModelWithOneToOneSetNull |
| 616 |
|
| 617 |
# Create a related model and a polymorphic model with OneToOne |
| 618 |
related = RelatedModel.objects.create(name="test") |
| 619 |
one_to_one_obj = ModelWithOneToOneSetNull.objects.create(related=related) |
| 620 |
one_to_one_obj_id = one_to_one_obj.id |
| 621 |
|
| 622 |
# Verify the relationship exists |
| 623 |
self.assertEqual(one_to_one_obj.related, related) |
| 624 |
|
| 625 |
# Delete the related model |
| 626 |
related.delete() |
| 627 |
|
| 628 |
# Verify the object still exists but the field is now null |
| 629 |
one_to_one_obj = ModelWithOneToOneSetNull.objects.get(id=one_to_one_obj_id) |
| 630 |
self.assertIsNone(one_to_one_obj.related) |
| 631 |
|
| 632 |
|
| 633 |
# class TestMigrationStateStability(TestCase): |
| 634 |
# """ |
| 635 |
# Test that unchanged models do not generate new migrations. |
| 636 |
# """ |
| 637 |
|
| 638 |
# def test_migration_state_stability(self): |
| 639 |
# call_command("makemigrations") |
| 640 |
|
| 641 |
# migrations_dirs = [ |
| 642 |
# Path(__file__).parent.parent / "deletion" / "migrations", |
| 643 |
# Path(__file__).parent.parent / "test_migrations" / "migrations", |
| 644 |
# Path(__file__).parent.parent / "migrations", |
| 645 |
# ] |
| 646 |
|
| 647 |
# migrations = set() |
| 648 |
|
| 649 |
# for migrations_dir in migrations_dirs: |
| 650 |
# migrations.update(migrations_dir.glob("00*.py")) |
| 651 |
|
| 652 |
# call_command("makemigrations") |
| 653 |
# call_command("makemigrations") |
| 654 |
|
| 655 |
# migrations_post = set() |
| 656 |
|
| 657 |
# for migrations_dir in migrations_dirs: |
| 658 |
# migrations_post.update(migrations_dir.glob("00*.py")) |
| 659 |
|
| 660 |
# self.assertEqual(migrations, migrations_post) |