repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py
tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py
# Ref: https://github.com/fastapi/fastapi/issues/14454 from typing import Annotated, Optional from fastapi import APIRouter, Depends, FastAPI, Security from fastapi.security import OAuth2AuthorizationCodeBearer from fastapi.testclient import TestClient from inline_snapshot import snapshot oauth2_scheme = OAuth2AuthorizationCodeBearer( authorizationUrl="authorize", tokenUrl="token", auto_error=True, scopes={"read": "Read access", "write": "Write access"}, ) async def get_token(token: Annotated[str, Depends(oauth2_scheme)]) -> str: return token app = FastAPI(dependencies=[Depends(get_token)]) @app.get("/") async def root(): return {"message": "Hello World"} @app.get( "/with-oauth2-scheme", dependencies=[Security(oauth2_scheme, scopes=["read", "write"])], ) async def read_with_oauth2_scheme(): return {"message": "Admin Access"} @app.get( "/with-get-token", dependencies=[Security(get_token, scopes=["read", "write"])] ) async def read_with_get_token(): return {"message": "Admin Access"} router = APIRouter(dependencies=[Security(oauth2_scheme, scopes=["read"])]) @router.get("/items/") async def read_items(token: Optional[str] = Depends(oauth2_scheme)): return {"token": token} @router.post("/items/") async def create_item( token: Optional[str] = Security(oauth2_scheme, scopes=["read", "write"]), ): return {"token": token} app.include_router(router) client = TestClient(app) def test_root(): response = client.get("/", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"message": "Hello World"} def test_read_with_oauth2_scheme(): response = client.get( "/with-oauth2-scheme", headers={"Authorization": "Bearer testtoken"} ) assert response.status_code == 200, response.text assert response.json() == {"message": "Admin Access"} def test_read_with_get_token(): response = client.get( "/with-get-token", headers={"Authorization": "Bearer testtoken"} ) assert response.status_code == 200, response.text assert response.json() == {"message": "Admin Access"} def test_read_token(): response = client.get("/items/", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} def test_create_token(): response = client.post("/items/", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "get": { "summary": "Root", "operationId": "root__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [{"OAuth2AuthorizationCodeBearer": []}], } }, "/with-oauth2-scheme": { "get": { "summary": "Read With Oauth2 Scheme", "operationId": "read_with_oauth2_scheme_with_oauth2_scheme_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [ {"OAuth2AuthorizationCodeBearer": ["read", "write"]} ], } }, "/with-get-token": { "get": { "summary": "Read With Get Token", "operationId": "read_with_get_token_with_get_token_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [ {"OAuth2AuthorizationCodeBearer": ["read", "write"]} ], } }, "/items/": { "get": { "summary": "Read Items", "operationId": "read_items_items__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [ {"OAuth2AuthorizationCodeBearer": ["read"]}, ], }, "post": { "summary": "Create Item", "operationId": "create_item_items__post", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [ {"OAuth2AuthorizationCodeBearer": ["read", "write"]}, ], }, }, }, "components": { "securitySchemes": { "OAuth2AuthorizationCodeBearer": { "type": "oauth2", "flows": { "authorizationCode": { "scopes": { "read": "Read access", "write": "Write access", }, "authorizationUrl": "authorize", "tokenUrl": "token", } }, } } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_union_inherited_body.py
tests/test_union_inherited_body.py
from typing import Optional, Union from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: Optional[str] = None class ExtendedItem(Item): age: int @app.post("/items/") def save_union_different_body(item: Union[ExtendedItem, Item]): return {"item": item} client = TestClient(app) def test_post_extended_item(): response = client.post("/items/", json={"name": "Foo", "age": 5}) assert response.status_code == 200, response.text assert response.json() == {"item": {"name": "Foo", "age": 5}} def test_post_item(): response = client.post("/items/", json={"name": "Foo"}) assert response.status_code == 200, response.text assert response.json() == {"item": {"name": "Foo"}} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Save Union Different Body", "operationId": "save_union_different_body_items__post", "requestBody": { "content": { "application/json": { "schema": { "title": "Item", "anyOf": [ {"$ref": "#/components/schemas/ExtendedItem"}, {"$ref": "#/components/schemas/Item"}, ], } } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "type": "object", "properties": { "name": { "title": "Name", "anyOf": [{"type": "string"}, {"type": "null"}], } }, }, "ExtendedItem": { "title": "ExtendedItem", "required": ["age"], "type": "object", "properties": { "name": { "title": "Name", "anyOf": [{"type": "string"}, {"type": "null"}], }, "age": {"title": "Age", "type": "integer"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_properties.py
tests/test_additional_properties.py
from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Items(BaseModel): items: dict[str, int] @app.post("/foo") def foo(items: Items): return items.items client = TestClient(app) def test_additional_properties_post(): response = client.post("/foo", json={"items": {"foo": 1, "bar": 2}}) assert response.status_code == 200, response.text assert response.json() == {"foo": 1, "bar": 2} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/foo": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Foo", "operationId": "foo_foo_post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Items"} } }, "required": True, }, } } }, "components": { "schemas": { "Items": { "title": "Items", "required": ["items"], "type": "object", "properties": { "items": { "title": "Items", "type": "object", "additionalProperties": {"type": "integer"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_custom_route_class.py
tests/test_custom_route_class.py
import pytest from fastapi import APIRouter, FastAPI from fastapi.routing import APIRoute from fastapi.testclient import TestClient from starlette.routing import Route app = FastAPI() class APIRouteA(APIRoute): x_type = "A" class APIRouteB(APIRoute): x_type = "B" class APIRouteC(APIRoute): x_type = "C" router_a = APIRouter(route_class=APIRouteA) router_b = APIRouter(route_class=APIRouteB) router_c = APIRouter(route_class=APIRouteC) @router_a.get("/") def get_a(): return {"msg": "A"} @router_b.get("/") def get_b(): return {"msg": "B"} @router_c.get("/") def get_c(): return {"msg": "C"} router_b.include_router(router=router_c, prefix="/c") router_a.include_router(router=router_b, prefix="/b") app.include_router(router=router_a, prefix="/a") client = TestClient(app) @pytest.mark.parametrize( "path,expected_status,expected_response", [ ("/a", 200, {"msg": "A"}), ("/a/b", 200, {"msg": "B"}), ("/a/b/c", 200, {"msg": "C"}), ], ) def test_get_path(path, expected_status, expected_response): response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response def test_route_classes(): routes = {} for r in app.router.routes: assert isinstance(r, Route) routes[r.path] = r assert getattr(routes["/a/"], "x_type") == "A" # noqa: B009 assert getattr(routes["/a/b/"], "x_type") == "B" # noqa: B009 assert getattr(routes["/a/b/c/"], "x_type") == "C" # noqa: B009 def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Get A", "operationId": "get_a_a__get", } }, "/a/b/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Get B", "operationId": "get_b_a_b__get", } }, "/a/b/c/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Get C", "operationId": "get_c_a_b_c__get", } }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_invalid_sequence_param.py
tests/test_invalid_sequence_param.py
from typing import Optional import pytest from fastapi import FastAPI, Query from pydantic import BaseModel def test_invalid_sequence(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/") def read_items(q: list[Item] = Query(default=None)): pass # pragma: no cover def test_invalid_tuple(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/") def read_items(q: tuple[Item, Item] = Query(default=None)): pass # pragma: no cover def test_invalid_dict(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/") def read_items(q: dict[str, Item] = Query(default=None)): pass # pragma: no cover def test_invalid_simple_dict(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/") def read_items(q: Optional[dict] = Query(default=None)): pass # pragma: no cover
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_overrides.py
tests/test_dependency_overrides.py
from typing import Optional import pytest from fastapi import APIRouter, Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() router = APIRouter() async def common_parameters(q: str, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/main-depends/") async def main_depends(commons: dict = Depends(common_parameters)): return {"in": "main-depends", "params": commons} @app.get("/decorator-depends/", dependencies=[Depends(common_parameters)]) async def decorator_depends(): return {"in": "decorator-depends"} @router.get("/router-depends/") async def router_depends(commons: dict = Depends(common_parameters)): return {"in": "router-depends", "params": commons} @router.get("/router-decorator-depends/", dependencies=[Depends(common_parameters)]) async def router_decorator_depends(): return {"in": "router-decorator-depends"} app.include_router(router) client = TestClient(app) async def overrider_dependency_simple(q: Optional[str] = None): return {"q": q, "skip": 5, "limit": 10} async def overrider_sub_dependency(k: str): return {"k": k} async def overrider_dependency_with_sub(msg: dict = Depends(overrider_sub_dependency)): return msg def test_main_depends(): response = client.get("/main-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": None, } ] } def test_main_depends_q_foo(): response = client.get("/main-depends/?q=foo") assert response.status_code == 200 assert response.json() == { "in": "main-depends", "params": {"q": "foo", "skip": 0, "limit": 100}, } def test_main_depends_q_foo_skip_100_limit_200(): response = client.get("/main-depends/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "in": "main-depends", "params": {"q": "foo", "skip": 100, "limit": 200}, } def test_decorator_depends(): response = client.get("/decorator-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": None, } ] } def test_decorator_depends_q_foo(): response = client.get("/decorator-depends/?q=foo") assert response.status_code == 200 assert response.json() == {"in": "decorator-depends"} def test_decorator_depends_q_foo_skip_100_limit_200(): response = client.get("/decorator-depends/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == {"in": "decorator-depends"} def test_router_depends(): response = client.get("/router-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": None, } ] } def test_router_depends_q_foo(): response = client.get("/router-depends/?q=foo") assert response.status_code == 200 assert response.json() == { "in": "router-depends", "params": {"q": "foo", "skip": 0, "limit": 100}, } def test_router_depends_q_foo_skip_100_limit_200(): response = client.get("/router-depends/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "in": "router-depends", "params": {"q": "foo", "skip": 100, "limit": 200}, } def test_router_decorator_depends(): response = client.get("/router-decorator-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": None, } ] } def test_router_decorator_depends_q_foo(): response = client.get("/router-decorator-depends/?q=foo") assert response.status_code == 200 assert response.json() == {"in": "router-decorator-depends"} def test_router_decorator_depends_q_foo_skip_100_limit_200(): response = client.get("/router-decorator-depends/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == {"in": "router-decorator-depends"} @pytest.mark.parametrize( "url,status_code,expected", [ ( "/main-depends/", 200, {"in": "main-depends", "params": {"q": None, "skip": 5, "limit": 10}}, ), ( "/main-depends/?q=foo", 200, {"in": "main-depends", "params": {"q": "foo", "skip": 5, "limit": 10}}, ), ( "/main-depends/?q=foo&skip=100&limit=200", 200, {"in": "main-depends", "params": {"q": "foo", "skip": 5, "limit": 10}}, ), ("/decorator-depends/", 200, {"in": "decorator-depends"}), ( "/router-depends/", 200, {"in": "router-depends", "params": {"q": None, "skip": 5, "limit": 10}}, ), ( "/router-depends/?q=foo", 200, {"in": "router-depends", "params": {"q": "foo", "skip": 5, "limit": 10}}, ), ( "/router-depends/?q=foo&skip=100&limit=200", 200, {"in": "router-depends", "params": {"q": "foo", "skip": 5, "limit": 10}}, ), ("/router-decorator-depends/", 200, {"in": "router-decorator-depends"}), ], ) def test_override_simple(url, status_code, expected): app.dependency_overrides[common_parameters] = overrider_dependency_simple response = client.get(url) assert response.status_code == status_code assert response.json() == expected app.dependency_overrides = {} def test_override_with_sub_main_depends(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/main-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub__main_depends_q_foo(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/main-depends/?q=foo") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_main_depends_k_bar(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/main-depends/?k=bar") assert response.status_code == 200 assert response.json() == {"in": "main-depends", "params": {"k": "bar"}} app.dependency_overrides = {} def test_override_with_sub_decorator_depends(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/decorator-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_decorator_depends_q_foo(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/decorator-depends/?q=foo") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_decorator_depends_k_bar(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/decorator-depends/?k=bar") assert response.status_code == 200 assert response.json() == {"in": "decorator-depends"} app.dependency_overrides = {} def test_override_with_sub_router_depends(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/router-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_router_depends_q_foo(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/router-depends/?q=foo") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_router_depends_k_bar(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/router-depends/?k=bar") assert response.status_code == 200 assert response.json() == {"in": "router-depends", "params": {"k": "bar"}} app.dependency_overrides = {} def test_override_with_sub_router_decorator_depends(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/router-decorator-depends/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_router_decorator_depends_q_foo(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/router-decorator-depends/?q=foo") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "k"], "msg": "Field required", "input": None, } ] } app.dependency_overrides = {} def test_override_with_sub_router_decorator_depends_k_bar(): app.dependency_overrides[common_parameters] = overrider_dependency_with_sub response = client.get("/router-decorator-depends/?k=bar") assert response.status_code == 200 assert response.json() == {"in": "router-decorator-depends"} app.dependency_overrides = {}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_password_bearer_optional_description.py
tests/test_security_oauth2_password_bearer_optional_description.py
from typing import Optional from fastapi import FastAPI, Security from fastapi.security import OAuth2PasswordBearer from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2PasswordBearer( tokenUrl="/token", description="OAuth2PasswordBearer security scheme", auto_error=False, ) @app.get("/items/") async def read_items(token: Optional[str] = Security(oauth2_scheme)): if token is None: return {"msg": "Create an account first"} return {"token": token} client = TestClient(app) def test_no_token(): response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_token(): response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} def test_incorrect_token(): response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Items", "operationId": "read_items_items__get", "security": [{"OAuth2PasswordBearer": []}], } } }, "components": { "securitySchemes": { "OAuth2PasswordBearer": { "type": "oauth2", "flows": {"password": {"scopes": {}, "tokenUrl": "/token"}}, "description": "OAuth2PasswordBearer security scheme", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_wrapped_method_forward_reference.py
tests/test_wrapped_method_forward_reference.py
import functools from fastapi import FastAPI from fastapi.testclient import TestClient from .forward_reference_type import forwardref_method def passthrough(f): @functools.wraps(f) def method(*args, **kwargs): return f(*args, **kwargs) return method def test_wrapped_method_type_inference(): """ Regression test ensuring that when a method imported from another module is decorated with something that sets the __wrapped__ attribute (functools.wraps), then the types are still processed correctly, including dereferencing of forward references. """ app = FastAPI() client = TestClient(app) app.post("/endpoint")(passthrough(forwardref_method)) app.post("/endpoint2")(passthrough(passthrough(forwardref_method))) with client: response = client.post("/endpoint", json={"input": {"x": 0}}) response2 = client.post("/endpoint2", json={"input": {"x": 0}}) assert response.json() == response2.json() == {"x": 1}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_query_parameter_extension.py
tests/test_openapi_query_parameter_extension.py
from typing import Optional from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get( "/", openapi_extra={ "parameters": [ { "required": False, "schema": {"title": "Extra Param 1"}, "name": "extra_param_1", "in": "query", }, { "required": True, "schema": {"title": "Extra Param 2"}, "name": "extra_param_2", "in": "query", }, ] }, ) def route_with_extra_query_parameters(standard_query_param: Optional[int] = 50): return {} client = TestClient(app) def test_get_route(): response = client.get("/") assert response.status_code == 200, response.text assert response.json() == {} def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "get": { "summary": "Route With Extra Query Parameters", "operationId": "route_with_extra_query_parameters__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "integer"}, {"type": "null"}], "default": 50, "title": "Standard Query Param", }, "name": "standard_query_param", "in": "query", }, { "required": False, "schema": {"title": "Extra Param 1"}, "name": "extra_param_1", "in": "query", }, { "required": True, "schema": {"title": "Extra Param 2"}, "name": "extra_param_2", "in": "query", }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_get_request_body.py
tests/test_get_request_body.py
from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Product(BaseModel): name: str description: str = None # type: ignore price: float @app.get("/product") async def create_item(product: Product): return product client = TestClient(app) def test_get_with_body(): body = {"name": "Foo", "description": "Some description", "price": 5.5} response = client.request("GET", "/product", json=body) assert response.json() == body def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/product": { "get": { "summary": "Create Item", "operationId": "create_item_product_get", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Product"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Product": { "title": "Product", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "description": {"title": "Description", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_password_bearer_optional.py
tests/test_security_oauth2_password_bearer_optional.py
from typing import Optional from fastapi import FastAPI, Security from fastapi.security import OAuth2PasswordBearer from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token", auto_error=False) @app.get("/items/") async def read_items(token: Optional[str] = Security(oauth2_scheme)): if token is None: return {"msg": "Create an account first"} return {"token": token} client = TestClient(app) def test_no_token(): response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_token(): response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} def test_incorrect_token(): response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Items", "operationId": "read_items_items__get", "security": [{"OAuth2PasswordBearer": []}], } } }, "components": { "securitySchemes": { "OAuth2PasswordBearer": { "type": "oauth2", "flows": {"password": {"scopes": {}, "tokenUrl": "/token"}}, } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_read_with_orm_mode.py
tests/test_read_with_orm_mode.py
from typing import Any from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, ConfigDict def test_read_with_orm_mode() -> None: class PersonBase(BaseModel): name: str lastname: str class Person(PersonBase): @property def full_name(self) -> str: return f"{self.name} {self.lastname}" model_config = ConfigDict(from_attributes=True) class PersonCreate(PersonBase): pass class PersonRead(PersonBase): full_name: str model_config = {"from_attributes": True} app = FastAPI() @app.post("/people/", response_model=PersonRead) def create_person(person: PersonCreate) -> Any: db_person = Person.model_validate(person) return db_person client = TestClient(app) person_data = {"name": "Dive", "lastname": "Wilson"} response = client.post("/people/", json=person_data) data = response.json() assert response.status_code == 200, response.text assert data["name"] == person_data["name"] assert data["lastname"] == person_data["lastname"] assert data["full_name"] == person_data["name"] + " " + person_data["lastname"]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_separate_input_output_schemas.py
tests/test_openapi_separate_input_output_schemas.py
from typing import Optional from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot from pydantic import BaseModel, computed_field class SubItem(BaseModel): subname: str sub_description: Optional[str] = None tags: list[str] = [] model_config = {"json_schema_serialization_defaults_required": True} class Item(BaseModel): name: str description: Optional[str] = None sub: Optional[SubItem] = None model_config = {"json_schema_serialization_defaults_required": True} class WithComputedField(BaseModel): name: str @computed_field @property def computed_field(self) -> str: return f"computed {self.name}" def get_app_client(separate_input_output_schemas: bool = True) -> TestClient: app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) @app.post("/items/", responses={402: {"model": Item}}) def create_item(item: Item) -> Item: return item @app.post("/items-list/") def create_item_list(item: list[Item]): return item @app.get("/items/") def read_items() -> list[Item]: return [ Item( name="Portal Gun", description="Device to travel through the multi-rick-verse", sub=SubItem(subname="subname"), ), Item(name="Plumbus"), ] @app.post("/with-computed-field/") def create_with_computed_field( with_computed_field: WithComputedField, ) -> WithComputedField: return with_computed_field client = TestClient(app) return client def test_create_item(): client = get_app_client() client_no = get_app_client(separate_input_output_schemas=False) response = client.post("/items/", json={"name": "Plumbus"}) response2 = client_no.post("/items/", json={"name": "Plumbus"}) assert response.status_code == response2.status_code == 200, response.text assert ( response.json() == response2.json() == {"name": "Plumbus", "description": None, "sub": None} ) def test_create_item_with_sub(): client = get_app_client() client_no = get_app_client(separate_input_output_schemas=False) data = { "name": "Plumbus", "sub": {"subname": "SubPlumbus", "sub_description": "Sub WTF"}, } response = client.post("/items/", json=data) response2 = client_no.post("/items/", json=data) assert response.status_code == response2.status_code == 200, response.text assert ( response.json() == response2.json() == { "name": "Plumbus", "description": None, "sub": {"subname": "SubPlumbus", "sub_description": "Sub WTF", "tags": []}, } ) def test_create_item_list(): client = get_app_client() client_no = get_app_client(separate_input_output_schemas=False) data = [ {"name": "Plumbus"}, { "name": "Portal Gun", "description": "Device to travel through the multi-rick-verse", }, ] response = client.post("/items-list/", json=data) response2 = client_no.post("/items-list/", json=data) assert response.status_code == response2.status_code == 200, response.text assert ( response.json() == response2.json() == [ {"name": "Plumbus", "description": None, "sub": None}, { "name": "Portal Gun", "description": "Device to travel through the multi-rick-verse", "sub": None, }, ] ) def test_read_items(): client = get_app_client() client_no = get_app_client(separate_input_output_schemas=False) response = client.get("/items/") response2 = client_no.get("/items/") assert response.status_code == response2.status_code == 200, response.text assert ( response.json() == response2.json() == [ { "name": "Portal Gun", "description": "Device to travel through the multi-rick-verse", "sub": {"subname": "subname", "sub_description": None, "tags": []}, }, {"name": "Plumbus", "description": None, "sub": None}, ] ) def test_with_computed_field(): client = get_app_client() client_no = get_app_client(separate_input_output_schemas=False) response = client.post("/with-computed-field/", json={"name": "example"}) response2 = client_no.post("/with-computed-field/", json={"name": "example"}) assert response.status_code == response2.status_code == 200, response.text assert ( response.json() == response2.json() == { "name": "example", "computed_field": "computed example", } ) def test_openapi_schema(): client = get_app_client() response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "summary": "Read Items", "operationId": "read_items_items__get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/Item-Output" }, "type": "array", "title": "Response Read Items Items Get", } } }, } }, }, "post": { "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item-Input" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item-Output" } } }, }, "402": { "description": "Payment Required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item-Output" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, "/items-list/": { "post": { "summary": "Create Item List", "operationId": "create_item_list_items_list__post", "requestBody": { "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/Item-Input" }, "type": "array", "title": "Item", } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/with-computed-field/": { "post": { "summary": "Create With Computed Field", "operationId": "create_with_computed_field_with_computed_field__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WithComputedField-Input" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WithComputedField-Output" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item-Input": { "properties": { "name": {"type": "string", "title": "Name"}, "description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Description", }, "sub": { "anyOf": [ {"$ref": "#/components/schemas/SubItem-Input"}, {"type": "null"}, ] }, }, "type": "object", "required": ["name"], "title": "Item", }, "Item-Output": { "properties": { "name": {"type": "string", "title": "Name"}, "description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Description", }, "sub": { "anyOf": [ {"$ref": "#/components/schemas/SubItem-Output"}, {"type": "null"}, ] }, }, "type": "object", "required": ["name", "description", "sub"], "title": "Item", }, "SubItem-Input": { "properties": { "subname": {"type": "string", "title": "Subname"}, "sub_description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Sub Description", }, "tags": { "items": {"type": "string"}, "type": "array", "title": "Tags", "default": [], }, }, "type": "object", "required": ["subname"], "title": "SubItem", }, "SubItem-Output": { "properties": { "subname": {"type": "string", "title": "Subname"}, "sub_description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Sub Description", }, "tags": { "items": {"type": "string"}, "type": "array", "title": "Tags", "default": [], }, }, "type": "object", "required": ["subname", "sub_description", "tags"], "title": "SubItem", }, "WithComputedField-Input": { "properties": {"name": {"type": "string", "title": "Name"}}, "type": "object", "required": ["name"], "title": "WithComputedField", }, "WithComputedField-Output": { "properties": { "name": {"type": "string", "title": "Name"}, "computed_field": { "type": "string", "title": "Computed Field", "readOnly": True, }, }, "type": "object", "required": ["name", "computed_field"], "title": "WithComputedField", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, } ) def test_openapi_schema_no_separate(): client = get_app_client(separate_input_output_schemas=False) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "summary": "Read Items", "operationId": "read_items_items__get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "items": {"$ref": "#/components/schemas/Item"}, "type": "array", "title": "Response Read Items Items Get", } } }, } }, }, "post": { "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "402": { "description": "Payment Required", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, "/items-list/": { "post": { "summary": "Create Item List", "operationId": "create_item_list_items_list__post", "requestBody": { "content": { "application/json": { "schema": { "items": {"$ref": "#/components/schemas/Item"}, "type": "array", "title": "Item", } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/with-computed-field/": { "post": { "summary": "Create With Computed Field", "operationId": "create_with_computed_field_with_computed_field__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WithComputedField-Input" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WithComputedField-Output" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item": { "properties": { "name": {"type": "string", "title": "Name"}, "description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Description", }, "sub": { "anyOf": [ {"$ref": "#/components/schemas/SubItem"}, {"type": "null"}, ] }, }, "type": "object", "required": ["name"], "title": "Item", }, "SubItem": { "properties": { "subname": {"type": "string", "title": "Subname"}, "sub_description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Sub Description", }, "tags": { "items": {"type": "string"}, "type": "array", "title": "Tags", "default": [], }, }, "type": "object", "required": ["subname"], "title": "SubItem", }, "WithComputedField-Input": { "properties": {"name": {"type": "string", "title": "Name"}}, "type": "object", "required": ["name"], "title": "WithComputedField", }, "WithComputedField-Output": { "properties": { "name": {"type": "string", "title": "Name"}, "computed_field": { "type": "string", "title": "Computed Field", "readOnly": True, }, }, "type": "object", "required": ["name", "computed_field"], "title": "WithComputedField", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_deprecated_openapi_prefix.py
tests/test_deprecated_openapi_prefix.py
from fastapi import FastAPI, Request from fastapi.testclient import TestClient app = FastAPI(openapi_prefix="/api/v1") @app.get("/app") def read_main(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")} client = TestClient(app) def test_main(): response = client.get("/app") assert response.status_code == 200 assert response.json() == {"message": "Hello World", "root_path": "/api/v1"} def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/app": { "get": { "summary": "Read Main", "operationId": "read_main_app_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } } }, "servers": [{"url": "/api/v1"}], }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_infer_param_optionality.py
tests/test_infer_param_optionality.py
from typing import Optional from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient app = FastAPI() user_router = APIRouter() item_router = APIRouter() @user_router.get("/") def get_users(): return [{"user_id": "u1"}, {"user_id": "u2"}] @user_router.get("/{user_id}") def get_user(user_id: str): return {"user_id": user_id} @item_router.get("/") def get_items(user_id: Optional[str] = None): if user_id is None: return [{"item_id": "i1", "user_id": "u1"}, {"item_id": "i2", "user_id": "u2"}] else: return [{"item_id": "i2", "user_id": user_id}] @item_router.get("/{item_id}") def get_item(item_id: str, user_id: Optional[str] = None): if user_id is None: return {"item_id": item_id} else: return {"item_id": item_id, "user_id": user_id} app.include_router(user_router, prefix="/users") app.include_router(item_router, prefix="/items") app.include_router(item_router, prefix="/users/{user_id}/items") client = TestClient(app) def test_get_users(): """Check that /users returns expected data""" response = client.get("/users") assert response.status_code == 200, response.text assert response.json() == [{"user_id": "u1"}, {"user_id": "u2"}] def test_get_user(): """Check that /users/{user_id} returns expected data""" response = client.get("/users/abc123") assert response.status_code == 200, response.text assert response.json() == {"user_id": "abc123"} def test_get_items_1(): """Check that /items returns expected data""" response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == [ {"item_id": "i1", "user_id": "u1"}, {"item_id": "i2", "user_id": "u2"}, ] def test_get_items_2(): """Check that /items returns expected data with user_id specified""" response = client.get("/items?user_id=abc123") assert response.status_code == 200, response.text assert response.json() == [{"item_id": "i2", "user_id": "abc123"}] def test_get_item_1(): """Check that /items/{item_id} returns expected data""" response = client.get("/items/item01") assert response.status_code == 200, response.text assert response.json() == {"item_id": "item01"} def test_get_item_2(): """Check that /items/{item_id} returns expected data with user_id specified""" response = client.get("/items/item01?user_id=abc123") assert response.status_code == 200, response.text assert response.json() == {"item_id": "item01", "user_id": "abc123"} def test_get_users_items(): """Check that /users/{user_id}/items returns expected data""" response = client.get("/users/abc123/items") assert response.status_code == 200, response.text assert response.json() == [{"item_id": "i2", "user_id": "abc123"}] def test_get_users_item(): """Check that /users/{user_id}/items returns expected data""" response = client.get("/users/abc123/items/item01") assert response.status_code == 200, response.text assert response.json() == {"item_id": "item01", "user_id": "abc123"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/": { "get": { "summary": "Get Users", "operationId": "get_users_users__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/users/{user_id}": { "get": { "summary": "Get User", "operationId": "get_user_users__user_id__get", "parameters": [ { "required": True, "schema": {"title": "User Id", "type": "string"}, "name": "user_id", "in": "path", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/items/": { "get": { "summary": "Get Items", "operationId": "get_items_items__get", "parameters": [ { "required": False, "name": "user_id", "in": "query", "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "User Id", }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/items/{item_id}": { "get": { "summary": "Get Item", "operationId": "get_item_items__item_id__get", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", }, { "required": False, "name": "user_id", "in": "query", "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "User Id", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/users/{user_id}/items/": { "get": { "summary": "Get Items", "operationId": "get_items_users__user_id__items__get", "parameters": [ { "required": True, "name": "user_id", "in": "path", "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "User Id", }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/users/{user_id}/items/{item_id}": { "get": { "summary": "Get Item", "operationId": "get_item_users__user_id__items__item_id__get", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", }, { "required": True, "name": "user_id", "in": "path", "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "User Id", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_yield_except_httpexception.py
tests/test_dependency_yield_except_httpexception.py
import pytest from fastapi import Body, Depends, FastAPI, HTTPException from fastapi.testclient import TestClient initial_fake_database = {"rick": "Rick Sanchez"} fake_database = initial_fake_database.copy() initial_state = {"except": False, "finally": False} state = initial_state.copy() app = FastAPI() async def get_database(): temp_database = fake_database.copy() try: yield temp_database fake_database.update(temp_database) except HTTPException: state["except"] = True raise finally: state["finally"] = True @app.put("/invalid-user/{user_id}") def put_invalid_user( user_id: str, name: str = Body(), db: dict = Depends(get_database) ): db[user_id] = name raise HTTPException(status_code=400, detail="Invalid user") @app.put("/user/{user_id}") def put_user(user_id: str, name: str = Body(), db: dict = Depends(get_database)): db[user_id] = name return {"message": "OK"} @pytest.fixture(autouse=True) def reset_state_and_db(): global fake_database global state fake_database = initial_fake_database.copy() state = initial_state.copy() client = TestClient(app) def test_dependency_gets_exception(): assert state["except"] is False assert state["finally"] is False response = client.put("/invalid-user/rick", json="Morty") assert response.status_code == 400, response.text assert response.json() == {"detail": "Invalid user"} assert state["except"] is True assert state["finally"] is True assert fake_database["rick"] == "Rick Sanchez" def test_dependency_no_exception(): assert state["except"] is False assert state["finally"] is False response = client.put("/user/rick", json="Morty") assert response.status_code == 200, response.text assert response.json() == {"message": "OK"} assert state["except"] is False assert state["finally"] is True assert fake_database["rick"] == "Morty"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_contextvars.py
tests/test_dependency_contextvars.py
from collections.abc import Awaitable from contextvars import ContextVar from typing import Any, Callable, Optional from fastapi import Depends, FastAPI, Request, Response from fastapi.testclient import TestClient legacy_request_state_context_var: ContextVar[Optional[dict[str, Any]]] = ContextVar( "legacy_request_state_context_var", default=None ) app = FastAPI() async def set_up_request_state_dependency(): request_state = {"user": "deadpond"} contextvar_token = legacy_request_state_context_var.set(request_state) yield request_state legacy_request_state_context_var.reset(contextvar_token) @app.middleware("http") async def custom_middleware( request: Request, call_next: Callable[[Request], Awaitable[Response]] ): response = await call_next(request) response.headers["custom"] = "foo" return response @app.get("/user", dependencies=[Depends(set_up_request_state_dependency)]) def get_user(): request_state = legacy_request_state_context_var.get() assert request_state return request_state["user"] client = TestClient(app) def test_dependency_contextvars(): """ Check that custom middlewares don't affect the contextvar context for dependencies. The code before yield and the code after yield should be run in the same contextvar context, so that request_state_context_var.reset(contextvar_token). If they are run in a different context, that raises an error. """ response = client.get("/user") assert response.json() == "deadpond" assert response.headers["custom"] == "foo"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_code_no_body.py
tests/test_response_code_no_body.py
from fastapi import FastAPI from fastapi.responses import JSONResponse from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class JsonApiResponse(JSONResponse): media_type = "application/vnd.api+json" class Error(BaseModel): status: str title: str class JsonApiError(BaseModel): errors: list[Error] @app.get( "/a", status_code=204, response_class=JsonApiResponse, responses={500: {"description": "Error", "model": JsonApiError}}, ) async def a(): pass @app.get("/b", responses={204: {"description": "No Content"}}) async def b(): pass # pragma: no cover client = TestClient(app) def test_get_response(): response = client.get("/a") assert response.status_code == 204, response.text assert "content-length" not in response.headers assert response.content == b"" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { "get": { "responses": { "500": { "description": "Error", "content": { "application/vnd.api+json": { "schema": { "$ref": "#/components/schemas/JsonApiError" } } }, }, "204": {"description": "Successful Response"}, }, "summary": "A", "operationId": "a_a_get", } }, "/b": { "get": { "responses": { "204": {"description": "No Content"}, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, }, "summary": "B", "operationId": "b_b_get", } }, }, "components": { "schemas": { "Error": { "title": "Error", "required": ["status", "title"], "type": "object", "properties": { "status": {"title": "Status", "type": "string"}, "title": {"title": "Title", "type": "string"}, }, }, "JsonApiError": { "title": "JsonApiError", "required": ["errors"], "type": "object", "properties": { "errors": { "title": "Errors", "type": "array", "items": {"$ref": "#/components/schemas/Error"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_query_cookie_header_model_extra_params.py
tests/test_query_cookie_header_model_extra_params.py
from fastapi import Cookie, FastAPI, Header, Query from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Model(BaseModel): param: str model_config = {"extra": "allow"} @app.get("/query") async def query_model_with_extra(data: Model = Query()): return data @app.get("/header") async def header_model_with_extra(data: Model = Header()): return data @app.get("/cookie") async def cookies_model_with_extra(data: Model = Cookie()): return data def test_query_pass_extra_list(): client = TestClient(app) resp = client.get( "/query", params={ "param": "123", "param2": ["456", "789"], # Pass a list of values as extra parameter }, ) assert resp.status_code == 200 assert resp.json() == { "param": "123", "param2": ["456", "789"], } def test_query_pass_extra_single(): client = TestClient(app) resp = client.get( "/query", params={ "param": "123", "param2": "456", }, ) assert resp.status_code == 200 assert resp.json() == { "param": "123", "param2": "456", } def test_header_pass_extra_list(): client = TestClient(app) resp = client.get( "/header", headers=[ ("param", "123"), ("param2", "456"), # Pass a list of values as extra parameter ("param2", "789"), ], ) assert resp.status_code == 200 resp_json = resp.json() assert "param2" in resp_json assert resp_json["param2"] == ["456", "789"] def test_header_pass_extra_single(): client = TestClient(app) resp = client.get( "/header", headers=[ ("param", "123"), ("param2", "456"), ], ) assert resp.status_code == 200 resp_json = resp.json() assert "param2" in resp_json assert resp_json["param2"] == "456" def test_cookie_pass_extra_list(): client = TestClient(app) client.cookies = [ ("param", "123"), ("param2", "456"), # Pass a list of values as extra parameter ("param2", "789"), ] resp = client.get("/cookie") assert resp.status_code == 200 resp_json = resp.json() assert "param2" in resp_json assert resp_json["param2"] == "789" # Cookies only keep the last value
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_cache.py
tests/test_dependency_cache.py
from fastapi import Depends, FastAPI, Security from fastapi.testclient import TestClient app = FastAPI() counter_holder = {"counter": 0} async def dep_counter(): counter_holder["counter"] += 1 return counter_holder["counter"] async def super_dep(count: int = Depends(dep_counter)): return count @app.get("/counter/") async def get_counter(count: int = Depends(dep_counter)): return {"counter": count} @app.get("/sub-counter/") async def get_sub_counter( subcount: int = Depends(super_dep), count: int = Depends(dep_counter) ): return {"counter": count, "subcounter": subcount} @app.get("/sub-counter-no-cache/") async def get_sub_counter_no_cache( subcount: int = Depends(super_dep), count: int = Depends(dep_counter, use_cache=False), ): return {"counter": count, "subcounter": subcount} @app.get("/scope-counter") async def get_scope_counter( count: int = Security(dep_counter), scope_count_1: int = Security(dep_counter, scopes=["scope"]), scope_count_2: int = Security(dep_counter, scopes=["scope"]), ): return { "counter": count, "scope_counter_1": scope_count_1, "scope_counter_2": scope_count_2, } client = TestClient(app) def test_normal_counter(): counter_holder["counter"] = 0 response = client.get("/counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 1} response = client.get("/counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 2} def test_sub_counter(): counter_holder["counter"] = 0 response = client.get("/sub-counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 1, "subcounter": 1} response = client.get("/sub-counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 2, "subcounter": 2} def test_sub_counter_no_cache(): counter_holder["counter"] = 0 response = client.get("/sub-counter-no-cache/") assert response.status_code == 200, response.text assert response.json() == {"counter": 2, "subcounter": 1} response = client.get("/sub-counter-no-cache/") assert response.status_code == 200, response.text assert response.json() == {"counter": 4, "subcounter": 3} def test_security_cache(): counter_holder["counter"] = 0 response = client.get("/scope-counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 1, "scope_counter_1": 2, "scope_counter_2": 2} response = client.get("/scope-counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 3, "scope_counter_1": 4, "scope_counter_2": 4}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_openid_connect_description.py
tests/test_security_openid_connect_description.py
from fastapi import Depends, FastAPI, Security from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() oid = OpenIdConnect( openIdConnectUrl="/openid", description="OpenIdConnect security scheme" ) class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(oid)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) def test_security_oauth2(): response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Bearer footokenbar"} def test_security_oauth2_password_other_header(): response = client.get("/users/me", headers={"Authorization": "Other footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Other footokenbar"} def test_security_oauth2_password_bearer_no_header(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"OpenIdConnect": []}], } } }, "components": { "securitySchemes": { "OpenIdConnect": { "type": "openIdConnect", "openIdConnectUrl": "/openid", "description": "OpenIdConnect security scheme", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_class_no_mediatype.py
tests/test_response_class_no_mediatype.py
from fastapi import FastAPI, Response from fastapi.responses import JSONResponse from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class JsonApiResponse(JSONResponse): media_type = "application/vnd.api+json" class Error(BaseModel): status: str title: str class JsonApiError(BaseModel): errors: list[Error] @app.get( "/a", response_class=Response, responses={500: {"description": "Error", "model": JsonApiError}}, ) async def a(): pass # pragma: no cover @app.get("/b", responses={500: {"description": "Error", "model": Error}}) async def b(): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { "get": { "responses": { "500": { "description": "Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/JsonApiError" } } }, }, "200": {"description": "Successful Response"}, }, "summary": "A", "operationId": "a_a_get", } }, "/b": { "get": { "responses": { "500": { "description": "Error", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Error"} } }, }, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, }, "summary": "B", "operationId": "b_b_get", } }, }, "components": { "schemas": { "Error": { "title": "Error", "required": ["status", "title"], "type": "object", "properties": { "status": {"title": "Status", "type": "string"}, "title": {"title": "Title", "type": "string"}, }, }, "JsonApiError": { "title": "JsonApiError", "required": ["errors"], "type": "object", "properties": { "errors": { "title": "Errors", "type": "array", "items": {"$ref": "#/components/schemas/Error"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_properties_bool.py
tests/test_additional_properties_bool.py
from typing import Union from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, ConfigDict class FooBaseModel(BaseModel): model_config = ConfigDict(extra="forbid") class Foo(FooBaseModel): pass app = FastAPI() @app.post("/") async def post( foo: Union[Foo, None] = None, ): return foo client = TestClient(app) def test_call_invalid(): response = client.post("/", json={"foo": {"bar": "baz"}}) assert response.status_code == 422 def test_call_valid(): response = client.post("/", json={}) assert response.status_code == 200 assert response.json() == {} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post", "operationId": "post__post", "requestBody": { "content": { "application/json": { "schema": { "anyOf": [ {"$ref": "#/components/schemas/Foo"}, {"type": "null"}, ], "title": "Foo", } } } }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "Foo": { "properties": {}, "additionalProperties": False, "type": "object", "title": "Foo", }, "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_validate_response.py
tests/test_validate_response.py
from typing import Optional, Union import pytest from fastapi import FastAPI from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: Optional[float] = None owner_ids: Optional[list[int]] = None @app.get("/items/invalid", response_model=Item) def get_invalid(): return {"name": "invalid", "price": "foo"} @app.get("/items/invalidnone", response_model=Item) def get_invalid_none(): return None @app.get("/items/validnone", response_model=Union[Item, None]) def get_valid_none(send_none: bool = False): if send_none: return None else: return {"name": "invalid", "price": 3.2} @app.get("/items/innerinvalid", response_model=Item) def get_innerinvalid(): return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]} @app.get("/items/invalidlist", response_model=list[Item]) def get_invalidlist(): return [ {"name": "foo"}, {"name": "bar", "price": "bar"}, {"name": "baz", "price": "baz"}, ] client = TestClient(app) def test_invalid(): with pytest.raises(ResponseValidationError): client.get("/items/invalid") def test_invalid_none(): with pytest.raises(ResponseValidationError): client.get("/items/invalidnone") def test_valid_none_data(): response = client.get("/items/validnone") data = response.json() assert response.status_code == 200 assert data == {"name": "invalid", "price": 3.2, "owner_ids": None} def test_valid_none_none(): response = client.get("/items/validnone", params={"send_none": "true"}) data = response.json() assert response.status_code == 200 assert data is None def test_double_invalid(): with pytest.raises(ResponseValidationError): client.get("/items/innerinvalid") def test_invalid_list(): with pytest.raises(ResponseValidationError): client.get("/items/invalidlist")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_cookie_description.py
tests/test_security_api_key_cookie_description.py
from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyCookie from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() api_key = APIKeyCookie(name="key", description="An API Cookie Key") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user def test_security_api_key(): client = TestClient(app, cookies={"key": "secret"}) response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"username": "secret"} def test_security_api_key_no_key(): client = TestClient(app) response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "APIKey" def test_openapi_schema(): client = TestClient(app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"APIKeyCookie": []}], } } }, "components": { "securitySchemes": { "APIKeyCookie": { "type": "apiKey", "name": "key", "in": "cookie", "description": "An API Cookie Key", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_change_status_code.py
tests/test_response_change_status_code.py
from fastapi import Depends, FastAPI, Response from fastapi.testclient import TestClient app = FastAPI() async def response_status_setter(response: Response): response.status_code = 201 async def parent_dep(result=Depends(response_status_setter)): return result @app.get("/", dependencies=[Depends(parent_dep)]) async def get_main(): return {"msg": "Hello World"} client = TestClient(app) def test_dependency_set_status_code(): response = client.get("/") assert response.status_code == 201, response.text assert response.json() == {"msg": "Hello World"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_schema_extra_examples.py
tests/test_schema_extra_examples.py
from typing import Union import pytest from fastapi import Body, Cookie, FastAPI, Header, Path, Query from fastapi.exceptions import FastAPIDeprecationWarning from fastapi.testclient import TestClient from pydantic import BaseModel, ConfigDict def create_app(): app = FastAPI() class Item(BaseModel): data: str model_config = ConfigDict( json_schema_extra={"example": {"data": "Data in schema_extra"}} ) @app.post("/schema_extra/") def schema_extra(item: Item): return item with pytest.warns(FastAPIDeprecationWarning): @app.post("/example/") def example(item: Item = Body(example={"data": "Data in Body example"})): return item @app.post("/examples/") def examples( item: Item = Body( examples=[ {"data": "Data in Body examples, example1"}, {"data": "Data in Body examples, example2"}, ], ), ): return item with pytest.warns(FastAPIDeprecationWarning): @app.post("/example_examples/") def example_examples( item: Item = Body( example={"data": "Overridden example"}, examples=[ {"data": "examples example_examples 1"}, {"data": "examples example_examples 2"}, ], ), ): return item # TODO: enable these tests once/if Form(embed=False) is supported # TODO: In that case, define if File() should support example/examples too # @app.post("/form_example") # def form_example(firstname: str = Form(example="John")): # return firstname # @app.post("/form_examples") # def form_examples( # lastname: str = Form( # ..., # examples={ # "example1": {"summary": "last name summary", "value": "Doe"}, # "example2": {"value": "Doesn't"}, # }, # ), # ): # return lastname # @app.post("/form_example_examples") # def form_example_examples( # lastname: str = Form( # ..., # example="Doe overridden", # examples={ # "example1": {"summary": "last name summary", "value": "Doe"}, # "example2": {"value": "Doesn't"}, # }, # ), # ): # return lastname with pytest.warns(FastAPIDeprecationWarning): @app.get("/path_example/{item_id}") def path_example( item_id: str = Path( example="item_1", ), ): return item_id @app.get("/path_examples/{item_id}") def path_examples( item_id: str = Path( examples=["item_1", "item_2"], ), ): return item_id with pytest.warns(FastAPIDeprecationWarning): @app.get("/path_example_examples/{item_id}") def path_example_examples( item_id: str = Path( example="item_overridden", examples=["item_1", "item_2"], ), ): return item_id with pytest.warns(FastAPIDeprecationWarning): @app.get("/query_example/") def query_example( data: Union[str, None] = Query( default=None, example="query1", ), ): return data @app.get("/query_examples/") def query_examples( data: Union[str, None] = Query( default=None, examples=["query1", "query2"], ), ): return data with pytest.warns(FastAPIDeprecationWarning): @app.get("/query_example_examples/") def query_example_examples( data: Union[str, None] = Query( default=None, example="query_overridden", examples=["query1", "query2"], ), ): return data with pytest.warns(FastAPIDeprecationWarning): @app.get("/header_example/") def header_example( data: Union[str, None] = Header( default=None, example="header1", ), ): return data @app.get("/header_examples/") def header_examples( data: Union[str, None] = Header( default=None, examples=[ "header1", "header2", ], ), ): return data with pytest.warns(FastAPIDeprecationWarning): @app.get("/header_example_examples/") def header_example_examples( data: Union[str, None] = Header( default=None, example="header_overridden", examples=["header1", "header2"], ), ): return data with pytest.warns(FastAPIDeprecationWarning): @app.get("/cookie_example/") def cookie_example( data: Union[str, None] = Cookie( default=None, example="cookie1", ), ): return data @app.get("/cookie_examples/") def cookie_examples( data: Union[str, None] = Cookie( default=None, examples=["cookie1", "cookie2"], ), ): return data with pytest.warns(FastAPIDeprecationWarning): @app.get("/cookie_example_examples/") def cookie_example_examples( data: Union[str, None] = Cookie( default=None, example="cookie_overridden", examples=["cookie1", "cookie2"], ), ): return data return app def test_call_api(): app = create_app() client = TestClient(app) response = client.post("/schema_extra/", json={"data": "Foo"}) assert response.status_code == 200, response.text response = client.post("/example/", json={"data": "Foo"}) assert response.status_code == 200, response.text response = client.post("/examples/", json={"data": "Foo"}) assert response.status_code == 200, response.text response = client.post("/example_examples/", json={"data": "Foo"}) assert response.status_code == 200, response.text response = client.get("/path_example/foo") assert response.status_code == 200, response.text response = client.get("/path_examples/foo") assert response.status_code == 200, response.text response = client.get("/path_example_examples/foo") assert response.status_code == 200, response.text response = client.get("/query_example/") assert response.status_code == 200, response.text response = client.get("/query_examples/") assert response.status_code == 200, response.text response = client.get("/query_example_examples/") assert response.status_code == 200, response.text response = client.get("/header_example/") assert response.status_code == 200, response.text response = client.get("/header_examples/") assert response.status_code == 200, response.text response = client.get("/header_example_examples/") assert response.status_code == 200, response.text response = client.get("/cookie_example/") assert response.status_code == 200, response.text response = client.get("/cookie_examples/") assert response.status_code == 200, response.text response = client.get("/cookie_example_examples/") assert response.status_code == 200, response.text def test_openapi_schema(): """ Test that example overrides work: * pydantic model schema_extra is included * Body(example={}) overrides schema_extra in pydantic model * Body(examples{}) overrides Body(example={}) and schema_extra in pydantic model """ app = create_app() client = TestClient(app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/schema_extra/": { "post": { "summary": "Schema Extra", "operationId": "schema_extra_schema_extra__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/example/": { "post": { "summary": "Example", "operationId": "example_example__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"}, "example": {"data": "Data in Body example"}, } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/examples/": { "post": { "summary": "Examples", "operationId": "examples_examples__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", "examples": [ {"data": "Data in Body examples, example1"}, {"data": "Data in Body examples, example2"}, ], } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/example_examples/": { "post": { "summary": "Example Examples", "operationId": "example_examples_example_examples__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", "examples": [ {"data": "examples example_examples 1"}, {"data": "examples example_examples 2"}, ], }, "example": {"data": "Overridden example"}, } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/path_example/{item_id}": { "get": { "summary": "Path Example", "operationId": "path_example_path_example__item_id__get", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "example": "item_1", "name": "item_id", "in": "path", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/path_examples/{item_id}": { "get": { "summary": "Path Examples", "operationId": "path_examples_path_examples__item_id__get", "parameters": [ { "required": True, "schema": { "title": "Item Id", "type": "string", "examples": ["item_1", "item_2"], }, "name": "item_id", "in": "path", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/path_example_examples/{item_id}": { "get": { "summary": "Path Example Examples", "operationId": "path_example_examples_path_example_examples__item_id__get", "parameters": [ { "required": True, "schema": { "title": "Item Id", "type": "string", "examples": ["item_1", "item_2"], }, "example": "item_overridden", "name": "item_id", "in": "path", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/query_example/": { "get": { "summary": "Query Example", "operationId": "query_example_query_example__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", }, "example": "query1", "name": "data", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/query_examples/": { "get": { "summary": "Query Examples", "operationId": "query_examples_query_examples__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", "examples": ["query1", "query2"], }, "name": "data", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/query_example_examples/": { "get": { "summary": "Query Example Examples", "operationId": "query_example_examples_query_example_examples__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", "examples": ["query1", "query2"], }, "example": "query_overridden", "name": "data", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/header_example/": { "get": { "summary": "Header Example", "operationId": "header_example_header_example__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", }, "example": "header1", "name": "data", "in": "header", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/header_examples/": { "get": { "summary": "Header Examples", "operationId": "header_examples_header_examples__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", "examples": ["header1", "header2"], }, "name": "data", "in": "header", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/header_example_examples/": { "get": { "summary": "Header Example Examples", "operationId": "header_example_examples_header_example_examples__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", "examples": ["header1", "header2"], }, "example": "header_overridden", "name": "data", "in": "header", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/cookie_example/": { "get": { "summary": "Cookie Example", "operationId": "cookie_example_cookie_example__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", }, "example": "cookie1", "name": "data", "in": "cookie", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/cookie_examples/": { "get": { "summary": "Cookie Examples", "operationId": "cookie_examples_cookie_examples__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", "examples": ["cookie1", "cookie2"], }, "name": "data", "in": "cookie", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/cookie_example_examples/": { "get": { "summary": "Cookie Example Examples", "operationId": "cookie_example_examples_cookie_example_examples__get", "parameters": [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Data", "examples": ["cookie1", "cookie2"], }, "example": "cookie_overridden", "name": "data", "in": "cookie", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["data"], "type": "object", "properties": {"data": {"title": "Data", "type": "string"}}, "example": {"data": "Data in schema_extra"}, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] },
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_required_noneable.py
tests/test_required_noneable.py
from typing import Union from fastapi import Body, FastAPI, Query from fastapi.testclient import TestClient app = FastAPI() @app.get("/query") def read_query(q: Union[str, None]): return q @app.get("/explicit-query") def read_explicit_query(q: Union[str, None] = Query()): return q @app.post("/body-embed") def send_body_embed(b: Union[str, None] = Body(embed=True)): return b client = TestClient(app) def test_required_nonable_query_invalid(): response = client.get("/query") assert response.status_code == 422 def test_required_noneable_query_value(): response = client.get("/query", params={"q": "foo"}) assert response.status_code == 200 assert response.json() == "foo" def test_required_nonable_explicit_query_invalid(): response = client.get("/explicit-query") assert response.status_code == 422 def test_required_nonable_explicit_query_value(): response = client.get("/explicit-query", params={"q": "foo"}) assert response.status_code == 200 assert response.json() == "foo" def test_required_nonable_body_embed_no_content(): response = client.post("/body-embed") assert response.status_code == 422 def test_required_nonable_body_embed_invalid(): response = client.post("/body-embed", json={"invalid": "invalid"}) assert response.status_code == 422 def test_required_noneable_body_embed_value(): response = client.post("/body-embed", json={"b": "foo"}) assert response.status_code == 200 assert response.json() == "foo"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_optional.py
tests/test_security_oauth2_optional.py
from typing import Optional import pytest from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() reusable_oauth2 = OAuth2( flows={ "password": { "tokenUrl": "token", "scopes": {"read:users": "Read the users", "write:users": "Create users"}, } }, auto_error=False, ) class User(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(reusable_oauth2)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.post("/login") def login(form_data: OAuth2PasswordRequestFormStrict = Depends()): return form_data @app.get("/users/me") def read_users_me(current_user: Optional[User] = Depends(get_current_user)): if current_user is None: return {"msg": "Create an account first"} return current_user client = TestClient(app) def test_security_oauth2(): response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Bearer footokenbar"} def test_security_oauth2_password_other_header(): response = client.get("/users/me", headers={"Authorization": "Other footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Other footokenbar"} def test_security_oauth2_password_bearer_no_header(): response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_strict_login_no_data(): response = client.post("/login") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "grant_type"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, }, ] } def test_strict_login_no_grant_type(): response = client.post("/login", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "grant_type"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( argnames=["grant_type"], argvalues=[ pytest.param("incorrect", id="incorrect value"), pytest.param("passwordblah", id="password with suffix"), pytest.param("blahpassword", id="password with prefix"), ], ) def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], "msg": "String should match pattern '^password$'", "input": grant_type, "ctx": {"pattern": "^password$"}, } ] } def test_strict_login_correct_data(): response = client.post( "/login", data={"username": "johndoe", "password": "secret", "grant_type": "password"}, ) assert response.status_code == 200 assert response.json() == { "grant_type": "password", "username": "johndoe", "password": "secret", "scopes": [], "client_id": None, "client_secret": None, } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Login", "operationId": "login_login_post", "requestBody": { "content": { "application/x-www-form-urlencoded": { "schema": { "$ref": "#/components/schemas/Body_login_login_post" } } }, "required": True, }, } }, "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Users Me", "operationId": "read_users_me_users_me_get", "security": [{"OAuth2": []}], } }, }, "components": { "schemas": { "Body_login_login_post": { "title": "Body_login_login_post", "required": ["grant_type", "username", "password"], "type": "object", "properties": { "grant_type": { "title": "Grant Type", "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, "scope": {"title": "Scope", "type": "string", "default": ""}, "client_id": { "title": "Client Id", "anyOf": [{"type": "string"}, {"type": "null"}], }, "client_secret": { "title": "Client Secret", "anyOf": [{"type": "string"}, {"type": "null"}], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, }, "securitySchemes": { "OAuth2": { "type": "oauth2", "flows": { "password": { "scopes": { "read:users": "Read the users", "write:users": "Create users", }, "tokenUrl": "token", } }, } }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_generate_unique_id_function.py
tests/test_generate_unique_id_function.py
import warnings from fastapi import APIRouter, FastAPI from fastapi.routing import APIRoute from fastapi.testclient import TestClient from pydantic import BaseModel def custom_generate_unique_id(route: APIRoute): return f"foo_{route.name}" def custom_generate_unique_id2(route: APIRoute): return f"bar_{route.name}" def custom_generate_unique_id3(route: APIRoute): return f"baz_{route.name}" class Item(BaseModel): name: str price: float class Message(BaseModel): title: str description: str def test_top_level_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter() @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=list[Item], responses={404: {"model": list[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "foo_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_router": { "title": "Body_foo_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_router_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=list[Item], responses={404: {"model": list[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "bar_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Bar Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_bar_post_router": { "title": "Body_bar_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_router_include_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=list[Item], responses={404: {"model": list[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router, generate_unique_id_function=custom_generate_unique_id3) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "bar_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Bar Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_bar_post_router": { "title": "Body_bar_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_subrouter_top_level_include_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter() sub_router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=list[Item], responses={404: {"model": list[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover @sub_router.post( "/subrouter", response_model=list[Item], responses={404: {"model": list[Message]}}, ) def post_subrouter(item1: Item, item2: Item): return item1, item2 # pragma: nocover router.include_router(sub_router) app.include_router(router, generate_unique_id_function=custom_generate_unique_id3) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "baz_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_baz_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Baz Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Baz Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/subrouter": { "post": { "summary": "Post Subrouter", "operationId": "bar_post_subrouter", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_subrouter" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Subrouter",
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_repeated_dependency_schema.py
tests/test_repeated_dependency_schema.py
from fastapi import Depends, FastAPI, Header, status from fastapi.testclient import TestClient app = FastAPI() def get_header(*, someheader: str = Header()): return someheader def get_something_else(*, someheader: str = Depends(get_header)): return f"{someheader}123" @app.get("/") def get_deps(dep1: str = Depends(get_header), dep2: str = Depends(get_something_else)): return {"dep1": dep1, "dep2": dep2} client = TestClient(app) schema = { "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "title": "Detail", "type": "array", } }, "title": "HTTPValidationError", "type": "object", }, "ValidationError": { "properties": { "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": "get_deps__get", "parameters": [ { "in": "header", "name": "someheader", "required": True, "schema": {"title": "Someheader", "type": "string"}, } ], "responses": { "200": { "content": {"application/json": {"schema": {}}}, "description": "Successful Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, "description": "Validation Error", }, }, "summary": "Get Deps", } } }, } def test_schema(): response = client.get("/openapi.json") assert response.status_code == status.HTTP_200_OK actual_schema = response.json() assert actual_schema == schema assert ( len(actual_schema["paths"]["/"]["get"]["parameters"]) == 1 ) # primary goal of this test def test_response(): response = client.get("/", headers={"someheader": "hello"}) assert response.status_code == status.HTTP_200_OK assert response.json() == {"dep1": "hello", "dep2": "hello123"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_examples.py
tests/test_openapi_examples.py
from typing import Union from fastapi import Body, Cookie, FastAPI, Header, Path, Query from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Item(BaseModel): data: str @app.post("/examples/") def examples( item: Item = Body( examples=[ {"data": "Data in Body examples, example1"}, ], openapi_examples={ "Example One": { "summary": "Example One Summary", "description": "Example One Description", "value": {"data": "Data in Body examples, example1"}, }, "Example Two": { "value": {"data": "Data in Body examples, example2"}, }, }, ), ): return item @app.get("/path_examples/{item_id}") def path_examples( item_id: str = Path( examples=[ "json_schema_item_1", "json_schema_item_2", ], openapi_examples={ "Path One": { "summary": "Path One Summary", "description": "Path One Description", "value": "item_1", }, "Path Two": { "value": "item_2", }, }, ), ): return item_id @app.get("/query_examples/") def query_examples( data: Union[str, None] = Query( default=None, examples=[ "json_schema_query1", "json_schema_query2", ], openapi_examples={ "Query One": { "summary": "Query One Summary", "description": "Query One Description", "value": "query1", }, "Query Two": { "value": "query2", }, }, ), ): return data @app.get("/header_examples/") def header_examples( data: Union[str, None] = Header( default=None, examples=[ "json_schema_header1", "json_schema_header2", ], openapi_examples={ "Header One": { "summary": "Header One Summary", "description": "Header One Description", "value": "header1", }, "Header Two": { "value": "header2", }, }, ), ): return data @app.get("/cookie_examples/") def cookie_examples( data: Union[str, None] = Cookie( default=None, examples=["json_schema_cookie1", "json_schema_cookie2"], openapi_examples={ "Cookie One": { "summary": "Cookie One Summary", "description": "Cookie One Description", "value": "cookie1", }, "Cookie Two": { "value": "cookie2", }, }, ), ): return data client = TestClient(app) def test_call_api(): response = client.post("/examples/", json={"data": "example1"}) assert response.status_code == 200, response.text response = client.get("/path_examples/foo") assert response.status_code == 200, response.text response = client.get("/query_examples/") assert response.status_code == 200, response.text response = client.get("/header_examples/") assert response.status_code == 200, response.text response = client.get("/cookie_examples/") assert response.status_code == 200, response.text def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/examples/": { "post": { "summary": "Examples", "operationId": "examples_examples__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", "examples": [ {"data": "Data in Body examples, example1"} ], }, "examples": { "Example One": { "summary": "Example One Summary", "description": "Example One Description", "value": { "data": "Data in Body examples, example1" }, }, "Example Two": { "value": { "data": "Data in Body examples, example2" } }, }, } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/path_examples/{item_id}": { "get": { "summary": "Path Examples", "operationId": "path_examples_path_examples__item_id__get", "parameters": [ { "name": "item_id", "in": "path", "required": True, "schema": { "type": "string", "examples": [ "json_schema_item_1", "json_schema_item_2", ], "title": "Item Id", }, "examples": { "Path One": { "summary": "Path One Summary", "description": "Path One Description", "value": "item_1", }, "Path Two": {"value": "item_2"}, }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/query_examples/": { "get": { "summary": "Query Examples", "operationId": "query_examples_query_examples__get", "parameters": [ { "name": "data", "in": "query", "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "examples": [ "json_schema_query1", "json_schema_query2", ], "title": "Data", }, "examples": { "Query One": { "summary": "Query One Summary", "description": "Query One Description", "value": "query1", }, "Query Two": {"value": "query2"}, }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/header_examples/": { "get": { "summary": "Header Examples", "operationId": "header_examples_header_examples__get", "parameters": [ { "name": "data", "in": "header", "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "examples": [ "json_schema_header1", "json_schema_header2", ], "title": "Data", }, "examples": { "Header One": { "summary": "Header One Summary", "description": "Header One Description", "value": "header1", }, "Header Two": {"value": "header2"}, }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/cookie_examples/": { "get": { "summary": "Cookie Examples", "operationId": "cookie_examples_cookie_examples__get", "parameters": [ { "name": "data", "in": "cookie", "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "examples": [ "json_schema_cookie1", "json_schema_cookie2", ], "title": "Data", }, "examples": { "Cookie One": { "summary": "Cookie One Summary", "description": "Cookie One Description", "value": "cookie1", }, "Cookie Two": {"value": "cookie2"}, }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item": { "properties": {"data": {"type": "string", "title": "Data"}}, "type": "object", "required": ["data"], "title": "Item", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_validation_error_context.py
tests/test_validation_error_context.py
from fastapi import FastAPI, Request, WebSocket from fastapi.exceptions import ( RequestValidationError, ResponseValidationError, WebSocketRequestValidationError, ) from fastapi.testclient import TestClient from pydantic import BaseModel class Item(BaseModel): id: int name: str class ExceptionCapture: def __init__(self): self.exception = None def capture(self, exc): self.exception = exc return exc app = FastAPI() sub_app = FastAPI() captured_exception = ExceptionCapture() app.mount(path="/sub", app=sub_app) @app.exception_handler(RequestValidationError) @sub_app.exception_handler(RequestValidationError) async def request_validation_handler(request: Request, exc: RequestValidationError): captured_exception.capture(exc) raise exc @app.exception_handler(ResponseValidationError) @sub_app.exception_handler(ResponseValidationError) async def response_validation_handler(_: Request, exc: ResponseValidationError): captured_exception.capture(exc) raise exc @app.exception_handler(WebSocketRequestValidationError) @sub_app.exception_handler(WebSocketRequestValidationError) async def websocket_validation_handler( websocket: WebSocket, exc: WebSocketRequestValidationError ): captured_exception.capture(exc) raise exc @app.get("/users/{user_id}") def get_user(user_id: int): return {"user_id": user_id} # pragma: no cover @app.get("/items/", response_model=Item) def get_item(): return {"name": "Widget"} @sub_app.get("/items/", response_model=Item) def get_sub_item(): return {"name": "Widget"} # pragma: no cover @app.websocket("/ws/{item_id}") async def websocket_endpoint(websocket: WebSocket, item_id: int): await websocket.accept() # pragma: no cover await websocket.send_text(f"Item: {item_id}") # pragma: no cover await websocket.close() # pragma: no cover @sub_app.websocket("/ws/{item_id}") async def subapp_websocket_endpoint(websocket: WebSocket, item_id: int): await websocket.accept() # pragma: no cover await websocket.send_text(f"Item: {item_id}") # pragma: no cover await websocket.close() # pragma: no cover client = TestClient(app) def test_request_validation_error_includes_endpoint_context(): captured_exception.exception = None try: client.get("/users/invalid") except Exception: pass assert captured_exception.exception is not None error_str = str(captured_exception.exception) assert "get_user" in error_str assert "/users/" in error_str def test_response_validation_error_includes_endpoint_context(): captured_exception.exception = None try: client.get("/items/") except Exception: pass assert captured_exception.exception is not None error_str = str(captured_exception.exception) assert "get_item" in error_str assert "/items/" in error_str def test_websocket_validation_error_includes_endpoint_context(): captured_exception.exception = None try: with client.websocket_connect("/ws/invalid"): pass # pragma: no cover except Exception: pass assert captured_exception.exception is not None error_str = str(captured_exception.exception) assert "websocket_endpoint" in error_str assert "/ws/" in error_str def test_subapp_request_validation_error_includes_endpoint_context(): captured_exception.exception = None try: client.get("/sub/items/") except Exception: pass assert captured_exception.exception is not None error_str = str(captured_exception.exception) assert "get_sub_item" in error_str assert "/sub/items/" in error_str def test_subapp_websocket_validation_error_includes_endpoint_context(): captured_exception.exception = None try: with client.websocket_connect("/sub/ws/invalid"): pass # pragma: no cover except Exception: pass assert captured_exception.exception is not None error_str = str(captured_exception.exception) assert "subapp_websocket_endpoint" in error_str assert "/sub/ws/" in error_str def test_validation_error_with_only_path(): errors = [{"type": "missing", "loc": ("body", "name"), "msg": "Field required"}] exc = RequestValidationError(errors, endpoint_ctx={"path": "GET /api/test"}) error_str = str(exc) assert "Endpoint: GET /api/test" in error_str assert 'File "' not in error_str def test_validation_error_with_no_context(): errors = [{"type": "missing", "loc": ("body", "name"), "msg": "Field required"}] exc = RequestValidationError(errors, endpoint_ctx={}) error_str = str(exc) assert "1 validation error:" in error_str assert "Endpoint" not in error_str assert 'File "' not in error_str
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_typing_python39.py
tests/test_typing_python39.py
from fastapi import FastAPI from fastapi.testclient import TestClient from .utils import needs_py310 @needs_py310 def test_typing(): types = { list[int]: [1, 2, 3], dict[str, list[int]]: {"a": [1, 2, 3], "b": [4, 5, 6]}, set[int]: [1, 2, 3], # `set` is converted to `list` tuple[int, ...]: [1, 2, 3], # `tuple` is converted to `list` } for test_type, expect in types.items(): app = FastAPI() @app.post("/", response_model=test_type) def post_endpoint(input: test_type): return input res = TestClient(app).post("/", json=expect) assert res.status_code == 200, res.json() assert res.json() == expect
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_serialize_response.py
tests/test_serialize_response.py
from typing import Optional from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: Optional[float] = None owner_ids: Optional[list[int]] = None @app.get("/items/valid", response_model=Item) def get_valid(): return {"name": "valid", "price": 1.0} @app.get("/items/coerce", response_model=Item) def get_coerce(): return {"name": "coerce", "price": "1.0"} @app.get("/items/validlist", response_model=list[Item]) def get_validlist(): return [ {"name": "foo"}, {"name": "bar", "price": 1.0}, {"name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, ] client = TestClient(app) def test_valid(): response = client.get("/items/valid") response.raise_for_status() assert response.json() == {"name": "valid", "price": 1.0, "owner_ids": None} def test_coerce(): response = client.get("/items/coerce") response.raise_for_status() assert response.json() == {"name": "coerce", "price": 1.0, "owner_ids": None} def test_validlist(): response = client.get("/items/validlist") response.raise_for_status() assert response.json() == [ {"name": "foo", "price": None, "owner_ids": None}, {"name": "bar", "price": 1.0, "owner_ids": None}, {"name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, ]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_forms_from_non_typing_sequences.py
tests/test_forms_from_non_typing_sequences.py
from fastapi import FastAPI, Form from fastapi.testclient import TestClient app = FastAPI() @app.post("/form/python-list") def post_form_param_list(items: list = Form()): return items @app.post("/form/python-set") def post_form_param_set(items: set = Form()): return items @app.post("/form/python-tuple") def post_form_param_tuple(items: tuple = Form()): return items client = TestClient(app) def test_python_list_param_as_form(): response = client.post( "/form/python-list", data={"items": ["first", "second", "third"]} ) assert response.status_code == 200, response.text assert response.json() == ["first", "second", "third"] def test_python_set_param_as_form(): response = client.post( "/form/python-set", data={"items": ["first", "second", "third"]} ) assert response.status_code == 200, response.text assert set(response.json()) == {"first", "second", "third"} def test_python_tuple_param_as_form(): response = client.post( "/form/python-tuple", data={"items": ["first", "second", "third"]} ) assert response.status_code == 200, response.text assert response.json() == ["first", "second", "third"]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/main.py
tests/main.py
import http from typing import Optional from fastapi import FastAPI, Path, Query external_docs = { "description": "External API documentation.", "url": "https://docs.example.com/api-general", } app = FastAPI(openapi_external_docs=external_docs) @app.api_route("/api_route") def non_operation(): return {"message": "Hello World"} def non_decorated_route(): return {"message": "Hello World"} app.add_api_route("/non_decorated_route", non_decorated_route) @app.get("/text") def get_text(): return "Hello World" @app.get("/path/{item_id}") def get_id(item_id): return item_id @app.get("/path/str/{item_id}") def get_str_id(item_id: str): return item_id @app.get("/path/int/{item_id}") def get_int_id(item_id: int): return item_id @app.get("/path/float/{item_id}") def get_float_id(item_id: float): return item_id @app.get("/path/bool/{item_id}") def get_bool_id(item_id: bool): return item_id @app.get("/path/param/{item_id}") def get_path_param_id(item_id: Optional[str] = Path()): return item_id @app.get("/path/param-minlength/{item_id}") def get_path_param_min_length(item_id: str = Path(min_length=3)): return item_id @app.get("/path/param-maxlength/{item_id}") def get_path_param_max_length(item_id: str = Path(max_length=3)): return item_id @app.get("/path/param-min_maxlength/{item_id}") def get_path_param_min_max_length(item_id: str = Path(max_length=3, min_length=2)): return item_id @app.get("/path/param-gt/{item_id}") def get_path_param_gt(item_id: float = Path(gt=3)): return item_id @app.get("/path/param-gt0/{item_id}") def get_path_param_gt0(item_id: float = Path(gt=0)): return item_id @app.get("/path/param-ge/{item_id}") def get_path_param_ge(item_id: float = Path(ge=3)): return item_id @app.get("/path/param-lt/{item_id}") def get_path_param_lt(item_id: float = Path(lt=3)): return item_id @app.get("/path/param-lt0/{item_id}") def get_path_param_lt0(item_id: float = Path(lt=0)): return item_id @app.get("/path/param-le/{item_id}") def get_path_param_le(item_id: float = Path(le=3)): return item_id @app.get("/path/param-lt-gt/{item_id}") def get_path_param_lt_gt(item_id: float = Path(lt=3, gt=1)): return item_id @app.get("/path/param-le-ge/{item_id}") def get_path_param_le_ge(item_id: float = Path(le=3, ge=1)): return item_id @app.get("/path/param-lt-int/{item_id}") def get_path_param_lt_int(item_id: int = Path(lt=3)): return item_id @app.get("/path/param-gt-int/{item_id}") def get_path_param_gt_int(item_id: int = Path(gt=3)): return item_id @app.get("/path/param-le-int/{item_id}") def get_path_param_le_int(item_id: int = Path(le=3)): return item_id @app.get("/path/param-ge-int/{item_id}") def get_path_param_ge_int(item_id: int = Path(ge=3)): return item_id @app.get("/path/param-lt-gt-int/{item_id}") def get_path_param_lt_gt_int(item_id: int = Path(lt=3, gt=1)): return item_id @app.get("/path/param-le-ge-int/{item_id}") def get_path_param_le_ge_int(item_id: int = Path(le=3, ge=1)): return item_id @app.get("/query") def get_query(query): return f"foo bar {query}" @app.get("/query/optional") def get_query_optional(query=None): if query is None: return "foo bar" return f"foo bar {query}" @app.get("/query/int") def get_query_type(query: int): return f"foo bar {query}" @app.get("/query/int/optional") def get_query_type_optional(query: Optional[int] = None): if query is None: return "foo bar" return f"foo bar {query}" @app.get("/query/int/default") def get_query_type_int_default(query: int = 10): return f"foo bar {query}" @app.get("/query/param") def get_query_param(query=Query(default=None)): if query is None: return "foo bar" return f"foo bar {query}" @app.get("/query/param-required") def get_query_param_required(query=Query()): return f"foo bar {query}" @app.get("/query/param-required/int") def get_query_param_required_type(query: int = Query()): return f"foo bar {query}" @app.get("/enum-status-code", status_code=http.HTTPStatus.CREATED) def get_enum_status_code(): return "foo bar" @app.get("/query/frozenset") def get_query_type_frozenset(query: frozenset[int] = Query(...)): return ",".join(map(str, sorted(query))) @app.get("/query/list") def get_query_list(device_ids: list[int] = Query()) -> list[int]: return device_ids @app.get("/query/list-default") def get_query_list_default(device_ids: list[int] = Query(default=[])) -> list[int]: return device_ids
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_contextmanager.py
tests/test_dependency_contextmanager.py
import json import pytest from fastapi import BackgroundTasks, Depends, FastAPI from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient app = FastAPI() state = { "/async": "asyncgen not started", "/sync": "generator not started", "/async_raise": "asyncgen raise not started", "/sync_raise": "generator raise not started", "context_a": "not started a", "context_b": "not started b", "bg": "not set", "sync_bg": "not set", } errors = [] async def get_state(): return state class AsyncDependencyError(Exception): pass class SyncDependencyError(Exception): pass class OtherDependencyError(Exception): pass async def asyncgen_state(state: dict[str, str] = Depends(get_state)): state["/async"] = "asyncgen started" yield state["/async"] state["/async"] = "asyncgen completed" def generator_state(state: dict[str, str] = Depends(get_state)): state["/sync"] = "generator started" yield state["/sync"] state["/sync"] = "generator completed" async def asyncgen_state_try(state: dict[str, str] = Depends(get_state)): state["/async_raise"] = "asyncgen raise started" try: yield state["/async_raise"] except AsyncDependencyError: errors.append("/async_raise") raise finally: state["/async_raise"] = "asyncgen raise finalized" def generator_state_try(state: dict[str, str] = Depends(get_state)): state["/sync_raise"] = "generator raise started" try: yield state["/sync_raise"] except SyncDependencyError: errors.append("/sync_raise") raise finally: state["/sync_raise"] = "generator raise finalized" async def context_a(state: dict = Depends(get_state)): state["context_a"] = "started a" try: yield state finally: state["context_a"] = "finished a" async def context_b(state: dict = Depends(context_a)): state["context_b"] = "started b" try: yield state finally: state["context_b"] = f"finished b with a: {state['context_a']}" @app.get("/async") async def get_async(state: str = Depends(asyncgen_state)): return state @app.get("/sync") async def get_sync(state: str = Depends(generator_state)): return state @app.get("/async_raise") async def get_async_raise(state: str = Depends(asyncgen_state_try)): assert state == "asyncgen raise started" raise AsyncDependencyError() @app.get("/sync_raise") async def get_sync_raise(state: str = Depends(generator_state_try)): assert state == "generator raise started" raise SyncDependencyError() @app.get("/async_raise_other") async def get_async_raise_other(state: str = Depends(asyncgen_state_try)): assert state == "asyncgen raise started" raise OtherDependencyError() @app.get("/sync_raise_other") async def get_sync_raise_other(state: str = Depends(generator_state_try)): assert state == "generator raise started" raise OtherDependencyError() @app.get("/context_b") async def get_context_b(state: dict = Depends(context_b)): return state @app.get("/context_b_raise") async def get_context_b_raise(state: dict = Depends(context_b)): assert state["context_b"] == "started b" assert state["context_a"] == "started a" raise OtherDependencyError() @app.get("/context_b_bg") async def get_context_b_bg(tasks: BackgroundTasks, state: dict = Depends(context_b)): async def bg(state: dict): state["bg"] = f"bg set - b: {state['context_b']} - a: {state['context_a']}" tasks.add_task(bg, state) return state # Sync versions @app.get("/sync_async") def get_sync_async(state: str = Depends(asyncgen_state)): return state @app.get("/sync_sync") def get_sync_sync(state: str = Depends(generator_state)): return state @app.get("/sync_async_raise") def get_sync_async_raise(state: str = Depends(asyncgen_state_try)): assert state == "asyncgen raise started" raise AsyncDependencyError() @app.get("/sync_sync_raise") def get_sync_sync_raise(state: str = Depends(generator_state_try)): assert state == "generator raise started" raise SyncDependencyError() @app.get("/sync_async_raise_other") def get_sync_async_raise_other(state: str = Depends(asyncgen_state_try)): assert state == "asyncgen raise started" raise OtherDependencyError() @app.get("/sync_sync_raise_other") def get_sync_sync_raise_other(state: str = Depends(generator_state_try)): assert state == "generator raise started" raise OtherDependencyError() @app.get("/sync_context_b") def get_sync_context_b(state: dict = Depends(context_b)): return state @app.get("/sync_context_b_raise") def get_sync_context_b_raise(state: dict = Depends(context_b)): assert state["context_b"] == "started b" assert state["context_a"] == "started a" raise OtherDependencyError() @app.get("/sync_context_b_bg") async def get_sync_context_b_bg( tasks: BackgroundTasks, state: dict = Depends(context_b) ): async def bg(state: dict): state["sync_bg"] = ( f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" ) tasks.add_task(bg, state) return state @app.middleware("http") async def middleware(request, call_next): response: StreamingResponse = await call_next(request) response.headers["x-state"] = json.dumps(state.copy()) return response client = TestClient(app) def test_async_state(): assert state["/async"] == "asyncgen not started" response = client.get("/async") assert response.status_code == 200, response.text assert response.json() == "asyncgen started" assert state["/async"] == "asyncgen completed" def test_sync_state(): assert state["/sync"] == "generator not started" response = client.get("/sync") assert response.status_code == 200, response.text assert response.json() == "generator started" assert state["/sync"] == "generator completed" def test_async_raise_other(): assert state["/async_raise"] == "asyncgen raise not started" with pytest.raises(OtherDependencyError): client.get("/async_raise_other") assert state["/async_raise"] == "asyncgen raise finalized" assert "/async_raise" not in errors def test_sync_raise_other(): assert state["/sync_raise"] == "generator raise not started" with pytest.raises(OtherDependencyError): client.get("/sync_raise_other") assert state["/sync_raise"] == "generator raise finalized" assert "/sync_raise" not in errors def test_async_raise_raises(): with pytest.raises(AsyncDependencyError): client.get("/async_raise") assert state["/async_raise"] == "asyncgen raise finalized" assert "/async_raise" in errors errors.clear() def test_async_raise_server_error(): client = TestClient(app, raise_server_exceptions=False) response = client.get("/async_raise") assert response.status_code == 500, response.text assert state["/async_raise"] == "asyncgen raise finalized" assert "/async_raise" in errors errors.clear() def test_context_b(): response = client.get("/context_b") data = response.json() assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" def test_context_b_raise(): with pytest.raises(OtherDependencyError): client.get("/context_b_raise") assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" def test_background_tasks(): response = client.get("/context_b_bg") data = response.json() assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert data["bg"] == "not set" middleware_state = json.loads(response.headers["x-state"]) assert middleware_state["context_b"] == "started b" assert middleware_state["context_a"] == "started a" assert middleware_state["bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" assert state["bg"] == "bg set - b: started b - a: started a" def test_sync_raise_raises(): with pytest.raises(SyncDependencyError): client.get("/sync_raise") assert state["/sync_raise"] == "generator raise finalized" assert "/sync_raise" in errors errors.clear() def test_sync_raise_server_error(): client = TestClient(app, raise_server_exceptions=False) response = client.get("/sync_raise") assert response.status_code == 500, response.text assert state["/sync_raise"] == "generator raise finalized" assert "/sync_raise" in errors errors.clear() def test_sync_async_state(): response = client.get("/sync_async") assert response.status_code == 200, response.text assert response.json() == "asyncgen started" assert state["/async"] == "asyncgen completed" def test_sync_sync_state(): response = client.get("/sync_sync") assert response.status_code == 200, response.text assert response.json() == "generator started" assert state["/sync"] == "generator completed" def test_sync_async_raise_other(): with pytest.raises(OtherDependencyError): client.get("/sync_async_raise_other") assert state["/async_raise"] == "asyncgen raise finalized" assert "/async_raise" not in errors def test_sync_sync_raise_other(): with pytest.raises(OtherDependencyError): client.get("/sync_sync_raise_other") assert state["/sync_raise"] == "generator raise finalized" assert "/sync_raise" not in errors def test_sync_async_raise_raises(): with pytest.raises(AsyncDependencyError): client.get("/sync_async_raise") assert state["/async_raise"] == "asyncgen raise finalized" assert "/async_raise" in errors errors.clear() def test_sync_async_raise_server_error(): client = TestClient(app, raise_server_exceptions=False) response = client.get("/sync_async_raise") assert response.status_code == 500, response.text assert state["/async_raise"] == "asyncgen raise finalized" assert "/async_raise" in errors errors.clear() def test_sync_sync_raise_raises(): with pytest.raises(SyncDependencyError): client.get("/sync_sync_raise") assert state["/sync_raise"] == "generator raise finalized" assert "/sync_raise" in errors errors.clear() def test_sync_sync_raise_server_error(): client = TestClient(app, raise_server_exceptions=False) response = client.get("/sync_sync_raise") assert response.status_code == 500, response.text assert state["/sync_raise"] == "generator raise finalized" assert "/sync_raise" in errors errors.clear() def test_sync_context_b(): response = client.get("/sync_context_b") data = response.json() assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" def test_sync_context_b_raise(): with pytest.raises(OtherDependencyError): client.get("/sync_context_b_raise") assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" def test_sync_background_tasks(): response = client.get("/sync_context_b_bg") data = response.json() assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert data["sync_bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" assert state["sync_bg"] == "sync_bg set - b: started b - a: started a"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_openid_connect_optional.py
tests/test_security_openid_connect_optional.py
from typing import Optional from fastapi import Depends, FastAPI, Security from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() oid = OpenIdConnect(openIdConnectUrl="/openid", auto_error=False) class User(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(oid)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: Optional[User] = Depends(get_current_user)): if current_user is None: return {"msg": "Create an account first"} return current_user client = TestClient(app) def test_security_oauth2(): response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Bearer footokenbar"} def test_security_oauth2_password_other_header(): response = client.get("/users/me", headers={"Authorization": "Other footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Other footokenbar"} def test_security_oauth2_password_bearer_no_header(): response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"OpenIdConnect": []}], } } }, "components": { "securitySchemes": { "OpenIdConnect": { "type": "openIdConnect", "openIdConnectUrl": "/openid", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_pydantic_v1_error.py
tests/test_pydantic_v1_error.py
import sys import warnings from typing import Union import pytest from tests.utils import skip_module_if_py_gte_314 if sys.version_info >= (3, 14): skip_module_if_py_gte_314() from fastapi import FastAPI from fastapi.exceptions import PydanticV1NotSupportedError with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) from pydantic.v1 import BaseModel def test_raises_pydantic_v1_model_in_endpoint_param() -> None: class ParamModelV1(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.post("/param") def endpoint(data: ParamModelV1): # pragma: no cover return data def test_raises_pydantic_v1_model_in_return_type() -> None: class ReturnModelV1(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.get("/return") def endpoint() -> ReturnModelV1: # pragma: no cover return ReturnModelV1(name="test") def test_raises_pydantic_v1_model_in_response_model() -> None: class ResponseModelV1(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.get("/response-model", response_model=ResponseModelV1) def endpoint(): # pragma: no cover return {"name": "test"} def test_raises_pydantic_v1_model_in_additional_responses_model() -> None: class ErrorModelV1(BaseModel): detail: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.get( "/responses", response_model=None, responses={400: {"model": ErrorModelV1}} ) def endpoint(): # pragma: no cover return {"ok": True} def test_raises_pydantic_v1_model_in_union() -> None: class ModelV1A(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.post("/union") def endpoint(data: Union[dict, ModelV1A]): # pragma: no cover return data def test_raises_pydantic_v1_model_in_sequence() -> None: class ModelV1A(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.post("/sequence") def endpoint(data: list[ModelV1A]): # pragma: no cover return data
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_partial.py
tests/test_dependency_partial.py
from collections.abc import AsyncGenerator, Generator from functools import partial from typing import Annotated import pytest from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() def function_dependency(value: str) -> str: return value async def async_function_dependency(value: str) -> str: return value def gen_dependency(value: str) -> Generator[str, None, None]: yield value async def async_gen_dependency(value: str) -> AsyncGenerator[str, None]: yield value class CallableDependency: def __call__(self, value: str) -> str: return value class CallableGenDependency: def __call__(self, value: str) -> Generator[str, None, None]: yield value class AsyncCallableDependency: async def __call__(self, value: str) -> str: return value class AsyncCallableGenDependency: async def __call__(self, value: str) -> AsyncGenerator[str, None]: yield value class MethodsDependency: def synchronous(self, value: str) -> str: return value async def asynchronous(self, value: str) -> str: return value def synchronous_gen(self, value: str) -> Generator[str, None, None]: yield value async def asynchronous_gen(self, value: str) -> AsyncGenerator[str, None]: yield value callable_dependency = CallableDependency() callable_gen_dependency = CallableGenDependency() async_callable_dependency = AsyncCallableDependency() async_callable_gen_dependency = AsyncCallableGenDependency() methods_dependency = MethodsDependency() @app.get("/partial-function-dependency") async def get_partial_function_dependency( value: Annotated[ str, Depends(partial(function_dependency, "partial-function-dependency")) ], ) -> str: return value @app.get("/partial-async-function-dependency") async def get_partial_async_function_dependency( value: Annotated[ str, Depends( partial(async_function_dependency, "partial-async-function-dependency") ), ], ) -> str: return value @app.get("/partial-gen-dependency") async def get_partial_gen_dependency( value: Annotated[str, Depends(partial(gen_dependency, "partial-gen-dependency"))], ) -> str: return value @app.get("/partial-async-gen-dependency") async def get_partial_async_gen_dependency( value: Annotated[ str, Depends(partial(async_gen_dependency, "partial-async-gen-dependency")) ], ) -> str: return value @app.get("/partial-callable-dependency") async def get_partial_callable_dependency( value: Annotated[ str, Depends(partial(callable_dependency, "partial-callable-dependency")) ], ) -> str: return value @app.get("/partial-callable-gen-dependency") async def get_partial_callable_gen_dependency( value: Annotated[ str, Depends(partial(callable_gen_dependency, "partial-callable-gen-dependency")), ], ) -> str: return value @app.get("/partial-async-callable-dependency") async def get_partial_async_callable_dependency( value: Annotated[ str, Depends( partial(async_callable_dependency, "partial-async-callable-dependency") ), ], ) -> str: return value @app.get("/partial-async-callable-gen-dependency") async def get_partial_async_callable_gen_dependency( value: Annotated[ str, Depends( partial( async_callable_gen_dependency, "partial-async-callable-gen-dependency" ) ), ], ) -> str: return value @app.get("/partial-synchronous-method-dependency") async def get_partial_synchronous_method_dependency( value: Annotated[ str, Depends( partial( methods_dependency.synchronous, "partial-synchronous-method-dependency" ) ), ], ) -> str: return value @app.get("/partial-synchronous-method-gen-dependency") async def get_partial_synchronous_method_gen_dependency( value: Annotated[ str, Depends( partial( methods_dependency.synchronous_gen, "partial-synchronous-method-gen-dependency", ) ), ], ) -> str: return value @app.get("/partial-asynchronous-method-dependency") async def get_partial_asynchronous_method_dependency( value: Annotated[ str, Depends( partial( methods_dependency.asynchronous, "partial-asynchronous-method-dependency", ) ), ], ) -> str: return value @app.get("/partial-asynchronous-method-gen-dependency") async def get_partial_asynchronous_method_gen_dependency( value: Annotated[ str, Depends( partial( methods_dependency.asynchronous_gen, "partial-asynchronous-method-gen-dependency", ) ), ], ) -> str: return value client = TestClient(app) @pytest.mark.parametrize( "route,value", [ ("/partial-function-dependency", "partial-function-dependency"), ( "/partial-async-function-dependency", "partial-async-function-dependency", ), ("/partial-gen-dependency", "partial-gen-dependency"), ("/partial-async-gen-dependency", "partial-async-gen-dependency"), ("/partial-callable-dependency", "partial-callable-dependency"), ("/partial-callable-gen-dependency", "partial-callable-gen-dependency"), ("/partial-async-callable-dependency", "partial-async-callable-dependency"), ( "/partial-async-callable-gen-dependency", "partial-async-callable-gen-dependency", ), ( "/partial-synchronous-method-dependency", "partial-synchronous-method-dependency", ), ( "/partial-synchronous-method-gen-dependency", "partial-synchronous-method-gen-dependency", ), ( "/partial-asynchronous-method-dependency", "partial-asynchronous-method-dependency", ), ( "/partial-asynchronous-method-gen-dependency", "partial-asynchronous-method-gen-dependency", ), ], ) def test_dependency_types_with_partial(route: str, value: str) -> None: response = client.get(route) assert response.status_code == 200, response.text assert response.json() == value
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_scopes_sub_dependency.py
tests/test_security_scopes_sub_dependency.py
# Ref: https://github.com/fastapi/fastapi/discussions/6024#discussioncomment-8541913 from typing import Annotated import pytest from fastapi import Depends, FastAPI, Security from fastapi.security import SecurityScopes from fastapi.testclient import TestClient @pytest.fixture(name="call_counts") def call_counts_fixture(): return { "get_db_session": 0, "get_current_user": 0, "get_user_me": 0, "get_user_items": 0, } @pytest.fixture(name="app") def app_fixture(call_counts: dict[str, int]): def get_db_session(): call_counts["get_db_session"] += 1 return f"db_session_{call_counts['get_db_session']}" def get_current_user( security_scopes: SecurityScopes, db_session: Annotated[str, Depends(get_db_session)], ): call_counts["get_current_user"] += 1 return { "user": f"user_{call_counts['get_current_user']}", "scopes": security_scopes.scopes, "db_session": db_session, } def get_user_me( current_user: Annotated[dict, Security(get_current_user, scopes=["me"])], ): call_counts["get_user_me"] += 1 return { "user_me": f"user_me_{call_counts['get_user_me']}", "current_user": current_user, } def get_user_items( user_me: Annotated[dict, Depends(get_user_me)], ): call_counts["get_user_items"] += 1 return { "user_items": f"user_items_{call_counts['get_user_items']}", "user_me": user_me, } app = FastAPI() @app.get("/") def path_operation( user_me: Annotated[dict, Depends(get_user_me)], user_items: Annotated[dict, Security(get_user_items, scopes=["items"])], ): return { "user_me": user_me, "user_items": user_items, } return app @pytest.fixture(name="client") def client_fixture(app: FastAPI): return TestClient(app) def test_security_scopes_sub_dependency_caching( client: TestClient, call_counts: dict[str, int] ): response = client.get("/") assert response.status_code == 200 assert call_counts["get_db_session"] == 1 assert call_counts["get_current_user"] == 2 assert call_counts["get_user_me"] == 2 assert call_counts["get_user_items"] == 1 assert response.json() == { "user_me": { "user_me": "user_me_1", "current_user": { "user": "user_1", "scopes": ["me"], "db_session": "db_session_1", }, }, "user_items": { "user_items": "user_items_1", "user_me": { "user_me": "user_me_2", "current_user": { "user": "user_2", "scopes": ["items", "me"], "db_session": "db_session_1", }, }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_router_prefix_with_template.py
tests/test_router_prefix_with_template.py
from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient app = FastAPI() router = APIRouter() @router.get("/users/{id}") def read_user(segment: str, id: str): return {"segment": segment, "id": id} app.include_router(router, prefix="/{segment}") client = TestClient(app) def test_get(): response = client.get("/seg/users/foo") assert response.status_code == 200, response.text assert response.json() == {"segment": "seg", "id": "foo"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_file_and_form_order_issue_9116.py
tests/test_file_and_form_order_issue_9116.py
""" Regression test, Error 422 if Form is declared before File See https://github.com/tiangolo/fastapi/discussions/9116 """ from pathlib import Path from typing import Annotated import pytest from fastapi import FastAPI, File, Form from fastapi.testclient import TestClient app = FastAPI() @app.post("/file_before_form") def file_before_form( file: bytes = File(), city: str = Form(), ): return {"file_content": file, "city": city} @app.post("/file_after_form") def file_after_form( city: str = Form(), file: bytes = File(), ): return {"file_content": file, "city": city} @app.post("/file_list_before_form") def file_list_before_form( files: Annotated[list[bytes], File()], city: Annotated[str, Form()], ): return {"file_contents": files, "city": city} @app.post("/file_list_after_form") def file_list_after_form( city: Annotated[str, Form()], files: Annotated[list[bytes], File()], ): return {"file_contents": files, "city": city} client = TestClient(app) @pytest.fixture def tmp_file_1(tmp_path: Path) -> Path: f = tmp_path / "example1.txt" f.write_text("foo") return f @pytest.fixture def tmp_file_2(tmp_path: Path) -> Path: f = tmp_path / "example2.txt" f.write_text("bar") return f @pytest.mark.parametrize("endpoint_path", ("/file_before_form", "/file_after_form")) def test_file_form_order(endpoint_path: str, tmp_file_1: Path): response = client.post( url=endpoint_path, data={"city": "Thimphou"}, files={"file": (tmp_file_1.name, tmp_file_1.read_bytes())}, ) assert response.status_code == 200, response.text assert response.json() == {"file_content": "foo", "city": "Thimphou"} @pytest.mark.parametrize( "endpoint_path", ("/file_list_before_form", "/file_list_after_form") ) def test_file_list_form_order(endpoint_path: str, tmp_file_1: Path, tmp_file_2: Path): response = client.post( url=endpoint_path, data={"city": "Thimphou"}, files=( ("files", (tmp_file_1.name, tmp_file_1.read_bytes())), ("files", (tmp_file_2.name, tmp_file_2.read_bytes())), ), ) assert response.status_code == 200, response.text assert response.json() == {"file_contents": ["foo", "bar"], "city": "Thimphou"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_multipart_installation.py
tests/test_multipart_installation.py
import warnings import pytest from fastapi import FastAPI, File, Form, UploadFile from fastapi.dependencies.utils import ( multipart_incorrect_install_error, multipart_not_installed_error, ) def test_incorrect_multipart_installed_form(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @app.post("/") async def root(username: str = Form()): return username # pragma: nocover def test_incorrect_multipart_installed_file_upload(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @app.post("/") async def root(f: UploadFile = File()): return f # pragma: nocover def test_incorrect_multipart_installed_file_bytes(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @app.post("/") async def root(f: bytes = File()): return f # pragma: nocover def test_incorrect_multipart_installed_multi_form(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @app.post("/") async def root(username: str = Form(), password: str = Form()): return username # pragma: nocover def test_incorrect_multipart_installed_form_file(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @app.post("/") async def root(username: str = Form(), f: UploadFile = File()): return username # pragma: nocover def test_no_multipart_installed(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.__version__", raising=False) with pytest.raises(RuntimeError, match=multipart_not_installed_error): app = FastAPI() @app.post("/") async def root(username: str = Form()): return username # pragma: nocover def test_no_multipart_installed_file(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.__version__", raising=False) with pytest.raises(RuntimeError, match=multipart_not_installed_error): app = FastAPI() @app.post("/") async def root(f: UploadFile = File()): return f # pragma: nocover def test_no_multipart_installed_file_bytes(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.__version__", raising=False) with pytest.raises(RuntimeError, match=multipart_not_installed_error): app = FastAPI() @app.post("/") async def root(f: bytes = File()): return f # pragma: nocover def test_no_multipart_installed_multi_form(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.__version__", raising=False) with pytest.raises(RuntimeError, match=multipart_not_installed_error): app = FastAPI() @app.post("/") async def root(username: str = Form(), password: str = Form()): return username # pragma: nocover def test_no_multipart_installed_form_file(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") monkeypatch.delattr("multipart.__version__", raising=False) with pytest.raises(RuntimeError, match=multipart_not_installed_error): app = FastAPI() @app.post("/") async def root(username: str = Form(), f: UploadFile = File()): return username # pragma: nocover def test_old_multipart_installed(monkeypatch): monkeypatch.setattr("python_multipart.__version__", "0.0.12") with warnings.catch_warnings(record=True): warnings.simplefilter("always") app = FastAPI() @app.post("/") async def root(username: str = Form()): return username # pragma: nocover
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_ws_router.py
tests/test_ws_router.py
import functools import pytest from fastapi import ( APIRouter, Depends, FastAPI, Header, WebSocket, WebSocketDisconnect, status, ) from fastapi.middleware import Middleware from fastapi.testclient import TestClient router = APIRouter() prefix_router = APIRouter() native_prefix_route = APIRouter(prefix="/native") app = FastAPI() @app.websocket_route("/") async def index(websocket: WebSocket): await websocket.accept() await websocket.send_text("Hello, world!") await websocket.close() @router.websocket_route("/router") async def routerindex(websocket: WebSocket): await websocket.accept() await websocket.send_text("Hello, router!") await websocket.close() @prefix_router.websocket_route("/") async def routerprefixindex(websocket: WebSocket): await websocket.accept() await websocket.send_text("Hello, router with prefix!") await websocket.close() @router.websocket("/router2") async def routerindex2(websocket: WebSocket): await websocket.accept() await websocket.send_text("Hello, router!") await websocket.close() @router.websocket("/router/{pathparam:path}") async def routerindexparams(websocket: WebSocket, pathparam: str, queryparam: str): await websocket.accept() await websocket.send_text(pathparam) await websocket.send_text(queryparam) await websocket.close() async def ws_dependency(): return "Socket Dependency" @router.websocket("/router-ws-depends/") async def router_ws_decorator_depends( websocket: WebSocket, data=Depends(ws_dependency) ): await websocket.accept() await websocket.send_text(data) await websocket.close() @native_prefix_route.websocket("/") async def router_native_prefix_ws(websocket: WebSocket): await websocket.accept() await websocket.send_text("Hello, router with native prefix!") await websocket.close() async def ws_dependency_err(): raise NotImplementedError() @router.websocket("/depends-err/") async def router_ws_depends_err(websocket: WebSocket, data=Depends(ws_dependency_err)): pass # pragma: no cover async def ws_dependency_validate(x_missing: str = Header()): pass # pragma: no cover @router.websocket("/depends-validate/") async def router_ws_depends_validate( websocket: WebSocket, data=Depends(ws_dependency_validate) ): pass # pragma: no cover class CustomError(Exception): pass @router.websocket("/custom_error/") async def router_ws_custom_error(websocket: WebSocket): raise CustomError() def make_app(app=None, **kwargs): app = app or FastAPI(**kwargs) app.include_router(router) app.include_router(prefix_router, prefix="/prefix") app.include_router(native_prefix_route) return app app = make_app(app) def test_app(): client = TestClient(app) with client.websocket_connect("/") as websocket: data = websocket.receive_text() assert data == "Hello, world!" def test_router(): client = TestClient(app) with client.websocket_connect("/router") as websocket: data = websocket.receive_text() assert data == "Hello, router!" def test_prefix_router(): client = TestClient(app) with client.websocket_connect("/prefix/") as websocket: data = websocket.receive_text() assert data == "Hello, router with prefix!" def test_native_prefix_router(): client = TestClient(app) with client.websocket_connect("/native/") as websocket: data = websocket.receive_text() assert data == "Hello, router with native prefix!" def test_router2(): client = TestClient(app) with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!" def test_router_ws_depends(): client = TestClient(app) with client.websocket_connect("/router-ws-depends/") as websocket: assert websocket.receive_text() == "Socket Dependency" def test_router_ws_depends_with_override(): client = TestClient(app) app.dependency_overrides[ws_dependency] = lambda: "Override" # noqa: E731 with client.websocket_connect("/router-ws-depends/") as websocket: assert websocket.receive_text() == "Override" def test_router_with_params(): client = TestClient(app) with client.websocket_connect( "/router/path/to/file?queryparam=a_query_param" ) as websocket: data = websocket.receive_text() assert data == "path/to/file" data = websocket.receive_text() assert data == "a_query_param" def test_wrong_uri(): """ Verify that a websocket connection to a non-existent endpoing returns in a shutdown """ client = TestClient(app) with pytest.raises(WebSocketDisconnect) as e: with client.websocket_connect("/no-router/"): pass # pragma: no cover assert e.value.code == status.WS_1000_NORMAL_CLOSURE def websocket_middleware(middleware_func): """ Helper to create a Starlette pure websocket middleware """ def middleware_constructor(app): @functools.wraps(app) async def wrapped_app(scope, receive, send): if scope["type"] != "websocket": return await app(scope, receive, send) # pragma: no cover async def call_next(): return await app(scope, receive, send) websocket = WebSocket(scope, receive=receive, send=send) return await middleware_func(websocket, call_next) return wrapped_app return middleware_constructor def test_depend_validation(): """ Verify that a validation in a dependency invokes the correct exception handler """ caught = [] @websocket_middleware async def catcher(websocket, call_next): try: return await call_next() except Exception as e: # pragma: no cover caught.append(e) raise myapp = make_app(middleware=[Middleware(catcher)]) client = TestClient(myapp) with pytest.raises(WebSocketDisconnect) as e: with client.websocket_connect("/depends-validate/"): pass # pragma: no cover # the validation error does produce a close message assert e.value.code == status.WS_1008_POLICY_VIOLATION # and no error is leaked assert caught == [] def test_depend_err_middleware(): """ Verify that it is possible to write custom WebSocket middleware to catch errors """ @websocket_middleware async def errorhandler(websocket: WebSocket, call_next): try: return await call_next() except Exception as e: await websocket.close(code=status.WS_1006_ABNORMAL_CLOSURE, reason=repr(e)) myapp = make_app(middleware=[Middleware(errorhandler)]) client = TestClient(myapp) with pytest.raises(WebSocketDisconnect) as e: with client.websocket_connect("/depends-err/"): pass # pragma: no cover assert e.value.code == status.WS_1006_ABNORMAL_CLOSURE assert "NotImplementedError" in e.value.reason def test_depend_err_handler(): """ Verify that it is possible to write custom WebSocket middleware to catch errors """ async def custom_handler(websocket: WebSocket, exc: CustomError) -> None: await websocket.close(1002, "foo") myapp = make_app(exception_handlers={CustomError: custom_handler}) client = TestClient(myapp) with pytest.raises(WebSocketDisconnect) as e: with client.websocket_connect("/custom_error/"): pass # pragma: no cover assert e.value.code == 1002 assert "foo" in e.value.reason
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/utils.py
tests/utils.py
import sys import pytest needs_py39 = pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9+") needs_py310 = pytest.mark.skipif( sys.version_info < (3, 10), reason="requires python3.10+" ) needs_py_lt_314 = pytest.mark.skipif( sys.version_info >= (3, 14), reason="requires python3.13-" ) def skip_module_if_py_gte_314(): """Skip entire module on Python 3.14+ at import time.""" if sys.version_info >= (3, 14): pytest.skip("requires python3.13-", allow_module_level=True)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_multi_query_errors.py
tests/test_multi_query_errors.py
from fastapi import FastAPI, Query from fastapi.testclient import TestClient app = FastAPI() @app.get("/items/") def read_items(q: list[int] = Query(default=None)): return {"q": q} client = TestClient(app) def test_multi_query(): response = client.get("/items/?q=5&q=6") assert response.status_code == 200, response.text assert response.json() == {"q": [5, 6]} def test_multi_query_incorrect(): response = client.get("/items/?q=five&q=six") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "int_parsing", "loc": ["query", "q", 0], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "five", }, { "type": "int_parsing", "loc": ["query", "q", 1], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "six", }, ] } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "title": "Q", "type": "array", "items": {"type": "integer"}, }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_sub_callbacks.py
tests/test_sub_callbacks.py
from typing import Optional from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, HttpUrl app = FastAPI() class Invoice(BaseModel): id: str title: Optional[str] = None customer: str total: float class InvoiceEvent(BaseModel): description: str paid: bool class InvoiceEventReceived(BaseModel): ok: bool invoices_callback_router = APIRouter() @invoices_callback_router.post( "{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived ) def invoice_notification(body: InvoiceEvent): pass # pragma: nocover class Event(BaseModel): name: str total: float events_callback_router = APIRouter() @events_callback_router.get("{$callback_url}/events/{$request.body.title}") def event_callback(event: Event): pass # pragma: nocover subrouter = APIRouter() @subrouter.post("/invoices/", callbacks=invoices_callback_router.routes) def create_invoice(invoice: Invoice, callback_url: Optional[HttpUrl] = None): """ Create an invoice. This will (let's imagine) let the API user (some external developer) create an invoice. And this path operation will: * Send the invoice to the client. * Collect the money from the client. * Send a notification back to the API user (the external developer), as a callback. * At this point is that the API will somehow send a POST request to the external API with the notification of the invoice event (e.g. "payment successful"). """ # Send the invoice, collect the money, send the notification (the callback) return {"msg": "Invoice received"} app.include_router(subrouter, callbacks=events_callback_router.routes) client = TestClient(app) def test_get(): response = client.post( "/invoices/", json={"id": "fooinvoice", "customer": "John", "total": 5.3} ) assert response.status_code == 200, response.text assert response.json() == {"msg": "Invoice received"} def test_openapi_schema(): with client: response = client.get("/openapi.json") assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/invoices/": { "post": { "summary": "Create Invoice", "description": 'Create an invoice.\n\nThis will (let\'s imagine) let the API user (some external developer) create an\ninvoice.\n\nAnd this path operation will:\n\n* Send the invoice to the client.\n* Collect the money from the client.\n* Send a notification back to the API user (the external developer), as a callback.\n * At this point is that the API will somehow send a POST request to the\n external API with the notification of the invoice event\n (e.g. "payment successful").', "operationId": "create_invoice_invoices__post", "parameters": [ { "required": False, "schema": { "title": "Callback Url", "anyOf": [ { "type": "string", "format": "uri", "minLength": 1, "maxLength": 2083, }, {"type": "null"}, ], }, "name": "callback_url", "in": "query", } ], "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Invoice"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "callbacks": { "event_callback": { "{$callback_url}/events/{$request.body.title}": { "get": { "summary": "Event Callback", "operationId": "event_callback__callback_url__events___request_body_title__get", "requestBody": { "required": True, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Event" } } }, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "invoice_notification": { "{$callback_url}/invoices/{$request.body.id}": { "post": { "summary": "Invoice Notification", "operationId": "invoice_notification__callback_url__invoices___request_body_id__post", "requestBody": { "required": True, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/InvoiceEvent" } } }, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/InvoiceEventReceived" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, } } }, "components": { "schemas": { "Event": { "title": "Event", "required": ["name", "total"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "total": {"title": "Total", "type": "number"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, "Invoice": { "title": "Invoice", "required": ["id", "customer", "total"], "type": "object", "properties": { "id": {"title": "Id", "type": "string"}, "title": { "title": "Title", "anyOf": [{"type": "string"}, {"type": "null"}], }, "customer": {"title": "Customer", "type": "string"}, "total": {"title": "Total", "type": "number"}, }, }, "InvoiceEvent": { "title": "InvoiceEvent", "required": ["description", "paid"], "type": "object", "properties": { "description": {"title": "Description", "type": "string"}, "paid": {"title": "Paid", "type": "boolean"}, }, }, "InvoiceEventReceived": { "title": "InvoiceEventReceived", "required": ["ok"], "type": "object", "properties": {"ok": {"title": "Ok", "type": "boolean"}}, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_cookie_optional.py
tests/test_security_api_key_cookie_optional.py
from typing import Optional from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyCookie from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() api_key = APIKeyCookie(name="key", auto_error=False) class User(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(api_key)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): if current_user is None: return {"msg": "Create an account first"} else: return current_user def test_security_api_key(): client = TestClient(app, cookies={"key": "secret"}) response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"username": "secret"} def test_security_api_key_no_key(): client = TestClient(app) response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): client = TestClient(app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"APIKeyCookie": []}], } } }, "components": { "securitySchemes": { "APIKeyCookie": {"type": "apiKey", "name": "key", "in": "cookie"} } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_basic_realm_description.py
tests/test_security_http_basic_realm_description.py
from base64 import b64encode from fastapi import FastAPI, Security from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi.testclient import TestClient app = FastAPI() security = HTTPBasic(realm="simple", description="HTTPBasic scheme") @app.get("/users/me") def read_current_user(credentials: HTTPBasicCredentials = Security(security)): return {"username": credentials.username, "password": credentials.password} client = TestClient(app) def test_security_http_basic(): response = client.get("/users/me", auth=("john", "secret")) assert response.status_code == 200, response.text assert response.json() == {"username": "john", "password": "secret"} def test_security_http_basic_no_credentials(): response = client.get("/users/me") assert response.json() == {"detail": "Not authenticated"} assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' def test_security_http_basic_invalid_credentials(): response = client.get( "/users/me", headers={"Authorization": "Basic notabase64token"} ) assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' assert response.json() == {"detail": "Not authenticated"} def test_security_http_basic_non_basic_credentials(): payload = b64encode(b"johnsecret").decode("ascii") auth_header = f"Basic {payload}" response = client.get("/users/me", headers={"Authorization": auth_header}) assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' assert response.json() == {"detail": "Not authenticated"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"HTTPBasic": []}], } } }, "components": { "securitySchemes": { "HTTPBasic": { "type": "http", "scheme": "basic", "description": "HTTPBasic scheme", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_responses_custom_model_in_callback.py
tests/test_additional_responses_custom_model_in_callback.py
from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot from pydantic import BaseModel, HttpUrl from starlette.responses import JSONResponse class CustomModel(BaseModel): a: int app = FastAPI() callback_router = APIRouter(default_response_class=JSONResponse) @callback_router.get( "{$callback_url}/callback/", responses={400: {"model": CustomModel}} ) def callback_route(): pass # pragma: no cover @app.post("/", callbacks=callback_router.routes) def main_route(callback_url: HttpUrl): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Main Route", "operationId": "main_route__post", "parameters": [ { "required": True, "schema": { "title": "Callback Url", "maxLength": 2083, "minLength": 1, "type": "string", "format": "uri", }, "name": "callback_url", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "callbacks": { "callback_route": { "{$callback_url}/callback/": { "get": { "summary": "Callback Route", "operationId": "callback_route__callback_url__callback__get", "responses": { "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CustomModel" } } }, "description": "Bad Request", }, "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, }, } } } }, } } }, "components": { "schemas": { "CustomModel": { "title": "CustomModel", "required": ["a"], "type": "object", "properties": {"a": {"title": "A", "type": "integer"}}, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_openid_connect.py
tests/test_security_openid_connect.py
from fastapi import Depends, FastAPI, Security from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() oid = OpenIdConnect(openIdConnectUrl="/openid") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(oid)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) def test_security_oauth2(): response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Bearer footokenbar"} def test_security_oauth2_password_other_header(): response = client.get("/users/me", headers={"Authorization": "Other footokenbar"}) assert response.status_code == 200, response.text assert response.json() == {"username": "Other footokenbar"} def test_security_oauth2_password_bearer_no_header(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"OpenIdConnect": []}], } } }, "components": { "securitySchemes": { "OpenIdConnect": { "type": "openIdConnect", "openIdConnectUrl": "/openid", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_serialize_response_model.py
tests/test_serialize_response_model.py
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, Field from starlette.testclient import TestClient app = FastAPI() class Item(BaseModel): name: str = Field(alias="aliased_name") price: Optional[float] = None owner_ids: Optional[list[int]] = None @app.get("/items/valid", response_model=Item) def get_valid(): return Item(aliased_name="valid", price=1.0) @app.get("/items/coerce", response_model=Item) def get_coerce(): return Item(aliased_name="coerce", price="1.0") @app.get("/items/validlist", response_model=list[Item]) def get_validlist(): return [ Item(aliased_name="foo"), Item(aliased_name="bar", price=1.0), Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]), ] @app.get("/items/validdict", response_model=dict[str, Item]) def get_validdict(): return { "k1": Item(aliased_name="foo"), "k2": Item(aliased_name="bar", price=1.0), "k3": Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]), } @app.get( "/items/valid-exclude-unset", response_model=Item, response_model_exclude_unset=True ) def get_valid_exclude_unset(): return Item(aliased_name="valid", price=1.0) @app.get( "/items/coerce-exclude-unset", response_model=Item, response_model_exclude_unset=True, ) def get_coerce_exclude_unset(): return Item(aliased_name="coerce", price="1.0") @app.get( "/items/validlist-exclude-unset", response_model=list[Item], response_model_exclude_unset=True, ) def get_validlist_exclude_unset(): return [ Item(aliased_name="foo"), Item(aliased_name="bar", price=1.0), Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]), ] @app.get( "/items/validdict-exclude-unset", response_model=dict[str, Item], response_model_exclude_unset=True, ) def get_validdict_exclude_unset(): return { "k1": Item(aliased_name="foo"), "k2": Item(aliased_name="bar", price=1.0), "k3": Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]), } client = TestClient(app) def test_valid(): response = client.get("/items/valid") response.raise_for_status() assert response.json() == {"aliased_name": "valid", "price": 1.0, "owner_ids": None} def test_coerce(): response = client.get("/items/coerce") response.raise_for_status() assert response.json() == { "aliased_name": "coerce", "price": 1.0, "owner_ids": None, } def test_validlist(): response = client.get("/items/validlist") response.raise_for_status() assert response.json() == [ {"aliased_name": "foo", "price": None, "owner_ids": None}, {"aliased_name": "bar", "price": 1.0, "owner_ids": None}, {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, ] def test_validdict(): response = client.get("/items/validdict") response.raise_for_status() assert response.json() == { "k1": {"aliased_name": "foo", "price": None, "owner_ids": None}, "k2": {"aliased_name": "bar", "price": 1.0, "owner_ids": None}, "k3": {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, } def test_valid_exclude_unset(): response = client.get("/items/valid-exclude-unset") response.raise_for_status() assert response.json() == {"aliased_name": "valid", "price": 1.0} def test_coerce_exclude_unset(): response = client.get("/items/coerce-exclude-unset") response.raise_for_status() assert response.json() == {"aliased_name": "coerce", "price": 1.0} def test_validlist_exclude_unset(): response = client.get("/items/validlist-exclude-unset") response.raise_for_status() assert response.json() == [ {"aliased_name": "foo"}, {"aliased_name": "bar", "price": 1.0}, {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, ] def test_validdict_exclude_unset(): response = client.get("/items/validdict-exclude-unset") response.raise_for_status() assert response.json() == { "k1": {"aliased_name": "foo"}, "k2": {"aliased_name": "bar", "price": 1.0}, "k3": {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_compat.py
tests/test_compat.py
from typing import Union from fastapi import FastAPI, UploadFile from fastapi._compat import ( Undefined, is_uploadfile_sequence_annotation, ) from fastapi._compat.shared import is_bytes_sequence_annotation from fastapi.testclient import TestClient from pydantic import BaseModel, ConfigDict from pydantic.fields import FieldInfo from .utils import needs_py310 def test_model_field_default_required(): from fastapi._compat import v2 # For coverage field_info = FieldInfo(annotation=str) field = v2.ModelField(name="foo", field_info=field_info) assert field.default is Undefined def test_complex(): app = FastAPI() @app.post("/") def foo(foo: Union[str, list[int]]): return foo client = TestClient(app) response = client.post("/", json="bar") assert response.status_code == 200, response.text assert response.json() == "bar" response2 = client.post("/", json=[1, 2]) assert response2.status_code == 200, response2.text assert response2.json() == [1, 2] def test_propagates_pydantic2_model_config(): app = FastAPI() class Missing: def __bool__(self): return False class EmbeddedModel(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) value: Union[str, Missing] = Missing() class Model(BaseModel): model_config = ConfigDict( arbitrary_types_allowed=True, ) value: Union[str, Missing] = Missing() embedded_model: EmbeddedModel = EmbeddedModel() @app.post("/") def foo(req: Model) -> dict[str, Union[str, None]]: return { "value": req.value or None, "embedded_value": req.embedded_model.value or None, } client = TestClient(app) response = client.post("/", json={}) assert response.status_code == 200, response.text assert response.json() == { "value": None, "embedded_value": None, } response2 = client.post( "/", json={"value": "foo", "embedded_model": {"value": "bar"}} ) assert response2.status_code == 200, response2.text assert response2.json() == { "value": "foo", "embedded_value": "bar", } def test_is_bytes_sequence_annotation_union(): # For coverage # TODO: in theory this would allow declaring types that could be lists of bytes # to be read from files and other types, but I'm not even sure it's a good idea # to support it as a first class "feature" assert is_bytes_sequence_annotation(Union[list[str], list[bytes]]) def test_is_uploadfile_sequence_annotation(): # For coverage # TODO: in theory this would allow declaring types that could be lists of UploadFile # and other types, but I'm not even sure it's a good idea to support it as a first # class "feature" assert is_uploadfile_sequence_annotation(Union[list[str], list[UploadFile]]) def test_serialize_sequence_value_with_optional_list(): """Test that serialize_sequence_value handles optional lists correctly.""" from fastapi._compat import v2 field_info = FieldInfo(annotation=Union[list[str], None]) field = v2.ModelField(name="items", field_info=field_info) result = v2.serialize_sequence_value(field=field, value=["a", "b", "c"]) assert result == ["a", "b", "c"] assert isinstance(result, list) @needs_py310 def test_serialize_sequence_value_with_optional_list_pipe_union(): """Test that serialize_sequence_value handles optional lists correctly (with new syntax).""" from fastapi._compat import v2 field_info = FieldInfo(annotation=list[str] | None) field = v2.ModelField(name="items", field_info=field_info) result = v2.serialize_sequence_value(field=field, value=["a", "b", "c"]) assert result == ["a", "b", "c"] assert isinstance(result, list) def test_serialize_sequence_value_with_none_first_in_union(): """Test that serialize_sequence_value handles Union[None, List[...]] correctly.""" from fastapi._compat import v2 field_info = FieldInfo(annotation=Union[None, list[str]]) field = v2.ModelField(name="items", field_info=field_info) result = v2.serialize_sequence_value(field=field, value=["x", "y"]) assert result == ["x", "y"] assert isinstance(result, list)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_default_response_class.py
tests/test_default_response_class.py
from typing import Any import orjson from fastapi import APIRouter, FastAPI from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse from fastapi.testclient import TestClient class ORJSONResponse(JSONResponse): media_type = "application/x-orjson" def render(self, content: Any) -> bytes: return orjson.dumps(content) class OverrideResponse(JSONResponse): media_type = "application/x-override" app = FastAPI(default_response_class=ORJSONResponse) router_a = APIRouter() router_a_a = APIRouter() router_a_b_override = APIRouter() # Overrides default class router_b_override = APIRouter() # Overrides default class router_b_a = APIRouter() router_b_a_c_override = APIRouter() # Overrides default class again @app.get("/") def get_root(): return {"msg": "Hello World"} @app.get("/override", response_class=PlainTextResponse) def get_path_override(): return "Hello World" @router_a.get("/") def get_a(): return {"msg": "Hello A"} @router_a.get("/override", response_class=PlainTextResponse) def get_a_path_override(): return "Hello A" @router_a_a.get("/") def get_a_a(): return {"msg": "Hello A A"} @router_a_a.get("/override", response_class=PlainTextResponse) def get_a_a_path_override(): return "Hello A A" @router_a_b_override.get("/") def get_a_b(): return "Hello A B" @router_a_b_override.get("/override", response_class=HTMLResponse) def get_a_b_path_override(): return "Hello A B" @router_b_override.get("/") def get_b(): return "Hello B" @router_b_override.get("/override", response_class=HTMLResponse) def get_b_path_override(): return "Hello B" @router_b_a.get("/") def get_b_a(): return "Hello B A" @router_b_a.get("/override", response_class=HTMLResponse) def get_b_a_path_override(): return "Hello B A" @router_b_a_c_override.get("/") def get_b_a_c(): return "Hello B A C" @router_b_a_c_override.get("/override", response_class=OverrideResponse) def get_b_a_c_path_override(): return {"msg": "Hello B A C"} router_b_a.include_router( router_b_a_c_override, prefix="/c", default_response_class=HTMLResponse ) router_b_override.include_router(router_b_a, prefix="/a") router_a.include_router(router_a_a, prefix="/a") router_a.include_router( router_a_b_override, prefix="/b", default_response_class=PlainTextResponse ) app.include_router(router_a, prefix="/a") app.include_router( router_b_override, prefix="/b", default_response_class=PlainTextResponse ) client = TestClient(app) orjson_type = "application/x-orjson" text_type = "text/plain; charset=utf-8" html_type = "text/html; charset=utf-8" override_type = "application/x-override" def test_app(): with client: response = client.get("/") assert response.json() == {"msg": "Hello World"} assert response.headers["content-type"] == orjson_type def test_app_override(): with client: response = client.get("/override") assert response.content == b"Hello World" assert response.headers["content-type"] == text_type def test_router_a(): with client: response = client.get("/a") assert response.json() == {"msg": "Hello A"} assert response.headers["content-type"] == orjson_type def test_router_a_override(): with client: response = client.get("/a/override") assert response.content == b"Hello A" assert response.headers["content-type"] == text_type def test_router_a_a(): with client: response = client.get("/a/a") assert response.json() == {"msg": "Hello A A"} assert response.headers["content-type"] == orjson_type def test_router_a_a_override(): with client: response = client.get("/a/a/override") assert response.content == b"Hello A A" assert response.headers["content-type"] == text_type def test_router_a_b(): with client: response = client.get("/a/b") assert response.content == b"Hello A B" assert response.headers["content-type"] == text_type def test_router_a_b_override(): with client: response = client.get("/a/b/override") assert response.content == b"Hello A B" assert response.headers["content-type"] == html_type def test_router_b(): with client: response = client.get("/b") assert response.content == b"Hello B" assert response.headers["content-type"] == text_type def test_router_b_override(): with client: response = client.get("/b/override") assert response.content == b"Hello B" assert response.headers["content-type"] == html_type def test_router_b_a(): with client: response = client.get("/b/a") assert response.content == b"Hello B A" assert response.headers["content-type"] == text_type def test_router_b_a_override(): with client: response = client.get("/b/a/override") assert response.content == b"Hello B A" assert response.headers["content-type"] == html_type def test_router_b_a_c(): with client: response = client.get("/b/a/c") assert response.content == b"Hello B A C" assert response.headers["content-type"] == html_type def test_router_b_a_c_override(): with client: response = client.get("/b/a/c/override") assert response.json() == {"msg": "Hello B A C"} assert response.headers["content-type"] == override_type
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_responses_default_validationerror.py
tests/test_additional_responses_default_validationerror.py
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get("/a/{id}") async def a(id): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/{id}": { "get": { "responses": { "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, }, "summary": "A", "operationId": "a_a__id__get", "parameters": [ { "required": True, "schema": {"title": "Id"}, "name": "id", "in": "path", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_base_optional.py
tests/test_security_http_base_optional.py
from typing import Optional from fastapi import FastAPI, Security from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase from fastapi.testclient import TestClient app = FastAPI() security = HTTPBase(scheme="Other", auto_error=False) @app.get("/users/me") def read_current_user( credentials: Optional[HTTPAuthorizationCredentials] = Security(security), ): if credentials is None: return {"msg": "Create an account first"} return {"scheme": credentials.scheme, "credentials": credentials.credentials} client = TestClient(app) def test_security_http_base(): response = client.get("/users/me", headers={"Authorization": "Other foobar"}) assert response.status_code == 200, response.text assert response.json() == {"scheme": "Other", "credentials": "foobar"} def test_security_http_base_no_credentials(): response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"HTTPBase": []}], } } }, "components": { "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}} }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_starlette_exception.py
tests/test_starlette_exception.py
from fastapi import FastAPI, HTTPException from fastapi.testclient import TestClient from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() items = {"foo": "The Foo Wrestlers"} @app.get("/items/{item_id}") async def read_item(item_id: str): if item_id not in items: raise HTTPException( status_code=404, detail="Item not found", headers={"X-Error": "Some custom header"}, ) return {"item": items[item_id]} @app.get("/http-no-body-statuscode-exception") async def no_body_status_code_exception(): raise HTTPException(status_code=204) @app.get("/http-no-body-statuscode-with-detail-exception") async def no_body_status_code_with_detail_exception(): raise HTTPException(status_code=204, detail="I should just disappear!") @app.get("/starlette-items/{item_id}") async def read_starlette_item(item_id: str): if item_id not in items: raise StarletteHTTPException(status_code=404, detail="Item not found") return {"item": items[item_id]} client = TestClient(app) def test_get_item(): response = client.get("/items/foo") assert response.status_code == 200, response.text assert response.json() == {"item": "The Foo Wrestlers"} def test_get_item_not_found(): response = client.get("/items/bar") assert response.status_code == 404, response.text assert response.headers.get("x-error") == "Some custom header" assert response.json() == {"detail": "Item not found"} def test_get_starlette_item(): response = client.get("/starlette-items/foo") assert response.status_code == 200, response.text assert response.json() == {"item": "The Foo Wrestlers"} def test_get_starlette_item_not_found(): response = client.get("/starlette-items/bar") assert response.status_code == 404, response.text assert response.headers.get("x-error") is None assert response.json() == {"detail": "Item not found"} def test_no_body_status_code_exception_handlers(): response = client.get("/http-no-body-statuscode-exception") assert response.status_code == 204 assert not response.content def test_no_body_status_code_with_detail_exception_handlers(): response = client.get("/http-no-body-statuscode-with-detail-exception") assert response.status_code == 204 assert not response.content def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/http-no-body-statuscode-exception": { "get": { "operationId": "no_body_status_code_exception_http_no_body_statuscode_exception_get", "responses": { "200": { "content": {"application/json": {"schema": {}}}, "description": "Successful Response", } }, "summary": "No Body Status Code Exception", } }, "/http-no-body-statuscode-with-detail-exception": { "get": { "operationId": "no_body_status_code_with_detail_exception_http_no_body_statuscode_with_detail_exception_get", "responses": { "200": { "content": {"application/json": {"schema": {}}}, "description": "Successful Response", } }, "summary": "No Body Status Code With Detail Exception", } }, "/items/{item_id}": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Item", "operationId": "read_item_items__item_id__get", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", } ], } }, "/starlette-items/{item_id}": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Starlette Item", "operationId": "read_starlette_item_starlette_items__item_id__get", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", } ], } }, }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_put_no_body.py
tests/test_put_no_body.py
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.put("/items/{item_id}") def save_item_no_body(item_id: str): return {"item_id": item_id} client = TestClient(app) def test_put_no_body(): response = client.put("/items/foo") assert response.status_code == 200, response.text assert response.json() == {"item_id": "foo"} def test_put_no_body_with_body(): response = client.put("/items/foo", json={"name": "Foo"}) assert response.status_code == 200, response.text assert response.json() == {"item_id": "foo"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Save Item No Body", "operationId": "save_item_no_body_items__item_id__put", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_wrapped.py
tests/test_dependency_wrapped.py
import inspect import sys from collections.abc import AsyncGenerator, Generator from functools import wraps import pytest from fastapi import Depends, FastAPI from fastapi.concurrency import iterate_in_threadpool, run_in_threadpool from fastapi.testclient import TestClient if sys.version_info >= (3, 13): # pragma: no cover from inspect import iscoroutinefunction else: # pragma: no cover from asyncio import iscoroutinefunction def noop_wrap(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper def noop_wrap_async(func): if inspect.isgeneratorfunction(func): @wraps(func) async def gen_wrapper(*args, **kwargs): async for item in iterate_in_threadpool(func(*args, **kwargs)): yield item return gen_wrapper elif inspect.isasyncgenfunction(func): @wraps(func) async def async_gen_wrapper(*args, **kwargs): async for item in func(*args, **kwargs): yield item return async_gen_wrapper @wraps(func) async def wrapper(*args, **kwargs): if inspect.isroutine(func) and iscoroutinefunction(func): return await func(*args, **kwargs) if inspect.isclass(func): return await run_in_threadpool(func, *args, **kwargs) dunder_call = getattr(func, "__call__", None) # noqa: B004 if iscoroutinefunction(dunder_call): return await dunder_call(*args, **kwargs) return await run_in_threadpool(func, *args, **kwargs) return wrapper class ClassInstanceDep: def __call__(self): return True class_instance_dep = ClassInstanceDep() wrapped_class_instance_dep = noop_wrap(class_instance_dep) wrapped_class_instance_dep_async_wrapper = noop_wrap_async(class_instance_dep) class ClassInstanceGenDep: def __call__(self): yield True class_instance_gen_dep = ClassInstanceGenDep() wrapped_class_instance_gen_dep = noop_wrap(class_instance_gen_dep) class ClassInstanceWrappedDep: @noop_wrap def __call__(self): return True class_instance_wrapped_dep = ClassInstanceWrappedDep() class ClassInstanceWrappedAsyncDep: @noop_wrap_async def __call__(self): return True class_instance_wrapped_async_dep = ClassInstanceWrappedAsyncDep() class ClassInstanceWrappedGenDep: @noop_wrap def __call__(self): yield True class_instance_wrapped_gen_dep = ClassInstanceWrappedGenDep() class ClassInstanceWrappedAsyncGenDep: @noop_wrap_async def __call__(self): yield True class_instance_wrapped_async_gen_dep = ClassInstanceWrappedAsyncGenDep() class ClassDep: def __init__(self): self.value = True wrapped_class_dep = noop_wrap(ClassDep) wrapped_class_dep_async_wrapper = noop_wrap_async(ClassDep) class ClassInstanceAsyncDep: async def __call__(self): return True class_instance_async_dep = ClassInstanceAsyncDep() wrapped_class_instance_async_dep = noop_wrap(class_instance_async_dep) wrapped_class_instance_async_dep_async_wrapper = noop_wrap_async( class_instance_async_dep ) class ClassInstanceAsyncGenDep: async def __call__(self): yield True class_instance_async_gen_dep = ClassInstanceAsyncGenDep() wrapped_class_instance_async_gen_dep = noop_wrap(class_instance_async_gen_dep) class ClassInstanceAsyncWrappedDep: @noop_wrap async def __call__(self): return True class_instance_async_wrapped_dep = ClassInstanceAsyncWrappedDep() class ClassInstanceAsyncWrappedAsyncDep: @noop_wrap_async async def __call__(self): return True class_instance_async_wrapped_async_dep = ClassInstanceAsyncWrappedAsyncDep() class ClassInstanceAsyncWrappedGenDep: @noop_wrap async def __call__(self): yield True class_instance_async_wrapped_gen_dep = ClassInstanceAsyncWrappedGenDep() class ClassInstanceAsyncWrappedGenAsyncDep: @noop_wrap_async async def __call__(self): yield True class_instance_async_wrapped_gen_async_dep = ClassInstanceAsyncWrappedGenAsyncDep() app = FastAPI() # Sync wrapper @noop_wrap def wrapped_dependency() -> bool: return True @noop_wrap def wrapped_gen_dependency() -> Generator[bool, None, None]: yield True @noop_wrap async def async_wrapped_dependency() -> bool: return True @noop_wrap async def async_wrapped_gen_dependency() -> AsyncGenerator[bool, None]: yield True @app.get("/wrapped-dependency/") async def get_wrapped_dependency(value: bool = Depends(wrapped_dependency)): return value @app.get("/wrapped-gen-dependency/") async def get_wrapped_gen_dependency(value: bool = Depends(wrapped_gen_dependency)): return value @app.get("/async-wrapped-dependency/") async def get_async_wrapped_dependency(value: bool = Depends(async_wrapped_dependency)): return value @app.get("/async-wrapped-gen-dependency/") async def get_async_wrapped_gen_dependency( value: bool = Depends(async_wrapped_gen_dependency), ): return value @app.get("/wrapped-class-instance-dependency/") async def get_wrapped_class_instance_dependency( value: bool = Depends(wrapped_class_instance_dep), ): return value @app.get("/wrapped-class-instance-async-dependency/") async def get_wrapped_class_instance_async_dependency( value: bool = Depends(wrapped_class_instance_async_dep), ): return value @app.get("/wrapped-class-instance-gen-dependency/") async def get_wrapped_class_instance_gen_dependency( value: bool = Depends(wrapped_class_instance_gen_dep), ): return value @app.get("/wrapped-class-instance-async-gen-dependency/") async def get_wrapped_class_instance_async_gen_dependency( value: bool = Depends(wrapped_class_instance_async_gen_dep), ): return value @app.get("/class-instance-wrapped-dependency/") async def get_class_instance_wrapped_dependency( value: bool = Depends(class_instance_wrapped_dep), ): return value @app.get("/class-instance-wrapped-async-dependency/") async def get_class_instance_wrapped_async_dependency( value: bool = Depends(class_instance_wrapped_async_dep), ): return value @app.get("/class-instance-async-wrapped-dependency/") async def get_class_instance_async_wrapped_dependency( value: bool = Depends(class_instance_async_wrapped_dep), ): return value @app.get("/class-instance-async-wrapped-async-dependency/") async def get_class_instance_async_wrapped_async_dependency( value: bool = Depends(class_instance_async_wrapped_async_dep), ): return value @app.get("/class-instance-wrapped-gen-dependency/") async def get_class_instance_wrapped_gen_dependency( value: bool = Depends(class_instance_wrapped_gen_dep), ): return value @app.get("/class-instance-wrapped-async-gen-dependency/") async def get_class_instance_wrapped_async_gen_dependency( value: bool = Depends(class_instance_wrapped_async_gen_dep), ): return value @app.get("/class-instance-async-wrapped-gen-dependency/") async def get_class_instance_async_wrapped_gen_dependency( value: bool = Depends(class_instance_async_wrapped_gen_dep), ): return value @app.get("/class-instance-async-wrapped-gen-async-dependency/") async def get_class_instance_async_wrapped_gen_async_dependency( value: bool = Depends(class_instance_async_wrapped_gen_async_dep), ): return value @app.get("/wrapped-class-dependency/") async def get_wrapped_class_dependency(value: ClassDep = Depends(wrapped_class_dep)): return value.value @app.get("/wrapped-endpoint/") @noop_wrap def get_wrapped_endpoint(): return True @app.get("/async-wrapped-endpoint/") @noop_wrap async def get_async_wrapped_endpoint(): return True # Async wrapper @noop_wrap_async def wrapped_dependency_async_wrapper() -> bool: return True @noop_wrap_async def wrapped_gen_dependency_async_wrapper() -> Generator[bool, None, None]: yield True @noop_wrap_async async def async_wrapped_dependency_async_wrapper() -> bool: return True @noop_wrap_async async def async_wrapped_gen_dependency_async_wrapper() -> AsyncGenerator[bool, None]: yield True @app.get("/wrapped-dependency-async-wrapper/") async def get_wrapped_dependency_async_wrapper( value: bool = Depends(wrapped_dependency_async_wrapper), ): return value @app.get("/wrapped-gen-dependency-async-wrapper/") async def get_wrapped_gen_dependency_async_wrapper( value: bool = Depends(wrapped_gen_dependency_async_wrapper), ): return value @app.get("/async-wrapped-dependency-async-wrapper/") async def get_async_wrapped_dependency_async_wrapper( value: bool = Depends(async_wrapped_dependency_async_wrapper), ): return value @app.get("/async-wrapped-gen-dependency-async-wrapper/") async def get_async_wrapped_gen_dependency_async_wrapper( value: bool = Depends(async_wrapped_gen_dependency_async_wrapper), ): return value @app.get("/wrapped-class-instance-dependency-async-wrapper/") async def get_wrapped_class_instance_dependency_async_wrapper( value: bool = Depends(wrapped_class_instance_dep_async_wrapper), ): return value @app.get("/wrapped-class-instance-async-dependency-async-wrapper/") async def get_wrapped_class_instance_async_dependency_async_wrapper( value: bool = Depends(wrapped_class_instance_async_dep_async_wrapper), ): return value @app.get("/wrapped-class-dependency-async-wrapper/") async def get_wrapped_class_dependency_async_wrapper( value: ClassDep = Depends(wrapped_class_dep_async_wrapper), ): return value.value @app.get("/wrapped-endpoint-async-wrapper/") @noop_wrap_async def get_wrapped_endpoint_async_wrapper(): return True @app.get("/async-wrapped-endpoint-async-wrapper/") @noop_wrap_async async def get_async_wrapped_endpoint_async_wrapper(): return True client = TestClient(app) @pytest.mark.parametrize( "route", [ "/wrapped-dependency/", "/wrapped-gen-dependency/", "/async-wrapped-dependency/", "/async-wrapped-gen-dependency/", "/wrapped-class-instance-dependency/", "/wrapped-class-instance-async-dependency/", "/wrapped-class-instance-gen-dependency/", "/wrapped-class-instance-async-gen-dependency/", "/class-instance-wrapped-dependency/", "/class-instance-wrapped-async-dependency/", "/class-instance-async-wrapped-dependency/", "/class-instance-async-wrapped-async-dependency/", "/class-instance-wrapped-gen-dependency/", "/class-instance-wrapped-async-gen-dependency/", "/class-instance-async-wrapped-gen-dependency/", "/class-instance-async-wrapped-gen-async-dependency/", "/wrapped-class-dependency/", "/wrapped-endpoint/", "/async-wrapped-endpoint/", "/wrapped-dependency-async-wrapper/", "/wrapped-gen-dependency-async-wrapper/", "/async-wrapped-dependency-async-wrapper/", "/async-wrapped-gen-dependency-async-wrapper/", "/wrapped-class-instance-dependency-async-wrapper/", "/wrapped-class-instance-async-dependency-async-wrapper/", "/wrapped-class-dependency-async-wrapper/", "/wrapped-endpoint-async-wrapper/", "/async-wrapped-endpoint-async-wrapper/", ], ) def test_class_dependency(route): response = client.get(route) assert response.status_code == 200, response.text assert response.json() is True
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_query.py
tests/test_security_api_key_query.py
from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyQuery from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() api_key = APIKeyQuery(name="key") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) def test_security_api_key(): response = client.get("/users/me?key=secret") assert response.status_code == 200, response.text assert response.json() == {"username": "secret"} def test_security_api_key_no_key(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "APIKey" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"APIKeyQuery": []}], } } }, "components": { "securitySchemes": { "APIKeyQuery": {"type": "apiKey", "name": "key", "in": "query"} } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_forms_single_model.py
tests/test_forms_single_model.py
from typing import Annotated, Optional from fastapi import FastAPI, Form from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() class FormModel(BaseModel): username: str lastname: str age: Optional[int] = None tags: list[str] = ["foo", "bar"] alias_with: str = Field(alias="with", default="nothing") class FormModelExtraAllow(BaseModel): param: str model_config = {"extra": "allow"} @app.post("/form/") def post_form(user: Annotated[FormModel, Form()]): return user @app.post("/form-extra-allow/") def post_form_extra_allow(params: Annotated[FormModelExtraAllow, Form()]): return params client = TestClient(app) def test_send_all_data(): response = client.post( "/form/", data={ "username": "Rick", "lastname": "Sanchez", "age": "70", "tags": ["plumbus", "citadel"], "with": "something", }, ) assert response.status_code == 200, response.text assert response.json() == { "username": "Rick", "lastname": "Sanchez", "age": 70, "tags": ["plumbus", "citadel"], "with": "something", } def test_defaults(): response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"}) assert response.status_code == 200, response.text assert response.json() == { "username": "Rick", "lastname": "Sanchez", "age": None, "tags": ["foo", "bar"], "with": "nothing", } def test_invalid_data(): response = client.post( "/form/", data={ "username": "Rick", "lastname": "Sanchez", "age": "seventy", "tags": ["plumbus", "citadel"], }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "int_parsing", "loc": ["body", "age"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "seventy", } ] } def test_no_data(): response = client.post("/form/") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": {"tags": ["foo", "bar"], "with": "nothing"}, }, { "type": "missing", "loc": ["body", "lastname"], "msg": "Field required", "input": {"tags": ["foo", "bar"], "with": "nothing"}, }, ] } def test_extra_param_single(): response = client.post( "/form-extra-allow/", data={ "param": "123", "extra_param": "456", }, ) assert response.status_code == 200, response.text assert response.json() == { "param": "123", "extra_param": "456", } def test_extra_param_list(): response = client.post( "/form-extra-allow/", data={ "param": "123", "extra_params": ["456", "789"], }, ) assert response.status_code == 200, response.text assert response.json() == { "param": "123", "extra_params": ["456", "789"], }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_fastapi_cli.py
tests/test_fastapi_cli.py
import os import subprocess import sys from unittest.mock import patch import fastapi.cli import pytest def test_fastapi_cli(): result = subprocess.run( [ sys.executable, "-m", "coverage", "run", "-m", "fastapi", "dev", "non_existent_file.py", ], capture_output=True, encoding="utf-8", env={**os.environ, "PYTHONIOENCODING": "utf-8"}, ) assert result.returncode == 1, result.stdout assert "Path does not exist non_existent_file.py" in result.stdout def test_fastapi_cli_not_installed(): with patch.object(fastapi.cli, "cli_main", None): with pytest.raises(RuntimeError) as exc_info: fastapi.cli.main() assert "To use the fastapi command, please install" in str(exc_info.value)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_stringified_annotations_simple.py
tests/test_stringified_annotations_simple.py
from __future__ import annotations from typing import Annotated from fastapi import Depends, FastAPI, Request from fastapi.testclient import TestClient from .utils import needs_py310 class Dep: def __call__(self, request: Request): return "test" @needs_py310 def test_stringified_annotations(): app = FastAPI() client = TestClient(app) @app.get("/test/") def call(test: Annotated[str, Depends(Dep())]): return {"test": test} response = client.get("/test") assert response.status_code == 200
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_cookie.py
tests/test_security_api_key_cookie.py
from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyCookie from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() api_key = APIKeyCookie(name="key") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user def test_security_api_key(): client = TestClient(app, cookies={"key": "secret"}) response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"username": "secret"} def test_security_api_key_no_key(): client = TestClient(app) response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "APIKey" def test_openapi_schema(): client = TestClient(app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"APIKeyCookie": []}], } } }, "components": { "securitySchemes": { "APIKeyCookie": {"type": "apiKey", "name": "key", "in": "cookie"} } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_responses_custom_validationerror.py
tests/test_additional_responses_custom_validationerror.py
from fastapi import FastAPI from fastapi.responses import JSONResponse from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class JsonApiResponse(JSONResponse): media_type = "application/vnd.api+json" class Error(BaseModel): status: str title: str class JsonApiError(BaseModel): errors: list[Error] @app.get( "/a/{id}", response_class=JsonApiResponse, responses={422: {"description": "Error", "model": JsonApiError}}, ) async def a(id): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/{id}": { "get": { "responses": { "422": { "description": "Error", "content": { "application/vnd.api+json": { "schema": { "$ref": "#/components/schemas/JsonApiError" } } }, }, "200": { "description": "Successful Response", "content": {"application/vnd.api+json": {"schema": {}}}, }, }, "summary": "A", "operationId": "a_a__id__get", "parameters": [ { "required": True, "schema": {"title": "Id"}, "name": "id", "in": "path", } ], } } }, "components": { "schemas": { "Error": { "title": "Error", "required": ["status", "title"], "type": "object", "properties": { "status": {"title": "Status", "type": "string"}, "title": {"title": "Title", "type": "string"}, }, }, "JsonApiError": { "title": "JsonApiError", "required": ["errors"], "type": "object", "properties": { "errors": { "title": "Errors", "type": "array", "items": {"$ref": "#/components/schemas/Error"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_reponse_set_reponse_code_empty.py
tests/test_reponse_set_reponse_code_empty.py
from typing import Any from fastapi import FastAPI, Response from fastapi.testclient import TestClient app = FastAPI() @app.delete( "/{id}", status_code=204, response_model=None, ) async def delete_deployment( id: int, response: Response, ) -> Any: response.status_code = 400 return {"msg": "Status overwritten", "id": id} client = TestClient(app) def test_dependency_set_status_code(): response = client.delete("/1") assert response.status_code == 400 and response.content assert response.json() == {"msg": "Status overwritten", "id": 1} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/{id}": { "delete": { "summary": "Delete Deployment", "operationId": "delete_deployment__id__delete", "parameters": [ { "required": True, "schema": {"title": "Id", "type": "integer"}, "name": "id", "in": "path", } ], "responses": { "204": {"description": "Successful Response"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_include_route.py
tests/test_include_route.py
from fastapi import APIRouter, FastAPI, Request from fastapi.responses import JSONResponse from fastapi.testclient import TestClient app = FastAPI() router = APIRouter() @router.route("/items/") def read_items(request: Request): return JSONResponse({"hello": "world"}) app.include_router(router) client = TestClient(app) def test_sub_router(): response = client.get("/items/") assert response.status_code == 200, response.text assert response.json() == {"hello": "world"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_custom_middleware_exception.py
tests/test_custom_middleware_exception.py
from pathlib import Path from typing import Optional from fastapi import APIRouter, FastAPI, File, UploadFile from fastapi.exceptions import HTTPException from fastapi.testclient import TestClient app = FastAPI() router = APIRouter() class ContentSizeLimitMiddleware: """Content size limiting middleware for ASGI applications Args: app (ASGI application): ASGI application max_content_size (optional): the maximum content size allowed in bytes, None for no limit """ def __init__(self, app: APIRouter, max_content_size: Optional[int] = None): self.app = app self.max_content_size = max_content_size def receive_wrapper(self, receive): received = 0 async def inner(): nonlocal received message = await receive() if message["type"] != "http.request": return message # pragma: no cover body_len = len(message.get("body", b"")) received += body_len if received > self.max_content_size: raise HTTPException( 422, detail={ "name": "ContentSizeLimitExceeded", "code": 999, "message": "File limit exceeded", }, ) return message return inner async def __call__(self, scope, receive, send): if scope["type"] != "http" or self.max_content_size is None: await self.app(scope, receive, send) return wrapper = self.receive_wrapper(receive) await self.app(scope, wrapper, send) @router.post("/middleware") def run_middleware(file: UploadFile = File(..., description="Big File")): return {"message": "OK"} app.include_router(router) app.add_middleware(ContentSizeLimitMiddleware, max_content_size=2**8) client = TestClient(app) def test_custom_middleware_exception(tmp_path: Path): default_pydantic_max_size = 2**16 path = tmp_path / "test.txt" path.write_bytes(b"x" * (default_pydantic_max_size + 1)) with client: with open(path, "rb") as file: response = client.post("/middleware", files={"file": file}) assert response.status_code == 422, response.text assert response.json() == { "detail": { "name": "ContentSizeLimitExceeded", "code": 999, "message": "File limit exceeded", } } def test_custom_middleware_exception_not_raised(tmp_path: Path): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with client: with open(path, "rb") as file: response = client.post("/middleware", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"message": "OK"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_top_level_security_scheme_in_openapi.py
tests/test_top_level_security_scheme_in_openapi.py
# Test security scheme at the top level, including OpenAPI # Ref: https://github.com/fastapi/fastapi/discussions/14263 # Ref: https://github.com/fastapi/fastapi/issues/14271 from fastapi import Depends, FastAPI from fastapi.security import HTTPBearer from fastapi.testclient import TestClient from inline_snapshot import snapshot app = FastAPI() bearer_scheme = HTTPBearer() @app.get("/", dependencies=[Depends(bearer_scheme)]) async def get_root(): return {"message": "Hello, World!"} client = TestClient(app) def test_get_root(): response = client.get("/", headers={"Authorization": "Bearer token"}) assert response.status_code == 200, response.text assert response.json() == {"message": "Hello, World!"} def test_get_root_no_token(): response = client.get("/") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "get": { "summary": "Get Root", "operationId": "get_root__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [{"HTTPBearer": []}], } } }, "components": { "securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}} }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/forward_reference_type.py
tests/forward_reference_type.py
from pydantic import BaseModel def forwardref_method(input: "ForwardRefModel") -> "ForwardRefModel": return ForwardRefModel(x=input.x + 1) class ForwardRefModel(BaseModel): x: int = 0
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_after_yield_websockets.py
tests/test_dependency_after_yield_websockets.py
from collections.abc import Generator from contextlib import contextmanager from typing import Annotated, Any import pytest from fastapi import Depends, FastAPI, WebSocket from fastapi.testclient import TestClient class Session: def __init__(self) -> None: self.data = ["foo", "bar", "baz"] self.open = True def __iter__(self) -> Generator[str, None, None]: for item in self.data: if self.open: yield item else: raise ValueError("Session closed") @contextmanager def acquire_session() -> Generator[Session, None, None]: session = Session() try: yield session finally: session.open = False def dep_session() -> Any: with acquire_session() as s: yield s def broken_dep_session() -> Any: with acquire_session() as s: s.open = False yield s SessionDep = Annotated[Session, Depends(dep_session)] BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket, session: SessionDep): await websocket.accept() for item in session: await websocket.send_text(f"{item}") @app.websocket("/ws-broken") async def websocket_endpoint_broken(websocket: WebSocket, session: BrokenSessionDep): await websocket.accept() for item in session: await websocket.send_text(f"{item}") # pragma no cover client = TestClient(app) def test_websocket_dependency_after_yield(): with client.websocket_connect("/ws") as websocket: data = websocket.receive_text() assert data == "foo" data = websocket.receive_text() assert data == "bar" data = websocket.receive_text() assert data == "baz" def test_websocket_dependency_after_yield_broken(): with pytest.raises(ValueError, match="Session closed"): with client.websocket_connect("/ws-broken"): pass # pragma no cover
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/__init__.py
tests/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_model_as_return_annotation.py
tests/test_response_model_as_return_annotation.py
from typing import Union import pytest from fastapi import FastAPI from fastapi.exceptions import FastAPIError, ResponseValidationError from fastapi.responses import JSONResponse, Response from fastapi.testclient import TestClient from pydantic import BaseModel class BaseUser(BaseModel): name: str class User(BaseUser): surname: str class DBUser(User): password_hash: str class Item(BaseModel): name: str price: float app = FastAPI() @app.get("/no_response_model-no_annotation-return_model") def no_response_model_no_annotation_return_model(): return User(name="John", surname="Doe") @app.get("/no_response_model-no_annotation-return_dict") def no_response_model_no_annotation_return_dict(): return {"name": "John", "surname": "Doe"} @app.get("/response_model-no_annotation-return_same_model", response_model=User) def response_model_no_annotation_return_same_model(): return User(name="John", surname="Doe") @app.get("/response_model-no_annotation-return_exact_dict", response_model=User) def response_model_no_annotation_return_exact_dict(): return {"name": "John", "surname": "Doe"} @app.get("/response_model-no_annotation-return_invalid_dict", response_model=User) def response_model_no_annotation_return_invalid_dict(): return {"name": "John"} @app.get("/response_model-no_annotation-return_invalid_model", response_model=User) def response_model_no_annotation_return_invalid_model(): return Item(name="Foo", price=42.0) @app.get( "/response_model-no_annotation-return_dict_with_extra_data", response_model=User ) def response_model_no_annotation_return_dict_with_extra_data(): return {"name": "John", "surname": "Doe", "password_hash": "secret"} @app.get( "/response_model-no_annotation-return_submodel_with_extra_data", response_model=User ) def response_model_no_annotation_return_submodel_with_extra_data(): return DBUser(name="John", surname="Doe", password_hash="secret") @app.get("/no_response_model-annotation-return_same_model") def no_response_model_annotation_return_same_model() -> User: return User(name="John", surname="Doe") @app.get("/no_response_model-annotation-return_exact_dict") def no_response_model_annotation_return_exact_dict() -> User: return {"name": "John", "surname": "Doe"} @app.get("/no_response_model-annotation-return_invalid_dict") def no_response_model_annotation_return_invalid_dict() -> User: return {"name": "John"} @app.get("/no_response_model-annotation-return_invalid_model") def no_response_model_annotation_return_invalid_model() -> User: return Item(name="Foo", price=42.0) @app.get("/no_response_model-annotation-return_dict_with_extra_data") def no_response_model_annotation_return_dict_with_extra_data() -> User: return {"name": "John", "surname": "Doe", "password_hash": "secret"} @app.get("/no_response_model-annotation-return_submodel_with_extra_data") def no_response_model_annotation_return_submodel_with_extra_data() -> User: return DBUser(name="John", surname="Doe", password_hash="secret") @app.get("/response_model_none-annotation-return_same_model", response_model=None) def response_model_none_annotation_return_same_model() -> User: return User(name="John", surname="Doe") @app.get("/response_model_none-annotation-return_exact_dict", response_model=None) def response_model_none_annotation_return_exact_dict() -> User: return {"name": "John", "surname": "Doe"} @app.get("/response_model_none-annotation-return_invalid_dict", response_model=None) def response_model_none_annotation_return_invalid_dict() -> User: return {"name": "John"} @app.get("/response_model_none-annotation-return_invalid_model", response_model=None) def response_model_none_annotation_return_invalid_model() -> User: return Item(name="Foo", price=42.0) @app.get( "/response_model_none-annotation-return_dict_with_extra_data", response_model=None ) def response_model_none_annotation_return_dict_with_extra_data() -> User: return {"name": "John", "surname": "Doe", "password_hash": "secret"} @app.get( "/response_model_none-annotation-return_submodel_with_extra_data", response_model=None, ) def response_model_none_annotation_return_submodel_with_extra_data() -> User: return DBUser(name="John", surname="Doe", password_hash="secret") @app.get( "/response_model_model1-annotation_model2-return_same_model", response_model=User ) def response_model_model1_annotation_model2_return_same_model() -> Item: return User(name="John", surname="Doe") @app.get( "/response_model_model1-annotation_model2-return_exact_dict", response_model=User ) def response_model_model1_annotation_model2_return_exact_dict() -> Item: return {"name": "John", "surname": "Doe"} @app.get( "/response_model_model1-annotation_model2-return_invalid_dict", response_model=User ) def response_model_model1_annotation_model2_return_invalid_dict() -> Item: return {"name": "John"} @app.get( "/response_model_model1-annotation_model2-return_invalid_model", response_model=User ) def response_model_model1_annotation_model2_return_invalid_model() -> Item: return Item(name="Foo", price=42.0) @app.get( "/response_model_model1-annotation_model2-return_dict_with_extra_data", response_model=User, ) def response_model_model1_annotation_model2_return_dict_with_extra_data() -> Item: return {"name": "John", "surname": "Doe", "password_hash": "secret"} @app.get( "/response_model_model1-annotation_model2-return_submodel_with_extra_data", response_model=User, ) def response_model_model1_annotation_model2_return_submodel_with_extra_data() -> Item: return DBUser(name="John", surname="Doe", password_hash="secret") @app.get( "/response_model_filtering_model-annotation_submodel-return_submodel", response_model=User, ) def response_model_filtering_model_annotation_submodel_return_submodel() -> DBUser: return DBUser(name="John", surname="Doe", password_hash="secret") @app.get("/response_model_list_of_model-no_annotation", response_model=list[User]) def response_model_list_of_model_no_annotation(): return [ DBUser(name="John", surname="Doe", password_hash="secret"), DBUser(name="Jane", surname="Does", password_hash="secret2"), ] @app.get("/no_response_model-annotation_list_of_model") def no_response_model_annotation_list_of_model() -> list[User]: return [ DBUser(name="John", surname="Doe", password_hash="secret"), DBUser(name="Jane", surname="Does", password_hash="secret2"), ] @app.get("/no_response_model-annotation_forward_ref_list_of_model") def no_response_model_annotation_forward_ref_list_of_model() -> "list[User]": return [ DBUser(name="John", surname="Doe", password_hash="secret"), DBUser(name="Jane", surname="Does", password_hash="secret2"), ] @app.get( "/response_model_union-no_annotation-return_model1", response_model=Union[User, Item], ) def response_model_union_no_annotation_return_model1(): return DBUser(name="John", surname="Doe", password_hash="secret") @app.get( "/response_model_union-no_annotation-return_model2", response_model=Union[User, Item], ) def response_model_union_no_annotation_return_model2(): return Item(name="Foo", price=42.0) @app.get("/no_response_model-annotation_union-return_model1") def no_response_model_annotation_union_return_model1() -> Union[User, Item]: return DBUser(name="John", surname="Doe", password_hash="secret") @app.get("/no_response_model-annotation_union-return_model2") def no_response_model_annotation_union_return_model2() -> Union[User, Item]: return Item(name="Foo", price=42.0) @app.get("/no_response_model-annotation_response_class") def no_response_model_annotation_response_class() -> Response: return Response(content="Foo") @app.get("/no_response_model-annotation_json_response_class") def no_response_model_annotation_json_response_class() -> JSONResponse: return JSONResponse(content={"foo": "bar"}) client = TestClient(app) def test_no_response_model_no_annotation_return_model(): response = client.get("/no_response_model-no_annotation-return_model") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_no_response_model_no_annotation_return_dict(): response = client.get("/no_response_model-no_annotation-return_dict") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_no_annotation_return_same_model(): response = client.get("/response_model-no_annotation-return_same_model") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_no_annotation_return_exact_dict(): response = client.get("/response_model-no_annotation-return_exact_dict") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_no_annotation_return_invalid_dict(): with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model-no_annotation-return_invalid_dict") assert "missing" in str(excinfo.value) def test_response_model_no_annotation_return_invalid_model(): with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model-no_annotation-return_invalid_model") assert "missing" in str(excinfo.value) def test_response_model_no_annotation_return_dict_with_extra_data(): response = client.get("/response_model-no_annotation-return_dict_with_extra_data") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_no_annotation_return_submodel_with_extra_data(): response = client.get( "/response_model-no_annotation-return_submodel_with_extra_data" ) assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_no_response_model_annotation_return_same_model(): response = client.get("/no_response_model-annotation-return_same_model") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_no_response_model_annotation_return_exact_dict(): response = client.get("/no_response_model-annotation-return_exact_dict") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_no_response_model_annotation_return_invalid_dict(): with pytest.raises(ResponseValidationError) as excinfo: client.get("/no_response_model-annotation-return_invalid_dict") assert "missing" in str(excinfo.value) def test_no_response_model_annotation_return_invalid_model(): with pytest.raises(ResponseValidationError) as excinfo: client.get("/no_response_model-annotation-return_invalid_model") assert "missing" in str(excinfo.value) def test_no_response_model_annotation_return_dict_with_extra_data(): response = client.get("/no_response_model-annotation-return_dict_with_extra_data") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_no_response_model_annotation_return_submodel_with_extra_data(): response = client.get( "/no_response_model-annotation-return_submodel_with_extra_data" ) assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_none_annotation_return_same_model(): response = client.get("/response_model_none-annotation-return_same_model") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_none_annotation_return_exact_dict(): response = client.get("/response_model_none-annotation-return_exact_dict") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_none_annotation_return_invalid_dict(): response = client.get("/response_model_none-annotation-return_invalid_dict") assert response.status_code == 200, response.text assert response.json() == {"name": "John"} def test_response_model_none_annotation_return_invalid_model(): response = client.get("/response_model_none-annotation-return_invalid_model") assert response.status_code == 200, response.text assert response.json() == {"name": "Foo", "price": 42.0} def test_response_model_none_annotation_return_dict_with_extra_data(): response = client.get("/response_model_none-annotation-return_dict_with_extra_data") assert response.status_code == 200, response.text assert response.json() == { "name": "John", "surname": "Doe", "password_hash": "secret", } def test_response_model_none_annotation_return_submodel_with_extra_data(): response = client.get( "/response_model_none-annotation-return_submodel_with_extra_data" ) assert response.status_code == 200, response.text assert response.json() == { "name": "John", "surname": "Doe", "password_hash": "secret", } def test_response_model_model1_annotation_model2_return_same_model(): response = client.get("/response_model_model1-annotation_model2-return_same_model") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_model1_annotation_model2_return_exact_dict(): response = client.get("/response_model_model1-annotation_model2-return_exact_dict") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_model1_annotation_model2_return_invalid_dict(): with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model_model1-annotation_model2-return_invalid_dict") assert "missing" in str(excinfo.value) def test_response_model_model1_annotation_model2_return_invalid_model(): with pytest.raises(ResponseValidationError) as excinfo: client.get("/response_model_model1-annotation_model2-return_invalid_model") assert "missing" in str(excinfo.value) def test_response_model_model1_annotation_model2_return_dict_with_extra_data(): response = client.get( "/response_model_model1-annotation_model2-return_dict_with_extra_data" ) assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_model1_annotation_model2_return_submodel_with_extra_data(): response = client.get( "/response_model_model1-annotation_model2-return_submodel_with_extra_data" ) assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_filtering_model_annotation_submodel_return_submodel(): response = client.get( "/response_model_filtering_model-annotation_submodel-return_submodel" ) assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_list_of_model_no_annotation(): response = client.get("/response_model_list_of_model-no_annotation") assert response.status_code == 200, response.text assert response.json() == [ {"name": "John", "surname": "Doe"}, {"name": "Jane", "surname": "Does"}, ] def test_no_response_model_annotation_list_of_model(): response = client.get("/no_response_model-annotation_list_of_model") assert response.status_code == 200, response.text assert response.json() == [ {"name": "John", "surname": "Doe"}, {"name": "Jane", "surname": "Does"}, ] def test_no_response_model_annotation_forward_ref_list_of_model(): response = client.get("/no_response_model-annotation_forward_ref_list_of_model") assert response.status_code == 200, response.text assert response.json() == [ {"name": "John", "surname": "Doe"}, {"name": "Jane", "surname": "Does"}, ] def test_response_model_union_no_annotation_return_model1(): response = client.get("/response_model_union-no_annotation-return_model1") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_response_model_union_no_annotation_return_model2(): response = client.get("/response_model_union-no_annotation-return_model2") assert response.status_code == 200, response.text assert response.json() == {"name": "Foo", "price": 42.0} def test_no_response_model_annotation_union_return_model1(): response = client.get("/no_response_model-annotation_union-return_model1") assert response.status_code == 200, response.text assert response.json() == {"name": "John", "surname": "Doe"} def test_no_response_model_annotation_union_return_model2(): response = client.get("/no_response_model-annotation_union-return_model2") assert response.status_code == 200, response.text assert response.json() == {"name": "Foo", "price": 42.0} def test_no_response_model_annotation_return_class(): response = client.get("/no_response_model-annotation_response_class") assert response.status_code == 200, response.text assert response.text == "Foo" def test_no_response_model_annotation_json_response_class(): response = client.get("/no_response_model-annotation_json_response_class") assert response.status_code == 200, response.text assert response.json() == {"foo": "bar"} def test_invalid_response_model_field(): app = FastAPI() with pytest.raises(FastAPIError) as e: @app.get("/") def read_root() -> Union[Response, None]: return Response(content="Foo") # pragma: no cover assert "valid Pydantic field type" in e.value.args[0] assert "parameter response_model=None" in e.value.args[0] def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/no_response_model-no_annotation-return_model": { "get": { "summary": "No Response Model No Annotation Return Model", "operationId": "no_response_model_no_annotation_return_model_no_response_model_no_annotation_return_model_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/no_response_model-no_annotation-return_dict": { "get": { "summary": "No Response Model No Annotation Return Dict", "operationId": "no_response_model_no_annotation_return_dict_no_response_model_no_annotation_return_dict_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/response_model-no_annotation-return_same_model": { "get": { "summary": "Response Model No Annotation Return Same Model", "operationId": "response_model_no_annotation_return_same_model_response_model_no_annotation_return_same_model_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/response_model-no_annotation-return_exact_dict": { "get": { "summary": "Response Model No Annotation Return Exact Dict", "operationId": "response_model_no_annotation_return_exact_dict_response_model_no_annotation_return_exact_dict_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/response_model-no_annotation-return_invalid_dict": { "get": { "summary": "Response Model No Annotation Return Invalid Dict", "operationId": "response_model_no_annotation_return_invalid_dict_response_model_no_annotation_return_invalid_dict_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/response_model-no_annotation-return_invalid_model": { "get": { "summary": "Response Model No Annotation Return Invalid Model", "operationId": "response_model_no_annotation_return_invalid_model_response_model_no_annotation_return_invalid_model_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/response_model-no_annotation-return_dict_with_extra_data": { "get": { "summary": "Response Model No Annotation Return Dict With Extra Data", "operationId": "response_model_no_annotation_return_dict_with_extra_data_response_model_no_annotation_return_dict_with_extra_data_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/response_model-no_annotation-return_submodel_with_extra_data": { "get": { "summary": "Response Model No Annotation Return Submodel With Extra Data", "operationId": "response_model_no_annotation_return_submodel_with_extra_data_response_model_no_annotation_return_submodel_with_extra_data_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/no_response_model-annotation-return_same_model": { "get": { "summary": "No Response Model Annotation Return Same Model", "operationId": "no_response_model_annotation_return_same_model_no_response_model_annotation_return_same_model_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/no_response_model-annotation-return_exact_dict": { "get": { "summary": "No Response Model Annotation Return Exact Dict", "operationId": "no_response_model_annotation_return_exact_dict_no_response_model_annotation_return_exact_dict_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/no_response_model-annotation-return_invalid_dict": { "get": { "summary": "No Response Model Annotation Return Invalid Dict", "operationId": "no_response_model_annotation_return_invalid_dict_no_response_model_annotation_return_invalid_dict_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/no_response_model-annotation-return_invalid_model": { "get": { "summary": "No Response Model Annotation Return Invalid Model", "operationId": "no_response_model_annotation_return_invalid_model_no_response_model_annotation_return_invalid_model_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/no_response_model-annotation-return_dict_with_extra_data": { "get": { "summary": "No Response Model Annotation Return Dict With Extra Data", "operationId": "no_response_model_annotation_return_dict_with_extra_data_no_response_model_annotation_return_dict_with_extra_data_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/no_response_model-annotation-return_submodel_with_extra_data": { "get": { "summary": "No Response Model Annotation Return Submodel With Extra Data", "operationId": "no_response_model_annotation_return_submodel_with_extra_data_no_response_model_annotation_return_submodel_with_extra_data_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/User"} } }, } }, } }, "/response_model_none-annotation-return_same_model": { "get": { "summary": "Response Model None Annotation Return Same Model", "operationId": "response_model_none_annotation_return_same_model_response_model_none_annotation_return_same_model_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/response_model_none-annotation-return_exact_dict": { "get": { "summary": "Response Model None Annotation Return Exact Dict", "operationId": "response_model_none_annotation_return_exact_dict_response_model_none_annotation_return_exact_dict_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/response_model_none-annotation-return_invalid_dict": { "get": { "summary": "Response Model None Annotation Return Invalid Dict", "operationId": "response_model_none_annotation_return_invalid_dict_response_model_none_annotation_return_invalid_dict_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/response_model_none-annotation-return_invalid_model": { "get": { "summary": "Response Model None Annotation Return Invalid Model", "operationId": "response_model_none_annotation_return_invalid_model_response_model_none_annotation_return_invalid_model_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/response_model_none-annotation-return_dict_with_extra_data": { "get": { "summary": "Response Model None Annotation Return Dict With Extra Data", "operationId": "response_model_none_annotation_return_dict_with_extra_data_response_model_none_annotation_return_dict_with_extra_data_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/response_model_none-annotation-return_submodel_with_extra_data": { "get": { "summary": "Response Model None Annotation Return Submodel With Extra Data", "operationId": "response_model_none_annotation_return_submodel_with_extra_data_response_model_none_annotation_return_submodel_with_extra_data_get", "responses": { "200": {
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py
tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py
from __future__ import annotations import uuid from dataclasses import dataclass, field from typing import Union from dirty_equals import IsUUID from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot @dataclass class Item: id: uuid.UUID name: str price: float tags: list[str] = field(default_factory=list) description: Union[str, None] = None tax: Union[float, None] = None app = FastAPI() @app.get("/item", response_model=Item) async def read_item(): return { "id": uuid.uuid4(), "name": "Island In The Moon", "price": 12.99, "description": "A place to be be playin' and havin' fun", "tags": ["breater"], } client = TestClient(app) def test_annotations(): response = client.get("/item") assert response.status_code == 200, response.text assert response.json() == snapshot( { "id": IsUUID(), "name": "Island In The Moon", "price": 12.99, "tags": ["breater"], "description": "A place to be be playin' and havin' fun", "tax": None, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_starlette_urlconvertors.py
tests/test_starlette_urlconvertors.py
from fastapi import FastAPI, Path, Query from fastapi.testclient import TestClient app = FastAPI() @app.get("/int/{param:int}") def int_convertor(param: int = Path()): return {"int": param} @app.get("/float/{param:float}") def float_convertor(param: float = Path()): return {"float": param} @app.get("/path/{param:path}") def path_convertor(param: str = Path()): return {"path": param} @app.get("/query/") def query_convertor(param: str = Query()): return {"query": param} client = TestClient(app) def test_route_converters_int(): # Test integer conversion response = client.get("/int/5") assert response.status_code == 200, response.text assert response.json() == {"int": 5} assert app.url_path_for("int_convertor", param=5) == "/int/5" # type: ignore def test_route_converters_float(): # Test float conversion response = client.get("/float/25.5") assert response.status_code == 200, response.text assert response.json() == {"float": 25.5} assert app.url_path_for("float_convertor", param=25.5) == "/float/25.5" # type: ignore def test_route_converters_path(): # Test path conversion response = client.get("/path/some/example") assert response.status_code == 200, response.text assert response.json() == {"path": "some/example"} def test_route_converters_query(): # Test query conversion response = client.get("/query", params={"param": "Qué tal!"}) assert response.status_code == 200, response.text assert response.json() == {"query": "Qué tal!"} def test_url_path_for_path_convertor(): assert ( app.url_path_for("path_convertor", param="some/example") == "/path/some/example" )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_param_in_path_and_dependency.py
tests/test_param_in_path_and_dependency.py
from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def user_exists(user_id: int): return True @app.get("/users/{user_id}", dependencies=[Depends(user_exists)]) async def read_users(user_id: int): pass client = TestClient(app) def test_read_users(): response = client.get("/users/42") assert response.status_code == 200, response.text def test_openapi_schema(): response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/{user_id}": { "get": { "summary": "Read Users", "operationId": "read_users_users__user_id__get", "parameters": [ { "required": True, "schema": {"title": "User Id", "type": "integer"}, "name": "user_id", "in": "path", }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_scopes.py
tests/test_security_scopes.py
from typing import Annotated import pytest from fastapi import Depends, FastAPI, Security from fastapi.testclient import TestClient @pytest.fixture(name="call_counter") def call_counter_fixture(): return {"count": 0} @pytest.fixture(name="app") def app_fixture(call_counter: dict[str, int]): def get_db(): call_counter["count"] += 1 return f"db_{call_counter['count']}" def get_user(db: Annotated[str, Depends(get_db)]): return "user" app = FastAPI() @app.get("/") def endpoint( db: Annotated[str, Depends(get_db)], user: Annotated[str, Security(get_user, scopes=["read"])], ): return {"db": db} return app @pytest.fixture(name="client") def client_fixture(app: FastAPI): return TestClient(app) def test_security_scopes_dependency_called_once( client: TestClient, call_counter: dict[str, int] ): response = client.get("/") assert response.status_code == 200 assert call_counter["count"] == 1
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_jsonable_encoder.py
tests/test_jsonable_encoder.py
import warnings from collections import deque from dataclasses import dataclass from datetime import datetime, timezone from decimal import Decimal from enum import Enum from math import isinf, isnan from pathlib import PurePath, PurePosixPath, PureWindowsPath from typing import Optional, TypedDict import pytest from fastapi._compat import Undefined from fastapi.encoders import jsonable_encoder from fastapi.exceptions import PydanticV1NotSupportedError from pydantic import BaseModel, Field, ValidationError class Person: def __init__(self, name: str): self.name = name class Pet: def __init__(self, owner: Person, name: str): self.owner = owner self.name = name @dataclass class Item: name: str count: int class DictablePerson(Person): def __iter__(self): return ((k, v) for k, v in self.__dict__.items()) class DictablePet(Pet): def __iter__(self): return ((k, v) for k, v in self.__dict__.items()) class Unserializable: def __iter__(self): raise NotImplementedError() @property def __dict__(self): raise NotImplementedError() class RoleEnum(Enum): admin = "admin" normal = "normal" class ModelWithConfig(BaseModel): role: Optional[RoleEnum] = None model_config = {"use_enum_values": True} class ModelWithAlias(BaseModel): foo: str = Field(alias="Foo") class ModelWithDefault(BaseModel): foo: str = ... # type: ignore bar: str = "bar" bla: str = "bla" def test_encode_dict(): pet = {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} assert jsonable_encoder(pet, include={}) == {} assert jsonable_encoder(pet, exclude={}) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_dict_include_exclude_list(): pet = {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include=["name"]) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude=["owner"]) == {"name": "Firulais"} assert jsonable_encoder(pet, include=[]) == {} assert jsonable_encoder(pet, exclude=[]) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_class(): person = Person(name="Foo") pet = Pet(owner=person, name="Firulais") assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} assert jsonable_encoder(pet, include={}) == {} assert jsonable_encoder(pet, exclude={}) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_dictable(): person = DictablePerson(name="Foo") pet = DictablePet(owner=person, name="Firulais") assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} assert jsonable_encoder(pet, include={}) == {} assert jsonable_encoder(pet, exclude={}) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_dataclass(): item = Item(name="foo", count=100) assert jsonable_encoder(item) == {"name": "foo", "count": 100} assert jsonable_encoder(item, include={"name"}) == {"name": "foo"} assert jsonable_encoder(item, exclude={"count"}) == {"name": "foo"} assert jsonable_encoder(item, include={}) == {} assert jsonable_encoder(item, exclude={}) == {"name": "foo", "count": 100} def test_encode_unsupported(): unserializable = Unserializable() with pytest.raises(ValueError): jsonable_encoder(unserializable) def test_encode_custom_json_encoders_model_pydanticv2(): from pydantic import field_serializer class ModelWithCustomEncoder(BaseModel): dt_field: datetime @field_serializer("dt_field") def serialize_dt_field(self, dt): return dt.replace(microsecond=0, tzinfo=timezone.utc).isoformat() class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): pass model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"} def test_json_encoder_error_with_pydanticv1(): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) from pydantic import v1 class ModelV1(v1.BaseModel): name: str data = ModelV1(name="test") with pytest.raises(PydanticV1NotSupportedError): jsonable_encoder(data) def test_encode_model_with_config(): model = ModelWithConfig(role=RoleEnum.admin) assert jsonable_encoder(model) == {"role": "admin"} def test_encode_model_with_alias_raises(): with pytest.raises(ValidationError): ModelWithAlias(foo="Bar") def test_encode_model_with_alias(): model = ModelWithAlias(Foo="Bar") assert jsonable_encoder(model) == {"Foo": "Bar"} def test_encode_model_with_default(): model = ModelWithDefault(foo="foo", bar="bar") assert jsonable_encoder(model) == {"foo": "foo", "bar": "bar", "bla": "bla"} assert jsonable_encoder(model, exclude_unset=True) == {"foo": "foo", "bar": "bar"} assert jsonable_encoder(model, exclude_defaults=True) == {"foo": "foo"} assert jsonable_encoder(model, exclude_unset=True, exclude_defaults=True) == { "foo": "foo" } assert jsonable_encoder(model, include={"foo"}) == {"foo": "foo"} assert jsonable_encoder(model, exclude={"bla"}) == {"foo": "foo", "bar": "bar"} assert jsonable_encoder(model, include={}) == {} assert jsonable_encoder(model, exclude={}) == { "foo": "foo", "bar": "bar", "bla": "bla", } def test_custom_encoders(): class safe_datetime(datetime): pass class MyDict(TypedDict): dt_field: safe_datetime instance = MyDict(dt_field=safe_datetime.now()) encoded_instance = jsonable_encoder( instance, custom_encoder={safe_datetime: lambda o: o.strftime("%H:%M:%S")} ) assert encoded_instance["dt_field"] == instance["dt_field"].strftime("%H:%M:%S") encoded_instance = jsonable_encoder( instance, custom_encoder={datetime: lambda o: o.strftime("%H:%M:%S")} ) assert encoded_instance["dt_field"] == instance["dt_field"].strftime("%H:%M:%S") encoded_instance2 = jsonable_encoder(instance) assert encoded_instance2["dt_field"] == instance["dt_field"].isoformat() def test_custom_enum_encoders(): def custom_enum_encoder(v: Enum): return v.value.lower() class MyEnum(Enum): ENUM_VAL_1 = "ENUM_VAL_1" instance = MyEnum.ENUM_VAL_1 encoded_instance = jsonable_encoder( instance, custom_encoder={MyEnum: custom_enum_encoder} ) assert encoded_instance == custom_enum_encoder(instance) def test_encode_model_with_pure_path(): class ModelWithPath(BaseModel): path: PurePath model_config = {"arbitrary_types_allowed": True} test_path = PurePath("/foo", "bar") obj = ModelWithPath(path=test_path) assert jsonable_encoder(obj) == {"path": str(test_path)} def test_encode_model_with_pure_posix_path(): class ModelWithPath(BaseModel): path: PurePosixPath model_config = {"arbitrary_types_allowed": True} obj = ModelWithPath(path=PurePosixPath("/foo", "bar")) assert jsonable_encoder(obj) == {"path": "/foo/bar"} def test_encode_model_with_pure_windows_path(): class ModelWithPath(BaseModel): path: PureWindowsPath model_config = {"arbitrary_types_allowed": True} obj = ModelWithPath(path=PureWindowsPath("/foo", "bar")) assert jsonable_encoder(obj) == {"path": "\\foo\\bar"} def test_encode_pure_path(): test_path = PurePath("/foo", "bar") assert jsonable_encoder({"path": test_path}) == {"path": str(test_path)} def test_decimal_encoder_float(): data = {"value": Decimal(1.23)} assert jsonable_encoder(data) == {"value": 1.23} def test_decimal_encoder_int(): data = {"value": Decimal(2)} assert jsonable_encoder(data) == {"value": 2} def test_decimal_encoder_nan(): data = {"value": Decimal("NaN")} assert isnan(jsonable_encoder(data)["value"]) def test_decimal_encoder_infinity(): data = {"value": Decimal("Infinity")} assert isinf(jsonable_encoder(data)["value"]) data = {"value": Decimal("-Infinity")} assert isinf(jsonable_encoder(data)["value"]) def test_encode_deque_encodes_child_models(): class Model(BaseModel): test: str dq = deque([Model(test="test")]) assert jsonable_encoder(dq)[0]["test"] == "test" def test_encode_pydantic_undefined(): data = {"value": Undefined} assert jsonable_encoder(data) == {"value": None}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_base.py
tests/test_security_http_base.py
from fastapi import FastAPI, Security from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase from fastapi.testclient import TestClient app = FastAPI() security = HTTPBase(scheme="Other") @app.get("/users/me") def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): return {"scheme": credentials.scheme, "credentials": credentials.credentials} client = TestClient(app) def test_security_http_base(): response = client.get("/users/me", headers={"Authorization": "Other foobar"}) assert response.status_code == 200, response.text assert response.json() == {"scheme": "Other", "credentials": "foobar"} def test_security_http_base_no_credentials(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Other" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"HTTPBase": []}], } } }, "components": { "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}} }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_bearer.py
tests/test_security_http_bearer.py
from fastapi import FastAPI, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.testclient import TestClient app = FastAPI() security = HTTPBearer() @app.get("/users/me") def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): return {"scheme": credentials.scheme, "credentials": credentials.credentials} client = TestClient(app) def test_security_http_bearer(): response = client.get("/users/me", headers={"Authorization": "Bearer foobar"}) assert response.status_code == 200, response.text assert response.json() == {"scheme": "Bearer", "credentials": "foobar"} def test_security_http_bearer_no_credentials(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" def test_security_http_bearer_incorrect_scheme_credentials(): response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"HTTPBearer": []}], } } }, "components": { "securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}} }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_responses_router.py
tests/test_additional_responses_router.py
from fastapi import APIRouter, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel class ResponseModel(BaseModel): message: str app = FastAPI() router = APIRouter() @router.get("/a", responses={501: {"description": "Error 1"}}) async def a(): return "a" @router.get( "/b", responses={ 502: {"description": "Error 2"}, "4XX": {"description": "Error with range, upper"}, }, ) async def b(): return "b" @router.get( "/c", responses={ "400": {"description": "Error with str"}, "5xx": {"description": "Error with range, lower"}, "default": {"description": "A default response"}, }, ) async def c(): return "c" @router.get( "/d", responses={ "400": {"description": "Error with str"}, "5XX": {"model": ResponseModel}, "default": {"model": ResponseModel}, }, ) async def d(): return "d" app.include_router(router) client = TestClient(app) def test_a(): response = client.get("/a") assert response.status_code == 200, response.text assert response.json() == "a" def test_b(): response = client.get("/b") assert response.status_code == 200, response.text assert response.json() == "b" def test_c(): response = client.get("/c") assert response.status_code == 200, response.text assert response.json() == "c" def test_d(): response = client.get("/d") assert response.status_code == 200, response.text assert response.json() == "d" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a": { "get": { "responses": { "501": {"description": "Error 1"}, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, }, "summary": "A", "operationId": "a_a_get", } }, "/b": { "get": { "responses": { "502": {"description": "Error 2"}, "4XX": {"description": "Error with range, upper"}, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, }, "summary": "B", "operationId": "b_b_get", } }, "/c": { "get": { "responses": { "400": {"description": "Error with str"}, "5XX": {"description": "Error with range, lower"}, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "default": {"description": "A default response"}, }, "summary": "C", "operationId": "c_c_get", } }, "/d": { "get": { "responses": { "400": {"description": "Error with str"}, "5XX": { "description": "Server Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseModel" } } }, }, "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "default": { "description": "Default Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseModel" } } }, }, }, "summary": "D", "operationId": "d_d_get", } }, }, "components": { "schemas": { "ResponseModel": { "title": "ResponseModel", "required": ["message"], "type": "object", "properties": {"message": {"title": "Message", "type": "string"}}, } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_optional_file_list.py
tests/test_optional_file_list.py
from typing import Optional from fastapi import FastAPI, File from fastapi.testclient import TestClient app = FastAPI() @app.post("/files") async def upload_files(files: Optional[list[bytes]] = File(None)): if files is None: return {"files_count": 0} return {"files_count": len(files), "sizes": [len(f) for f in files]} def test_optional_bytes_list(): client = TestClient(app) response = client.post( "/files", files=[("files", b"content1"), ("files", b"content2")], ) assert response.status_code == 200 assert response.json() == {"files_count": 2, "sizes": [8, 8]} def test_optional_bytes_list_no_files(): client = TestClient(app) response = client.post("/files") assert response.status_code == 200 assert response.json() == {"files_count": 0}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py
tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py
# Ref: https://github.com/fastapi/fastapi/issues/14454 from typing import Annotated from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2AuthorizationCodeBearer from fastapi.testclient import TestClient from inline_snapshot import snapshot oauth2_scheme = OAuth2AuthorizationCodeBearer( authorizationUrl="api/oauth/authorize", tokenUrl="/api/oauth/token", scopes={"read": "Read access", "write": "Write access"}, ) async def get_token(token: Annotated[str, Depends(oauth2_scheme)]) -> str: return token app = FastAPI(dependencies=[Depends(get_token)]) @app.get("/admin", dependencies=[Security(get_token, scopes=["read", "write"])]) async def read_admin(): return {"message": "Admin Access"} client = TestClient(app) def test_read_admin(): response = client.get("/admin", headers={"Authorization": "Bearer faketoken"}) assert response.status_code == 200, response.text assert response.json() == {"message": "Admin Access"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/admin": { "get": { "summary": "Read Admin", "operationId": "read_admin_admin_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "security": [ {"OAuth2AuthorizationCodeBearer": ["read", "write"]} ], } } }, "components": { "securitySchemes": { "OAuth2AuthorizationCodeBearer": { "type": "oauth2", "flows": { "authorizationCode": { "scopes": { "read": "Read access", "write": "Write access", }, "authorizationUrl": "api/oauth/authorize", "tokenUrl": "/api/oauth/token", } }, } } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_get_model_definitions_formfeed_escape.py
tests/test_get_model_definitions_formfeed_escape.py
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot @pytest.fixture(name="client") def client_fixture() -> TestClient: from pydantic import BaseModel class Address(BaseModel): """ This is a public description of an Address \f You can't see this part of the docstring, it's private! """ line_1: str city: str state_province: str class Facility(BaseModel): id: str address: Address app = FastAPI() @app.get("/facilities/{facility_id}") def get_facility(facility_id: str) -> Facility: return Facility( id=facility_id, address=Address(line_1="123 Main St", city="Anytown", state_province="CA"), ) client = TestClient(app) return client def test_get(client: TestClient): response = client.get("/facilities/42") assert response.status_code == 200, response.text assert response.json() == { "id": "42", "address": { "line_1": "123 Main St", "city": "Anytown", "state_province": "CA", }, } def test_openapi_schema(client: TestClient): """ Sanity check to ensure our app's openapi schema renders as we expect """ response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "components": { "schemas": { "Address": { # NOTE: the description of this model shows only the public-facing text, before the `\f` in docstring "description": "This is a public description of an Address\n", "properties": { "city": {"title": "City", "type": "string"}, "line_1": {"title": "Line 1", "type": "string"}, "state_province": { "title": "State Province", "type": "string", }, }, "required": ["line_1", "city", "state_province"], "title": "Address", "type": "object", }, "Facility": { "properties": { "address": {"$ref": "#/components/schemas/Address"}, "id": {"title": "Id", "type": "string"}, }, "required": ["id", "address"], "title": "Facility", "type": "object", }, "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "title": "Detail", "type": "array", } }, "title": "HTTPValidationError", "type": "object", }, "ValidationError": { "properties": { "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": { "/facilities/{facility_id}": { "get": { "operationId": "get_facility_facilities__facility_id__get", "parameters": [ { "in": "path", "name": "facility_id", "required": True, "schema": {"title": "Facility Id", "type": "string"}, } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Facility" } } }, "description": "Successful Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, "description": "Validation Error", }, }, "summary": "Get Facility", } } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_no_schema_split.py
tests/test_no_schema_split.py
# Test with parts from, and to verify the report in: # https://github.com/fastapi/fastapi/discussions/14177 # Made an issue in: # https://github.com/fastapi/fastapi/issues/14247 from enum import Enum from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot from pydantic import BaseModel, Field class MessageEventType(str, Enum): alpha = "alpha" beta = "beta" class MessageEvent(BaseModel): event_type: MessageEventType = Field(default=MessageEventType.alpha) output: str class MessageOutput(BaseModel): body: str = "" events: list[MessageEvent] = [] class Message(BaseModel): input: str output: MessageOutput app = FastAPI(title="Minimal FastAPI App", version="1.0.0") @app.post("/messages", response_model=Message) async def create_message(input_message: str) -> Message: return Message( input=input_message, output=MessageOutput(body=f"Processed: {input_message}"), ) client = TestClient(app) def test_create_message(): response = client.post("/messages", params={"input_message": "Hello"}) assert response.status_code == 200, response.text assert response.json() == { "input": "Hello", "output": {"body": "Processed: Hello", "events": []}, } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "Minimal FastAPI App", "version": "1.0.0"}, "paths": { "/messages": { "post": { "summary": "Create Message", "operationId": "create_message_messages_post", "parameters": [ { "name": "input_message", "in": "query", "required": True, "schema": {"type": "string", "title": "Input Message"}, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Message" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Message": { "properties": { "input": {"type": "string", "title": "Input"}, "output": {"$ref": "#/components/schemas/MessageOutput"}, }, "type": "object", "required": ["input", "output"], "title": "Message", }, "MessageEvent": { "properties": { "event_type": { "$ref": "#/components/schemas/MessageEventType", "default": "alpha", }, "output": {"type": "string", "title": "Output"}, }, "type": "object", "required": ["output"], "title": "MessageEvent", }, "MessageEventType": { "type": "string", "enum": ["alpha", "beta"], "title": "MessageEventType", }, "MessageOutput": { "properties": { "body": {"type": "string", "title": "Body", "default": ""}, "events": { "items": {"$ref": "#/components/schemas/MessageEvent"}, "type": "array", "title": "Events", "default": [], }, }, "type": "object", "title": "MessageOutput", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_basic_optional.py
tests/test_security_http_basic_optional.py
from base64 import b64encode from typing import Optional from fastapi import FastAPI, Security from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi.testclient import TestClient app = FastAPI() security = HTTPBasic(auto_error=False) @app.get("/users/me") def read_current_user(credentials: Optional[HTTPBasicCredentials] = Security(security)): if credentials is None: return {"msg": "Create an account first"} return {"username": credentials.username, "password": credentials.password} client = TestClient(app) def test_security_http_basic(): response = client.get("/users/me", auth=("john", "secret")) assert response.status_code == 200, response.text assert response.json() == {"username": "john", "password": "secret"} def test_security_http_basic_no_credentials(): response = client.get("/users/me") assert response.status_code == 200, response.text assert response.json() == {"msg": "Create an account first"} def test_security_http_basic_invalid_credentials(): response = client.get( "/users/me", headers={"Authorization": "Basic notabase64token"} ) assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == "Basic" assert response.json() == {"detail": "Not authenticated"} def test_security_http_basic_non_basic_credentials(): payload = b64encode(b"johnsecret").decode("ascii") auth_header = f"Basic {payload}" response = client.get("/users/me", headers={"Authorization": auth_header}) assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == "Basic" assert response.json() == {"detail": "Not authenticated"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"HTTPBasic": []}], } } }, "components": { "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_scopes_dont_propagate.py
tests/test_security_scopes_dont_propagate.py
# Ref: https://github.com/tiangolo/fastapi/issues/5623 from typing import Annotated, Any from fastapi import FastAPI, Security from fastapi.security import SecurityScopes from fastapi.testclient import TestClient async def security1(scopes: SecurityScopes): return scopes.scopes async def security2(scopes: SecurityScopes): return scopes.scopes async def dep3( dep1: Annotated[list[str], Security(security1, scopes=["scope1"])], dep2: Annotated[list[str], Security(security2, scopes=["scope2"])], ): return {"dep1": dep1, "dep2": dep2} app = FastAPI() @app.get("/scopes") def get_scopes( dep3: Annotated[dict[str, Any], Security(dep3, scopes=["scope3"])], ): return dep3 client = TestClient(app) def test_security_scopes_dont_propagate(): response = client.get("/scopes") assert response.status_code == 200 assert response.json() == { "dep1": ["scope3", "scope1"], "dep2": ["scope3", "scope2"], }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_model_data_filter_no_inheritance.py
tests/test_response_model_data_filter_no_inheritance.py
from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class UserCreate(BaseModel): email: str password: str class UserDB(BaseModel): email: str hashed_password: str class User(BaseModel): email: str class PetDB(BaseModel): name: str owner: UserDB class PetOut(BaseModel): name: str owner: User @app.post("/users/", response_model=User) async def create_user(user: UserCreate): return user @app.get("/pets/{pet_id}", response_model=PetOut) async def read_pet(pet_id: int): user = UserDB( email="johndoe@example.com", hashed_password="secrethashed", ) pet = PetDB(name="Nibbler", owner=user) return pet @app.get("/pets/", response_model=list[PetOut]) async def read_pets(): user = UserDB( email="johndoe@example.com", hashed_password="secrethashed", ) pet1 = PetDB(name="Nibbler", owner=user) pet2 = PetDB(name="Zoidberg", owner=user) return [pet1, pet2] client = TestClient(app) def test_filter_top_level_model(): response = client.post( "/users", json={"email": "johndoe@example.com", "password": "secret"} ) assert response.json() == {"email": "johndoe@example.com"} def test_filter_second_level_model(): response = client.get("/pets/1") assert response.json() == { "name": "Nibbler", "owner": {"email": "johndoe@example.com"}, } def test_list_of_models(): response = client.get("/pets/") assert response.json() == [ {"name": "Nibbler", "owner": {"email": "johndoe@example.com"}}, {"name": "Zoidberg", "owner": {"email": "johndoe@example.com"}}, ]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_param_model_by_alias.py
tests/test_request_param_model_by_alias.py
from dirty_equals import IsPartialDict from fastapi import Cookie, FastAPI, Header, Query from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() class Model(BaseModel): param: str = Field(alias="param_alias") @app.get("/query") async def query_model(data: Model = Query()): return {"param": data.param} @app.get("/header") async def header_model(data: Model = Header()): return {"param": data.param} @app.get("/cookie") async def cookie_model(data: Model = Cookie()): return {"param": data.param} def test_query_model_with_alias(): client = TestClient(app) response = client.get("/query", params={"param_alias": "value"}) assert response.status_code == 200, response.text assert response.json() == {"param": "value"} def test_header_model_with_alias(): client = TestClient(app) response = client.get("/header", headers={"param_alias": "value"}) assert response.status_code == 200, response.text assert response.json() == {"param": "value"} def test_cookie_model_with_alias(): client = TestClient(app) client.cookies.set("param_alias", "value") response = client.get("/cookie") assert response.status_code == 200, response.text assert response.json() == {"param": "value"} def test_query_model_with_alias_by_name(): client = TestClient(app) response = client.get("/query", params={"param": "value"}) assert response.status_code == 422, response.text details = response.json() assert details["detail"][0]["input"] == {"param": "value"} def test_header_model_with_alias_by_name(): client = TestClient(app) response = client.get("/header", headers={"param": "value"}) assert response.status_code == 422, response.text details = response.json() assert details["detail"][0]["input"] == IsPartialDict({"param": "value"}) def test_cookie_model_with_alias_by_name(): client = TestClient(app) client.cookies.set("param", "value") response = client.get("/cookie") assert response.status_code == 422, response.text details = response.json() assert details["detail"][0]["input"] == {"param": "value"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_authorization_code_bearer_description.py
tests/test_security_oauth2_authorization_code_bearer_description.py
from typing import Optional from fastapi import FastAPI, Security from fastapi.security import OAuth2AuthorizationCodeBearer from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2AuthorizationCodeBearer( authorizationUrl="authorize", tokenUrl="token", description="OAuth2 Code Bearer", auto_error=True, ) @app.get("/items/") async def read_items(token: Optional[str] = Security(oauth2_scheme)): return {"token": token} client = TestClient(app) def test_no_token(): response = client.get("/items") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} def test_incorrect_token(): response = client.get("/items", headers={"Authorization": "Non-existent testtoken"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} def test_token(): response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Items", "operationId": "read_items_items__get", "security": [{"OAuth2AuthorizationCodeBearer": []}], } } }, "components": { "securitySchemes": { "OAuth2AuthorizationCodeBearer": { "type": "oauth2", "flows": { "authorizationCode": { "authorizationUrl": "authorize", "tokenUrl": "token", "scopes": {}, } }, "description": "OAuth2 Code Bearer", } } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_enforce_once_required_parameter.py
tests/test_enforce_once_required_parameter.py
from typing import Optional from fastapi import Depends, FastAPI, Query, status from fastapi.testclient import TestClient app = FastAPI() def _get_client_key(client_id: str = Query(...)) -> str: return f"{client_id}_key" def _get_client_tag(client_id: Optional[str] = Query(None)) -> Optional[str]: if client_id is None: return None return f"{client_id}_tag" @app.get("/foo") def foo_handler( client_key: str = Depends(_get_client_key), client_tag: Optional[str] = Depends(_get_client_tag), ): return {"client_id": client_key, "client_tag": client_tag} client = TestClient(app) expected_schema = { "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "title": "Detail", "type": "array", } }, "title": "HTTPValidationError", "type": "object", }, "ValidationError": { "properties": { "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": { "/foo": { "get": { "operationId": "foo_handler_foo_get", "parameters": [ { "in": "query", "name": "client_id", "required": True, "schema": {"title": "Client Id", "type": "string"}, }, ], "responses": { "200": { "content": {"application/json": {"schema": {}}}, "description": "Successful Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, "description": "Validation Error", }, }, "summary": "Foo Handler", } } }, } def test_schema(): response = client.get("/openapi.json") assert response.status_code == status.HTTP_200_OK actual_schema = response.json() assert actual_schema == expected_schema def test_get_invalid(): response = client.get("/foo") assert response.status_code == 422 def test_get_valid(): response = client.get("/foo", params={"client_id": "bar"}) assert response.status_code == 200 assert response.json() == {"client_id": "bar_key", "client_tag": "bar_tag"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_header.py
tests/test_security_api_key_header.py
from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyHeader from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() api_key = APIKeyHeader(name="key") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) def test_security_api_key(): response = client.get("/users/me", headers={"key": "secret"}) assert response.status_code == 200, response.text assert response.json() == {"username": "secret"} def test_security_api_key_no_key(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "APIKey" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"APIKeyHeader": []}], } } }, "components": { "securitySchemes": { "APIKeyHeader": {"type": "apiKey", "name": "key", "in": "header"} } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_invalid_path_param.py
tests/test_invalid_path_param.py
import pytest from fastapi import FastAPI from pydantic import BaseModel def test_invalid_sequence(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/{id}") def read_items(id: list[Item]): pass # pragma: no cover def test_invalid_tuple(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/{id}") def read_items(id: tuple[Item, Item]): pass # pragma: no cover def test_invalid_dict(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/{id}") def read_items(id: dict[str, Item]): pass # pragma: no cover def test_invalid_simple_list(): with pytest.raises(AssertionError): app = FastAPI() @app.get("/items/{id}") def read_items(id: list): pass # pragma: no cover def test_invalid_simple_tuple(): with pytest.raises(AssertionError): app = FastAPI() @app.get("/items/{id}") def read_items(id: tuple): pass # pragma: no cover def test_invalid_simple_set(): with pytest.raises(AssertionError): app = FastAPI() @app.get("/items/{id}") def read_items(id: set): pass # pragma: no cover def test_invalid_simple_dict(): with pytest.raises(AssertionError): app = FastAPI() @app.get("/items/{id}") def read_items(id: dict): pass # pragma: no cover
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_params_repr.py
tests/test_params_repr.py
from typing import Any from fastapi.params import Body, Cookie, Header, Param, Path, Query test_data: list[Any] = ["teststr", None, ..., 1, []] def get_user(): return {} # pragma: no cover def test_param_repr_str(): assert repr(Param("teststr")) == "Param(teststr)" def test_param_repr_none(): assert repr(Param(None)) == "Param(None)" def test_param_repr_ellipsis(): assert repr(Param(...)) == "Param(PydanticUndefined)" def test_param_repr_number(): assert repr(Param(1)) == "Param(1)" def test_param_repr_list(): assert repr(Param([])) == "Param([])" def test_path_repr(): assert repr(Path()) == "Path(PydanticUndefined)" assert repr(Path(...)) == "Path(PydanticUndefined)" def test_query_repr_str(): assert repr(Query("teststr")) == "Query(teststr)" def test_query_repr_none(): assert repr(Query(None)) == "Query(None)" def test_query_repr_ellipsis(): assert repr(Query(...)) == "Query(PydanticUndefined)" def test_query_repr_number(): assert repr(Query(1)) == "Query(1)" def test_query_repr_list(): assert repr(Query([])) == "Query([])" def test_header_repr_str(): assert repr(Header("teststr")) == "Header(teststr)" def test_header_repr_none(): assert repr(Header(None)) == "Header(None)" def test_header_repr_ellipsis(): assert repr(Header(...)) == "Header(PydanticUndefined)" def test_header_repr_number(): assert repr(Header(1)) == "Header(1)" def test_header_repr_list(): assert repr(Header([])) == "Header([])" def test_cookie_repr_str(): assert repr(Cookie("teststr")) == "Cookie(teststr)" def test_cookie_repr_none(): assert repr(Cookie(None)) == "Cookie(None)" def test_cookie_repr_ellipsis(): assert repr(Cookie(...)) == "Cookie(PydanticUndefined)" def test_cookie_repr_number(): assert repr(Cookie(1)) == "Cookie(1)" def test_cookie_repr_list(): assert repr(Cookie([])) == "Cookie([])" def test_body_repr_str(): assert repr(Body("teststr")) == "Body(teststr)" def test_body_repr_none(): assert repr(Body(None)) == "Body(None)" def test_body_repr_ellipsis(): assert repr(Body(...)) == "Body(PydanticUndefined)" def test_body_repr_number(): assert repr(Body(1)) == "Body(1)" def test_body_repr_list(): assert repr(Body([])) == "Body([])"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_union_body_discriminator_annotated.py
tests/test_union_body_discriminator_annotated.py
# Ref: https://github.com/fastapi/fastapi/discussions/14495 from typing import Annotated, Union import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot from pydantic import BaseModel @pytest.fixture(name="client") def client_fixture() -> TestClient: from fastapi import Body from pydantic import Discriminator, Tag class Cat(BaseModel): pet_type: str = "cat" meows: int class Dog(BaseModel): pet_type: str = "dog" barks: float def get_pet_type(v): assert isinstance(v, dict) return v.get("pet_type", "") Pet = Annotated[ Union[Annotated[Cat, Tag("cat")], Annotated[Dog, Tag("dog")]], Discriminator(get_pet_type), ] app = FastAPI() @app.post("/pet/assignment") async def create_pet_assignment(pet: Pet = Body()): return pet @app.post("/pet/annotated") async def create_pet_annotated(pet: Annotated[Pet, Body()]): return pet client = TestClient(app) return client def test_union_body_discriminator_assignment(client: TestClient) -> None: response = client.post("/pet/assignment", json={"pet_type": "cat", "meows": 5}) assert response.status_code == 200, response.text assert response.json() == {"pet_type": "cat", "meows": 5} def test_union_body_discriminator_annotated(client: TestClient) -> None: response = client.post("/pet/annotated", json={"pet_type": "dog", "barks": 3.5}) assert response.status_code == 200, response.text assert response.json() == {"pet_type": "dog", "barks": 3.5} def test_openapi_schema(client: TestClient) -> None: response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/pet/assignment": { "post": { "summary": "Create Pet Assignment", "operationId": "create_pet_assignment_pet_assignment_post", "requestBody": { "content": { "application/json": { "schema": { "anyOf": [ {"$ref": "#/components/schemas/Cat"}, {"$ref": "#/components/schemas/Dog"}, ], "title": "Pet", } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/pet/annotated": { "post": { "summary": "Create Pet Annotated", "operationId": "create_pet_annotated_pet_annotated_post", "requestBody": { "content": { "application/json": { "schema": { "oneOf": [ {"$ref": "#/components/schemas/Cat"}, {"$ref": "#/components/schemas/Dog"}, ], "title": "Pet", } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Cat": { "properties": { "pet_type": { "type": "string", "title": "Pet Type", "default": "cat", }, "meows": {"type": "integer", "title": "Meows"}, }, "type": "object", "required": ["meows"], "title": "Cat", }, "Dog": { "properties": { "pet_type": { "type": "string", "title": "Pet Type", "default": "dog", }, "barks": {"type": "number", "title": "Barks"}, }, "type": "object", "required": ["barks"], "title": "Dog", }, "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_digest.py
tests/test_security_http_digest.py
from fastapi import FastAPI, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest from fastapi.testclient import TestClient app = FastAPI() security = HTTPDigest() @app.get("/users/me") def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): return {"scheme": credentials.scheme, "credentials": credentials.credentials} client = TestClient(app) def test_security_http_digest(): response = client.get("/users/me", headers={"Authorization": "Digest foobar"}) assert response.status_code == 200, response.text assert response.json() == {"scheme": "Digest", "credentials": "foobar"} def test_security_http_digest_no_credentials(): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Digest" def test_security_http_digest_incorrect_scheme_credentials(): response = client.get( "/users/me", headers={"Authorization": "Other invalidauthorization"} ) assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Digest" def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/users/me": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Read Current User", "operationId": "read_current_user_users_me_get", "security": [{"HTTPDigest": []}], } } }, "components": { "securitySchemes": {"HTTPDigest": {"type": "http", "scheme": "digest"}} }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_filter_pydantic_sub_model_pv2.py
tests/test_filter_pydantic_sub_model_pv2.py
from typing import Optional import pytest from dirty_equals import HasRepr from fastapi import Depends, FastAPI from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient from inline_snapshot import snapshot @pytest.fixture(name="client") def get_client(): from pydantic import BaseModel, ValidationInfo, field_validator app = FastAPI() class ModelB(BaseModel): username: str class ModelC(ModelB): password: str class ModelA(BaseModel): name: str description: Optional[str] = None foo: ModelB tags: dict[str, str] = {} @field_validator("name") def lower_username(cls, name: str, info: ValidationInfo): if not name.endswith("A"): raise ValueError("name must end in A") return name async def get_model_c() -> ModelC: return ModelC(username="test-user", password="test-password") @app.get("/model/{name}", response_model=ModelA) async def get_model_a(name: str, model_c=Depends(get_model_c)): return { "name": name, "description": "model-a-desc", "foo": model_c, "tags": {"key1": "value1", "key2": "value2"}, } client = TestClient(app) return client def test_filter_sub_model(client: TestClient): response = client.get("/model/modelA") assert response.status_code == 200, response.text assert response.json() == { "name": "modelA", "description": "model-a-desc", "foo": {"username": "test-user"}, "tags": {"key1": "value1", "key2": "value2"}, } def test_validator_is_cloned(client: TestClient): with pytest.raises(ResponseValidationError) as err: client.get("/model/modelX") assert err.value.errors() == [ { "type": "value_error", "loc": ("response", "name"), "msg": "Value error, name must end in A", "input": "modelX", "ctx": {"error": HasRepr("ValueError('name must end in A')")}, } ] def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/model/{name}": { "get": { "summary": "Get Model A", "operationId": "get_model_a_model__name__get", "parameters": [ { "required": True, "schema": {"title": "Name", "type": "string"}, "name": "name", "in": "path", } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ModelA" } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, "ModelA": { "title": "ModelA", "required": ["name", "foo"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "foo": {"$ref": "#/components/schemas/ModelB"}, "tags": { "additionalProperties": {"type": "string"}, "type": "object", "title": "Tags", "default": {}, }, }, }, "ModelB": { "title": "ModelB", "required": ["username"], "type": "object", "properties": { "username": {"title": "Username", "type": "string"} }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_skip_defaults.py
tests/test_skip_defaults.py
from typing import Optional from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class SubModel(BaseModel): a: Optional[str] = "foo" class Model(BaseModel): x: Optional[int] = None sub: SubModel class ModelSubclass(Model): y: int z: int = 0 w: Optional[int] = None class ModelDefaults(BaseModel): w: Optional[str] = None x: Optional[str] = None y: str = "y" z: str = "z" @app.get("/", response_model=Model, response_model_exclude_unset=True) def get_root() -> ModelSubclass: return ModelSubclass(sub={}, y=1, z=0) @app.get( "/exclude_unset", response_model=ModelDefaults, response_model_exclude_unset=True ) def get_exclude_unset() -> ModelDefaults: return ModelDefaults(x=None, y="y") @app.get( "/exclude_defaults", response_model=ModelDefaults, response_model_exclude_defaults=True, ) def get_exclude_defaults() -> ModelDefaults: return ModelDefaults(x=None, y="y") @app.get( "/exclude_none", response_model=ModelDefaults, response_model_exclude_none=True ) def get_exclude_none() -> ModelDefaults: return ModelDefaults(x=None, y="y") @app.get( "/exclude_unset_none", response_model=ModelDefaults, response_model_exclude_unset=True, response_model_exclude_none=True, ) def get_exclude_unset_none() -> ModelDefaults: return ModelDefaults(x=None, y="y") client = TestClient(app) def test_return_defaults(): response = client.get("/") assert response.json() == {"sub": {}} def test_return_exclude_unset(): response = client.get("/exclude_unset") assert response.json() == {"x": None, "y": "y"} def test_return_exclude_defaults(): response = client.get("/exclude_defaults") assert response.json() == {} def test_return_exclude_none(): response = client.get("/exclude_none") assert response.json() == {"y": "y", "z": "z"} def test_return_exclude_unset_none(): response = client.get("/exclude_unset_none") assert response.json() == {"y": "y"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false