Debian Codegraph @

tests/test_add_decorator_async.py

raw symbols SCIP
1 import asyncio
2 from functools import wraps
3
4 import pytest
5
6 from ninja import NinjaAPI, Router
7 from ninja.testing import TestAsyncClient, TestClient
8
9
10 # Async test decorators
11 def async_operation_decorator(func):
12 """Async decorator that adds data after validation (operation level)"""
13
14 @wraps(func)
15 async def wrapper(request, *args, **kwargs):
16 result = await func(request, *args, **kwargs)
17 if isinstance(result, dict):
18 result["async_operation_decorated"] = True
19 return result
20
21 return wrapper
22
23
24 def async_view_decorator(func):
25 """Async decorator that adds a header before validation (view level)"""
26
27 @wraps(func)
28 async def wrapper(request, *args, **kwargs):
29 response = await func(request, *args, **kwargs)
30 response["X-Async-View-Decorator"] = "applied"
31 return response
32
33 return wrapper
34
35
36 @pytest.mark.asyncio
37 async def test_router_add_decorator_async_operation_mode():
38 """Test add_decorator on router with async operations in OPERATION mode"""
39 api = NinjaAPI()
40 router = Router()
41
42 # Add decorator to router
43 router.add_decorator(async_operation_decorator, mode="operation")
44
45 @router.get("/test")
46 async def endpoint(request):
47 await asyncio.sleep(0) # Simulate async work
48 return {"message": "async test"}
49
50 api.add_router("/", router)
51 client = TestAsyncClient(api)
52
53 response = await client.get("/test")
54 assert response.status_code == 200
55 assert response.json() == {
56 "message": "async test",
57 "async_operation_decorated": True,
58 }
59
60
61 @pytest.mark.asyncio
62 async def test_router_add_decorator_async_view_mode():
63 """Test add_decorator on router with async operations in VIEW mode"""
64 api = NinjaAPI()
65 router = Router()
66
67 # Add decorator to router
68 router.add_decorator(async_view_decorator, mode="view")
69
70 @router.get("/test")
71 async def endpoint(request):
72 await asyncio.sleep(0)
73 return {"message": "async test"}
74
75 api.add_router("/", router)
76 client = TestAsyncClient(api)
77
78 response = await client.get("/test")
79 assert response.status_code == 200
80 assert response["X-Async-View-Decorator"] == "applied"
81 assert response.json() == {"message": "async test"}
82
83
84 @pytest.mark.asyncio
85 async def test_api_add_decorator_async():
86 """Test add_decorator on API with async operations"""
87 api = NinjaAPI()
88
89 # Add decorator to entire API
90 api.add_decorator(async_operation_decorator, mode="operation")
91
92 @api.get("/test1")
93 async def endpoint1(request):
94 await asyncio.sleep(0)
95 return {"message": "test1"}
96
97 @api.get("/test2")
98 async def endpoint2(request):
99 await asyncio.sleep(0)
100 return {"message": "test2"}
101
102 client = TestAsyncClient(api)
103
104 # Both endpoints should be decorated
105 response = await client.get("/test1")
106 assert response.status_code == 200
107 assert response.json() == {"message": "test1", "async_operation_decorated": True}
108
109 response = await client.get("/test2")
110 assert response.status_code == 200
111 assert response.json() == {"message": "test2", "async_operation_decorated": True}
112
113
114 @pytest.mark.asyncio
115 async def test_mixed_sync_async_decorators():
116 """Test that sync decorators work with async endpoints"""
117 api = NinjaAPI()
118 router = Router()
119
120 # Use a sync decorator on async endpoint
121 def sync_decorator(func):
122 @wraps(func)
123 def wrapper(request, *args, **kwargs):
124 # For async functions, this will return a coroutine
125 result = func(request, *args, **kwargs)
126 if asyncio.iscoroutine(result):
127
128 async def async_wrapper():
129 actual_result = await result
130 if isinstance(actual_result, dict):
131 actual_result["sync_decorated"] = True
132 return actual_result
133
134 return async_wrapper()
135 else:
136 # For sync functions, modify the result directly
137 if isinstance(result, dict):
138 result["sync_decorated"] = True
139 return result
140
141 return wrapper
142
143 router.add_decorator(sync_decorator, mode="operation")
144
145 @router.get("/async")
146 async def async_endpoint(request):
147 await asyncio.sleep(0)
148 return {"type": "async"}
149
150 @router.get("/sync")
151 def sync_endpoint(request):
152 return {"type": "sync"}
153
154 api.add_router("/", router)
155 client = TestAsyncClient(api)
156
157 # Test async endpoint
158 response = await client.get("/async")
159 assert response.status_code == 200
160 assert response.json() == {"type": "async", "sync_decorated": True}
161
162 # Test sync endpoint with regular TestClient
163 from ninja.testing import TestClient
164
165 sync_client = TestClient(api)
166 response = sync_client.get("/sync")
167 assert response.status_code == 200
168 assert response.json() == {"type": "sync", "sync_decorated": True}
169
170
171 @pytest.mark.asyncio
172 async def test_mixed_sync_async_endpoints_same_router():
173 """Test router with both sync and async endpoints using the same decorator"""
174 api = NinjaAPI()
175 router = Router()
176
177 # Universal decorator that works with both sync and async functions
178 def universal_decorator(func):
179 if asyncio.iscoroutinefunction(func):
180 # Handle async functions
181 @wraps(func)
182 async def async_wrapper(request, *args, **kwargs):
183 result = await func(request, *args, **kwargs)
184 if isinstance(result, dict):
185 result["universal_decorated"] = True
186 result["func_type"] = "async"
187 return result
188
189 return async_wrapper
190 else:
191 # Handle sync functions
192 @wraps(func)
193 def sync_wrapper(request, *args, **kwargs):
194 result = func(request, *args, **kwargs)
195 if isinstance(result, dict):
196 result["universal_decorated"] = True
197 result["func_type"] = "sync"
198 return result
199
200 return sync_wrapper
201
202 router.add_decorator(universal_decorator, mode="operation")
203
204 @router.get("/async")
205 async def async_endpoint(request):
206 await asyncio.sleep(0)
207 return {"endpoint": "async"}
208
209 @router.get("/sync")
210 def sync_endpoint(request):
211 return {"endpoint": "sync"}
212
213 api.add_router("/", router)
214
215 # Test both endpoints with appropriate clients
216 async_client = TestAsyncClient(api)
217 sync_client = TestClient(api)
218
219 # Test async endpoint
220 response = await async_client.get("/async")
221 assert response.status_code == 200
222 assert response.json() == {
223 "endpoint": "async",
224 "universal_decorated": True,
225 "func_type": "async",
226 }
227
228 # Test sync endpoint
229 response = sync_client.get("/sync")
230 assert response.status_code == 200
231 assert response.json() == {
232 "endpoint": "sync",
233 "universal_decorated": True,
234 "func_type": "sync",
235 }