Debian Codegraph @

tests/test_router_reuse.py

raw symbols SCIP
1 """
2 Tests for router reuse (template/instance architecture).
3
4 These tests verify that:
5 1. Routers can be mounted to multiple APIs
6 2. Routers can be mounted multiple times with url_name_prefix
7 3. Decorators are isolated between mounts
8 4. Freeze mechanism works correctly
9 5. Operation.clone() copies all attributes
10 """
11
12 import pytest
13
14 from ninja import NinjaAPI, Router
15 from ninja.errors import ConfigError
16 from ninja.operation import Operation, PathView
17 from ninja.testing import TestClient
18
19
20 class TestRouterReuse:
21 """Test that routers can be reused across multiple APIs."""
22
23 def test_same_router_different_apis(self):
24 """Same router can be mounted to different NinjaAPI instances."""
25 router = Router(tags=["shared"])
26
27 @router.get("/items")
28 def list_items(request):
29 return [{"id": 1}]
30
31 api_v1 = NinjaAPI(version="1.0", urls_namespace="api-v1")
32 api_v1.add_router("/v1", router)
33
34 api_v2 = NinjaAPI(version="2.0", urls_namespace="api-v2")
35 api_v2.add_router("/v2", router)
36
37 # Both APIs should work
38 client_v1 = TestClient(api_v1)
39 client_v2 = TestClient(api_v2)
40
41 response_v1 = client_v1.get("/v1/items")
42 response_v2 = client_v2.get("/v2/items")
43
44 assert response_v1.status_code == 200
45 assert response_v2.status_code == 200
46 assert response_v1.json() == [{"id": 1}]
47 assert response_v2.json() == [{"id": 1}]
48
49 def test_same_router_multiple_mounts_requires_url_name_prefix(self):
50 """Mounting same router twice without url_name_prefix raises ConfigError."""
51 router = Router()
52
53 @router.get("/items")
54 def list_items(request):
55 return []
56
57 api = NinjaAPI()
58 api.add_router("/v1", router)
59
60 with pytest.raises(ConfigError, match="url_name_prefix"):
61 api.add_router("/v2", router)
62
63 def test_same_router_multiple_mounts_with_url_name_prefix(self):
64 """Same router can be mounted multiple times with different url_name_prefix."""
65 router = Router()
66
67 @router.get("/items")
68 def list_items(request):
69 return [{"source": "shared"}]
70
71 api = NinjaAPI(urls_namespace="multi-mount")
72 api.add_router("/admin", router, url_name_prefix="admin")
73 api.add_router("/public", router, url_name_prefix="public")
74
75 client = TestClient(api)
76
77 response_admin = client.get("/admin/items")
78 response_public = client.get("/public/items")
79
80 assert response_admin.status_code == 200
81 assert response_public.status_code == 200
82
83
84 class TestDecoratorIsolation:
85 """Test that decorators are isolated between mounts."""
86
87 def test_decorators_not_shared_between_apis(self):
88 """Decorators added to one API don't affect the same router on another API."""
89 router = Router()
90 calls = {"api1": 0, "api2": 0}
91
92 @router.get("/test")
93 def test_endpoint(request):
94 return {"ok": True}
95
96 def api1_decorator(func):
97 def wrapper(*args, **kwargs):
98 calls["api1"] += 1
99 return func(*args, **kwargs)
100
101 return wrapper
102
103 def api2_decorator(func):
104 def wrapper(*args, **kwargs):
105 calls["api2"] += 1
106 return func(*args, **kwargs)
107
108 return wrapper
109
110 api1 = NinjaAPI(urls_namespace="iso-api1")
111 api1.add_decorator(api1_decorator)
112 api1.add_router("", router)
113
114 api2 = NinjaAPI(urls_namespace="iso-api2")
115 api2.add_decorator(api2_decorator)
116 api2.add_router("", router)
117
118 client1 = TestClient(api1)
119 client2 = TestClient(api2)
120
121 # Reset calls
122 calls["api1"] = 0
123 calls["api2"] = 0
124
125 client1.get("/test")
126 assert calls["api1"] == 1
127 assert calls["api2"] == 0
128
129 client2.get("/test")
130 assert calls["api1"] == 1
131 assert calls["api2"] == 1
132
133
134 class TestFreezeBehavior:
135 """Test that routers are frozen after URLs are generated."""
136
137 def test_router_frozen_after_urls_accessed(self):
138 """Router becomes frozen after api.urls is accessed."""
139 router = Router()
140
141 @router.get("/items")
142 def list_items(request):
143 return []
144
145 api = NinjaAPI(urls_namespace="freeze-test")
146 api.add_router("", router)
147
148 # Access urls (triggers freezing)
149 _ = api.urls
150
151 # Trying to add more operations should fail
152 with pytest.raises(ConfigError, match="frozen"):
153
154 @router.get("/new")
155 def new_endpoint(request):
156 return []
157
158 def test_cannot_add_router_after_urls_accessed(self):
159 """Cannot add routers after URLs have been generated."""
160 api = NinjaAPI(urls_namespace="freeze-add-router")
161
162 # Access urls
163 _ = api.urls
164
165 router = Router()
166
167 with pytest.raises(ConfigError, match="Cannot add routers"):
168 api.add_router("/new", router)
169
170 def test_cannot_add_decorator_to_frozen_router(self):
171 """Cannot add decorator to frozen router."""
172 router = Router()
173
174 @router.get("/items")
175 def list_items(request):
176 return []
177
178 api = NinjaAPI(urls_namespace="freeze-decorator")
179 api.add_router("", router)
180
181 # Access urls (triggers freezing)
182 _ = api.urls
183
184 def some_decorator(func):
185 return func
186
187 with pytest.raises(ConfigError, match="frozen"):
188 router.add_decorator(some_decorator)
189
190
191 class TestOperationClone:
192 """Test Operation.clone() method completeness."""
193
194 def test_clone_copies_all_attributes(self):
195 """clone() should copy all essential attributes from original operation."""
196
197 def dummy_view(request):
198 return {"test": True}
199
200 original = Operation(
201 path="/test/{id}",
202 methods=["GET", "POST"],
203 view_func=dummy_view,
204 operation_id="test_op",
205 summary="Test Summary",
206 description="Test Description",
207 tags=["tag1", "tag2"],
208 deprecated=True,
209 by_alias=True,
210 exclude_unset=True,
211 exclude_defaults=True,
212 exclude_none=True,
213 include_in_schema=False,
214 url_name="custom_url_name",
215 openapi_extra={"x-custom": "value"},
216 )
217
218 cloned = original.clone()
219
220 # Verify all key attributes are copied
221 assert cloned.path == original.path
222 assert cloned.methods == original.methods
223 assert cloned.methods is not original.methods # Should be a copy
224 assert cloned.view_func is original.view_func # Same callable reference
225 assert cloned.operation_id == original.operation_id
226 assert cloned.summary == original.summary
227 assert cloned.description == original.description
228 assert cloned.tags == original.tags
229 assert cloned.tags is not original.tags # Should be a copy
230 assert cloned.deprecated == original.deprecated
231 assert cloned.by_alias == original.by_alias
232 assert cloned.exclude_unset == original.exclude_unset
233 assert cloned.exclude_defaults == original.exclude_defaults
234 assert cloned.exclude_none == original.exclude_none
235 assert cloned.include_in_schema == original.include_in_schema
236 assert cloned.url_name == original.url_name
237 assert cloned.openapi_extra == original.openapi_extra
238 assert cloned.openapi_extra is not original.openapi_extra # Should be a copy
239
240 # These should be references (immutable after creation)
241 assert cloned.signature is original.signature
242 assert cloned.models is original.models
243
244 # Response models should be copied
245 assert cloned.response_models == original.response_models
246 assert cloned.response_models is not original.response_models
247
248 # API should be None on clone (not bound yet)
249 assert cloned.api is None
250
251 def test_clone_preserves_auth_settings(self):
252 """clone() should preserve auth settings."""
253
254 def auth_callback(request):
255 return True
256
257 def dummy_view(request):
258 return {"test": True}
259
260 original = Operation(
261 path="/test",
262 methods=["GET"],
263 view_func=dummy_view,
264 auth=[auth_callback],
265 )
266
267 cloned = original.clone()
268
269 assert cloned.auth_param == original.auth_param
270 assert cloned.auth_callbacks == original.auth_callbacks
271 assert cloned.auth_callbacks is not original.auth_callbacks
272
273 def test_pathview_clone(self):
274 """PathView.clone() should clone all contained operations."""
275 pv = PathView()
276
277 def view1(request):
278 return {"method": "get"}
279
280 def view2(request, data: dict):
281 return {"method": "post"}
282
283 pv.add_operation("/test", ["GET"], view1)
284 pv.add_operation("/test", ["POST"], view2)
285
286 cloned = pv.clone()
287
288 assert len(cloned.operations) == len(pv.operations)
289 assert cloned.is_async == pv.is_async
290 assert cloned.url_name == pv.url_name
291
292 # Operations should be cloned, not same instances
293 for orig_op, clone_op in zip(pv.operations, cloned.operations):
294 assert orig_op is not clone_op
295 assert clone_op.path == orig_op.path
296 assert clone_op.methods == orig_op.methods
297
298
299 class TestCloneCompleteness:
300 """Test that clone() is updated when new attributes are added to Operation."""
301
302 def test_clone_attribute_completeness(self):
303 """
304 Verify that all instance attributes set in __init__ are handled by clone().
305
306 This test helps catch cases where new attributes are added to Operation
307 but clone() is not updated accordingly.
308 """
309
310 def dummy_view(request):
311 return {}
312
313 # Create operation with all parameters
314 op = Operation(
315 path="/test",
316 methods=["GET"],
317 view_func=dummy_view,
318 )
319
320 cloned = op.clone()
321
322 # Get all instance attributes that should be present
323 # These are the key attributes that clone() should handle
324 expected_attrs = [
325 "is_async",
326 "path",
327 "methods",
328 "view_func",
329 "csrf_exempt",
330 "auth_param",
331 "auth_callbacks",
332 "throttle_param",
333 "throttle_objects",
334 "signature",
335 "models",
336 "response_models",
337 "operation_id",
338 "summary",
339 "description",
340 "tags",
341 "deprecated",
342 "include_in_schema",
343 "openapi_extra",
344 "by_alias",
345 "exclude_unset",
346 "exclude_defaults",
347 "exclude_none",
348 ]
349
350 for attr in expected_attrs:
351 assert hasattr(cloned, attr), f"clone() missing attribute: {attr}"
352
353 # For mutable types, ensure they're copies (not same reference)
354 orig_val = getattr(op, attr)
355 clone_val = getattr(cloned, attr)
356
357 if isinstance(orig_val, (list, dict)) and orig_val:
358 assert clone_val is not orig_val, f"clone() should copy {attr}"
359
360 def test_clone_catches_new_attributes(self):
361 """
362 IMPORTANT: This test will FAIL if you add a new attribute to Operation
363 but forget to handle it in clone().
364
365 When this test fails, update Operation.clone() to handle the new attribute,
366 then add it to the KNOWN_ATTRIBUTES set below.
367 """
368
369 def dummy_view(request):
370 return {}
371
372 op = Operation(
373 path="/test/{id}",
374 methods=["GET", "POST"],
375 view_func=dummy_view,
376 auth=lambda r: True,
377 response={200: dict},
378 tags=["test"],
379 summary="Test summary",
380 description="Test description",
381 operation_id="test_op",
382 deprecated=True,
383 by_alias=True,
384 exclude_unset=True,
385 exclude_defaults=True,
386 exclude_none=True,
387 url_name="test_url",
388 include_in_schema=True,
389 openapi_extra={"x-custom": "value"},
390 )
391
392 cloned = op.clone()
393
394 # Attributes that are known and handled by clone()
395 # If you add a new attribute to Operation, you MUST:
396 # 1. Add it to clone() method
397 # 2. Add it to this set
398 KNOWN_ATTRIBUTES = {
399 # Core operation attributes
400 "is_async",
401 "path",
402 "methods",
403 "view_func",
404 "api",
405 # Auth/security
406 "csrf_exempt",
407 "auth_param",
408 "auth_callbacks",
409 # Throttling
410 "throttle_param",
411 "throttle_objects",
412 # Signature and models
413 "signature",
414 "models",
415 "response_models",
416 # Streaming
417 "stream_format",
418 "stream_item_model",
419 # OpenAPI metadata
420 "operation_id",
421 "summary",
422 "description",
423 "tags",
424 "deprecated",
425 "include_in_schema",
426 "openapi_extra",
427 "url_name",
428 # Response serialization options
429 "by_alias",
430 "exclude_unset",
431 "exclude_defaults",
432 "exclude_none",
433 }
434
435 # Attributes that are intentionally not cloned (internal/runtime state)
436 EXCLUDED_ATTRIBUTES = {
437 "_run_decorators", # Re-applied during clone, not copied
438 "_applied_decorators", # Router-level decorator tracking
439 }
440
441 # Get all instance attributes from the original operation
442 original_attrs = {
443 attr
444 for attr in dir(op)
445 if not attr.startswith("_") # Skip private/dunder
446 and not callable(getattr(op, attr)) # Skip methods
447 and not isinstance(
448 getattr(type(op), attr, None), property
449 ) # Skip properties
450 }
451
452 # Also check for underscore attributes that we explicitly track
453 for attr in dir(op):
454 if attr.startswith("_") and not attr.startswith("__"):
455 if attr in EXCLUDED_ATTRIBUTES:
456 continue
457 if hasattr(op, attr) and not callable(getattr(op, attr)):
458 original_attrs.add(attr)
459
460 # Find any attributes that exist on original but aren't in our known set
461 unknown_attrs = original_attrs - KNOWN_ATTRIBUTES - EXCLUDED_ATTRIBUTES
462
463 if unknown_attrs:
464 raise AssertionError(
465 f"New attribute(s) found on Operation that may not be handled by clone(): "
466 f"{unknown_attrs}\n\n"
467 f"If you added a new attribute to Operation:\n"
468 f"1. Update Operation.clone() to handle it\n"
469 f"2. Add it to KNOWN_ATTRIBUTES in this test\n"
470 f"3. Add it to EXCLUDED_ATTRIBUTES if it should NOT be cloned"
471 )
472
473 # Verify all known attributes exist on both original and clone
474 for attr in KNOWN_ATTRIBUTES:
475 assert hasattr(
476 op, attr
477 ), f"KNOWN_ATTRIBUTES lists '{attr}' but Operation doesn't have it"
478 assert hasattr(cloned, attr), f"clone() doesn't set attribute: {attr}"
479
480
481 class TestThrottleAndTagsInheritance:
482 """Test throttle and tags inheritance in BoundRouter."""
483
484 def test_throttle_inheritance_from_template(self):
485 """Router's own throttle takes precedence over inherited."""
486 from ninja.throttling import BaseThrottle
487
488 class TestThrottle(BaseThrottle):
489 def allow_request(self, request):
490 return True
491
492 def wait(self):
493 return None
494
495 router = Router(throttle=TestThrottle())
496
497 @router.get("/test")
498 def test_op(request):
499 return {"ok": True}
500
501 api = NinjaAPI(urls_namespace="throttle-template-test")
502 api.add_router("", router)
503 _ = api.urls
504
505 bound = api._get_bound_routers()[1] # Skip default router
506 assert bound.throttle is not None
507 # Check that operations have throttle applied
508 for path_view in bound.path_operations.values():
509 for op in path_view.operations:
510 assert len(op.throttle_objects) == 1
511
512 def test_throttle_inheritance_from_parent(self):
513 """Child router inherits throttle from parent."""
514 from ninja.throttling import BaseThrottle
515
516 class ParentThrottle(BaseThrottle):
517 def allow_request(self, request):
518 return True
519
520 def wait(self):
521 return None
522
523 parent = Router(throttle=ParentThrottle())
524 child = Router()
525
526 @child.get("/test")
527 def test_op(request):
528 return {"ok": True}
529
530 parent.add_router("/child", child)
531
532 api = NinjaAPI(urls_namespace="throttle-inherit-test")
533 api.add_router("/parent", parent)
534 _ = api.urls
535
536 # Find the child's bound router
537 bound_routers = api._get_bound_routers()
538 child_bound = next(b for b in bound_routers if b.template is child)
539 assert child_bound.throttle is not None
540
541 def test_tags_inheritance_from_parent(self):
542 """Child router inherits tags from parent if not set."""
543 parent = Router(tags=["parent-tag"])
544 child = Router()
545
546 @child.get("/test")
547 def test_op(request):
548 return {"ok": True}
549
550 parent.add_router("/child", child)
551
552 api = NinjaAPI(urls_namespace="tags-inherit-test")
553 api.add_router("/parent", parent)
554 _ = api.urls
555
556 # Find the child's bound router
557 bound_routers = api._get_bound_routers()
558 child_bound = next(b for b in bound_routers if b.template is child)
559 assert child_bound.tags == ["parent-tag"]
560
561 def test_tags_accumulation(self):
562 """
563 Test for issue #794: Tags from parent routers should accumulate with child tags.
564
565 When a child router has its own tags, they should be combined with parent tags,
566 not replace them.
567 """
568 parent = Router(tags=["Parent Tag"])
569 child = Router(tags=["Child Tag"])
570
571 @child.get("/test")
572 def test_op(request):
573 return {"ok": True}
574
575 parent.add_router("/child", child)
576
577 api = NinjaAPI()
578 api.add_router("/", parent)
579
580 # Check OpenAPI schema
581 schema = api.get_openapi_schema(path_prefix="")
582 path_info = schema["paths"]["/child/test"]["get"]
583
584 # Tags should include BOTH parent and child tags
585 tags = path_info.get("tags", [])
586 assert "Parent Tag" in tags, f"Parent tag missing. Got: {tags}"
587 assert "Child Tag" in tags, f"Child tag missing. Got: {tags}"
588
589
590 class TestRouterUrlsPathsMethod:
591 """Test Router.urls_paths() method for backward compatibility."""
592
593 def test_urls_paths_generates_patterns(self):
594 """Router.urls_paths() should generate URL patterns."""
595 router = Router()
596
597 @router.get("/test")
598 def test_op(request):
599 return {"ok": True}
600
601 patterns = list(router.urls_paths("prefix"))
602 assert len(patterns) == 1
603 assert "prefix/test" in str(patterns[0].pattern)
604
605 def test_urls_paths_with_api(self):
606 """Router.urls_paths() with API generates proper URL names."""
607 router = Router()
608
609 @router.get("/test")
610 def test_op(request):
611 return {"ok": True}
612
613 api = NinjaAPI(urls_namespace="urls-paths-test")
614 patterns = list(router.urls_paths("prefix", api=api))
615 assert len(patterns) == 1
616 assert patterns[0].name == "test_op"
617
618
619 class TestRouterAddRouterStringImport:
620 """Test Router.add_router() with string import path."""
621
622 def test_add_router_direct(self):
623 """Router.add_router() should accept Router instance."""
624 parent = Router()
625 child = Router()
626 parent.add_router("/test", child)
627
628 assert len(parent._routers) == 1
629 _, added_child, mount_tags = parent._routers[0]
630 assert isinstance(added_child, Router)
631 assert added_child is child
632 assert mount_tags is None # No tags specified in add_router
633
634
635 class TestBuildRoutersEdgeCases:
636 """Test edge cases in build_routers."""
637
638 def test_build_routers_without_inherited_decorators(self):
639 """build_routers() called directly without inherited_decorators."""
640 router = Router()
641
642 @router.get("/test")
643 def test_op(request):
644 return {"ok": True}
645
646 # Call build_routers directly without inherited_decorators
647 mounts = router.build_routers("prefix")
648 assert len(mounts) == 1
649 assert mounts[0].prefix == "prefix"
650 assert mounts[0].inherited_decorators == []
651
652
653 class TestApplyDecoratorsToOperations:
654 """Test _apply_decorators_to_operations method."""
655
656 def test_apply_decorators_view_mode(self):
657 """Test applying decorators in view mode."""
658 router = Router()
659
660 calls = []
661
662 def view_decorator(func):
663 def wrapper(*args, **kwargs):
664 calls.append("view")
665 return func(*args, **kwargs)
666
667 return wrapper
668
669 @router.get("/test")
670 def test_op(request):
671 return {"ok": True}
672
673 router.add_decorator(view_decorator, mode="view")
674
675 # Force decorator application
676 router._apply_decorators_to_operations()
677
678 # Check decorator was applied
679 for path_view in router.path_operations.values():
680 for op in path_view.operations:
681 assert hasattr(op, "_applied_decorators")
682 assert len(op._applied_decorators) == 1
683
684 def test_apply_decorators_operation_mode(self):
685 """Test applying decorators in operation mode."""
686 router = Router()
687
688 calls = []
689
690 def op_decorator(func):
691 def wrapper(*args, **kwargs):
692 calls.append("operation")
693 return func(*args, **kwargs)
694
695 return wrapper
696
697 @router.get("/test")
698 def test_op(request):
699 return {"ok": True}
700
701 router.add_decorator(op_decorator, mode="operation")
702
703 # Force decorator application
704 router._apply_decorators_to_operations()
705
706 # Check decorator was applied
707 for path_view in router.path_operations.values():
708 for op in path_view.operations:
709 assert hasattr(op, "_applied_decorators")
710 assert len(op._applied_decorators) == 1
711
712 def test_apply_decorators_idempotent(self):
713 """Test that decorators are not applied twice."""
714 router = Router()
715
716 calls = []
717
718 def decorator(func):
719 def wrapper(*args, **kwargs):
720 calls.append("called")
721 return func(*args, **kwargs)
722
723 return wrapper
724
725 @router.get("/test")
726 def test_op(request):
727 return {"ok": True}
728
729 router.add_decorator(decorator, mode="view")
730
731 # Apply twice - should be idempotent
732 router._apply_decorators_to_operations()
733 router._apply_decorators_to_operations()
734
735 # Check decorator was only applied once
736 for path_view in router.path_operations.values():
737 for op in path_view.operations:
738 assert len(op._applied_decorators) == 1
739
740
741 class TestBoundRouterOperationModeDecorator:
742 """Test BoundRouter with operation mode decorators."""
743
744 def test_operation_mode_decorator_in_bound_router(self):
745 """Test that operation mode decorators work in BoundRouter."""
746 router = Router()
747 calls = []
748
749 def op_decorator(func):
750 def wrapper(*args, **kwargs):
751 calls.append("operation")
752 return func(*args, **kwargs)
753
754 return wrapper
755
756 @router.get("/test")
757 def test_op(request):
758 return {"ok": True}
759
760 router.add_decorator(op_decorator, mode="operation")
761
762 api = NinjaAPI(urls_namespace="op-mode-decorator-test")
763 api.add_router("", router)
764
765 client = TestClient(api)
766 response = client.get("/test")
767 assert response.status_code == 200
768 assert "operation" in calls
769
770
771 class TestRouterAddRouterWithThrottle:
772 """Test Router.add_router with throttle parameter."""
773
774 def test_add_router_with_throttle(self):
775 """Test adding a child router with throttle parameter."""
776 from ninja.throttling import BaseThrottle
777
778 class TestThrottle(BaseThrottle):
779 def allow_request(self, request):
780 return True
781
782 def wait(self):
783 return None
784
785 parent = Router()
786 child = Router()
787
788 @child.get("/test")
789 def test_op(request):
790 return {"ok": True}
791
792 parent.add_router("/child", child, throttle=TestThrottle())
793
794 # Verify throttle was set on child
795 assert child.throttle is not None
796
797 api = NinjaAPI(urls_namespace="throttle-add-router-test")
798 api.add_router("", parent)
799
800 client = TestClient(api)
801 response = client.get("/child/test")
802 assert response.status_code == 200
803
804
805 class TestDecorateViewMultipleCalls:
806 """Test decorate_view called multiple times."""
807
808 def test_decorate_view_multiple_decorators(self):
809 """Test applying multiple view decorators to same operation."""
810 from ninja.decorators import decorate_view
811
812 router = Router()
813 calls = []
814
815 def decorator1(func):
816 def wrapper(*args, **kwargs):
817 calls.append("deco1")
818 return func(*args, **kwargs)
819
820 return wrapper
821
822 def decorator2(func):
823 def wrapper(*args, **kwargs):
824 calls.append("deco2")
825 return func(*args, **kwargs)
826
827 return wrapper
828
829 @router.get("/test")
830 @decorate_view(decorator1)
831 @decorate_view(decorator2)
832 def test_op(request):
833 return {"ok": True}
834
835 api = NinjaAPI(urls_namespace="multi-decorate-view-test")
836 api.add_router("", router)
837
838 client = TestClient(api)
839 response = client.get("/test")
840 assert response.status_code == 200
841 # Both decorators should be called
842 assert "deco1" in calls
843 assert "deco2" in calls