Debian Codegraph @

tests/test_streaming.py

raw symbols SCIP
1 import json
2
3 import pytest
4 from django.http import HttpResponse
5
6 from ninja import NinjaAPI, Schema
7 from ninja.streaming import JSONL, SSE, StreamFormat
8 from ninja.testing import TestAsyncClient, TestClient
9
10
11 class Item(Schema):
12 name: str
13 price: float = 0.0
14
15
16 # --- Sync JSONL ---
17
18 api = NinjaAPI()
19
20
21 @api.get("/jsonl/items", response=JSONL[Item])
22 def jsonl_items(request):
23 for i in range(3):
24 yield {"name": f"item-{i}", "price": float(i)}
25
26
27 @api.get("/sse/items", response=SSE[Item])
28 def sse_items(request):
29 for i in range(3):
30 yield {"name": f"item-{i}", "price": float(i)}
31
32
33 @api.post("/jsonl/echo", response=JSONL[Item])
34 def jsonl_echo(request):
35 yield {"name": "posted", "price": 1.0}
36
37
38 @api.get("/jsonl/with-params/{item_id}", response=JSONL[Item])
39 def jsonl_with_params(request, item_id: int, q: str = "default"):
40 yield {"name": f"item-{item_id}-{q}", "price": 0.0}
41
42
43 @api.get("/jsonl/with-headers", response=JSONL[Item])
44 def jsonl_with_headers(request, response: HttpResponse):
45 response["X-Custom"] = "hello"
46 response.set_cookie("session", "abc123")
47 yield {"name": "with-headers", "price": 0.0}
48
49
50 client = TestClient(api)
51
52
53 class TestJSONLSync:
54 def test_jsonl_basic(self):
55 response = client.get("/jsonl/items")
56 assert response.status_code == 200
57 assert response["Content-Type"] == "application/jsonl"
58 lines = response.content.decode().strip().split("\n")
59 assert len(lines) == 3
60 for i, line in enumerate(lines):
61 data = json.loads(line)
62 assert data == {"name": f"item-{i}", "price": float(i)}
63
64 def test_jsonl_validates_schema(self):
65 """Each item is validated through Pydantic schema."""
66 response = client.get("/jsonl/items")
67 lines = response.content.decode().strip().split("\n")
68 for line in lines:
69 data = json.loads(line)
70 # Should have both fields (price has default)
71 assert "name" in data
72 assert "price" in data
73
74
75 class TestSSESync:
76 def test_sse_basic(self):
77 response = client.get("/sse/items")
78 assert response.status_code == 200
79 assert response["Content-Type"] == "text/event-stream"
80 content = response.content.decode()
81 events = content.strip().split("\n\n")
82 assert len(events) == 3
83 for i, event in enumerate(events):
84 assert event.startswith("data: ")
85 data = json.loads(event[len("data: ") :])
86 assert data == {"name": f"item-{i}", "price": float(i)}
87
88 def test_sse_headers(self):
89 response = client.get("/sse/items")
90 assert response["Cache-Control"] == "no-cache"
91 assert response["X-Accel-Buffering"] == "no"
92
93
94 class TestPostStreaming:
95 def test_post_jsonl(self):
96 response = client.post("/jsonl/echo")
97 assert response.status_code == 200
98 lines = response.content.decode().strip().split("\n")
99 assert len(lines) == 1
100 assert json.loads(lines[0]) == {"name": "posted", "price": 1.0}
101
102
103 class TestStreamingWithParams:
104 def test_path_and_query_params(self):
105 response = client.get("/jsonl/with-params/42?q=test")
106 assert response.status_code == 200
107 lines = response.content.decode().strip().split("\n")
108 assert json.loads(lines[0]) == {"name": "item-42-test", "price": 0.0}
109
110
111 class TestStreamingHeaders:
112 def test_temporal_response_headers(self):
113 response = client.get("/jsonl/with-headers")
114 assert response.status_code == 200
115 assert response["X-Custom"] == "hello"
116 assert "session" in response.cookies
117
118
119 # --- Async ---
120
121 async_api = NinjaAPI()
122
123
124 @async_api.get("/jsonl/items", response=JSONL[Item])
125 async def async_jsonl_items(request):
126 for i in range(3):
127 yield {"name": f"item-{i}", "price": float(i)}
128
129
130 @async_api.get("/sse/items", response=SSE[Item])
131 async def async_sse_items(request):
132 for i in range(3):
133 yield {"name": f"item-{i}", "price": float(i)}
134
135
136 @async_api.get("/jsonl/with-headers", response=JSONL[Item])
137 async def async_jsonl_with_headers(request, response: HttpResponse):
138 response["X-Custom"] = "async-hello"
139 response.set_cookie("token", "xyz")
140 yield {"name": "async-headers", "price": 0.0}
141
142
143 async_client = TestAsyncClient(async_api)
144
145
146 @pytest.mark.asyncio
147 class TestAsyncJSONL:
148 async def test_async_jsonl(self):
149 response = await async_client.get("/jsonl/items")
150 assert response.status_code == 200
151 assert response["Content-Type"] == "application/jsonl"
152 lines = response.content.decode().strip().split("\n")
153 assert len(lines) == 3
154 for i, line in enumerate(lines):
155 data = json.loads(line)
156 assert data == {"name": f"item-{i}", "price": float(i)}
157
158
159 @pytest.mark.asyncio
160 class TestAsyncSSE:
161 async def test_async_sse(self):
162 response = await async_client.get("/sse/items")
163 assert response.status_code == 200
164 assert response["Content-Type"] == "text/event-stream"
165 assert response["Cache-Control"] == "no-cache"
166 content = response.content.decode()
167 events = content.strip().split("\n\n")
168 assert len(events) == 3
169
170
171 @pytest.mark.asyncio
172 class TestAsyncHeaders:
173 async def test_async_temporal_response_headers(self):
174 response = await async_client.get("/jsonl/with-headers")
175 assert response.status_code == 200
176 assert response["X-Custom"] == "async-hello"
177 assert "token" in response.cookies
178
179
180 # --- OpenAPI Schema ---
181
182
183 class TestOpenAPISchema:
184 def test_jsonl_openapi(self):
185 schema = api.get_openapi_schema()
186 path = schema["paths"]["/api/jsonl/items"]["get"]
187 resp = path["responses"][200]
188 assert "application/jsonl" in resp["content"]
189 item_schema = resp["content"]["application/jsonl"]["schema"]
190 # Should reference the Item schema
191 assert item_schema.get("$ref") or item_schema.get("properties")
192
193 def test_sse_openapi(self):
194 schema = api.get_openapi_schema()
195 path = schema["paths"]["/api/sse/items"]["get"]
196 resp = path["responses"][200]
197 assert "text/event-stream" in resp["content"]
198 sse_schema = resp["content"]["text/event-stream"]["schema"]
199 assert sse_schema["type"] == "object"
200 assert "data" in sse_schema["properties"]
201
202
203 # --- Custom StreamFormat ---
204
205
206 class NDJSON(StreamFormat):
207 media_type = "application/x-ndjson"
208
209 @classmethod
210 def format_chunk(cls, data: str) -> str:
211 return data + "\n"
212
213
214 custom_api = NinjaAPI()
215
216
217 @custom_api.get("/ndjson/items", response=NDJSON[Item])
218 def ndjson_items(request):
219 for i in range(2):
220 yield {"name": f"item-{i}", "price": float(i)}
221
222
223 custom_client = TestClient(custom_api)
224
225
226 class TestCustomFormat:
227 def test_custom_ndjson(self):
228 response = custom_client.get("/ndjson/items")
229 assert response.status_code == 200
230 assert response["Content-Type"] == "application/x-ndjson"
231 lines = response.content.decode().strip().split("\n")
232 assert len(lines) == 2
233
234 def test_custom_openapi(self):
235 schema = custom_api.get_openapi_schema()
236 path = schema["paths"]["/api/ndjson/items"]["get"]
237 resp = path["responses"][200]
238 assert "application/x-ndjson" in resp["content"]
239
240
241 # --- Multiple methods ---
242
243 multi_api = NinjaAPI()
244
245
246 @multi_api.patch("/patch-stream", response=JSONL[Item])
247 def patch_stream(request):
248 yield {"name": "patched", "price": 0.0}
249
250
251 @multi_api.put("/put-stream", response=JSONL[Item])
252 def put_stream(request):
253 yield {"name": "put", "price": 0.0}
254
255
256 @multi_api.delete("/delete-stream", response=JSONL[Item])
257 def delete_stream(request):
258 yield {"name": "deleted", "price": 0.0}
259
260
261 multi_client = TestClient(multi_api)
262
263
264 class TestMultipleMethods:
265 def test_patch_stream(self):
266 response = multi_client.patch("/patch-stream")
267 assert response.status_code == 200
268 assert json.loads(response.content.decode().strip()) == {
269 "name": "patched",
270 "price": 0.0,
271 }
272
273 def test_put_stream(self):
274 response = multi_client.put("/put-stream")
275 assert response.status_code == 200
276 assert json.loads(response.content.decode().strip()) == {
277 "name": "put",
278 "price": 0.0,
279 }
280
281 def test_delete_stream(self):
282 response = multi_client.delete("/delete-stream")
283 assert response.status_code == 200
284 assert json.loads(response.content.decode().strip()) == {
285 "name": "deleted",
286 "price": 0.0,
287 }