Coverage for tests / test_tutorial / test_server_sent_events / test_tutorial003.py: 100%
22 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1import importlib 1abcd
3import pytest 1abcd
4from fastapi.testclient import TestClient 1abcd
5from inline_snapshot import snapshot 1abcd
8@pytest.fixture( 1abcd
9 name="client",
10 params=[
11 pytest.param("tutorial003_py310"),
12 ],
13)
14def get_client(request: pytest.FixtureRequest): 1abcd
15 mod = importlib.import_module(f"docs_src.server_sent_events.{request.param}") 1ijklmno
16 client = TestClient(mod.app) 1ijklmno
17 return client 1ijklmno
20def test_stream_logs(client: TestClient): 1abcd
21 response = client.get("/logs/stream") 1efgh
22 assert response.status_code == 200, response.text 1efgh
23 assert response.headers["content-type"] == "text/event-stream; charset=utf-8" 1efgh
25 data_lines = [ 1efgh
26 line for line in response.text.strip().split("\n") if line.startswith("data: ")
27 ]
28 assert len(data_lines) == 3 1efgh
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" 1efgh
32 assert data_lines[1] == "data: 2025-01-01 DEBUG Connected to database" 1efgh
33 assert data_lines[2] == "data: 2025-01-01 WARN High memory usage detected" 1efgh
36def test_openapi_schema(client: TestClient): 1abcd
37 response = client.get("/openapi.json") 1pqrs
38 assert response.status_code == 200, response.text 1pqrs
39 assert response.json() == snapshot( 1pqrs
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 )