Debian Codegraph @

tests/test_api_instance.py

raw symbols SCIP
1 import pytest
2
3 from ninja import NinjaAPI, Router
4 from ninja.errors import ConfigError
5
6
7 def test_api_instance():
8 """Test that operations are properly bound to API via bound routers."""
9 api = NinjaAPI(urls_namespace="api-instance-test")
10 router = Router()
11
12 @api.get("/global")
13 def global_op(request):
14 pass
15
16 @router.get("/router")
17 def router_op(request):
18 pass
19
20 api.add_router("/", router)
21
22 # Access URLs to trigger binding
23 _ = api.urls
24
25 # Check via bound routers (the new architecture)
26 bound_routers = api._get_bound_routers()
27 assert len(bound_routers) == 2 # default + extra
28
29 for bound_router in bound_routers:
30 for path_ops in bound_router.path_operations.values():
31 for op in path_ops.operations:
32 assert op.api is api
33
34
35 def test_reuse_router_requires_url_name_prefix():
36 """Mounting same router twice requires url_name_prefix."""
37 test_api = NinjaAPI(urls_namespace="reuse-test")
38 test_router = Router()
39
40 @test_router.get("/test")
41 def test_op(request):
42 pass
43
44 test_api.add_router("/", test_router)
45
46 # Same router mounted again without url_name_prefix should raise
47 match = "Router is already mounted"
48 with pytest.raises(ConfigError, match=match):
49 test_api.add_router("/another-path", test_router)
50
51
52 def test_reuse_router_with_url_name_prefix():
53 """Same router can be mounted multiple times with different url_name_prefix."""
54 test_api = NinjaAPI(urls_namespace="reuse-prefix-test")
55 test_router = Router()
56
57 @test_router.get("/test")
58 def test_op(request):
59 pass
60
61 test_api.add_router("/v1", test_router, url_name_prefix="v1")
62 test_api.add_router("/v2", test_router, url_name_prefix="v2")
63
64 # Should work - verify URLs are generated
65 _ = test_api.urls
66
67 # Both mounts should work
68 bound_routers = test_api._get_bound_routers()
69 # default router + 2 mounts of test_router
70 assert len(bound_routers) == 3