| 1 |
import json |
| 2 |
from typing import AsyncIterable, Iterable # noqa: UP035 to test coverage |
| 3 |
|
| 4 |
from fastapi import APIRouter, FastAPI |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
from pydantic import BaseModel |
| 7 |
|
| 8 |
|
| 9 |
class Item(BaseModel): |
| 10 |
name: str |
| 11 |
optional: str | None = None |
| 12 |
|
| 13 |
|
| 14 |
app = FastAPI() |
| 15 |
|
| 16 |
|
| 17 |
@app.get("/items/stream-bare-async") |
| 18 |
async def stream_bare_async() -> AsyncIterable: |
| 19 |
yield {"name": "foo"} |
| 20 |
|
| 21 |
|
| 22 |
@app.get("/items/stream-bare-sync") |
| 23 |
def stream_bare_sync() -> Iterable: |
| 24 |
yield {"name": "bar"} |
| 25 |
|
| 26 |
|
| 27 |
router = APIRouter() |
| 28 |
|
| 29 |
|
| 30 |
@router.get("/events-jsonl", response_model_exclude_none=True) |
| 31 |
async def stream_events_jsonl() -> AsyncIterable[Item]: |
| 32 |
yield Item(name="foo") |
| 33 |
|
| 34 |
|
| 35 |
app.include_router(router, prefix="/api") |
| 36 |
|
| 37 |
client = TestClient(app) |
| 38 |
|
| 39 |
|
| 40 |
def test_stream_bare_async_iterable(): |
| 41 |
response = client.get("/items/stream-bare-async") |
| 42 |
assert response.status_code == 200 |
| 43 |
assert response.headers["content-type"] == "application/jsonl" |
| 44 |
lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 45 |
assert lines == [{"name": "foo"}] |
| 46 |
|
| 47 |
|
| 48 |
def test_stream_bare_sync_iterable(): |
| 49 |
response = client.get("/items/stream-bare-sync") |
| 50 |
assert response.status_code == 200 |
| 51 |
assert response.headers["content-type"] == "application/jsonl" |
| 52 |
lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 53 |
assert lines == [{"name": "bar"}] |
| 54 |
|
| 55 |
|
| 56 |
def test_jsonl_router_typed_stream(): |
| 57 |
response = client.get("/api/events-jsonl") |
| 58 |
assert response.status_code == 200 |
| 59 |
assert response.headers["content-type"] == "application/jsonl" |
| 60 |
lines = [json.loads(line) for line in response.text.strip().splitlines()] |
| 61 |
assert lines == [{"name": "foo"}] |
| 62 |
|
| 63 |
|
| 64 |
def test_jsonl_router_typed_openapi_schema(): |
| 65 |
response = client.get("/openapi.json") |
| 66 |
assert response.status_code == 200 |
| 67 |
paths = response.json()["paths"] |
| 68 |
jsonl_response = paths["/api/events-jsonl"]["get"]["responses"]["200"] |
| 69 |
assert jsonl_response == { |
| 70 |
"description": "Successful Response", |
| 71 |
"content": { |
| 72 |
"application/jsonl": {"itemSchema": {"$ref": "#/components/schemas/Item"}} |
| 73 |
}, |
| 74 |
} |