| 1 |
import importlib |
| 2 |
|
| 3 |
import pytest |
| 4 |
from fastapi.testclient import TestClient |
| 5 |
from inline_snapshot import snapshot |
| 6 |
|
| 7 |
|
| 8 |
@pytest.fixture( |
| 9 |
name="client", |
| 10 |
params=[ |
| 11 |
pytest.param("tutorial003_py310"), |
| 12 |
], |
| 13 |
) |
| 14 |
def get_client(request: pytest.FixtureRequest): |
| 15 |
mod = importlib.import_module(f"docs_src.server_sent_events.{request.param}") |
| 16 |
client = TestClient(mod.app) |
| 17 |
return client |
| 18 |
|
| 19 |
|
| 20 |
def test_stream_logs(client: TestClient): |
| 21 |
response = client.get("/logs/stream") |
| 22 |
assert response.status_code == 200, response.text |
| 23 |
assert response.headers["content-type"] == "text/event-stream; charset=utf-8" |
| 24 |
|
| 25 |
data_lines = [ |
| 26 |
line for line in response.text.strip().split("\n") if line.startswith("data: ") |
| 27 |
] |
| 28 |
assert len(data_lines) == 3 |
| 29 |
|
| 30 |
# raw_data is sent without JSON encoding (no quotes around the string) |
| 31 |
assert data_lines[0] == "data: 2025-01-01 INFO Application started" |
| 32 |
assert data_lines[1] == "data: 2025-01-01 DEBUG Connected to database" |
| 33 |
assert data_lines[2] == "data: 2025-01-01 WARN High memory usage detected" |
| 34 |
|
| 35 |
|
| 36 |
def test_openapi_schema(client: TestClient): |
| 37 |
response = client.get("/openapi.json") |
| 38 |
assert response.status_code == 200, response.text |
| 39 |
assert response.json() == snapshot( |
| 40 |
{ |
| 41 |
"openapi": "3.1.0", |
| 42 |
"info": {"title": "FastAPI", "version": "0.1.0"}, |
| 43 |
"paths": { |
| 44 |
"/logs/stream": { |
| 45 |
"get": { |
| 46 |
"summary": "Stream Logs", |
| 47 |
"operationId": "stream_logs_logs_stream_get", |
| 48 |
"responses": { |
| 49 |
"200": { |
| 50 |
"description": "Successful Response", |
| 51 |
"content": { |
| 52 |
"text/event-stream": { |
| 53 |
"itemSchema": { |
| 54 |
"type": "object", |
| 55 |
"properties": { |
| 56 |
"data": {"type": "string"}, |
| 57 |
"event": {"type": "string"}, |
| 58 |
"id": {"type": "string"}, |
| 59 |
"retry": { |
| 60 |
"type": "integer", |
| 61 |
"minimum": 0, |
| 62 |
}, |
| 63 |
}, |
| 64 |
} |
| 65 |
} |
| 66 |
}, |
| 67 |
} |
| 68 |
}, |
| 69 |
} |
| 70 |
} |
| 71 |
}, |
| 72 |
} |
| 73 |
) |