| 1 |
from django.core.checks import Error, run_checks |
| 2 |
from django.test.utils import override_settings |
| 3 |
from django.test import SimpleTestCase, TestCase |
| 4 |
from django.core.exceptions import FieldError |
| 5 |
|
| 6 |
|
| 7 |
@override_settings( |
| 8 |
INSTALLED_APPS=[ |
| 9 |
"polymorphic.tests.errata", |
| 10 |
"django.contrib.contenttypes", |
| 11 |
"django.contrib.auth", |
| 12 |
] |
| 13 |
) |
| 14 |
class TestErrata(SimpleTestCase): |
| 15 |
def test_system_checks(self): |
| 16 |
"""Test that using reserved field names triggers polymorphic.E001 system check.""" |
| 17 |
|
| 18 |
# Run the check function directly on the model |
| 19 |
errors = run_checks() |
| 20 |
|
| 21 |
assert len(errors) == 5, f"Expected 12 system check errors but got {len(errors)}: {errors}" |
| 22 |
|
| 23 |
assert errors[0].id == "polymorphic.E001" |
| 24 |
assert errors[0].msg == "Field 'instance_of' on model 'BadModel' is a reserved name." |
| 25 |
assert errors[1].id == "polymorphic.E001" |
| 26 |
assert errors[1].msg == "Field 'not_instance_of' on model 'BadModel' is a reserved name." |
| 27 |
|
| 28 |
assert errors[2].id == "polymorphic.E002" |
| 29 |
assert ( |
| 30 |
errors[2].msg |
| 31 |
== "The migration manager 'errata.BadMigrationManager.objects' is polymorphic." |
| 32 |
) |
| 33 |
|
| 34 |
assert errors[3].id == "polymorphic.W001" |
| 35 |
assert ( |
| 36 |
errors[3].msg == "The default manager errata.BadManager.objects' is not polymorphic." |
| 37 |
) |
| 38 |
|
| 39 |
assert errors[4].id == "polymorphic.W002" |
| 40 |
assert ( |
| 41 |
errors[4].msg |
| 42 |
== "The default manager errata.BadManager.objects' is not using a PolymorphicQuerySet." |
| 43 |
) |
| 44 |
|
| 45 |
def test_polymorphic_guard_requires_callable(self): |
| 46 |
"""Test that PolymorphicGuard raises TypeError if initialized with non-callable.""" |
| 47 |
|
| 48 |
from polymorphic.deletion import PolymorphicGuard |
| 49 |
|
| 50 |
non_callable_values = [42, "not a function", None, 3.14, [], {}] |
| 51 |
|
| 52 |
for value in non_callable_values: |
| 53 |
try: |
| 54 |
PolymorphicGuard(value) |
| 55 |
except TypeError as e: |
| 56 |
assert str(e) == "action must be callable", ( |
| 57 |
f"Expected TypeError with message 'action must be callable' but got: {e}" |
| 58 |
) |
| 59 |
else: |
| 60 |
assert False, f"Expected TypeError when initializing PolymorphicGuard with {value}" |
| 61 |
|
| 62 |
|
| 63 |
class TestFilterErrata(TestCase): |
| 64 |
def test_invalid_field_lookup_raises_field_error(self): |
| 65 |
from polymorphic.tests.models import Participant |
| 66 |
|
| 67 |
with self.assertRaises(FieldError): |
| 68 |
Participant.objects.get(tests__Model2C___field3="userprofile1") |
| 69 |
|
| 70 |
with self.assertRaises(FieldError): |
| 71 |
Participant.objects.get(notreal__Model2C___field3="userprofile1") |
| 72 |
|
| 73 |
with self.assertRaises(FieldError): |
| 74 |
Participant.objects.get(tests__NotReal___field3="userprofile1") |