Debian Codegraph @

src/polymorphic/tests/test_missing_coverage.py

raw
1 """
2 Tests specifically targeting uncovered code paths to achieve 100% coverage.
3 """
4
5 import warnings
6
7 import pytest
8 from django.contrib.contenttypes.models import ContentType
9 from django.db.models.query import ModelIterable
10 from django.test import TestCase, TransactionTestCase
11
12 from polymorphic.formsets.models import (
13 BasePolymorphicModelFormSet,
14 PolymorphicFormSetChild,
15 polymorphic_modelformset_factory,
16 )
17 from polymorphic.models import PolymorphicModel
18 from polymorphic.query import PolymorphicModelIterable, PolymorphicQuerySet
19 from polymorphic.tests.models import (
20 Model2A,
21 Model2B,
22 Model2C,
23 Model2D,
24 ModelShow1,
25 ModelShow2,
26 ModelShow3,
27 RelationBase,
28 SubclassSelectorProxyBaseModel,
29 SubclassSelectorProxyModel,
30 )
31 from polymorphic.utils import reset_polymorphic_ctype
32
33
34 # ===========================================================================
35 # base.py - deprecated base_objects property (lines 157-163)
36 # ===========================================================================
37
38
39 class TestBaseObjectsDeprecated(TestCase):
40 """Test the deprecated base_objects property on PolymorphicModelBase metaclass."""
41
42 def test_base_objects_deprecated_warning(self):
43 """Accessing Model.base_objects raises DeprecationWarning."""
44 with warnings.catch_warnings(record=True) as caught:
45 warnings.simplefilter("always")
46 mgr = Model2A.base_objects
47 assert len(caught) == 1
48 w = caught[0]
49 assert issubclass(w.category, DeprecationWarning)
50 assert "base_objects" in str(w.message)
51 assert "non_polymorphic()" in str(w.message)
52 # The manager returned should be a django Manager
53 from django.db import models as djmodels
54
55 assert isinstance(mgr, djmodels.Manager)
56
57 def test_base_objects_returns_manager(self):
58 """base_objects manager can filter/query normally."""
59 Model2A.objects.create(field1="test_deprecated")
60 with warnings.catch_warnings(record=True):
61 warnings.simplefilter("always")
62 mgr = Model2A.base_objects
63 # should return base (non-polymorphic) instances
64 obj = mgr.filter(field1="test_deprecated").first()
65 assert obj is not None
66
67
68 # ===========================================================================
69 # managers.py - PolymorphicManager.__str__ (line 106)
70 # ===========================================================================
71
72
73 class TestPolymorphicManagerStr(TestCase):
74 """Test PolymorphicManager.__str__ method."""
75
76 def test_manager_str(self):
77 """PolymorphicManager.__str__ includes class name and queryset class name."""
78 # Use the actual manager from the model rather than constructing one manually
79 result = str(Model2A.objects)
80 assert "PolymorphicManager" in result
81 assert "PolymorphicQuerySet" in result
82
83 def test_custom_manager_str(self):
84 """Custom PolymorphicManager subclass has correct __str__."""
85 from polymorphic.tests.models import ModelWithMyManager
86
87 # Use the actual manager from the model (ModelWithMyManager uses MyManager)
88 result = str(ModelWithMyManager.objects)
89 assert "MyManager" in result
90 assert "MyManagerQuerySet" in result
91
92
93 # ===========================================================================
94 # deletion.py - PolymorphicGuard.__eq__ with tuple (lines 97-103)
95 # ===========================================================================
96
97
98 class TestPolymorphicGuardEqWithTuple(TestCase):
99 """Test PolymorphicGuard.__eq__ when compared with a 3-tuple (migration autodetector case)."""
100
101 def test_guard_eq_tuple_with_deconstructible_action(self):
102 """When compared to a 3-tuple and action has deconstruct(), compare via deconstruct."""
103 from django.db import models as dj_models
104
105 from polymorphic.deletion import PolymorphicGuard
106
107 # models.SET(value) returns an object with a deconstruct() method
108 action = dj_models.SET(42)
109 guard = PolymorphicGuard(action)
110
111 # deconstruct() returns ('django.db.models.SET', (42,), {})
112 path, args, kwargs = action.deconstruct()
113
114 # Compare guard to the equivalent 3-tuple
115 assert guard == (path, args, kwargs)
116
117 def test_guard_eq_tuple_with_list_args(self):
118 """When compared to a 3-tuple with list args instead of tuple, still works."""
119 from django.db import models as dj_models
120
121 from polymorphic.deletion import PolymorphicGuard
122
123 action = dj_models.SET(99)
124 guard = PolymorphicGuard(action)
125 path, args, kwargs = action.deconstruct()
126
127 # Use list instead of tuple for args element (list [99] instead of tuple (99,))
128 assert guard == (path, list(args), kwargs)
129
130 def test_guard_eq_tuple_wrong_length(self):
131 """Tuple with wrong length is not compared via deconstruct."""
132 from django.db import models as dj_models
133
134 from polymorphic.deletion import PolymorphicGuard
135
136 action = dj_models.SET_NULL
137 guard = PolymorphicGuard(action)
138
139 # 2-tuple does NOT trigger the deconstruct path
140 result = guard.__eq__(("some_path", []))
141 # falls through to migration_key comparison - should return False
142 assert result is False
143
144 def test_guard_eq_tuple_action_without_deconstruct(self):
145 """If action lacks deconstruct(), tuple comparison falls through."""
146 from polymorphic.deletion import PolymorphicGuard
147
148 # A plain callable without deconstruct()
149 def my_handler(collector, field, sub_objs, using):
150 pass
151
152 guard = PolymorphicGuard(my_handler)
153 # 3-tuple, but my_handler has no deconstruct() -> condition False -> migration_key path
154 result = guard.__eq__(("some.path", (), {}))
155 # my_handler != SET_NULL fingerprint, so False
156 assert result is False
157
158
159 # ===========================================================================
160 # utils.py - reset_polymorphic_ctype with ignore_existing + filters (lines 41, 50, 52)
161 # utils.py - line 70 (unreachable - pragma: no cover is appropriate)
162 # ===========================================================================
163
164
165 class TestResetPolymorphicCtypeExtended(TransactionTestCase):
166 """Extended tests for reset_polymorphic_ctype covering ignore_existing and filters."""
167
168 def test_reset_with_ignore_existing(self):
169 """
170 reset_polymorphic_ctype with ignore_existing=True reverses the order (line 41)
171 and filters for objects with null ctype (line 50).
172 """
173 # Create objects and null out their ctypes
174 obj_a = Model2A.objects.create(field1="A_ignore")
175 obj_b = Model2B.objects.create(field1="B_ignore", field2="B2")
176
177 # Null out ctypes
178 Model2A.objects.all().update(polymorphic_ctype_id=None)
179
180 # Call with ignore_existing=True
181 reset_polymorphic_ctype(Model2A, Model2B, ignore_existing=True)
182
183 # Ctypes should now be set
184 obj_a.refresh_from_db()
185 obj_b.refresh_from_db()
186 ct_a = ContentType.objects.get_for_model(Model2A, for_concrete_model=False)
187 ct_b = ContentType.objects.get_for_model(Model2B, for_concrete_model=False)
188 assert obj_a.polymorphic_ctype_id == ct_a.pk
189 assert obj_b.polymorphic_ctype_id == ct_b.pk
190
191 def test_reset_with_ignore_existing_skips_already_set(self):
192 """
193 With ignore_existing=True, already-set ctypes are NOT overwritten (line 50).
194 """
195 # Create objects - ctypes are set by default
196 obj_a = Model2A.objects.create(field1="A_skip")
197 original_ct_id = obj_a.polymorphic_ctype_id
198
199 # Do NOT null out ctype - it should be skipped
200 reset_polymorphic_ctype(Model2A, ignore_existing=True)
201
202 obj_a.refresh_from_db()
203 # Should still be the same ctype (not changed)
204 assert obj_a.polymorphic_ctype_id == original_ct_id
205
206 def test_reset_with_extra_filters(self):
207 """
208 reset_polymorphic_ctype with extra **filters applies them (line 52).
209 """
210 # Create objects
211 Model2A.objects.create(field1="filter_me")
212 Model2A.objects.create(field1="not_me")
213
214 # Null out all ctypes
215 Model2A.objects.all().update(polymorphic_ctype_id=None)
216
217 # Reset only for objects matching the filter
218 reset_polymorphic_ctype(Model2A, field1="filter_me")
219
220 ct_a = ContentType.objects.get_for_model(Model2A, for_concrete_model=False)
221 # filter_me should be set
222 assert Model2A.objects.filter(field1="filter_me", polymorphic_ctype_id=ct_a.pk).exists()
223 # not_me should still be null
224 assert Model2A.objects.filter(field1="not_me", polymorphic_ctype_id__isnull=True).exists()
225
226 def test_reset_with_ignore_existing_and_filters(self):
227 """
228 Combined test: ignore_existing=True AND extra filters (lines 41, 50, 52 together).
229 """
230 # Create objects with null ctypes
231 obj1 = Model2A.objects.create(field1="combo_reset")
232 obj2 = Model2A.objects.create(field1="combo_skip")
233
234 Model2A.objects.all().update(polymorphic_ctype_id=None)
235
236 # Reset only field1="combo_reset" with ignore_existing=True
237 reset_polymorphic_ctype(Model2A, ignore_existing=True, field1="combo_reset")
238
239 ct_a = ContentType.objects.get_for_model(Model2A, for_concrete_model=False)
240 # Use non_polymorphic() to bypass polymorphic ctype checks when ct is still null
241 obj1_data = (
242 Model2A.objects.non_polymorphic()
243 .filter(pk=obj1.pk)
244 .values("polymorphic_ctype_id")
245 .first()
246 )
247 obj2_data = (
248 Model2A.objects.non_polymorphic()
249 .filter(pk=obj2.pk)
250 .values("polymorphic_ctype_id")
251 .first()
252 )
253 assert obj1_data["polymorphic_ctype_id"] == ct_a.pk
254 assert obj2_data["polymorphic_ctype_id"] is None
255
256
257 # ===========================================================================
258 # query.py - PolymorphicModelIterable.__iter__ when polymorphic_disabled (line 78)
259 # ===========================================================================
260
261
262 class TestPolymorphicModelIterableDisabled(TransactionTestCase):
263 """Test PolymorphicModelIterable when polymorphic_disabled=True (line 78)."""
264
265 def test_polymorphic_iterable_returns_base_iter_when_disabled(self):
266 """
267 When qs.polymorphic_disabled=True and _iterable_class is still
268 PolymorphicModelIterable, __iter__ returns base_iter directly.
269 """
270 Model2A.objects.create(field1="disabled_test")
271
272 qs = Model2A.objects.all()
273 # The _iterable_class is PolymorphicModelIterable by default
274 assert issubclass(qs._iterable_class, PolymorphicModelIterable)
275
276 # Set polymorphic_disabled=True without calling non_polymorphic()
277 # (which would also replace _iterable_class with ModelIterable)
278 qs2 = qs._clone()
279 qs2.polymorphic_disabled = True
280 # _iterable_class is still PolymorphicModelIterable
281
282 results = list(qs2)
283 # Should return base class (Model2A) objects
284 assert len(results) >= 1
285 for obj in results:
286 assert type(obj) is Model2A
287
288
289 # ===========================================================================
290 # query.py - max_chunk=0 (falsy) branch (lines 97->104)
291 # ===========================================================================
292
293
294 class TestPolymorphicIteratorMaxChunk(TransactionTestCase):
295 """Test _polymorphic_iterator when max_chunk is 0/falsy."""
296
297 def test_iterator_with_zero_max_query_params(self):
298 """
299 Lines 97->104: When max_query_params is 0 (falsy), the if max_chunk branch
300 is skipped and sql_chunk falls back to Polymorphic_QuerySet_objects_per_request.
301 """
302 from unittest.mock import MagicMock, patch
303
304 Model2A.objects.create(field1="chunk_test")
305 Model2B.objects.create(field1="chunk_b", field2="B2")
306
307 qs = Model2A.objects.all()
308
309 class FakeFeatures:
310 max_query_params = 0
311
312 class FakeConnection:
313 features = FakeFeatures()
314
315 # Patch connections to return 0 for max_query_params
316 # Then actually iterate the queryset to exercise _polymorphic_iterator
317 with patch("polymorphic.query.connections") as mock_connections:
318 mock_connections.__getitem__ = MagicMock(return_value=FakeConnection())
319 # Iterate the queryset - this calls _polymorphic_iterator which checks max_chunk
320 # With max_chunk=0, the if branch is skipped (97->104)
321 results = list(qs)
322 assert len(results) >= 2
323
324
325 # ===========================================================================
326 # query.py - non_polymorphic() False branch of issubclass check (lines 216->218)
327 # ===========================================================================
328
329
330 class TestNonPolymorphicIterable(TestCase):
331 """Test non_polymorphic() when _iterable_class is NOT PolymorphicModelIterable."""
332
333 def test_non_polymorphic_with_non_polymorphic_iterable(self):
334 """
335 non_polymorphic() when _iterable_class is already ModelIterable (not a subclass
336 of PolymorphicModelIterable) - the False branch of the issubclass check (line 216->218).
337
338 Calling non_polymorphic() twice hits the False branch naturally: the first call
339 switches _iterable_class to ModelIterable; the second call finds it is already
340 ModelIterable (not a subclass of PolymorphicModelIterable) and skips the swap.
341 """
342 qs2 = Model2A.objects.non_polymorphic().non_polymorphic()
343 assert qs2.polymorphic_disabled is True
344 # _iterable_class should be ModelIterable after the second call
345 assert qs2._iterable_class is ModelIterable
346
347
348 # ===========================================================================
349 # query.py - defer(None) case (line 295)
350 # ===========================================================================
351
352
353 class TestDeferNone(TransactionTestCase):
354 """Test the defer(None) case in PolymorphicQuerySet."""
355
356 def test_defer_none(self):
357 """defer(None) should reset deferred loading."""
358 Model2B.objects.create(field1="defer_none_b", field2="B2")
359
360 # First defer a field
361 qs = Model2A.objects.defer("field1")
362 # Then call defer(None) to reset
363 qs2 = qs.defer(None)
364 # Should work without error - returns all fields
365 results = list(qs2)
366 assert len(results) >= 1
367
368
369 # ===========================================================================
370 # query.py - _polymorphic_add_deferred_loading False branch (line 323)
371 # ===========================================================================
372
373
374 class TestPolymorphicDeferredLoading(TransactionTestCase):
375 """Test the _polymorphic_add_deferred_loading branches."""
376
377 def test_add_deferred_loading_remove_from_immediate(self):
378 """
379 Test line 323: when defer=False, removing field names from immediate load set.
380 Verify the code path is traversed by ensuring the query works without error.
381 """
382 Model2B.objects.create(field1="defer_load_b", field2="B2")
383
384 # First use only() to set up 'immediate load' mode (defer=False)
385 # Then call defer() on this qs - this triggers the False branch
386 # (removes from immediate load set)
387 qs2 = Model2A.objects.only("field1").defer("field1")
388 # Verify the query executes without error (code path covered by execution)
389 results = list(qs2)
390 assert len(results) >= 1
391
392 def test_add_immediate_loading_when_defer_is_false(self):
393 """
394 Test line 342: when defer=False (already in only() mode), replaces immediate fields.
395 Verify the code path is traversed by ensuring the query works without error.
396 """
397 Model2B.objects.create(field1="only_load_b", field2="B2")
398 # Call only() then only() again - this triggers line 342 (defer=False → replace fields)
399 qs2 = Model2A.objects.only("field1").only("polymorphic_ctype_id")
400 # Verify the query executes without error (code path covered by execution)
401 results = list(qs2)
402 assert len(results) >= 1
403
404
405 # ===========================================================================
406 # query.py - patch_lookup else branch (line 366)
407 # ===========================================================================
408
409
410 class TestAnnotateAggregatePatchLookup(TransactionTestCase):
411 """Test the else branch in patch_lookup (line 366) - direct .name attribute."""
412
413 def test_annotate_with_direct_name_aggregate(self):
414 """
415 Test annotate with an aggregate that has a .name attribute directly
416 (not get_source_expressions, not Q, not FilteredRelation, not F).
417 This tests the else branch in patch_lookup.
418 """
419 from django.db.models import Count
420
421 Model2A.objects.create(field1="patch_lookup_test")
422
423 # Test that annotate works normally - exercises patch_lookup via kwargs
424 qs = Model2A.objects.annotate(count=Count("id"))
425 results = list(qs)
426 assert len(results) >= 1
427
428 def test_patch_lookup_else_branch_direct(self):
429 """
430 Line 366: The else branch in patch_lookup for objects with .name but
431 no get_source_expressions (not Q, not FilteredRelation, not F).
432
433 NOTE: There is no clean public API way to reach this branch in modern Django,
434 because all standard Django aggregate/expression classes have get_source_expressions().
435 The else branch is only reachable with a custom expression that has .name but
436 lacks get_source_expressions. We call _process_aggregate_args directly here
437 because this branch cannot be triggered through qs.annotate() or qs.aggregate()
438 in practice with any built-in Django expression type.
439 """
440 Model2A.objects.create(field1="patch_lookup_else")
441
442 # Create a fake expression with .name but no get_source_expressions
443 class FakeExpr:
444 def __init__(self, name):
445 self.name = name
446
447 fake = FakeExpr("field1")
448 qs = Model2A.objects.all()
449
450 # Call _process_aggregate_args with fake as a kwarg value
451 # This triggers patch_lookup(fake) → not Q, not FilteredRelation,
452 # not F, no get_source_expressions → else: a.name = translate(...)
453 kwargs = {"test_fake": fake}
454 qs._process_aggregate_args([], kwargs)
455 # field1 has no ___ so translate returns it unchanged
456 assert fake.name == "field1"
457
458
459 class TestAnnotateWithQObject(TransactionTestCase):
460 """Test tree_node_test___lookup when 'a' is a Q object (lines 373-385)."""
461
462 def test_aggregate_with_q_positional_args(self):
463 """
464 Lines 373-385: aggregate() with Q as positional arg triggers tree_node_test___lookup.
465 When a Q object is passed as a positional arg to annotate/aggregate,
466 test___lookup is called with it, which calls tree_node_test___lookup.
467
468 NOTE: Passing Q as a positional argument to qs.aggregate() is not valid in the
469 public Django API (aggregate() requires keyword arguments for named results).
470 This code path in _process_aggregate_args handles Q positional args that come
471 from internal callers. We call _process_aggregate_args directly because there
472 is no public API way to pass a Q as a positional arg to aggregate/annotate.
473 """
474 from django.db.models import Count, Q
475
476 Model2A.objects.create(field1="q_agg_test")
477 Model2B.objects.create(field1="q_agg_b", field2="B2")
478
479 # _process_aggregate_args processes positional args with test___lookup
480 q = Q(field1="q_agg_test")
481 args = [q]
482 kwargs = {}
483 # Directly call _process_aggregate_args to test the Q object path
484 qs = Model2A.objects.all()
485 qs._process_aggregate_args(args, kwargs) # triggers tree_node_test___lookup
486
487 def test_aggregate_with_nested_q_objects_positional(self):
488 """
489 Nested Q objects in positional args test the recursive tree_node_test___lookup.
490
491 NOTE: Same rationale as test_aggregate_with_q_positional_args - no public API
492 accepts Q as positional arg to aggregate/annotate.
493 """
494 from django.db.models import Q
495
496 Model2A.objects.create(field1="nested_q")
497
498 qs = Model2A.objects.all()
499 # Nested Q objects - tests recursion in tree_node_test___lookup
500 nested_q = Q(Q(field1="nested_q") | Q(field1="other"))
501 qs._process_aggregate_args([nested_q], {})
502
503 def test_aggregate_with_q_object_no_triple_underscore(self):
504 """
505 aggregate() with Q object in kwargs filter exercises patch_lookup with Q.
506 """
507 from django.db.models import Count, Q
508
509 Model2A.objects.create(field1="q_agg_test2")
510
511 qs = Model2A.objects.all()
512 result = qs.aggregate(count=Count("id", filter=Q(field1="q_agg_test2")))
513 assert "count" in result
514
515 def test_test___lookup_with_expression_having_source_expressions(self):
516 """
517 Lines 386-389: test___lookup for expressions with get_source_expressions.
518 """
519 from django.db.models import Count, F
520
521 qs = Model2A.objects.all()
522 # F expression has no get_source_expressions but Count does
523 # This tests the elif hasattr(a, 'get_source_expressions') branch in test___lookup
524 count_expr = Count("id")
525 qs._process_aggregate_args([count_expr], {})
526
527
528 # ===========================================================================
529 # query.py - stale content type (line 497) + real_concrete_class is None (lines 513->527)
530 # ===========================================================================
531
532
533 class TestGetRealInstancesEdgeCases(TransactionTestCase):
534 """Test _get_real_instances with stale/missing content types."""
535
536 def test_stale_content_type_skipped(self):
537 """
538 Line 497: When real_concrete_class_id is None (stale content type), skip the object.
539
540 We iterate the full queryset using the public list(qs) API, patching
541 get_real_concrete_instance_class_id at the class level so that all instances
542 appear to have a stale (None) content type. The objects should be skipped.
543 """
544 from unittest.mock import patch
545
546 Model2B.objects.create(field1="stale_ct", field2="B2")
547
548 qs = Model2A.objects.all()
549
550 # Patch at the class level so all base objects appear to have a stale CT
551 with patch.object(
552 Model2A,
553 "get_real_concrete_instance_class_id",
554 return_value=None,
555 ):
556 # list(qs) triggers _polymorphic_iterator → _get_real_instances
557 # Each object's get_real_concrete_instance_class_id() returns None → skipped
558 results = list(qs)
559 assert len(results) == 0
560
561
562 # ===========================================================================
563 # query.py - AssertionError else branch (line 569)
564 # ===========================================================================
565
566
567 class TestDeferLoadingAssertionElseBranch(TransactionTestCase):
568 """Test the else branch when AssertionError is raised without '___' in field (line 569)."""
569
570 def test_field_without_triple_underscore_reraises(self):
571 """
572 When translating deferred fields in _get_real_instances, if AssertionError raised
573 and '___' not in field name, it should re-raise. This tests line 569.
574
575 We use the public qs.defer("field1") API to set up deferred loading, then iterate
576 with list(qs) (also public) while patching translate_polymorphic_field_path to raise
577 AssertionError for the plain field name (no '___'). The patch is needed because
578 there is no standard way to trigger this specific code path through purely unpatched
579 public API - the else-raise branch requires an AssertionError from the translator
580 for a field name that contains no triple-underscore.
581 """
582 from unittest.mock import patch
583
584 from polymorphic.query_translate import translate_polymorphic_field_path as orig_translate
585
586 Model2B.objects.create(field1="assert_test", field2="B2")
587
588 def patched_translate(model, field_path):
589 if field_path == "field1":
590 raise AssertionError("simulated assertion for plain field")
591 return orig_translate(model, field_path)
592
593 # Use public API: defer("field1") sets polymorphic_deferred_loading for "field1"
594 qs = Model2A.objects.defer("field1")
595
596 with patch(
597 "polymorphic.query.translate_polymorphic_field_path", side_effect=patched_translate
598 ):
599 with pytest.raises(AssertionError, match="simulated assertion"):
600 # list(qs) iterates via _polymorphic_iterator → _get_real_instances
601 # which translates deferred fields → patched_translate raises for "field1"
602 # "field1" has no "___" → else: raise
603 list(qs)
604
605
606 # ===========================================================================
607 # query.py - annotation not on base object (lines 625->624)
608 # ===========================================================================
609
610
611 class TestAnnotationNotOnBaseObject(TransactionTestCase):
612 """Test hasattr(base_object, anno_field_name) is False (line 625->624)."""
613
614 def test_annotation_missing_from_base_object(self):
615 """
616 When a real object is fetched via _get_real_instances and an annotation
617 is NOT on the base object (hasattr returns False), the annotation is skipped.
618 """
619 from django.db.models import Value
620
621 Model2B.objects.create(field1="ann_missing", field2="B2")
622
623 # Annotate the queryset
624 qs = Model2A.objects.annotate(my_test_annotation=Value(42))
625 results = list(qs)
626
627 # At least the annotation is present on results
628 for obj in results:
629 if hasattr(obj, "my_test_annotation"):
630 assert obj.my_test_annotation == 42
631
632
633 # ===========================================================================
634 # query.py - __repr__ for non-multiline queryset (line 660)
635 # ===========================================================================
636
637
638 class TestQuerySetRepr(TransactionTestCase):
639 """Test PolymorphicQuerySet.__repr__ for non-multiline output."""
640
641 def test_repr_multiline(self):
642 """Models with polymorphic_query_multiline_output=True use multiline repr."""
643 # Model2A uses ShowFieldType which sets polymorphic_query_multiline_output=True
644 Model2A.objects.create(field1="repr_test")
645 qs = Model2A.objects.all()
646 assert qs.model.polymorphic_query_multiline_output is True
647 r = repr(qs)
648 assert "[" in r or "repr_test" in r
649
650 def test_repr_non_multiline(self):
651 """
652 Line 660: When polymorphic_query_multiline_output=False, use super().__repr__().
653 """
654 from polymorphic.tests.models import Duck
655
656 Duck.objects.create(name="repr_duck")
657 qs = Duck.objects.all()
658 # Duck uses PolymorphicModel without ShowField mixin
659 assert qs.model.polymorphic_query_multiline_output is False
660 r = repr(qs)
661 # Django's default repr includes QuerySet
662 assert "QuerySet" in r or "repr_duck" in r or "[" in r
663
664
665 # ===========================================================================
666 # query.py - _p_list_class.__repr__ (lines 664-665)
667 # ===========================================================================
668
669
670 class TestPListClassRepr(TransactionTestCase):
671 """Test _p_list_class.__repr__ method."""
672
673 def test_p_list_class_repr(self):
674 """_p_list_class wraps items with multiline repr."""
675 Model2A.objects.create(field1="plist_test")
676
677 qs = Model2A.objects.all()
678 # get_real_instances with multiline output returns _p_list_class
679 result = qs.get_real_instances()
680 # Since Model2A has ShowFieldType (multiline_output=True), result is _p_list_class
681 assert isinstance(result, PolymorphicQuerySet._p_list_class)
682 r = repr(result)
683 assert "plist_test" in r or "[" in r
684
685
686 # ===========================================================================
687 # query.py - get_real_instances when polymorphic_query_multiline_output=False (line 690)
688 # ===========================================================================
689
690
691 class TestGetRealInstancesNonMultiline(TransactionTestCase):
692 """Test get_real_instances returns plain list for non-multiline models."""
693
694 def test_get_real_instances_no_multiline(self):
695 """
696 Line 690: When polymorphic_query_multiline_output=False,
697 get_real_instances() returns plain olist.
698 """
699 from polymorphic.tests.models import Duck
700
701 Duck.objects.create(name="duck_real")
702 qs = Duck.objects.all()
703 assert qs.model.polymorphic_query_multiline_output is False
704
705 result = qs.get_real_instances()
706 assert isinstance(result, list)
707 # Should NOT be _p_list_class
708 assert type(result) is not PolymorphicQuerySet._p_list_class
709
710
711 # ===========================================================================
712 # query_translate.py - RelatedField path return (line 181->188)
713 # ===========================================================================
714
715
716 class TestTranslatePolymorphicFieldPath(TestCase):
717 """Test translate_polymorphic_field_path for RelatedField detection."""
718
719 def test_related_field_path_passed_through_to_django(self):
720 """
721 The True branch at line 181 (isinstance is True → return field_path).
722 When a path starts with a RelatedField name (FK/M2M), polymorphic returns it
723 unchanged and passes it to Django. Django then handles it (possibly raising
724 FieldError for unusual lookup syntax), confirming polymorphic did NOT try to
725 interpret 'fk' as a model class name (which would raise AssertionError).
726
727 RelationBase.fk is a ForeignKey to self (a RelatedField).
728 """
729 from django.core.exceptions import FieldError
730
731 # fk is a ForeignKey on RelationBase → polymorphic returns "fk___field_base" unchanged
732 # Django receives the path and raises FieldError (not AssertionError from polymorphic),
733 # confirming that line 184 (return field_path) was hit.
734 with pytest.raises(FieldError):
735 RelationBase.objects.filter(fk___field_base="x").count()
736
737 def test_m2m_field_path_passed_through_to_django(self):
738 """M2M field name at the start of a path is returned unchanged by polymorphic."""
739 from django.core.exceptions import FieldError
740
741 # m2m is a ManyToManyField on RelationBase → passed through unchanged
742 # Django raises FieldError (not AssertionError from polymorphic)
743 with pytest.raises(FieldError):
744 RelationBase.objects.filter(m2m___something="x").count()
745
746 def test_plain_field_name_as_classname_falls_through(self):
747 """
748 Line 181->188: The False branch - field IS found in _meta but is NOT a RelatedField.
749 E.g., field1 is a CharField. It's found by get_field('field1') but isinstance
750 check fails, so falls through to _map_queryname_to_class.
751 """
752 # field1 is a CharField on Model2A - not a RelatedField
753 # Falls through from 181 False branch to line 188 (_map_queryname_to_class)
754 # which raises AssertionError since 'field1' is not a model class name
755 with pytest.raises(AssertionError, match="is not a subclass"):
756 Model2A.objects.filter(field1___something="x").count()
757
758 def test_get_query_related_name_iterates_fields(self):
759 """
760 Line 223->222: The loop in _get_query_related_name iterates over local_fields.
761 When a field is not a OneToOneField parent_link, the loop continues (223->222).
762
763 Model2A.objects.filter(Model2B___field2="x") calls translate_polymorphic_field_path
764 → _create_base_path → _get_query_related_name(Model2B), covering the True branch
765 (parent_link O2O found, loop returns).
766
767 For the False/continue branch (223->222): One2OneRelatingModel is a ROOT concrete
768 polymorphic model (PolymorphicModel is abstract → no parent_ptr O2O). Its local_fields
769 are [id, polymorphic_ctype, one2one, field1] — none are O2O parent_links — so the
770 loop iterates all 4 fields hitting 223->222 each time, then falls through to line 228.
771 There is no public API path that calls _get_query_related_name on a ROOT model
772 (it's only called for child models during path building), so a direct call is needed.
773 """
774 from polymorphic.query_translate import _get_query_related_name
775 from polymorphic.tests.models import One2OneRelatingModel
776
777 # filter covers True branch of 223 (parent_link found, returns "model2b")
778 count = Model2A.objects.filter(Model2B___field2="x").count()
779 assert count == 0 # no matching objects, but translation succeeded
780
781 # Direct call covers False branch of 223 (223->222, loop continues for non-parent-link fields)
782 # and line 228 fallback (no parent_link found in any local field)
783 result = _get_query_related_name(One2OneRelatingModel)
784 assert result == "one2onerelatingmodel"
785
786 def test_get_query_related_name_fallback_for_proxy_model(self):
787 """
788 Line 228: Fallback return (class name lower) when no OneToOneField parent_link
789 is found in local_fields. This happens for proxy models, which have empty
790 local_fields (no concrete fields added).
791
792 SubclassSelectorProxyBaseModel.objects.filter(SubclassSelectorProxyModel___base_field=...)
793 calls _get_query_related_name(SubclassSelectorProxyModel) during translation.
794 SubclassSelectorProxyModel is a proxy with no local_fields, so the for loop
795 doesn't execute → line 228 fallback is hit. The translation completes successfully,
796 and then Django raises FieldError since proxy models share their parent's table
797 (no join path exists). The FieldError from Django (not AssertionError from polymorphic)
798 confirms the fallback path was traversed.
799 """
800 from django.core.exceptions import FieldError
801
802 # The translate call hits line 228 (fallback), then Django raises FieldError
803 # because proxy models share the base table (no separate DB join path).
804 with pytest.raises(FieldError):
805 SubclassSelectorProxyBaseModel.objects.filter(
806 SubclassSelectorProxyModel___base_field="x"
807 ).count()
808
809
810 # ===========================================================================
811 # query_translate.py - empty path from _create_base_path (line 223->222)
812 # ===========================================================================
813
814
815 class TestCreateBasePath(TestCase):
816 """Test _create_base_path returns empty string for same base class."""
817
818 def test_create_base_path_empty(self):
819 """
820 Line 198->201: When _create_base_path returns '' (basepath is falsy), newpath
821 is just the pure_field_path without a '__' prefix.
822
823 Model2A___field1 where Model2A IS the queryset model → _create_base_path returns ''
824 → newpath = '' + 'field1' = 'field1' (the if basepath branch is skipped).
825 Verified via queryset filter: Model2A___field1 translates to plain 'field1'.
826 """
827 # Model2A___field1 where Model2A IS the queryset model → basepath = '' → newpath = 'field1'
828 # The filter works since 'field1' is a valid field on Model2A
829 Model2A.objects.create(field1="base_path_test")
830 count = Model2A.objects.filter(Model2A___field1="base_path_test").count()
831 assert count == 1
832
833
834 # ===========================================================================
835 # query_translate.py - modellist is a single PolymorphicModel (line 248)
836 # ===========================================================================
837
838
839 class TestCreateInstanceofQ(TestCase):
840 """Test create_instanceof_q with various inputs."""
841
842 def test_empty_modellist_returns_none(self):
843 """
844 Line 248: When modellist is empty/falsy, return None.
845 """
846 from polymorphic.query_translate import create_instanceof_q
847
848 result = create_instanceof_q([])
849 assert result is None
850
851 def test_single_polymorphic_model(self):
852 """
853 Lines 250-254: When modellist is a single PolymorphicModel (not list/tuple),
854 it's converted to [modellist]. Triggered via filter(instance_of=Model2A) where
855 the value is passed as a single class (not a tuple), going through
856 _translate_polymorphic_filter_definition → create_instanceof_q(Model2A).
857 """
858 # filter(instance_of=Model2A) passes Model2A (not a tuple) to create_instanceof_q
859 # → hits the "if not isinstance(modellist, (list, tuple))" branch (lines 250-254)
860 count = Model2A.objects.filter(instance_of=Model2A).count()
861 assert count >= 0 # filter created successfully, query executes without error
862
863 def test_non_polymorphic_model_raises(self):
864 """
865 Lines 255-258: TypeError raised when single non-PolymorphicModel passed.
866 """
867 from polymorphic.query_translate import create_instanceof_q
868 from polymorphic.tests.models import PlainA # PlainA is a plain Django model
869
870 with pytest.raises(TypeError, match="instance_of expects"):
871 create_instanceof_q(PlainA)
872
873
874 # ===========================================================================
875 # showfields.py - polymorphic_showfield_old_format (line 38)
876 # ===========================================================================
877
878
879 class TestShowFieldsOldFormat(TransactionTestCase):
880 """Test showfields with old format separator."""
881
882 def test_old_format_colon_separator(self):
883 """
884 Line 38: polymorphic_showfield_old_format=True uses ': ' as separator.
885 """
886 from polymorphic.tests.models import ModelExtraA
887
888 # ModelExtraA has ShowFieldTypeAndContent but no m2m, so str() is safe to call
889 obj = ModelExtraA(field1="test_old_format")
890 obj.__class__.polymorphic_showfield_old_format = True
891 try:
892 result = str(obj)
893 assert ": " in result
894 finally:
895 obj.__class__.polymorphic_showfield_old_format = False
896
897
898 # ===========================================================================
899 # showfields.py - FK field content is None (line 51)
900 # ===========================================================================
901
902
903 class TestShowFieldsNoneContent(TransactionTestCase):
904 """Test showfields when FK content is None."""
905
906 def test_fk_field_none_content(self):
907 """
908 Line 42-43: FK is None shows 'None'.
909
910 ModelExtraA uses ShowFieldTypeAndContent. An unsaved instance has no
911 polymorphic_ctype set (it's a ForeignKey). str() calls _showfields_get_content
912 internally, hitting the FK-is-None branch (lines 42-43).
913 """
914 from polymorphic.tests.models import ModelExtraA
915
916 # Unsaved object: polymorphic_ctype is None (ForeignKey not yet set)
917 obj = ModelExtraA(field1="fk_none_test")
918 result = str(obj)
919 assert "None" in result
920
921 def test_none_content_for_regular_field(self):
922 """
923 Line 51: content is None for a regular (non-FK) field shows 'None'.
924
925 ModelExtraA uses ShowFieldTypeAndContent. Setting field1=None and calling
926 str() exercises _showfields_get_content for a CharField with None value,
927 hitting the elif content is None branch (line 51).
928 """
929 from polymorphic.tests.models import ModelExtraA
930
931 obj = ModelExtraA(field1=None)
932 result = str(obj)
933 assert "None" in result
934
935
936 # ===========================================================================
937 # showfields.py - text truncation (line 56)
938 # ===========================================================================
939
940
941 class TestShowFieldsTruncation(TransactionTestCase):
942 """Test showfields truncation of long field values."""
943
944 def test_long_field_truncated(self):
945 """
946 Line 56: When field content is longer than max_field_width, truncate it.
947 """
948 from polymorphic.tests.models import ModelExtraA
949
950 # ModelExtraA has ShowFieldTypeAndContent, no m2m
951 # Default max_field_width is 20
952 obj = ModelExtraA(field1="x" * 30) # 30 chars > 20 default max
953 result = str(obj)
954 # Should contain truncated version with ".."
955 assert ".." in result
956
957
958 # ===========================================================================
959 # showfields.py - diamond inheritance deduplication (line 67)
960 # ===========================================================================
961
962
963 class TestShowFieldsDiamondInheritance(TransactionTestCase):
964 """Test showfields deduplication in diamond inheritance (line 67)."""
965
966 def test_diamond_inheritance_no_duplicate_fields(self):
967 """
968 Line 67: In diamond inheritance, same field name not shown twice.
969 Enhance_Inherit inherits from both Enhance_Base and Enhance_Plain.
970 """
971 from polymorphic.tests.models import Enhance_Inherit
972
973 # Enhance_Inherit has multiple inheritance
974 # showfields should not duplicate fields
975 obj = Enhance_Inherit(field_b="base", field_i="inherit", field_p="plain")
976 result = str(obj)
977 # field_p should appear at most once
978 assert result.count("field_p") <= 1
979
980
981 # ===========================================================================
982 # showfields.py - deferred fields display (lines 127-128)
983 # ===========================================================================
984
985
986 class TestShowFieldsDeferred(TransactionTestCase):
987 """Test showfields for deferred fields display."""
988
989 def test_deferred_fields_shown(self):
990 """
991 Lines 127-128: When polymorphic_showfield_deferred=True and there are
992 deferred fields, they are shown in the __str__ output.
993 """
994 # Model2A has polymorphic_showfield_deferred = True
995 obj = Model2A.objects.create(field1="deferred_test")
996
997 # Fetch with defer to actually have deferred fields
998 obj_deferred = Model2A.objects.defer("field1").get(pk=obj.pk)
999 result = str(obj_deferred)
1000 assert "deferred" in result or "field1" in result
1001
1002
1003 # ===========================================================================
1004 # showfields.py - line breaking (lines 149-152)
1005 # ===========================================================================
1006
1007
1008 class TestShowFieldsLineBreaking(TransactionTestCase):
1009 """Test showfields line breaking when max_line_width is set."""
1010
1011 def test_line_breaking_with_max_line_width(self):
1012 """
1013 Lines 149-152: When polymorphic_showfield_max_line_width is set and
1014 content exceeds it, a newline+indent is inserted.
1015 """
1016 from polymorphic.showfields import ShowFieldTypeAndContent
1017
1018 # Create object with many/wide fields to trigger line breaking
1019 obj = Model2C.objects.create(
1020 field1="short",
1021 field2="short2",
1022 field3="short3",
1023 )
1024
1025 # Temporarily set max_line_width to trigger line breaking
1026 original = Model2C.polymorphic_showfield_max_line_width
1027 try:
1028 # Monkey-patch to set small max line width
1029 Model2C.polymorphic_showfield_max_line_width = 20
1030 result = str(obj)
1031 # Should contain newlines due to line breaking
1032 assert "\n" in result
1033 finally:
1034 Model2C.polymorphic_showfield_max_line_width = original
1035
1036
1037 # ===========================================================================
1038 # formsets/models.py - IndexError in initial_extra (lines 192-193)
1039 # ===========================================================================
1040
1041
1042 class TestFormsetInitialExtra(TestCase):
1043 """Test IndexError when initial_extra has fewer items than extra forms."""
1044
1045 def test_initial_extra_index_error_handled(self):
1046 """
1047 Lines 192-193: IndexError is caught silently when initial_extra
1048 has fewer items than the extra form index.
1049 """
1050 FormSet = polymorphic_modelformset_factory(
1051 model=Model2A,
1052 fields="__all__",
1053 extra=3,
1054 formset_children=[PolymorphicFormSetChild(model=Model2A)],
1055 )
1056
1057 # Create formset with initial_extra having only 1 item but extra=3
1058 formset = FormSet(queryset=Model2A.objects.none())
1059 # Set initial_extra with only 1 item for 3 extra forms
1060 formset.initial_extra = [{"field1": "initial_extra_0"}]
1061
1062 # Accessing forms should not raise; forms 1 and 2 have no initial
1063 forms = formset.forms
1064 assert len(forms) == 3
1065 # First extra form has initial value set
1066 assert forms[0].initial.get("field1") == "initial_extra_0"
1067 # Second and third extra forms had IndexError → no initial
1068 assert "field1" not in forms[1].initial
1069 assert "field1" not in forms[2].initial
1070
1071
1072 # ===========================================================================
1073 # formsets/models.py - self.initial for regular forms (lines 205-208)
1074 # ===========================================================================
1075
1076
1077 class TestFormsetSelfInitial(TestCase):
1078 """Test self.initial for regular (non-extra) forms."""
1079
1080 def test_formset_with_initial_data_for_extra_forms(self):
1081 """
1082 Lines 205-208: When self.initial is provided to the FormSet constructor,
1083 it can be used for extra forms (when initial_extra is not set).
1084 """
1085 FormSet = polymorphic_modelformset_factory(
1086 model=Model2A,
1087 fields="__all__",
1088 extra=2,
1089 formset_children=[PolymorphicFormSetChild(model=Model2A)],
1090 )
1091
1092 initial = [{"field1": "initial_val_0"}, {"field1": "initial_val_1"}]
1093 formset = FormSet(queryset=Model2A.objects.none(), initial=initial)
1094
1095 forms = formset.forms
1096 # Forms were created - verify they exist
1097 assert len(forms) == 2
1098
1099 def test_formset_self_initial_for_existing_objects_with_extra_initial(self):
1100 """
1101 Lines 205-208: self.initial is used when i < initial_form_count()
1102 AND "initial" is not already in kwargs (e.g., not set by initial_extra).
1103
1104 For an unbound formset with a queryset that has existing objects AND
1105 self.initial is provided, the self.initial[i] provides initial data
1106 for those existing-object forms.
1107 """
1108 obj_a = Model2A.objects.create(field1="existing_A")
1109
1110 FormSet = polymorphic_modelformset_factory(
1111 model=Model2A,
1112 fields="__all__",
1113 extra=0,
1114 formset_children=[PolymorphicFormSetChild(model=Model2A)],
1115 )
1116
1117 # Provide self.initial for the queryset forms
1118 # This is an unusual but valid usage: override initial data for bound-query forms
1119 initial = [{"field1": "override_initial"}]
1120 formset = FormSet(queryset=Model2A.objects.filter(pk=obj_a.pk), initial=initial)
1121
1122 forms = formset.forms
1123 assert len(forms) >= 1
1124 # The instance is set from queryset, but self.initial may provide extra initial
1125
1126 def test_formset_initial_index_error_handled(self):
1127 """
1128 Lines 205-208: IndexError when self.initial has fewer items than forms.
1129 In this case, formset.initial has items but some indices don't exist.
1130 """
1131 FormSet = polymorphic_modelformset_factory(
1132 model=Model2A,
1133 fields="__all__",
1134 extra=3,
1135 formset_children=[PolymorphicFormSetChild(model=Model2A)],
1136 )
1137
1138 # Manually set self.initial after creation to test lines 205-208
1139 formset = FormSet(queryset=Model2A.objects.none())
1140 formset.initial = [{"field1": "only_one"}]
1141 # Reset initial_extra to None so the initial_extra branch is skipped
1142 formset.initial_extra = None
1143
1144 forms = formset.forms
1145 # form[0] uses initial[0], forms[1] and [2] get IndexError → pass
1146 assert len(forms) == 3
1147
1148
1149 # ===========================================================================
1150 # formsets/models.py - ContentType ID (int) in initial (lines 253, 271->277)
1151 # ===========================================================================
1152
1153
1154 class TestFormsetCTypeAsInt(TestCase):
1155 """Test unbound formset with polymorphic_ctype as int (not ContentType instance)."""
1156
1157 def test_unbound_formset_ct_as_int(self):
1158 """
1159 Line 253: ct_value is an int (not ContentType instance) in unbound formset.
1160 Line 271->277: The False branch - ct_value is NOT a ContentType instance.
1161 """
1162 FormSet = polymorphic_modelformset_factory(
1163 model=Model2A,
1164 fields="__all__",
1165 extra=1,
1166 formset_children=[
1167 PolymorphicFormSetChild(model=Model2A),
1168 PolymorphicFormSetChild(model=Model2B),
1169 ],
1170 )
1171
1172 ct_b = ContentType.objects.get_for_model(Model2B, for_concrete_model=False)
1173 # Pass the CT as an integer ID (not a ContentType instance)
1174 initial = [{"polymorphic_ctype": ct_b.pk}]
1175 formset = FormSet(queryset=Model2A.objects.none(), initial=initial)
1176
1177 # Form should be for Model2B (looked up via int ID)
1178 forms = formset.forms
1179 assert len(forms) == 1
1180 assert "field2" in forms[0].fields
1181
1182
1183 # ===========================================================================
1184 # formsets/models.py - per-row model selection for an unbound formset
1185 # ===========================================================================
1186
1187
1188 class TestFormsetModelFromQuerysetData(TestCase):
1189 """Test that an unbound formset built from a mixed-type queryset selects the
1190 correct child model for each row."""
1191
1192 def test_model_from_queryset_data(self):
1193 """
1194 Each initial form is bound to its queryset object's real concrete class
1195 (the ``defaults["instance"]`` branch in ``_construct_form``), so a formset
1196 over a mixed Model2A/Model2B queryset produces one correctly-typed form
1197 per row.
1198 """
1199 obj_a = Model2A.objects.create(field1="qs_data_a")
1200 obj_b = Model2B.objects.create(field1="qs_data_b", field2="B2")
1201
1202 FormSet = polymorphic_modelformset_factory(
1203 model=Model2A,
1204 fields="__all__",
1205 extra=0,
1206 formset_children=[
1207 PolymorphicFormSetChild(model=Model2A),
1208 PolymorphicFormSetChild(model=Model2B),
1209 ],
1210 )
1211
1212 # Provide existing queryset with real objects - forms use queryset_data
1213 queryset = Model2A.objects.filter(pk__in=[obj_a.pk, obj_b.pk]).order_by("pk")
1214 formset = FormSet(queryset=queryset)
1215
1216 forms = formset.forms
1217 # The form types come from the queryset_data items
1218 assert len(forms) == 2
1219 # queryset_data drives the model for each form: one Model2A and one Model2B
1220 form_models = {form.instance.__class__ for form in forms if form.instance.pk}
1221 assert form_models == {Model2A, Model2B}
1222
1223
1224 # ===========================================================================
1225 # DRF serializers (contrib/drf/serializers.py)
1226 # ===========================================================================
1227
1228
1229 class TestPolymorphicSerializerBase(TestCase):
1230 """Tests for PolymorphicSerializer."""
1231
1232 pytestmark = pytest.mark.integration
1233
1234 def setUp(self):
1235 from rest_framework import serializers
1236
1237 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1238
1239 class ModelASerializer(serializers.Serializer):
1240 field1 = serializers.CharField()
1241
1242 def create(self, validated_data):
1243 return Model2A(**validated_data)
1244
1245 def update(self, instance, validated_data):
1246 instance.field1 = validated_data.get("field1", instance.field1)
1247 return instance
1248
1249 class ModelBSerializer(serializers.Serializer):
1250 field1 = serializers.CharField()
1251 field2 = serializers.CharField()
1252
1253 def create(self, validated_data):
1254 return Model2B(**validated_data)
1255
1256 def update(self, instance, validated_data):
1257 instance.field1 = validated_data.get("field1", instance.field1)
1258 instance.field2 = validated_data.get("field2", instance.field2)
1259 return instance
1260
1261 class TestPolymorphicSerializer(PolymorphicSerializer):
1262 model_serializer_mapping = {
1263 Model2A: ModelASerializer,
1264 Model2B: ModelBSerializer,
1265 }
1266
1267 self.PolymorphicSerializer = TestPolymorphicSerializer
1268 self.ModelASerializer = ModelASerializer
1269 self.ModelBSerializer = ModelBSerializer
1270
1271 def test_new_requires_model_serializer_mapping(self):
1272 """__new__ raises ImproperlyConfigured when model_serializer_mapping is missing."""
1273 from django.core.exceptions import ImproperlyConfigured
1274
1275 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1276
1277 class MissingMapping(PolymorphicSerializer):
1278 pass
1279
1280 with pytest.raises(ImproperlyConfigured, match="model_serializer_mapping"):
1281 MissingMapping()
1282
1283 def test_new_requires_string_resource_type_field_name(self):
1284 """__new__ raises ImproperlyConfigured when resource_type_field_name is not a string."""
1285 from django.core.exceptions import ImproperlyConfigured
1286
1287 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1288
1289 class BadResourceType(PolymorphicSerializer):
1290 model_serializer_mapping = {Model2A: None}
1291 resource_type_field_name = 123 # not a string
1292
1293 with pytest.raises(ImproperlyConfigured, match="resource_type_field_name"):
1294 BadResourceType()
1295
1296 def test_init_sets_up_mappings(self):
1297 """__init__ sets up model_serializer_mapping and resource_type_model_mapping."""
1298 serializer = self.PolymorphicSerializer()
1299 assert Model2A in serializer.model_serializer_mapping
1300 assert Model2B in serializer.model_serializer_mapping
1301 assert "Model2A" in serializer.resource_type_model_mapping
1302 assert "Model2B" in serializer.resource_type_model_mapping
1303
1304 def test_to_resource_type(self):
1305 """to_resource_type returns the model's object_name."""
1306 serializer = self.PolymorphicSerializer()
1307 assert serializer.to_resource_type(Model2A) == "Model2A"
1308 assert serializer.to_resource_type(Model2B) == "Model2B"
1309
1310 def test_to_representation_with_instance(self):
1311 """to_representation with a model instance."""
1312 serializer = self.PolymorphicSerializer()
1313 obj = Model2A(field1="test_rep")
1314 result = serializer.to_representation(obj)
1315 assert result["field1"] == "test_rep"
1316 assert result["resourcetype"] == "Model2A"
1317
1318 def test_to_representation_with_mapping(self):
1319 """to_representation with a mapping (dict)."""
1320 serializer = self.PolymorphicSerializer()
1321 data = {"resourcetype": "Model2A", "field1": "map_test"}
1322 result = serializer.to_representation(data)
1323 assert result["field1"] == "map_test"
1324 assert result["resourcetype"] == "Model2A"
1325
1326 def test_to_internal_value_regular(self):
1327 """to_internal_value for regular (non-partial) case."""
1328 serializer = self.PolymorphicSerializer()
1329 data = {"resourcetype": "Model2A", "field1": "internal_val"}
1330 result = serializer.to_internal_value(data)
1331 assert result["field1"] == "internal_val"
1332 assert result["resourcetype"] == "Model2A"
1333
1334 def test_to_internal_value_partial_with_instance(self):
1335 """to_internal_value for partial update uses instance's resource type."""
1336 obj = Model2A(field1="partial_obj")
1337 serializer = self.PolymorphicSerializer(instance=obj, partial=True)
1338 data = {"field1": "updated"}
1339 result = serializer.to_internal_value(data)
1340 assert result["field1"] == "updated"
1341 assert result["resourcetype"] == "Model2A"
1342
1343 def test_create(self):
1344 """create() delegates to the child serializer."""
1345 serializer = self.PolymorphicSerializer()
1346 validated_data = {"resourcetype": "Model2A", "field1": "created"}
1347 result = serializer.create(validated_data)
1348 assert result.field1 == "created"
1349
1350 def test_update(self):
1351 """update() delegates to the child serializer."""
1352 obj = Model2A(field1="original")
1353 serializer = self.PolymorphicSerializer()
1354 validated_data = {"resourcetype": "Model2A", "field1": "updated"}
1355 result = serializer.update(obj, validated_data)
1356 assert result.field1 == "updated"
1357
1358 def test_is_valid_success(self):
1359 """is_valid() returns True for valid data."""
1360 data = {"resourcetype": "Model2A", "field1": "valid_data"}
1361 serializer = self.PolymorphicSerializer(data=data)
1362 assert serializer.is_valid()
1363
1364 def test_is_valid_partial_with_instance(self):
1365 """is_valid() with partial=True and instance uses instance's type."""
1366 obj = Model2A(field1="existing")
1367 data = {"field1": "patched"}
1368 serializer = self.PolymorphicSerializer(instance=obj, data=data, partial=True)
1369 assert serializer.is_valid()
1370
1371 def test_is_valid_missing_resource_type(self):
1372 """is_valid() returns False when resourcetype is missing."""
1373 data = {"field1": "no_type"}
1374 serializer = self.PolymorphicSerializer(data=data)
1375 result = serializer.is_valid()
1376 assert result is False
1377 assert "resourcetype" in serializer.errors
1378
1379 def test_is_valid_updates_validated_data_from_child(self):
1380 """is_valid() updates validated_data from child serializer."""
1381 data = {"resourcetype": "Model2A", "field1": "child_valid"}
1382 serializer = self.PolymorphicSerializer(data=data)
1383 valid = serializer.is_valid()
1384 assert valid
1385 assert "field1" in serializer.validated_data
1386
1387 def test_run_validation_regular(self):
1388 """run_validation for regular (non-partial) case."""
1389 data = {"resourcetype": "Model2A", "field1": "run_val"}
1390 serializer = self.PolymorphicSerializer()
1391 result = serializer.run_validation(data)
1392 assert result["field1"] == "run_val"
1393 assert result["resourcetype"] == "Model2A"
1394
1395 def test_run_validation_partial_with_instance(self):
1396 """run_validation for partial update uses instance's resource type."""
1397 obj = Model2A(field1="existing_run")
1398 serializer = self.PolymorphicSerializer(instance=obj, partial=True)
1399 data = {"field1": "run_updated"}
1400 result = serializer.run_validation(data)
1401 assert result["field1"] == "run_updated"
1402
1403 def test_missing_resource_type_raises_validation_error(self):
1404 """
1405 _get_resource_type_from_mapping raises ValidationError when resourcetype is absent.
1406 Tested via the public run_validation() API with an empty data dict, which
1407 internally calls _get_resource_type_from_mapping({}).
1408 """
1409 from rest_framework import serializers
1410
1411 s = self.PolymorphicSerializer()
1412 with pytest.raises(serializers.ValidationError, match="required"):
1413 s.run_validation({})
1414
1415 def test_unknown_resource_type_raises_validation_error(self):
1416 """
1417 _get_serializer_from_resource_type raises ValidationError for an unknown type.
1418 Tested via the public run_validation() API with an unrecognized resourcetype,
1419 which internally calls _get_serializer_from_resource_type("UnknownModel").
1420 """
1421 from rest_framework import serializers
1422
1423 s = self.PolymorphicSerializer()
1424 with pytest.raises(serializers.ValidationError, match="Invalid"):
1425 s.run_validation({"resourcetype": "UnknownModel", "field1": "x"})
1426
1427 def test_unregistered_model_raises_key_error_on_representation(self):
1428 """
1429 _get_serializer_from_model_or_instance raises KeyError for an unregistered model.
1430 Tested via the public to_representation() API with a Duck instance, which
1431 internally calls _get_serializer_from_model_or_instance(Duck) and raises KeyError
1432 since Duck is not in model_serializer_mapping.
1433 """
1434 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1435 from polymorphic.tests.models import Duck
1436
1437 class TestSer(PolymorphicSerializer):
1438 model_serializer_mapping = {
1439 Model2A: self.ModelASerializer,
1440 }
1441
1442 s = TestSer()
1443 # to_representation(Duck()) calls _get_serializer_from_model_or_instance(Duck)
1444 # Duck is not in model_serializer_mapping and shares no MRO with Model2A
1445 with pytest.raises(KeyError, match="missing"):
1446 s.to_representation(Duck(name="test_duck"))
1447
1448 def test_init_with_callable_serializer(self):
1449 """When serializer in mapping is callable (class), it gets instantiated."""
1450 from rest_framework import serializers as drf_serializers
1451
1452 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1453
1454 class ModelCSerializer(drf_serializers.Serializer):
1455 field3 = drf_serializers.CharField()
1456
1457 class TestSerializer(PolymorphicSerializer):
1458 model_serializer_mapping = {
1459 Model2C: ModelCSerializer, # Callable (class)
1460 }
1461
1462 s = TestSerializer()
1463 assert Model2C in s.model_serializer_mapping
1464 # The serializer should be an instance, not the class
1465 assert isinstance(s.model_serializer_mapping[Model2C], ModelCSerializer)
1466
1467 def test_is_valid_validation_error_in_child(self):
1468 """is_valid() handles ValidationError when getting child serializer."""
1469 from rest_framework import serializers as drf_serializers
1470
1471 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1472
1473 class StrictSerializer(PolymorphicSerializer):
1474 model_serializer_mapping = {
1475 Model2A: self.ModelASerializer,
1476 }
1477
1478 # Data with unknown resource type -> ValidationError in child serializer lookup
1479 data = {"resourcetype": "Unknown", "field1": "test"}
1480 s = StrictSerializer(data=data)
1481 result = s.is_valid()
1482 assert result is False
1483
1484
1485 # ===========================================================================
1486 # contrib/extra_views.py - PolymorphicFormSetMixin tests (lines 48-52, 55, 65-69)
1487 # ===========================================================================
1488
1489
1490 class TestPolymorphicFormSetMixin(TestCase):
1491 """Tests for PolymorphicFormSetMixin in contrib/extra_views.py."""
1492
1493 pytestmark = pytest.mark.integration
1494
1495 def test_get_formset_children_raises_when_not_set(self):
1496 """
1497 Lines 48-51: get_formset_children() raises ImproperlyConfigured
1498 when formset_children is not set.
1499 """
1500 from django.core.exceptions import ImproperlyConfigured
1501
1502 from polymorphic.contrib.extra_views import PolymorphicFormSetMixin
1503
1504 mixin = PolymorphicFormSetMixin()
1505 mixin.formset_children = None
1506
1507 with pytest.raises(ImproperlyConfigured, match="formset_children"):
1508 mixin.get_formset_children()
1509
1510 def test_get_formset_children_raises_when_empty_list(self):
1511 """
1512 Lines 48-51: Empty list also raises ImproperlyConfigured
1513 (falsy value).
1514 """
1515 from django.core.exceptions import ImproperlyConfigured
1516
1517 from polymorphic.contrib.extra_views import PolymorphicFormSetMixin
1518
1519 mixin = PolymorphicFormSetMixin()
1520 mixin.formset_children = [] # falsy
1521
1522 with pytest.raises(ImproperlyConfigured, match="formset_children"):
1523 mixin.get_formset_children()
1524
1525 def test_get_formset_children_returns_when_set(self):
1526 """
1527 Line 52: When formset_children is set, returns it.
1528 """
1529 from polymorphic.contrib.extra_views import PolymorphicFormSetMixin
1530
1531 children = [PolymorphicFormSetChild(Model2A)]
1532 mixin = PolymorphicFormSetMixin()
1533 mixin.formset_children = children
1534
1535 result = mixin.get_formset_children()
1536 assert result is children
1537
1538 def test_get_formset_child_kwargs_returns_empty_dict(self):
1539 """
1540 Line 55: get_formset_child_kwargs() returns empty dict.
1541 """
1542 from polymorphic.contrib.extra_views import PolymorphicFormSetMixin
1543
1544 mixin = PolymorphicFormSetMixin()
1545 result = mixin.get_formset_child_kwargs()
1546 assert result == {}
1547
1548 def test_get_formset_calls_super_and_adds_child_forms(self):
1549 """
1550 Lines 65-69: get_formset() calls super().get_formset() then
1551 adds child_forms via polymorphic_child_forms_factory.
1552
1553 Tests this through the actual view's get_formset() method to exercise
1554 lines 65-69 via the public API rather than calling polymorphic_child_forms_factory
1555 directly.
1556 """
1557 from django.test import RequestFactory
1558
1559 from polymorphic.contrib.extra_views import PolymorphicFormSetView
1560
1561 children = [
1562 PolymorphicFormSetChild(Model2A, fields=["field1"]),
1563 PolymorphicFormSetChild(Model2B, fields=["field1", "field2"]),
1564 ]
1565
1566 class TestFormSetView(PolymorphicFormSetView):
1567 model = Model2A
1568 formset_children = children
1569 fields = ["field1"]
1570
1571 factory = RequestFactory()
1572 request = factory.get("/")
1573
1574 view = TestFormSetView()
1575 view.request = request
1576 view.kwargs = {}
1577 view.args = []
1578 view.object_list = Model2A.objects.none()
1579
1580 # Call get_formset() via the view - this tests lines 65-69
1581 FormSet = view.get_formset()
1582 assert hasattr(FormSet, "child_forms")
1583 assert Model2A in FormSet.child_forms
1584 assert Model2B in FormSet.child_forms
1585
1586 def test_polymorphic_formset_view_integration(self):
1587 """
1588 Integration test: PolymorphicFormSetView with get_formset method.
1589 Tests lines 65-69 by creating an actual FormSet via the view's factory.
1590 """
1591 from polymorphic.contrib.extra_views import PolymorphicFormSetView
1592
1593 children = [
1594 PolymorphicFormSetChild(Model2A, fields=["field1"]),
1595 PolymorphicFormSetChild(Model2B, fields=["field1", "field2"]),
1596 ]
1597
1598 class TestFormSetView(PolymorphicFormSetView):
1599 model = Model2A
1600 formset_children = children
1601 fields = ["field1"]
1602
1603 # Create a request factory to simulate a GET request
1604 from django.test import RequestFactory
1605
1606 factory = RequestFactory()
1607 request = factory.get("/")
1608
1609 view = TestFormSetView()
1610 view.request = request
1611 view.kwargs = {}
1612 view.args = []
1613 view.object_list = Model2A.objects.none()
1614
1615 # Call get_formset() - this tests lines 65-69
1616 FormSet = view.get_formset()
1617 assert hasattr(FormSet, "child_forms")
1618 assert Model2A in FormSet.child_forms
1619 assert Model2B in FormSet.child_forms
1620
1621
1622 # ===========================================================================
1623 # deletion.py - PolymorphicGuard.__init__ TypeError (line 53)
1624 # ===========================================================================
1625
1626
1627 class TestPolymorphicGuardTypeError(TestCase):
1628 """Test PolymorphicGuard raises TypeError when action is not callable."""
1629
1630 def test_guard_with_non_callable_raises(self):
1631 """
1632 Line 53: PolymorphicGuard.__init__ raises TypeError when action is not callable.
1633 """
1634 from polymorphic.deletion import PolymorphicGuard
1635
1636 with pytest.raises(TypeError, match="action must be callable"):
1637 PolymorphicGuard("not_a_callable")
1638
1639 def test_guard_with_integer_raises(self):
1640 """TypeError also raised for integer action."""
1641 from polymorphic.deletion import PolymorphicGuard
1642
1643 with pytest.raises(TypeError, match="action must be callable"):
1644 PolymorphicGuard(42)
1645
1646
1647 # ===========================================================================
1648 # query.py - real_concrete_class is None (branch 513->527)
1649 # ===========================================================================
1650
1651
1652 class TestRealConcreteClassIsNone(TransactionTestCase):
1653 """Test branch 513->527 when content_type_manager returns model_class()=None."""
1654
1655 def test_real_concrete_class_none_from_get_for_id(self):
1656 """
1657 Branch 513->527: When content_type_manager.get_for_id(id).model_class()
1658 returns None, the object is appended as None and filtered out.
1659
1660 The tricky part: for concrete models, polymorphic_ctype_id and
1661 real_concrete_class_id are the SAME ContentType pk, so naively patching
1662 model_class() to return None would also affect get_real_instance_class()
1663 → causing the stale CT path (continue at line 497) to trigger instead.
1664
1665 Solution: use a stateful db_manager patch that returns a WrappedMgr only
1666 for the FIRST call (line 474 in _get_real_instances), which is what the
1667 content_type_manager uses at line 511. Subsequent calls from
1668 get_real_instance_class() and get_real_concrete_instance_class_id() get
1669 the normal manager and resolve correctly.
1670 """
1671 from unittest.mock import MagicMock, patch
1672 from django.contrib.contenttypes.models import ContentTypeManager
1673
1674 obj_b = Model2B.objects.create(field1="ct_none_real_b", field2="B2")
1675 qs = Model2A.objects.all()
1676
1677 b_concrete_ct = ContentType.objects.get_for_model(Model2B, for_concrete_model=True)
1678
1679 # Create a mock CT whose model_class() returns None
1680 mock_ct = MagicMock()
1681 mock_ct.model_class.return_value = None
1682
1683 # Patch ContentTypeManager.get_for_id with a call-count approach.
1684 #
1685 # For a Model2B object in a Model2A queryset, get_for_id(b_concrete_ct.pk)
1686 # is called 3 times with our target CT id:
1687 # Call 1: from get_real_instance_class() at query.py line 492
1688 # Call 2: from get_real_instance_class() nested inside get_real_concrete_instance_class_id() at line 493
1689 # Call 3: from content_type_manager.get_for_id() at line 511 (the branch we want to cover)
1690 #
1691 # The first 2 calls must return the real CT (so get_real_instance_class returns Model2B
1692 # and real_concrete_class_id is set correctly). The 3rd call returns mock_ct → model_class()=None
1693 # → real_concrete_class=None → line 513 is False → branch 513->527 is taken.
1694 get_for_id_count = [0]
1695 original_get_for_id = ContentTypeManager.get_for_id
1696
1697 def fake_get_for_id(self_mgr, ct_id):
1698 if ct_id == b_concrete_ct.pk:
1699 get_for_id_count[0] += 1
1700 if get_for_id_count[0] > 2:
1701 # 3rd+ call: simulate orphaned content type (model has been uninstalled)
1702 return mock_ct
1703 return original_get_for_id(self_mgr, ct_id)
1704
1705 with patch.object(ContentTypeManager, "get_for_id", fake_get_for_id):
1706 # list(qs) triggers _polymorphic_iterator → _get_real_instances
1707 # Calls 1-2: get_real_instance_class/get_real_concrete_instance_class_id → real CT → Model2B
1708 # Call 3 at line 511: content_type_manager.get_for_id(b_concrete_ct.pk) → mock_ct → None
1709 # → branch 513->527: resultlist.append(None) → filtered out at line 636
1710 results = list(qs)
1711 model2b_results = [r for r in results if isinstance(r, Model2B)]
1712 assert len(model2b_results) == 0
1713
1714
1715 # ===========================================================================
1716 # query.py - annotation not on base object (branch 625->624)
1717 # ===========================================================================
1718
1719
1720 class TestAnnotationMissingFromBaseObject(TransactionTestCase):
1721 """Test branch 625->624 when annotation key is not on base_object."""
1722
1723 def test_annotation_not_on_base_object_skipped(self):
1724 """
1725 Branch 625->624: When iterating annotation_select keys, if the annotation
1726 is NOT on base_object (hasattr returns False), it is skipped.
1727
1728 We use the public qs.get_real_instances(base_objs) API (not _get_real_instances),
1729 passing base objects that have had their annotation stripped to simulate the case
1730 where a base object lacks an annotation attribute.
1731 """
1732 from django.db.models import Value
1733
1734 Model2B.objects.create(field1="anno_miss_b", field2="B2")
1735
1736 qs_annotated = Model2A.objects.annotate(phantom_annotation=Value(99))
1737
1738 # Get base objects from annotated queryset using the public non_polymorphic() API
1739 base_objs = list(qs_annotated.non_polymorphic())
1740
1741 # Strip the annotation attribute from base_objs to simulate it being absent
1742 for obj in base_objs:
1743 if "phantom_annotation" in obj.__dict__:
1744 del obj.__dict__["phantom_annotation"]
1745
1746 # Use the PUBLIC get_real_instances() method (not _get_real_instances)
1747 # Branch 625->624: hasattr(base_object, "phantom_annotation") is False → skip
1748 result = qs_annotated.get_real_instances(base_objs)
1749 # The annotation won't be set on real objects, but no crash should occur
1750 assert isinstance(result, list)
1751
1752
1753 # ===========================================================================
1754 # query_translate.py - app-label path errors (lines 164-165, 167)
1755 # ===========================================================================
1756
1757
1758 class TestQueryTranslateAppLabelErrors(TestCase):
1759 """Test error paths in translate_polymorphic_Q_object when using app__Model syntax."""
1760
1761 def test_nonexistent_model_raises_field_error(self):
1762 """
1763 Lines 164-165: LookupError is raised when app__Model doesn't exist,
1764 converted to FieldError.
1765 """
1766 from django.core.exceptions import FieldError
1767
1768 from polymorphic.query_translate import translate_polymorphic_field_path
1769
1770 # Use appname__ClassName syntax where the class doesn't exist
1771 with pytest.raises(FieldError, match="does not exist"):
1772 translate_polymorphic_field_path(Model2A, "tests__NonExistentModel123___field1")
1773
1774 def test_unrelated_model_raises_field_error(self):
1775 """
1776 Line 167: FieldError raised when model exists but is not derived from queryset model.
1777 """
1778 from django.core.exceptions import FieldError
1779
1780 from polymorphic.query_translate import translate_polymorphic_field_path
1781
1782 # Duck is not derived from Model2A
1783 # Use app__ClassName syntax: 'tests__Duck___something'
1784 with pytest.raises(FieldError, match="not derived from"):
1785 translate_polymorphic_field_path(Model2A, "tests__Duck___field1")
1786
1787
1788 # ===========================================================================
1789 # contrib/drf/serializers.py - non-callable serializer (branch 35->39)
1790 # ===========================================================================
1791
1792
1793 class TestPolymorphicSerializerNonCallable(TestCase):
1794 """Test PolymorphicSerializer when mapping contains serializer instances (not classes)."""
1795
1796 pytestmark = pytest.mark.integration
1797
1798 def test_init_with_serializer_instance_not_callable(self):
1799 """
1800 Branch 35->39: When serializer in model_serializer_mapping is already an instance
1801 (not callable), it's used directly without calling it.
1802 """
1803 from rest_framework import serializers as drf_serializers
1804
1805 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1806
1807 class Model2ASerializer(drf_serializers.Serializer):
1808 field1 = drf_serializers.CharField()
1809
1810 # Pass an INSTANCE (not a class) - this should NOT be called again
1811 serializer_instance = Model2ASerializer()
1812
1813 class TestSerializer(PolymorphicSerializer):
1814 model_serializer_mapping = {
1815 Model2A: serializer_instance, # already an instance, not callable
1816 }
1817
1818 s = TestSerializer()
1819 # The instance should be used directly (same object)
1820 assert s.model_serializer_mapping[Model2A] is serializer_instance
1821
1822
1823 # ===========================================================================
1824 # contrib/drf/serializers.py - child_valid True but no _validated_data (branch 98->101)
1825 # ===========================================================================
1826
1827
1828 class TestPolymorphicSerializerChildValidNoValidatedData(TestCase):
1829 """Test branch 98->101 when child is valid but parent has no _validated_data."""
1830
1831 pytestmark = pytest.mark.integration
1832
1833 def test_is_valid_child_valid_parent_fails(self):
1834 """
1835 Branch 98->101: child_valid is True but hasattr(self, "_validated_data") is False.
1836 This happens when super().is_valid() returns False (so _validated_data is not set)
1837 but the child serializer still validates successfully.
1838
1839 We can achieve this by making the parent's super() raise a ValidationError
1840 that is caught by the parent, returning False without setting _validated_data.
1841 """
1842 from rest_framework import serializers as drf_serializers
1843
1844 from polymorphic.contrib.drf.serializers import PolymorphicSerializer
1845
1846 class Model2ASerializer(drf_serializers.Serializer):
1847 field1 = drf_serializers.CharField()
1848
1849 def create(self, validated_data):
1850 return Model2A(**validated_data)
1851
1852 class TestSerializer(PolymorphicSerializer):
1853 model_serializer_mapping = {
1854 Model2A: Model2ASerializer,
1855 }
1856
1857 # Provide valid data but mock super().is_valid() to return False without
1858 # setting _validated_data
1859 data = {"resourcetype": "Model2A", "field1": "test_val"}
1860 s = TestSerializer(data=data)
1861
1862 # Patch the parent Serializer.is_valid to return False without setting _validated_data
1863 import unittest.mock as mock
1864
1865 original_is_valid = drf_serializers.Serializer.is_valid
1866
1867 def patched_is_valid(self_inner, *args, **kwargs):
1868 # Call real is_valid but then clear _validated_data to simulate absence
1869 result = original_is_valid(self_inner, *args, **kwargs)
1870 # Only affect the PolymorphicSerializer instance (not child serializers)
1871 if type(self_inner).__name__ == "TestSerializer":
1872 # Remove _validated_data if it was set
1873 if hasattr(self_inner, "_validated_data"):
1874 del self_inner._validated_data
1875 return True # Return True so child serializer is called
1876 return result
1877
1878 with mock.patch.object(drf_serializers.Serializer, "is_valid", patched_is_valid):
1879 result = s.is_valid()
1880 # _validated_data was deleted before the check, so branch 98->101 executes:
1881 # the child's _validated_data is NOT merged into the parent, but no
1882 # AttributeError is raised and is_valid still returns True (parent + child valid).
1883 assert result is True