|
| 1 | +import json |
| 2 | +from collections.abc import AsyncIterable, Iterator |
| 3 | + |
| 4 | +import pytest |
| 5 | +from fastapi import APIRouter, FastAPI |
| 6 | +from fastapi.exceptions import ResponseValidationError |
| 7 | +from fastapi.sse import EventSourceResponse, ServerSentEvent |
| 8 | +from fastapi.testclient import TestClient |
| 9 | +from pydantic import BaseModel |
| 10 | + |
| 11 | + |
| 12 | +class Item(BaseModel): |
| 13 | + name: str |
| 14 | + secret: str |
| 15 | + optional: str | None = None |
| 16 | + |
| 17 | + |
| 18 | +class PriceItem(BaseModel): |
| 19 | + name: str |
| 20 | + price: float |
| 21 | + |
| 22 | + |
| 23 | +app = FastAPI() |
| 24 | + |
| 25 | + |
| 26 | +@app.get( |
| 27 | + "/items/stream-jsonl", |
| 28 | + response_model=Item, |
| 29 | + response_model_exclude={"secret"}, |
| 30 | + response_model_exclude_none=True, |
| 31 | +) |
| 32 | +async def stream_jsonl(): |
| 33 | + yield Item(name="foo", secret="hidden", optional=None) |
| 34 | + |
| 35 | + |
| 36 | +@app.get( |
| 37 | + "/items/stream-async-iterable", |
| 38 | + response_model=AsyncIterable[Item], |
| 39 | + response_model_exclude={"secret"}, |
| 40 | +) |
| 41 | +async def stream_async_iterable(): |
| 42 | + yield Item(name="bar", secret="hidden") |
| 43 | + |
| 44 | + |
| 45 | +@app.get( |
| 46 | + "/items/stream-iterator", |
| 47 | + response_model=Iterator[Item], |
| 48 | + response_model_exclude={"secret"}, |
| 49 | +) |
| 50 | +def stream_iterator(): |
| 51 | + yield Item(name="baz", secret="hidden") |
| 52 | + |
| 53 | + |
| 54 | +@app.get( |
| 55 | + "/items/stream-sse", |
| 56 | + response_class=EventSourceResponse, |
| 57 | + response_model=Item, |
| 58 | + response_model_exclude={"secret"}, |
| 59 | +) |
| 60 | +async def stream_sse(): |
| 61 | + yield Item(name="sse-item", secret="hidden") |
| 62 | + |
| 63 | + |
| 64 | +@app.get( |
| 65 | + "/items/stream-sse-events", |
| 66 | + response_class=EventSourceResponse, |
| 67 | +) |
| 68 | +async def stream_sse_events(): |
| 69 | + yield ServerSentEvent(data="plain text", event="custom") |
| 70 | + |
| 71 | + |
| 72 | +@app.get( |
| 73 | + "/items/stream-sse-server-sent-event-model", |
| 74 | + response_class=EventSourceResponse, |
| 75 | + response_model=ServerSentEvent, |
| 76 | +) |
| 77 | +async def stream_sse_server_sent_event_model(): |
| 78 | + yield ServerSentEvent(data="sse-explicit", event="message") |
| 79 | + |
| 80 | + |
| 81 | +@app.get( |
| 82 | + "/items/non-stream", |
| 83 | + response_model=Item, |
| 84 | + response_model_exclude={"secret"}, |
| 85 | +) |
| 86 | +def non_stream(): |
| 87 | + return Item(name="regular", secret="hidden") |
| 88 | + |
| 89 | + |
| 90 | +@app.get( |
| 91 | + "/items/stream-invalid-async", |
| 92 | + response_model=PriceItem, |
| 93 | +) |
| 94 | +async def stream_invalid_async(): |
| 95 | + yield {"name": "valid", "price": 10.0} |
| 96 | + yield {"name": "invalid", "price": "not-a-float"} |
| 97 | + |
| 98 | + |
| 99 | +@app.get( |
| 100 | + "/items/stream-invalid-sync", |
| 101 | + response_model=PriceItem, |
| 102 | +) |
| 103 | +def stream_invalid_sync(): |
| 104 | + yield {"name": "valid", "price": 10.0} |
| 105 | + yield {"name": "invalid", "price": "not-a-float"} |
| 106 | + |
| 107 | + |
| 108 | +router = APIRouter() |
| 109 | + |
| 110 | + |
| 111 | +@router.get( |
| 112 | + "/stream-router", |
| 113 | + response_model=Item, |
| 114 | + response_model_exclude={"secret"}, |
| 115 | +) |
| 116 | +async def stream_router(): |
| 117 | + yield Item(name="router-item", secret="hidden") |
| 118 | + |
| 119 | + |
| 120 | +app.include_router(router, prefix="/api") |
| 121 | + |
| 122 | +client = TestClient(app) |
| 123 | + |
| 124 | + |
| 125 | +def test_stream_jsonl_with_explicit_response_model(): |
| 126 | + response = client.get("/items/stream-jsonl") |
| 127 | + assert response.status_code == 200 |
| 128 | + assert response.headers["content-type"] == "application/jsonl" |
| 129 | + lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 130 | + assert lines == [{"name": "foo"}] |
| 131 | + |
| 132 | + |
| 133 | +def test_stream_jsonl_with_async_iterable_response_model(): |
| 134 | + response = client.get("/items/stream-async-iterable") |
| 135 | + assert response.status_code == 200 |
| 136 | + assert response.headers["content-type"] == "application/jsonl" |
| 137 | + lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 138 | + assert lines == [{"name": "bar", "optional": None}] |
| 139 | + |
| 140 | + |
| 141 | +def test_stream_jsonl_with_iterator_response_model(): |
| 142 | + response = client.get("/items/stream-iterator") |
| 143 | + assert response.status_code == 200 |
| 144 | + assert response.headers["content-type"] == "application/jsonl" |
| 145 | + lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 146 | + assert lines == [{"name": "baz", "optional": None}] |
| 147 | + |
| 148 | + |
| 149 | +def test_stream_sse_with_explicit_response_model(): |
| 150 | + response = client.get("/items/stream-sse") |
| 151 | + assert response.status_code == 200 |
| 152 | + assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 153 | + assert response.text == 'data: {"name":"sse-item","optional":null}\n\n' |
| 154 | + |
| 155 | + |
| 156 | +def test_stream_sse_with_server_sent_event(): |
| 157 | + response = client.get("/items/stream-sse-events") |
| 158 | + assert response.status_code == 200 |
| 159 | + assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 160 | + assert response.text == 'event: custom\ndata: "plain text"\n\n' |
| 161 | + |
| 162 | + |
| 163 | +def test_stream_sse_with_server_sent_event_response_model(): |
| 164 | + response = client.get("/items/stream-sse-server-sent-event-model") |
| 165 | + assert response.status_code == 200 |
| 166 | + assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 167 | + assert response.text == 'event: message\ndata: "sse-explicit"\n\n' |
| 168 | + |
| 169 | + |
| 170 | +def test_non_stream_endpoint_remains_unchanged(): |
| 171 | + response = client.get("/items/non-stream") |
| 172 | + assert response.status_code == 200 |
| 173 | + assert response.json() == {"name": "regular", "optional": None} |
| 174 | + |
| 175 | + |
| 176 | +def test_stream_jsonl_validation_failure_async(): |
| 177 | + with pytest.raises(ResponseValidationError): |
| 178 | + client.get("/items/stream-invalid-async") |
| 179 | + |
| 180 | + |
| 181 | +def test_stream_jsonl_validation_failure_sync(): |
| 182 | + with pytest.raises(ResponseValidationError): |
| 183 | + client.get("/items/stream-invalid-sync") |
| 184 | + |
| 185 | + |
| 186 | +def test_stream_router_with_explicit_response_model(): |
| 187 | + response = client.get("/api/stream-router") |
| 188 | + assert response.status_code == 200 |
| 189 | + assert response.headers["content-type"] == "application/jsonl" |
| 190 | + lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 191 | + assert lines == [{"name": "router-item", "optional": None}] |
| 192 | + |
| 193 | + |
| 194 | +def test_stream_openapi_schemas(): |
| 195 | + response = client.get("/openapi.json") |
| 196 | + assert response.status_code == 200 |
| 197 | + paths = response.json()["paths"] |
| 198 | + |
| 199 | + jsonl_schema = paths["/items/stream-jsonl"]["get"]["responses"]["200"] |
| 200 | + assert jsonl_schema == { |
| 201 | + "description": "Successful Response", |
| 202 | + "content": { |
| 203 | + "application/jsonl": {"itemSchema": {"$ref": "#/components/schemas/Item"}} |
| 204 | + }, |
| 205 | + } |
| 206 | + |
| 207 | + async_schema = paths["/items/stream-async-iterable"]["get"]["responses"]["200"] |
| 208 | + assert async_schema == { |
| 209 | + "description": "Successful Response", |
| 210 | + "content": { |
| 211 | + "application/jsonl": {"itemSchema": {"$ref": "#/components/schemas/Item"}} |
| 212 | + }, |
| 213 | + } |
| 214 | + |
| 215 | + sse_schema = paths["/items/stream-sse"]["get"]["responses"]["200"] |
| 216 | + assert sse_schema == { |
| 217 | + "description": "Successful Response", |
| 218 | + "content": { |
| 219 | + "text/event-stream": { |
| 220 | + "itemSchema": { |
| 221 | + "type": "object", |
| 222 | + "properties": { |
| 223 | + "data": { |
| 224 | + "type": "string", |
| 225 | + "contentMediaType": "application/json", |
| 226 | + "contentSchema": {"$ref": "#/components/schemas/Item"}, |
| 227 | + }, |
| 228 | + "event": {"type": "string"}, |
| 229 | + "id": {"type": "string"}, |
| 230 | + "retry": {"type": "integer", "minimum": 0}, |
| 231 | + }, |
| 232 | + "required": ["data"], |
| 233 | + } |
| 234 | + } |
| 235 | + }, |
| 236 | + } |
| 237 | + |
| 238 | + non_stream_schema = paths["/items/non-stream"]["get"]["responses"]["200"] |
| 239 | + assert non_stream_schema == { |
| 240 | + "description": "Successful Response", |
| 241 | + "content": { |
| 242 | + "application/json": {"schema": {"$ref": "#/components/schemas/Item"}} |
| 243 | + }, |
| 244 | + } |
0 commit comments