mirror of
https://github.com/fastapi/fastapi.git
synced 2026-09-09 20:07:23 -04:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
628663f4f8 | ||
|
|
0b54fd0027 | ||
|
|
e92a0dc3ce | ||
|
|
6215d8a6f3 | ||
|
|
12242c4fba | ||
|
|
70a8f3dd03 | ||
|
|
4f0152c028 | ||
|
|
5f255058f4 | ||
|
|
76e2c833b5 | ||
|
|
0f3e7bd682 | ||
|
|
31ce3cb8d7 | ||
|
|
4a01c7f1a5 | ||
|
|
d6537f774b | ||
|
|
0f3d3b2f9f | ||
|
|
584efa0981 | ||
|
|
65e42bd5ec | ||
|
|
9db320278c | ||
|
|
d3cd6054e4 | ||
|
|
19a461a19e | ||
|
|
0a4cd1c78f | ||
|
|
64ae6c977c | ||
|
|
7d123d9537 |
No files matched your search
@@ -201,6 +201,78 @@ jobs:
|
||||
mode: memory
|
||||
run: uv run --no-sync pytest tests/memory_benchmarks --codspeed
|
||||
|
||||
regression-test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out the pull request
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: pr
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- name: Find changed tests
|
||||
if: github.event_name == 'pull_request'
|
||||
id: changed-tests
|
||||
working-directory: pr
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
git diff --name-only --diff-filter=AM -z "$BASE_SHA" "$HEAD_SHA" -- tests \
|
||||
| while IFS= read -r -d '' file; do
|
||||
case "$(basename "$file")" in
|
||||
test_*.py) printf '%s\0' "$file" ;;
|
||||
esac
|
||||
done > "$RUNNER_TEMP/changed-tests"
|
||||
if [ -s "$RUNNER_TEMP/changed-tests" ]; then
|
||||
echo "found=true" >> "$GITHUB_OUTPUT"
|
||||
git diff --binary "$BASE_SHA" "$HEAD_SHA" -- tests \
|
||||
> "$RUNNER_TEMP/tests.patch"
|
||||
else
|
||||
echo "found=false" >> "$GITHUB_OUTPUT"
|
||||
echo "No added or modified test files; regression proof is not applicable."
|
||||
fi
|
||||
- name: Check out the base revision
|
||||
if: steps.changed-tests.outputs.found == 'true'
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.sha }}
|
||||
path: base
|
||||
persist-credentials: false
|
||||
- name: Set up Python
|
||||
if: steps.changed-tests.outputs.found == 'true'
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version-file: "base/.python-version"
|
||||
- name: Setup uv
|
||||
if: steps.changed-tests.outputs.found == 'true'
|
||||
uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0
|
||||
with:
|
||||
# Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum.
|
||||
# See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837
|
||||
version: "0.11.18"
|
||||
enable-cache: true
|
||||
- name: Run the changed tests against the base code
|
||||
if: steps.changed-tests.outputs.found == 'true'
|
||||
working-directory: base
|
||||
run: |
|
||||
git apply "$RUNNER_TEMP/tests.patch"
|
||||
uv sync --locked --no-dev --group tests --extra all
|
||||
set +e
|
||||
xargs -0 uv run --no-sync pytest -- < "$RUNNER_TEMP/changed-tests"
|
||||
status=$?
|
||||
set -e
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo "::warning::The changed tests already pass on the base revision. Check whether the fix is still needed."
|
||||
echo "### Regression proof: base already passes :warning:" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The changed tests pass without the pull request's code changes." >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "The changed tests fail on the base revision as expected (pytest exit code $status)."
|
||||
echo "### Regression proof: base fails as expected :white_check_mark:" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
coverage-combine:
|
||||
needs:
|
||||
- test
|
||||
@@ -253,6 +325,7 @@ jobs:
|
||||
- test
|
||||
- coverage-combine
|
||||
- benchmark
|
||||
- regression-test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Server-Sent Events - `EventSourceResponse` and `ServerSentEvent`
|
||||
|
||||
To stream Server-Sent Events (SSE), use `yield` in your *path operation function* and set `response_class=EventSourceResponse`.
|
||||
|
||||
If you need to set SSE fields like `event`, `id`, `retry`, or `comment`, you can `yield` `ServerSentEvent` objects instead of plain data.
|
||||
|
||||
Read more about it in the [FastAPI docs for Server-Sent Events (SSE)](https://fastapi.tiangolo.com/tutorial/server-sent-events/).
|
||||
|
||||
You can import them directly from `fastapi.sse`:
|
||||
|
||||
```python
|
||||
from fastapi.sse import EventSourceResponse, ServerSentEvent
|
||||
```
|
||||
|
||||
::: fastapi.sse.EventSourceResponse
|
||||
|
||||
::: fastapi.sse.ServerSentEvent
|
||||
@@ -7,6 +7,41 @@ hide:
|
||||
|
||||
## Latest Changes
|
||||
|
||||
## 0.140.13 (2026-07-28)
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix `status_code` being ignored for SSE and JSONL streaming endpoints. PR [#15937](https://github.com/fastapi/fastapi/pull/15937) by [@SAURABHSALVE](https://github.com/SAURABHSALVE).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Fix `format_sse_event` docstring rendering of `\n\n` terminator. PR [#15613](https://github.com/fastapi/fastapi/pull/15613) by [@AshNicolus](https://github.com/AshNicolus).
|
||||
* 📝 Add API reference page for fastapi.sse. PR [#15930](https://github.com/fastapi/fastapi/pull/15930) by [@SAURABHSALVE](https://github.com/SAURABHSALVE).
|
||||
|
||||
## 0.140.12 (2026-07-28)
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix line splitting in `format_sse_event` to comply with SSE spec. PR [#15515](https://github.com/fastapi/fastapi/pull/15515) by [@Zawwarsami16](https://github.com/Zawwarsami16).
|
||||
|
||||
## 0.140.11 (2026-07-28)
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix `response_model_*` params ignored for non-generator endpoints with `Iterable[..]` return type. PR [#15093](https://github.com/fastapi/fastapi/pull/15093) by [@YuriiMotov](https://github.com/YuriiMotov).
|
||||
|
||||
## 0.140.10 (2026-07-28)
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix handling sequences with nested Annotated types. PR [#14874](https://github.com/fastapi/fastapi/pull/14874) by [@YuriiMotov](https://github.com/YuriiMotov).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🐛 Accept any base test failure as regression. PR [#16092](https://github.com/fastapi/fastapi/pull/16092) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🐛 Preserve pytest exit code in regression check. PR [#16091](https://github.com/fastapi/fastapi/pull/16091) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✅ Test PR regressions against base code. PR [#16090](https://github.com/fastapi/fastapi/pull/16090) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.140.9 (2026-07-28)
|
||||
|
||||
### Fixes
|
||||
|
||||
@@ -211,6 +211,7 @@ nav:
|
||||
- reference/httpconnection.md
|
||||
- reference/response.md
|
||||
- reference/responses.md
|
||||
- reference/sse.md
|
||||
- reference/middleware.md
|
||||
- "":
|
||||
- reference/openapi/index.md
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
||||
|
||||
__version__ = "0.140.9"
|
||||
__version__ = "0.140.13"
|
||||
|
||||
from starlette import status as status
|
||||
|
||||
|
||||
@@ -63,6 +63,10 @@ def _annotation_is_sequence(annotation: type[Any] | None) -> bool:
|
||||
|
||||
def field_annotation_is_sequence(annotation: type[Any] | None) -> bool:
|
||||
origin = get_origin(annotation)
|
||||
|
||||
if origin is Annotated:
|
||||
return field_annotation_is_sequence(get_args(annotation)[0])
|
||||
|
||||
if origin is Union or origin is UnionType:
|
||||
for arg in get_args(annotation):
|
||||
if field_annotation_is_sequence(arg):
|
||||
@@ -108,6 +112,10 @@ def field_annotation_is_scalar(annotation: Any) -> bool:
|
||||
|
||||
def field_annotation_is_scalar_sequence(annotation: type[Any] | None) -> bool:
|
||||
origin = get_origin(annotation)
|
||||
|
||||
if origin is Annotated:
|
||||
return field_annotation_is_scalar_sequence(get_args(annotation)[0])
|
||||
|
||||
if origin is Union or origin is UnionType:
|
||||
at_least_one_scalar_sequence = False
|
||||
for arg in get_args(annotation):
|
||||
|
||||
+51
-45
@@ -630,10 +630,13 @@ def get_request_handler(
|
||||
_sse_with_checkpoints(sse_receive_stream)
|
||||
)
|
||||
|
||||
response_args = _build_response_args(
|
||||
status_code=status_code, solved_result=solved_result
|
||||
)
|
||||
response = StreamingResponse(
|
||||
sse_stream_content,
|
||||
media_type="text/event-stream",
|
||||
background=solved_result.background_tasks,
|
||||
**response_args,
|
||||
)
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
# For Nginx proxies to not buffer server sent events
|
||||
@@ -666,10 +669,13 @@ def get_request_handler(
|
||||
|
||||
jsonl_stream_content = _sync_stream_jsonl()
|
||||
|
||||
response_args = _build_response_args(
|
||||
status_code=status_code, solved_result=solved_result
|
||||
)
|
||||
response = StreamingResponse(
|
||||
jsonl_stream_content,
|
||||
media_type="application/jsonl",
|
||||
background=solved_result.background_tasks,
|
||||
**response_args,
|
||||
)
|
||||
response.headers.raw.extend(solved_result.response.headers.raw)
|
||||
elif _is_async_gen_callable(dependant.call) or _is_gen_callable(
|
||||
@@ -987,28 +993,6 @@ def _populate_api_route_state(
|
||||
route.path = path
|
||||
route.endpoint = endpoint
|
||||
route.stream_item_type = stream_item_type
|
||||
if isinstance(response_model, DefaultPlaceholder):
|
||||
return_annotation = get_typed_return_annotation(endpoint)
|
||||
if lenient_issubclass(return_annotation, Response):
|
||||
response_model = None
|
||||
else:
|
||||
stream_item = get_stream_item_type(return_annotation)
|
||||
if stream_item is not None:
|
||||
# Extract item type for JSONL or SSE streaming when
|
||||
# response_class is DefaultPlaceholder (JSONL) or
|
||||
# EventSourceResponse (SSE).
|
||||
# ServerSentEvent is excluded: it's a transport
|
||||
# wrapper, not a data model, so it shouldn't feed
|
||||
# into validation or OpenAPI schema generation.
|
||||
if (
|
||||
isinstance(response_class, DefaultPlaceholder)
|
||||
or lenient_issubclass(response_class, EventSourceResponse)
|
||||
) and not lenient_issubclass(stream_item, ServerSentEvent):
|
||||
route.stream_item_type = stream_item
|
||||
response_model = None
|
||||
else:
|
||||
response_model = return_annotation
|
||||
route.response_model = response_model
|
||||
route.summary = summary
|
||||
route.response_description = response_description
|
||||
route.deprecated = deprecated
|
||||
@@ -1044,27 +1028,6 @@ def _populate_api_route_state(
|
||||
if isinstance(status_code, IntEnum):
|
||||
status_code = int(status_code)
|
||||
route.status_code = status_code
|
||||
if route.response_model:
|
||||
assert is_body_allowed_for_status_code(status_code), (
|
||||
f"Status code {status_code} must not have a response body"
|
||||
)
|
||||
response_name = "Response_" + route.unique_id
|
||||
route.response_field = create_model_field(
|
||||
name=response_name,
|
||||
type_=route.response_model,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.response_field = None
|
||||
if route.stream_item_type:
|
||||
stream_item_name = "StreamItem_" + route.unique_id
|
||||
route.stream_item_field = create_model_field(
|
||||
name=stream_item_name,
|
||||
type_=route.stream_item_type,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.stream_item_field = None
|
||||
route.dependencies = list(dependencies or [])
|
||||
route.description = description or inspect.cleandoc(route.endpoint.__doc__ or "")
|
||||
# if a "form feed" character (page break) is found in the description text,
|
||||
@@ -1113,6 +1076,49 @@ def _populate_api_route_state(
|
||||
route.is_json_stream = is_generator and isinstance(
|
||||
response_class, DefaultPlaceholder
|
||||
)
|
||||
if isinstance(response_model, DefaultPlaceholder):
|
||||
return_annotation = get_typed_return_annotation(endpoint)
|
||||
if lenient_issubclass(return_annotation, Response):
|
||||
response_model = None
|
||||
else:
|
||||
stream_item = get_stream_item_type(return_annotation)
|
||||
if stream_item is not None and is_generator:
|
||||
# Extract item type for JSONL or SSE streaming for
|
||||
# generator endpoints when response_class is
|
||||
# DefaultPlaceholder (JSONL) or EventSourceResponse (SSE).
|
||||
# ServerSentEvent is excluded: it's a transport
|
||||
# wrapper, not a data model, so it shouldn't feed
|
||||
# into validation or OpenAPI schema generation.
|
||||
if (
|
||||
isinstance(response_class, DefaultPlaceholder)
|
||||
or lenient_issubclass(response_class, EventSourceResponse)
|
||||
) and not lenient_issubclass(stream_item, ServerSentEvent):
|
||||
route.stream_item_type = stream_item
|
||||
response_model = None
|
||||
else:
|
||||
response_model = return_annotation
|
||||
route.response_model = response_model
|
||||
if route.response_model:
|
||||
assert is_body_allowed_for_status_code(status_code), (
|
||||
f"Status code {status_code} must not have a response body"
|
||||
)
|
||||
response_name = "Response_" + route.unique_id
|
||||
route.response_field = create_model_field(
|
||||
name=response_name,
|
||||
type_=route.response_model,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.response_field = None
|
||||
if route.stream_item_type:
|
||||
stream_item_name = "StreamItem_" + route.unique_id
|
||||
route.stream_item_field = create_model_field(
|
||||
name=stream_item_name,
|
||||
type_=route.stream_item_type,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.stream_item_field = None
|
||||
|
||||
|
||||
class APIRoute(routing.Route):
|
||||
|
||||
+9
-3
@@ -156,6 +156,12 @@ class ServerSentEvent(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
def _split_sse_lines(value: str) -> list[str]:
|
||||
# Split on SSE-spec line terminators only (\n, \r\n, \r), preserving
|
||||
# trailing empty strings.
|
||||
return value.replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
||||
|
||||
|
||||
def format_sse_event(
|
||||
*,
|
||||
data_str: Annotated[
|
||||
@@ -201,19 +207,19 @@ def format_sse_event(
|
||||
) -> bytes:
|
||||
"""Build SSE wire-format bytes from **pre-serialized** data.
|
||||
|
||||
The result always ends with `\n\n` (the event terminator).
|
||||
The result always ends with `\\n\\n` (the event terminator).
|
||||
"""
|
||||
lines: list[str] = []
|
||||
|
||||
if comment is not None:
|
||||
for line in comment.splitlines():
|
||||
for line in _split_sse_lines(comment):
|
||||
lines.append(f": {line}")
|
||||
|
||||
if event is not None:
|
||||
lines.append(f"event: {event}")
|
||||
|
||||
if data_str is not None:
|
||||
for line in data_str.splitlines():
|
||||
for line in _split_sse_lines(data_str):
|
||||
lines.append(f"data: {line}")
|
||||
|
||||
if id is not None:
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
from typing import Annotated
|
||||
|
||||
from dirty_equals import IsList
|
||||
from fastapi import FastAPI, Query
|
||||
from fastapi.testclient import TestClient
|
||||
from inline_snapshot import snapshot
|
||||
from pydantic import Field
|
||||
|
||||
MaxSizedSet = Annotated[set[str], Field(max_length=3)]
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root(foo: Annotated[MaxSizedSet | None, Query()] = None):
|
||||
return {"foo": foo}
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_endpoint_none():
|
||||
response = client.get("/")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"foo": None}
|
||||
|
||||
|
||||
def test_endpoint_valid():
|
||||
response = client.get("/", params={"foo": ["a", "b"]})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"foo": IsList("a", "b", check_order=False)}
|
||||
|
||||
|
||||
def test_endpoint_too_long():
|
||||
response = client.get("/", params={"foo": ["a", "b", "c", "d"]})
|
||||
assert response.status_code == 422
|
||||
assert response.json() == snapshot(
|
||||
{
|
||||
"detail": [
|
||||
{
|
||||
"type": "too_long",
|
||||
"loc": ["query", "foo"],
|
||||
"msg": "Set should have at most 3 items after validation, not more",
|
||||
"input": IsList("a", "b", "c", "d", check_order=False),
|
||||
"ctx": {
|
||||
"actual_length": None,
|
||||
"field_type": "Set",
|
||||
"max_length": 3,
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_openapi():
|
||||
assert app.openapi() == snapshot(
|
||||
{
|
||||
"components": {
|
||||
"schemas": {
|
||||
"HTTPValidationError": {
|
||||
"properties": {
|
||||
"detail": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ValidationError"
|
||||
},
|
||||
"title": "Detail",
|
||||
"type": "array",
|
||||
},
|
||||
},
|
||||
"title": "HTTPValidationError",
|
||||
"type": "object",
|
||||
},
|
||||
"ValidationError": {
|
||||
"properties": {
|
||||
"ctx": {"title": "Context", "type": "object"},
|
||||
"input": {"title": "Input"},
|
||||
"loc": {
|
||||
"items": {
|
||||
"anyOf": [{"type": "string"}, {"type": "integer"}],
|
||||
},
|
||||
"title": "Location",
|
||||
"type": "array",
|
||||
},
|
||||
"msg": {"title": "Message", "type": "string"},
|
||||
"type": {"title": "Error Type", "type": "string"},
|
||||
},
|
||||
"required": ["loc", "msg", "type"],
|
||||
"title": "ValidationError",
|
||||
"type": "object",
|
||||
},
|
||||
},
|
||||
},
|
||||
"info": {
|
||||
"title": "FastAPI",
|
||||
"version": "0.1.0",
|
||||
},
|
||||
"openapi": "3.1.0",
|
||||
"paths": {
|
||||
"/": {
|
||||
"get": {
|
||||
"operationId": "read_root__get",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "foo",
|
||||
"required": False,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {"type": "string"},
|
||||
"maxItems": 3,
|
||||
"type": "array",
|
||||
"uniqueItems": True,
|
||||
},
|
||||
{"type": "null"},
|
||||
],
|
||||
"title": "Foo",
|
||||
},
|
||||
},
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {"application/json": {"schema": {}}},
|
||||
"description": "Successful Response",
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError",
|
||||
},
|
||||
},
|
||||
},
|
||||
"description": "Validation Error",
|
||||
},
|
||||
},
|
||||
"summary": "Read Root",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,3 +1,5 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import BaseModel
|
||||
@@ -65,6 +67,21 @@ def get_exclude_unset_none() -> ModelDefaults:
|
||||
return ModelDefaults(x=None, y="y")
|
||||
|
||||
|
||||
@app.get("/iterable_exclude_unset", response_model_exclude_unset=True)
|
||||
def get_iterable_exclude_unset() -> Iterable[ModelDefaults]:
|
||||
return [ModelDefaults(x=None, y="y")]
|
||||
|
||||
|
||||
@app.get("/iterable_exclude_defaults", response_model_exclude_defaults=True)
|
||||
def get_iterable_exclude_defaults() -> Iterable[ModelDefaults]:
|
||||
return [ModelDefaults(x=None, y="y")]
|
||||
|
||||
|
||||
@app.get("/iterable_exclude_none", response_model_exclude_none=True)
|
||||
def get_iterable_exclude_none() -> Iterable[ModelDefaults]:
|
||||
return [ModelDefaults(x=None, y="y")]
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
@@ -91,3 +108,18 @@ def test_return_exclude_none():
|
||||
def test_return_exclude_unset_none():
|
||||
response = client.get("/exclude_unset_none")
|
||||
assert response.json() == {"y": "y"}
|
||||
|
||||
|
||||
def test_return_iterable_exclude_unset():
|
||||
response = client.get("/iterable_exclude_unset")
|
||||
assert response.json() == [{"x": None, "y": "y"}]
|
||||
|
||||
|
||||
def test_return_iterable_exclude_defaults():
|
||||
response = client.get("/iterable_exclude_defaults")
|
||||
assert response.json() == [{}]
|
||||
|
||||
|
||||
def test_return_iterable_exclude_none():
|
||||
response = client.get("/iterable_exclude_none")
|
||||
assert response.json() == [{"y": "y", "z": "z"}]
|
||||
+24
-1
@@ -6,7 +6,7 @@ import fastapi.routing
|
||||
import pytest
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.responses import EventSourceResponse
|
||||
from fastapi.sse import ServerSentEvent
|
||||
from fastapi.sse import ServerSentEvent, format_sse_event
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -373,6 +373,29 @@ def test_no_keepalive_when_fast(client: TestClient):
|
||||
assert ": ping\n" not in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("data", "expected_result"),
|
||||
[
|
||||
("Hello\n", b"data: Hello\ndata: \n\n"),
|
||||
("Hello\n\n", b"data: Hello\ndata: \ndata: \n\n"),
|
||||
("\n", b"data: \ndata: \n\n"),
|
||||
("Hello\r\nWorld", b"data: Hello\ndata: World\n\n"),
|
||||
("Hello\rWorld", b"data: Hello\ndata: World\n\n"),
|
||||
("A\u2028B", "data: A\u2028B\n\n".encode()),
|
||||
("A\vB", b"data: A\x0bB\n\n"),
|
||||
("", b"data: \n\n"),
|
||||
],
|
||||
)
|
||||
def test_format_sse_event_splitlines_behavior_in_data(
|
||||
data: str, expected_result: bytes
|
||||
) -> None:
|
||||
assert format_sse_event(data_str=data) == expected_result
|
||||
|
||||
|
||||
def test_format_sse_event_splitlines_behavior_in_comment():
|
||||
assert format_sse_event(comment="hi\n") == b": hi\n: \n\n"
|
||||
|
||||
|
||||
# default_response_class tests
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
from collections.abc import AsyncIterable
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends, FastAPI, Response
|
||||
from fastapi.responses import EventSourceResponse, StreamingResponse
|
||||
from fastapi.testclient import TestClient
|
||||
from inline_snapshot import snapshot
|
||||
|
||||
SSE_RESPONSE = {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "SSE stream item",
|
||||
},
|
||||
},
|
||||
"event": {"type": "string"},
|
||||
"id": {"type": "string"},
|
||||
"retry": {"type": "integer", "minimum": 0},
|
||||
},
|
||||
"required": ["data"],
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
JSONL_RESPONSE = {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/jsonl": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "JSONL stream item",
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
def set_accepted(response: Response) -> None:
|
||||
response.status_code = 202
|
||||
|
||||
|
||||
@app.post("/sse", response_class=EventSourceResponse, status_code=201)
|
||||
async def sse() -> AsyncIterable[dict[str, str]]:
|
||||
yield {"message": "created"}
|
||||
|
||||
|
||||
@app.post("/jsonl", status_code=201)
|
||||
async def jsonl() -> AsyncIterable[dict[str, str]]:
|
||||
yield {"message": "created"}
|
||||
|
||||
|
||||
@app.post("/raw", response_class=StreamingResponse, status_code=201)
|
||||
async def raw() -> AsyncIterable[str]:
|
||||
yield "accepted"
|
||||
|
||||
|
||||
@app.post(
|
||||
"/sse-dependency",
|
||||
response_class=EventSourceResponse,
|
||||
responses={202: SSE_RESPONSE},
|
||||
)
|
||||
async def sse_dependency(
|
||||
accepted: None = Depends(set_accepted),
|
||||
) -> AsyncIterable[dict[str, str]]:
|
||||
yield {"message": "accepted"}
|
||||
|
||||
|
||||
@app.post("/jsonl-dependency", responses={202: JSONL_RESPONSE})
|
||||
async def jsonl_dependency(
|
||||
accepted: None = Depends(set_accepted),
|
||||
) -> AsyncIterable[dict[str, str]]:
|
||||
yield {"message": "accepted"}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/raw-dependency",
|
||||
response_class=StreamingResponse,
|
||||
responses={202: {"description": "Accepted"}},
|
||||
)
|
||||
async def raw_dependency(
|
||||
accepted: None = Depends(set_accepted),
|
||||
) -> AsyncIterable[str]:
|
||||
yield "accepted"
|
||||
|
||||
|
||||
@app.post(
|
||||
"/sse-dependency-override",
|
||||
response_class=EventSourceResponse,
|
||||
status_code=201,
|
||||
responses={202: SSE_RESPONSE},
|
||||
)
|
||||
async def sse_dependency_override(
|
||||
accepted: None = Depends(set_accepted),
|
||||
) -> AsyncIterable[dict[str, str]]:
|
||||
yield {"message": "overridden"}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/jsonl-dependency-override",
|
||||
status_code=201,
|
||||
responses={202: JSONL_RESPONSE},
|
||||
)
|
||||
async def jsonl_dependency_override(
|
||||
accepted: None = Depends(set_accepted),
|
||||
) -> AsyncIterable[dict[str, str]]:
|
||||
yield {"message": "overridden"}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/raw-dependency-override",
|
||||
response_class=StreamingResponse,
|
||||
status_code=201,
|
||||
responses={202: {"description": "Accepted"}},
|
||||
)
|
||||
async def raw_dependency_override(
|
||||
accepted: None = Depends(set_accepted),
|
||||
) -> AsyncIterable[str]:
|
||||
yield "overridden"
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path,expected_status_code",
|
||||
[
|
||||
("/sse", 201),
|
||||
("/jsonl", 201),
|
||||
("/raw", 201),
|
||||
("/sse-dependency", 202),
|
||||
("/jsonl-dependency", 202),
|
||||
("/raw-dependency", 202),
|
||||
("/sse-dependency-override", 202),
|
||||
("/jsonl-dependency-override", 202),
|
||||
("/raw-dependency-override", 202),
|
||||
],
|
||||
)
|
||||
def test_status_code(path: str, expected_status_code: int) -> None:
|
||||
response = client.post(path)
|
||||
assert response.status_code == expected_status_code
|
||||
|
||||
|
||||
def test_openapi() -> None:
|
||||
openapi = app.openapi()
|
||||
|
||||
assert openapi == snapshot(
|
||||
{
|
||||
"openapi": "3.1.0",
|
||||
"info": {"title": "FastAPI", "version": "0.1.0"},
|
||||
"paths": {
|
||||
"/sse": {
|
||||
"post": {
|
||||
"summary": "Sse",
|
||||
"operationId": "sse_sse_post",
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": "Streamitem Sse Sse Post",
|
||||
},
|
||||
},
|
||||
"event": {"type": "string"},
|
||||
"id": {"type": "string"},
|
||||
"retry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
},
|
||||
},
|
||||
"required": ["data"],
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
"/jsonl": {
|
||||
"post": {
|
||||
"summary": "Jsonl",
|
||||
"operationId": "jsonl_jsonl_post",
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/jsonl": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "Streamitem Jsonl Jsonl Post",
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
"/raw": {
|
||||
"post": {
|
||||
"summary": "Raw",
|
||||
"operationId": "raw_raw_post",
|
||||
"responses": {"201": {"description": "Successful Response"}},
|
||||
}
|
||||
},
|
||||
"/sse-dependency": {
|
||||
"post": {
|
||||
"summary": "Sse Dependency",
|
||||
"operationId": "sse_dependency_sse_dependency_post",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": "Streamitem Sse Dependency Sse Dependency Post",
|
||||
},
|
||||
},
|
||||
"event": {"type": "string"},
|
||||
"id": {"type": "string"},
|
||||
"retry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
},
|
||||
},
|
||||
"required": ["data"],
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"202": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": "SSE stream item",
|
||||
},
|
||||
},
|
||||
"event": {"type": "string"},
|
||||
"id": {"type": "string"},
|
||||
"retry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
},
|
||||
},
|
||||
"required": ["data"],
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
"/jsonl-dependency": {
|
||||
"post": {
|
||||
"summary": "Jsonl Dependency",
|
||||
"operationId": "jsonl_dependency_jsonl_dependency_post",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/jsonl": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "Streamitem Jsonl Dependency Jsonl Dependency Post",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"202": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/jsonl": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "JSONL stream item",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
"/raw-dependency": {
|
||||
"post": {
|
||||
"summary": "Raw Dependency",
|
||||
"operationId": "raw_dependency_raw_dependency_post",
|
||||
"responses": {
|
||||
"200": {"description": "Successful Response"},
|
||||
"202": {"description": "Accepted"},
|
||||
},
|
||||
}
|
||||
},
|
||||
"/sse-dependency-override": {
|
||||
"post": {
|
||||
"summary": "Sse Dependency Override",
|
||||
"operationId": "sse_dependency_override_sse_dependency_override_post",
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": "Streamitem Sse Dependency Override Sse Dependency Override Post",
|
||||
},
|
||||
},
|
||||
"event": {"type": "string"},
|
||||
"id": {"type": "string"},
|
||||
"retry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
},
|
||||
},
|
||||
"required": ["data"],
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"202": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": "SSE stream item",
|
||||
},
|
||||
},
|
||||
"event": {"type": "string"},
|
||||
"id": {"type": "string"},
|
||||
"retry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
},
|
||||
},
|
||||
"required": ["data"],
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
"/jsonl-dependency-override": {
|
||||
"post": {
|
||||
"summary": "Jsonl Dependency Override",
|
||||
"operationId": "jsonl_dependency_override_jsonl_dependency_override_post",
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/jsonl": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "Streamitem Jsonl Dependency Override Jsonl Dependency Override Post",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"202": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/jsonl": {
|
||||
"itemSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string"},
|
||||
"title": "JSONL stream item",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
"/raw-dependency-override": {
|
||||
"post": {
|
||||
"summary": "Raw Dependency Override",
|
||||
"operationId": "raw_dependency_override_raw_dependency_override_post",
|
||||
"responses": {
|
||||
"201": {"description": "Successful Response"},
|
||||
"202": {"description": "Accepted"},
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
Reference in new issue
Block a user