| 1 |
import asyncio |
| 2 |
import time |
| 3 |
from collections.abc import AsyncIterable, Iterable |
| 4 |
|
| 5 |
import fastapi.routing |
| 6 |
import pytest |
| 7 |
from fastapi import APIRouter, FastAPI |
| 8 |
from fastapi.responses import EventSourceResponse |
| 9 |
from fastapi.sse import ServerSentEvent, format_sse_event |
| 10 |
from fastapi.testclient import TestClient |
| 11 |
from pydantic import BaseModel |
| 12 |
|
| 13 |
|
| 14 |
class Item(BaseModel): |
| 15 |
name: str |
| 16 |
description: str | None = None |
| 17 |
|
| 18 |
|
| 19 |
items = [ |
| 20 |
Item(name="Plumbus", description="A multi-purpose household device."), |
| 21 |
Item(name="Portal Gun", description="A portal opening device."), |
| 22 |
Item(name="Meeseeks Box", description="A box that summons a Meeseeks."), |
| 23 |
] |
| 24 |
|
| 25 |
|
| 26 |
app = FastAPI() |
| 27 |
|
| 28 |
|
| 29 |
@app.get("/items/stream", response_class=EventSourceResponse) |
| 30 |
async def sse_items() -> AsyncIterable[Item]: |
| 31 |
for item in items: |
| 32 |
yield item |
| 33 |
|
| 34 |
|
| 35 |
@app.get("/items/stream-sync", response_class=EventSourceResponse) |
| 36 |
def sse_items_sync() -> Iterable[Item]: |
| 37 |
yield from items |
| 38 |
|
| 39 |
|
| 40 |
@app.get("/items/stream-no-annotation", response_class=EventSourceResponse) |
| 41 |
async def sse_items_no_annotation(): |
| 42 |
for item in items: |
| 43 |
yield item |
| 44 |
|
| 45 |
|
| 46 |
@app.get("/items/stream-sync-no-annotation", response_class=EventSourceResponse) |
| 47 |
def sse_items_sync_no_annotation(): |
| 48 |
yield from items |
| 49 |
|
| 50 |
|
| 51 |
@app.get("/items/stream-dict", response_class=EventSourceResponse) |
| 52 |
async def sse_items_dict(): |
| 53 |
for item in items: |
| 54 |
yield {"name": item.name, "description": item.description} |
| 55 |
|
| 56 |
|
| 57 |
@app.get("/items/stream-sse-event", response_class=EventSourceResponse) |
| 58 |
async def sse_items_event(): |
| 59 |
yield ServerSentEvent(data="hello", event="greeting", id="1") |
| 60 |
yield ServerSentEvent(data={"key": "value"}, event="json-data", id="2") |
| 61 |
yield ServerSentEvent(comment="just a comment") |
| 62 |
yield ServerSentEvent(data="retry-test", retry=5000) |
| 63 |
|
| 64 |
|
| 65 |
@app.get("/items/stream-mixed", response_class=EventSourceResponse) |
| 66 |
async def sse_items_mixed() -> AsyncIterable[Item]: |
| 67 |
for item in items: |
| 68 |
yield item |
| 69 |
yield ServerSentEvent(data="custom-event", event="special") |
| 70 |
yield items[1] |
| 71 |
|
| 72 |
|
| 73 |
@app.get("/items/stream-string", response_class=EventSourceResponse) |
| 74 |
async def sse_items_string(): |
| 75 |
yield ServerSentEvent(data="plain text data") |
| 76 |
|
| 77 |
|
| 78 |
@app.post("/items/stream-post", response_class=EventSourceResponse) |
| 79 |
async def sse_items_post() -> AsyncIterable[Item]: |
| 80 |
for item in items: |
| 81 |
yield item |
| 82 |
|
| 83 |
|
| 84 |
@app.get("/items/stream-raw", response_class=EventSourceResponse) |
| 85 |
async def sse_items_raw(): |
| 86 |
yield ServerSentEvent(raw_data="plain text without quotes") |
| 87 |
yield ServerSentEvent(raw_data="<div>html fragment</div>", event="html") |
| 88 |
yield ServerSentEvent(raw_data="cpu,87.3,1709145600", event="csv") |
| 89 |
|
| 90 |
|
| 91 |
router = APIRouter() |
| 92 |
|
| 93 |
|
| 94 |
@router.get("/events", response_class=EventSourceResponse) |
| 95 |
async def stream_events(): |
| 96 |
yield {"msg": "hello"} |
| 97 |
yield {"msg": "world"} |
| 98 |
|
| 99 |
|
| 100 |
@router.get("/events-typed", response_class=EventSourceResponse) |
| 101 |
async def stream_events_typed() -> AsyncIterable[Item]: |
| 102 |
for item in items: |
| 103 |
yield item |
| 104 |
|
| 105 |
|
| 106 |
app.include_router(router, prefix="/api") |
| 107 |
|
| 108 |
|
| 109 |
@pytest.fixture(name="client") |
| 110 |
def client_fixture(): |
| 111 |
with TestClient(app) as c: |
| 112 |
yield c |
| 113 |
|
| 114 |
|
| 115 |
def test_async_generator_with_model(client: TestClient): |
| 116 |
response = client.get("/items/stream") |
| 117 |
assert response.status_code == 200 |
| 118 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 119 |
assert response.headers["cache-control"] == "no-cache" |
| 120 |
assert response.headers["x-accel-buffering"] == "no" |
| 121 |
|
| 122 |
lines = response.text.strip().split("\n") |
| 123 |
data_lines = [line for line in lines if line.startswith("data: ")] |
| 124 |
assert len(data_lines) == 3 |
| 125 |
assert '"name":"Plumbus"' in data_lines[0] or '"name": "Plumbus"' in data_lines[0] |
| 126 |
assert ( |
| 127 |
'"name":"Portal Gun"' in data_lines[1] |
| 128 |
or '"name": "Portal Gun"' in data_lines[1] |
| 129 |
) |
| 130 |
assert ( |
| 131 |
'"name":"Meeseeks Box"' in data_lines[2] |
| 132 |
or '"name": "Meeseeks Box"' in data_lines[2] |
| 133 |
) |
| 134 |
|
| 135 |
|
| 136 |
def test_sync_generator_with_model(client: TestClient): |
| 137 |
response = client.get("/items/stream-sync") |
| 138 |
assert response.status_code == 200 |
| 139 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 140 |
|
| 141 |
data_lines = [ |
| 142 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 143 |
] |
| 144 |
assert len(data_lines) == 3 |
| 145 |
|
| 146 |
|
| 147 |
def test_async_generator_no_annotation(client: TestClient): |
| 148 |
response = client.get("/items/stream-no-annotation") |
| 149 |
assert response.status_code == 200 |
| 150 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 151 |
|
| 152 |
data_lines = [ |
| 153 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 154 |
] |
| 155 |
assert len(data_lines) == 3 |
| 156 |
|
| 157 |
|
| 158 |
def test_sync_generator_no_annotation(client: TestClient): |
| 159 |
response = client.get("/items/stream-sync-no-annotation") |
| 160 |
assert response.status_code == 200 |
| 161 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 162 |
|
| 163 |
data_lines = [ |
| 164 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 165 |
] |
| 166 |
assert len(data_lines) == 3 |
| 167 |
|
| 168 |
|
| 169 |
def test_dict_items(client: TestClient): |
| 170 |
response = client.get("/items/stream-dict") |
| 171 |
assert response.status_code == 200 |
| 172 |
data_lines = [ |
| 173 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 174 |
] |
| 175 |
assert len(data_lines) == 3 |
| 176 |
assert '"name"' in data_lines[0] |
| 177 |
|
| 178 |
|
| 179 |
def test_post_method_sse(client: TestClient): |
| 180 |
"""SSE should work with POST (needed for MCP compatibility).""" |
| 181 |
response = client.post("/items/stream-post") |
| 182 |
assert response.status_code == 200 |
| 183 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 184 |
data_lines = [ |
| 185 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 186 |
] |
| 187 |
assert len(data_lines) == 3 |
| 188 |
|
| 189 |
|
| 190 |
def test_sse_events_with_fields(client: TestClient): |
| 191 |
response = client.get("/items/stream-sse-event") |
| 192 |
assert response.status_code == 200 |
| 193 |
text = response.text |
| 194 |
|
| 195 |
assert "event: greeting\n" in text |
| 196 |
assert 'data: "hello"\n' in text |
| 197 |
assert "id: 1\n" in text |
| 198 |
|
| 199 |
assert "event: json-data\n" in text |
| 200 |
assert "id: 2\n" in text |
| 201 |
assert 'data: {"key": "value"}\n' in text |
| 202 |
|
| 203 |
assert ": just a comment\n" in text |
| 204 |
|
| 205 |
assert "retry: 5000\n" in text |
| 206 |
assert 'data: "retry-test"\n' in text |
| 207 |
|
| 208 |
|
| 209 |
def test_mixed_plain_and_sse_events(client: TestClient): |
| 210 |
response = client.get("/items/stream-mixed") |
| 211 |
assert response.status_code == 200 |
| 212 |
text = response.text |
| 213 |
|
| 214 |
assert "event: special\n" in text |
| 215 |
assert 'data: "custom-event"\n' in text |
| 216 |
assert '"name"' in text |
| 217 |
|
| 218 |
|
| 219 |
def test_string_data_json_encoded(client: TestClient): |
| 220 |
"""Strings are always JSON-encoded (quoted).""" |
| 221 |
response = client.get("/items/stream-string") |
| 222 |
assert response.status_code == 200 |
| 223 |
assert 'data: "plain text data"\n' in response.text |
| 224 |
|
| 225 |
|
| 226 |
def test_server_sent_event_null_id_rejected(): |
| 227 |
with pytest.raises(ValueError, match="null"): |
| 228 |
ServerSentEvent(data="test", id="has\0null") |
| 229 |
|
| 230 |
|
| 231 |
@pytest.mark.parametrize("field_name", ["event", "id"]) |
| 232 |
@pytest.mark.parametrize("value", ["first\nsecond", "first\rsecond", "first\r\nsecond"]) |
| 233 |
def test_server_sent_event_single_line_fields_reject_newlines( |
| 234 |
field_name: str, value: str |
| 235 |
): |
| 236 |
with pytest.raises(ValueError, match=f"SSE '{field_name}' must be a single line"): |
| 237 |
ServerSentEvent(data="test", **{field_name: value}) # ty: ignore[invalid-argument-type] |
| 238 |
|
| 239 |
|
| 240 |
def test_server_sent_event_negative_retry_rejected(): |
| 241 |
with pytest.raises(ValueError): |
| 242 |
ServerSentEvent(data="test", retry=-1) |
| 243 |
|
| 244 |
|
| 245 |
def test_server_sent_event_float_retry_rejected(): |
| 246 |
with pytest.raises(ValueError): |
| 247 |
ServerSentEvent(data="test", retry=1.5) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] |
| 248 |
|
| 249 |
|
| 250 |
def test_raw_data_sent_without_json_encoding(client: TestClient): |
| 251 |
"""raw_data is sent as-is, not JSON-encoded.""" |
| 252 |
response = client.get("/items/stream-raw") |
| 253 |
assert response.status_code == 200 |
| 254 |
text = response.text |
| 255 |
|
| 256 |
# raw_data should appear without JSON quotes |
| 257 |
assert "data: plain text without quotes\n" in text |
| 258 |
# Not JSON-quoted |
| 259 |
assert 'data: "plain text without quotes"' not in text |
| 260 |
|
| 261 |
assert "event: html\n" in text |
| 262 |
assert "data: <div>html fragment</div>\n" in text |
| 263 |
|
| 264 |
assert "event: csv\n" in text |
| 265 |
assert "data: cpu,87.3,1709145600\n" in text |
| 266 |
|
| 267 |
|
| 268 |
def test_data_and_raw_data_mutually_exclusive(): |
| 269 |
"""Cannot set both data and raw_data.""" |
| 270 |
with pytest.raises(ValueError, match="Cannot set both"): |
| 271 |
ServerSentEvent(data="json", raw_data="raw") |
| 272 |
|
| 273 |
|
| 274 |
def test_sse_on_router_included_in_app(client: TestClient): |
| 275 |
response = client.get("/api/events") |
| 276 |
assert response.status_code == 200 |
| 277 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 278 |
data_lines = [ |
| 279 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 280 |
] |
| 281 |
assert len(data_lines) == 2 |
| 282 |
|
| 283 |
|
| 284 |
def test_sse_router_typed_stream(client: TestClient): |
| 285 |
response = client.get("/api/events-typed") |
| 286 |
assert response.status_code == 200 |
| 287 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 288 |
data_lines = [ |
| 289 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 290 |
] |
| 291 |
assert len(data_lines) == 3 |
| 292 |
|
| 293 |
|
| 294 |
def test_sse_router_typed_openapi_schema(client: TestClient): |
| 295 |
"""Typed SSE endpoint on a router should preserve itemSchema with contentSchema.""" |
| 296 |
response = client.get("/openapi.json") |
| 297 |
assert response.status_code == 200 |
| 298 |
paths = response.json()["paths"] |
| 299 |
sse_response = paths["/api/events-typed"]["get"]["responses"]["200"] |
| 300 |
assert sse_response == { |
| 301 |
"description": "Successful Response", |
| 302 |
"content": { |
| 303 |
"text/event-stream": { |
| 304 |
"itemSchema": { |
| 305 |
"type": "object", |
| 306 |
"properties": { |
| 307 |
"data": { |
| 308 |
"type": "string", |
| 309 |
"contentMediaType": "application/json", |
| 310 |
"contentSchema": {"$ref": "#/components/schemas/Item"}, |
| 311 |
}, |
| 312 |
"event": {"type": "string"}, |
| 313 |
"id": {"type": "string"}, |
| 314 |
"retry": {"type": "integer", "minimum": 0}, |
| 315 |
}, |
| 316 |
"required": ["data"], |
| 317 |
} |
| 318 |
} |
| 319 |
}, |
| 320 |
} |
| 321 |
|
| 322 |
|
| 323 |
# Keepalive ping tests |
| 324 |
|
| 325 |
|
| 326 |
keepalive_app = FastAPI() |
| 327 |
|
| 328 |
|
| 329 |
@keepalive_app.get("/slow-async", response_class=EventSourceResponse) |
| 330 |
async def slow_async_stream(): |
| 331 |
yield {"n": 1} |
| 332 |
# Sleep longer than the (monkeypatched) ping interval so a keepalive |
| 333 |
# comment is emitted before the next item. |
| 334 |
await asyncio.sleep(0.3) |
| 335 |
yield {"n": 2} |
| 336 |
|
| 337 |
|
| 338 |
@keepalive_app.get("/slow-sync", response_class=EventSourceResponse) |
| 339 |
def slow_sync_stream(): |
| 340 |
yield {"n": 1} |
| 341 |
time.sleep(0.3) |
| 342 |
yield {"n": 2} |
| 343 |
|
| 344 |
|
| 345 |
def test_keepalive_ping_async(monkeypatch: pytest.MonkeyPatch): |
| 346 |
monkeypatch.setattr(fastapi.routing, "_PING_INTERVAL", 0.05) |
| 347 |
with TestClient(keepalive_app) as c: |
| 348 |
response = c.get("/slow-async") |
| 349 |
assert response.status_code == 200 |
| 350 |
text = response.text |
| 351 |
# The keepalive comment ": ping" should appear between the two data events |
| 352 |
assert ": ping\n" in text |
| 353 |
data_lines = [line for line in text.split("\n") if line.startswith("data: ")] |
| 354 |
assert len(data_lines) == 2 |
| 355 |
|
| 356 |
|
| 357 |
def test_keepalive_ping_sync(monkeypatch: pytest.MonkeyPatch): |
| 358 |
monkeypatch.setattr(fastapi.routing, "_PING_INTERVAL", 0.05) |
| 359 |
with TestClient(keepalive_app) as c: |
| 360 |
response = c.get("/slow-sync") |
| 361 |
assert response.status_code == 200 |
| 362 |
text = response.text |
| 363 |
assert ": ping\n" in text |
| 364 |
data_lines = [line for line in text.split("\n") if line.startswith("data: ")] |
| 365 |
assert len(data_lines) == 2 |
| 366 |
|
| 367 |
|
| 368 |
def test_no_keepalive_when_fast(client: TestClient): |
| 369 |
"""No keepalive comment when items arrive quickly.""" |
| 370 |
response = client.get("/items/stream") |
| 371 |
assert response.status_code == 200 |
| 372 |
# KEEPALIVE_COMMENT is ": ping\n\n". |
| 373 |
assert ": ping\n" not in response.text |
| 374 |
|
| 375 |
|
| 376 |
@pytest.mark.parametrize( |
| 377 |
("data", "expected_result"), |
| 378 |
[ |
| 379 |
("Hello\n", b"data: Hello\ndata: \n\n"), |
| 380 |
("Hello\n\n", b"data: Hello\ndata: \ndata: \n\n"), |
| 381 |
("\n", b"data: \ndata: \n\n"), |
| 382 |
("Hello\r\nWorld", b"data: Hello\ndata: World\n\n"), |
| 383 |
("Hello\rWorld", b"data: Hello\ndata: World\n\n"), |
| 384 |
("A\u2028B", "data: A\u2028B\n\n".encode()), |
| 385 |
("A\vB", b"data: A\x0bB\n\n"), |
| 386 |
("", b"data: \n\n"), |
| 387 |
], |
| 388 |
) |
| 389 |
def test_format_sse_event_splitlines_behavior_in_data( |
| 390 |
data: str, expected_result: bytes |
| 391 |
) -> None: |
| 392 |
assert format_sse_event(data_str=data) == expected_result |
| 393 |
|
| 394 |
|
| 395 |
def test_format_sse_event_splitlines_behavior_in_comment(): |
| 396 |
assert format_sse_event(comment="hi\n") == b": hi\n: \n\n" |
| 397 |
|
| 398 |
|
| 399 |
# default_response_class tests |
| 400 |
|
| 401 |
|
| 402 |
sse_schema_response = { |
| 403 |
"description": "Successful Response", |
| 404 |
"content": { |
| 405 |
"text/event-stream": { |
| 406 |
"itemSchema": { |
| 407 |
"type": "object", |
| 408 |
"properties": { |
| 409 |
"data": { |
| 410 |
"type": "string", |
| 411 |
"contentMediaType": "application/json", |
| 412 |
"contentSchema": {"$ref": "#/components/schemas/Item"}, |
| 413 |
}, |
| 414 |
"event": {"type": "string"}, |
| 415 |
"id": {"type": "string"}, |
| 416 |
"retry": {"type": "integer", "minimum": 0}, |
| 417 |
}, |
| 418 |
"required": ["data"], |
| 419 |
} |
| 420 |
} |
| 421 |
}, |
| 422 |
} |
| 423 |
|
| 424 |
|
| 425 |
# default_response_class on app |
| 426 |
|
| 427 |
default_app_app = FastAPI(default_response_class=EventSourceResponse) |
| 428 |
default_app_router = APIRouter() |
| 429 |
|
| 430 |
|
| 431 |
@default_app_router.get("/stream") |
| 432 |
async def default_app_stream() -> AsyncIterable[Item]: |
| 433 |
for item in items: |
| 434 |
yield item |
| 435 |
|
| 436 |
|
| 437 |
default_app_app.include_router(default_app_router, prefix="/api") |
| 438 |
|
| 439 |
|
| 440 |
def test_default_response_class_on_app_stream(): |
| 441 |
with TestClient(default_app_app) as client: |
| 442 |
response = client.get("/api/stream") |
| 443 |
assert response.status_code == 200 |
| 444 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 445 |
data_lines = [ |
| 446 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 447 |
] |
| 448 |
assert len(data_lines) == 3 |
| 449 |
|
| 450 |
|
| 451 |
def test_default_response_class_on_app_openapi_schema(): |
| 452 |
assert ( |
| 453 |
default_app_app.openapi()["paths"]["/api/stream"]["get"]["responses"]["200"] |
| 454 |
== sse_schema_response |
| 455 |
) |
| 456 |
|
| 457 |
|
| 458 |
# default_response_class on parent router |
| 459 |
|
| 460 |
default_parent_app = FastAPI() |
| 461 |
parent_router = APIRouter(default_response_class=EventSourceResponse) |
| 462 |
child_router = APIRouter() |
| 463 |
|
| 464 |
|
| 465 |
@child_router.get("/stream") |
| 466 |
async def default_parent_stream() -> AsyncIterable[Item]: |
| 467 |
for item in items: |
| 468 |
yield item |
| 469 |
|
| 470 |
|
| 471 |
parent_router.include_router(child_router) |
| 472 |
default_parent_app.include_router(parent_router, prefix="/api") |
| 473 |
|
| 474 |
|
| 475 |
def test_default_response_class_on_parent_router_stream(): |
| 476 |
with TestClient(default_parent_app) as client: |
| 477 |
response = client.get("/api/stream") |
| 478 |
assert response.status_code == 200 |
| 479 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 480 |
data_lines = [ |
| 481 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 482 |
] |
| 483 |
assert len(data_lines) == 3 |
| 484 |
|
| 485 |
|
| 486 |
def test_default_response_class_on_parent_router_openapi_schema(): |
| 487 |
assert ( |
| 488 |
default_parent_app.openapi()["paths"]["/api/stream"]["get"]["responses"]["200"] |
| 489 |
== sse_schema_response |
| 490 |
) |