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_dependency_class.py | tests/test_dependency_class.py | from collections.abc import AsyncGenerator, Generator
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
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("/callable-dependency-class")
async def get_callable_dependency_class(
value: str, instance: CallableDependency = Depends()
):
return instance(value)
@app.get("/callable-gen-dependency-class")
async def get_callable_gen_dependency_class(
value: str, instance: CallableGenDependency = Depends()
):
return next(instance(value))
@app.get("/async-callable-dependency-class")
async def get_async_callable_dependency_class(
value: str, instance: AsyncCallableDependency = Depends()
):
return await instance(value)
@app.get("/async-callable-gen-dependency-class")
async def get_async_callable_gen_dependency_class(
value: str, instance: AsyncCallableGenDependency = Depends()
):
return await instance(value).__anext__()
@app.get("/callable-dependency")
async def get_callable_dependency(value: str = Depends(callable_dependency)):
return value
@app.get("/callable-gen-dependency")
async def get_callable_gen_dependency(value: str = Depends(callable_gen_dependency)):
return value
@app.get("/async-callable-dependency")
async def get_async_callable_dependency(
value: str = Depends(async_callable_dependency),
):
return value
@app.get("/async-callable-gen-dependency")
async def get_async_callable_gen_dependency(
value: str = Depends(async_callable_gen_dependency),
):
return value
@app.get("/synchronous-method-dependency")
async def get_synchronous_method_dependency(
value: str = Depends(methods_dependency.synchronous),
):
return value
@app.get("/synchronous-method-gen-dependency")
async def get_synchronous_method_gen_dependency(
value: str = Depends(methods_dependency.synchronous_gen),
):
return value
@app.get("/asynchronous-method-dependency")
async def get_asynchronous_method_dependency(
value: str = Depends(methods_dependency.asynchronous),
):
return value
@app.get("/asynchronous-method-gen-dependency")
async def get_asynchronous_method_gen_dependency(
value: str = Depends(methods_dependency.asynchronous_gen),
):
return value
client = TestClient(app)
@pytest.mark.parametrize(
"route,value",
[
("/callable-dependency", "callable-dependency"),
("/callable-gen-dependency", "callable-gen-dependency"),
("/async-callable-dependency", "async-callable-dependency"),
("/async-callable-gen-dependency", "async-callable-gen-dependency"),
("/synchronous-method-dependency", "synchronous-method-dependency"),
("/synchronous-method-gen-dependency", "synchronous-method-gen-dependency"),
("/asynchronous-method-dependency", "asynchronous-method-dependency"),
("/asynchronous-method-gen-dependency", "asynchronous-method-gen-dependency"),
("/callable-dependency-class", "callable-dependency-class"),
("/callable-gen-dependency-class", "callable-gen-dependency-class"),
("/async-callable-dependency-class", "async-callable-dependency-class"),
("/async-callable-gen-dependency-class", "async-callable-gen-dependency-class"),
],
)
def test_class_dependency(route, value):
response = client.get(route, params={"value": value})
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_router_events.py | tests/test_router_events.py | from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from typing import Union
import pytest
from fastapi import APIRouter, FastAPI, Request
from fastapi.testclient import TestClient
from pydantic import BaseModel
class State(BaseModel):
app_startup: bool = False
app_shutdown: bool = False
router_startup: bool = False
router_shutdown: bool = False
sub_router_startup: bool = False
sub_router_shutdown: bool = False
@pytest.fixture
def state() -> State:
return State()
@pytest.mark.filterwarnings(
r"ignore:\s*on_event is deprecated, use lifespan event handlers instead.*:DeprecationWarning"
)
def test_router_events(state: State) -> None:
app = FastAPI()
@app.get("/")
def main() -> dict[str, str]:
return {"message": "Hello World"}
@app.on_event("startup")
def app_startup() -> None:
state.app_startup = True
@app.on_event("shutdown")
def app_shutdown() -> None:
state.app_shutdown = True
router = APIRouter()
@router.on_event("startup")
def router_startup() -> None:
state.router_startup = True
@router.on_event("shutdown")
def router_shutdown() -> None:
state.router_shutdown = True
sub_router = APIRouter()
@sub_router.on_event("startup")
def sub_router_startup() -> None:
state.sub_router_startup = True
@sub_router.on_event("shutdown")
def sub_router_shutdown() -> None:
state.sub_router_shutdown = True
router.include_router(sub_router)
app.include_router(router)
assert state.app_startup is False
assert state.router_startup is False
assert state.sub_router_startup is False
assert state.app_shutdown is False
assert state.router_shutdown is False
assert state.sub_router_shutdown is False
with TestClient(app) as client:
assert state.app_startup is True
assert state.router_startup is True
assert state.sub_router_startup is True
assert state.app_shutdown is False
assert state.router_shutdown is False
assert state.sub_router_shutdown is False
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert state.app_startup is True
assert state.router_startup is True
assert state.sub_router_startup is True
assert state.app_shutdown is True
assert state.router_shutdown is True
assert state.sub_router_shutdown is True
def test_app_lifespan_state(state: State) -> None:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
state.app_startup = True
yield
state.app_shutdown = True
app = FastAPI(lifespan=lifespan)
@app.get("/")
def main() -> dict[str, str]:
return {"message": "Hello World"}
assert state.app_startup is False
assert state.app_shutdown is False
with TestClient(app) as client:
assert state.app_startup is True
assert state.app_shutdown is False
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert state.app_startup is True
assert state.app_shutdown is True
def test_router_nested_lifespan_state(state: State) -> None:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
state.app_startup = True
yield {"app": True}
state.app_shutdown = True
@asynccontextmanager
async def router_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
state.router_startup = True
yield {"router": True}
state.router_shutdown = True
@asynccontextmanager
async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
state.sub_router_startup = True
yield {"sub_router": True}
state.sub_router_shutdown = True
sub_router = APIRouter(lifespan=subrouter_lifespan)
router = APIRouter(lifespan=router_lifespan)
router.include_router(sub_router)
app = FastAPI(lifespan=lifespan)
app.include_router(router)
@app.get("/")
def main(request: Request) -> dict[str, str]:
assert request.state.app
assert request.state.router
assert request.state.sub_router
return {"message": "Hello World"}
assert state.app_startup is False
assert state.router_startup is False
assert state.sub_router_startup is False
assert state.app_shutdown is False
assert state.router_shutdown is False
assert state.sub_router_shutdown is False
with TestClient(app) as client:
assert state.app_startup is True
assert state.router_startup is True
assert state.sub_router_startup is True
assert state.app_shutdown is False
assert state.router_shutdown is False
assert state.sub_router_shutdown is False
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert state.app_startup is True
assert state.router_startup is True
assert state.sub_router_startup is True
assert state.app_shutdown is True
assert state.router_shutdown is True
assert state.sub_router_shutdown is True
def test_router_nested_lifespan_state_overriding_by_parent() -> None:
@asynccontextmanager
async def lifespan(
app: FastAPI,
) -> AsyncGenerator[dict[str, Union[str, bool]], None]:
yield {
"app_specific": True,
"overridden": "app",
}
@asynccontextmanager
async def router_lifespan(
app: FastAPI,
) -> AsyncGenerator[dict[str, Union[str, bool]], None]:
yield {
"router_specific": True,
"overridden": "router", # should override parent
}
router = APIRouter(lifespan=router_lifespan)
app = FastAPI(lifespan=lifespan)
app.include_router(router)
with TestClient(app) as client:
assert client.app_state == {
"app_specific": True,
"router_specific": True,
"overridden": "app",
}
def test_merged_no_return_lifespans_return_none() -> None:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
yield
@asynccontextmanager
async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
yield
router = APIRouter(lifespan=router_lifespan)
app = FastAPI(lifespan=lifespan)
app.include_router(router)
with TestClient(app) as client:
assert not client.app_state
def test_merged_mixed_state_lifespans() -> None:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
yield
@asynccontextmanager
async def router_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
yield {"router": True}
@asynccontextmanager
async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
yield
sub_router = APIRouter(lifespan=sub_router_lifespan)
router = APIRouter(lifespan=router_lifespan)
app = FastAPI(lifespan=lifespan)
router.include_router(sub_router)
app.include_router(router)
with TestClient(app) as client:
assert client.app_state == {"router": True}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tuples.py | tests/test_tuples.py | from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class ItemGroup(BaseModel):
items: list[tuple[str, str]]
class Coordinate(BaseModel):
x: float
y: float
@app.post("/model-with-tuple/")
def post_model_with_tuple(item_group: ItemGroup):
return item_group
@app.post("/tuple-of-models/")
def post_tuple_of_models(square: tuple[Coordinate, Coordinate]):
return square
@app.post("/tuple-form/")
def hello(values: tuple[int, int] = Form()):
return values
client = TestClient(app)
def test_model_with_tuple_valid():
data = {"items": [["foo", "bar"], ["baz", "whatelse"]]}
response = client.post("/model-with-tuple/", json=data)
assert response.status_code == 200, response.text
assert response.json() == data
def test_model_with_tuple_invalid():
data = {"items": [["foo", "bar"], ["baz", "whatelse", "too", "much"]]}
response = client.post("/model-with-tuple/", json=data)
assert response.status_code == 422, response.text
data = {"items": [["foo", "bar"], ["baz"]]}
response = client.post("/model-with-tuple/", json=data)
assert response.status_code == 422, response.text
def test_tuple_with_model_valid():
data = [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
response = client.post("/tuple-of-models/", json=data)
assert response.status_code == 200, response.text
assert response.json() == data
def test_tuple_with_model_invalid():
data = [{"x": 1, "y": 2}, {"x": 3, "y": 4}, {"x": 5, "y": 6}]
response = client.post("/tuple-of-models/", json=data)
assert response.status_code == 422, response.text
data = [{"x": 1, "y": 2}]
response = client.post("/tuple-of-models/", json=data)
assert response.status_code == 422, response.text
def test_tuple_form_valid():
response = client.post("/tuple-form/", data={"values": ("1", "2")})
assert response.status_code == 200, response.text
assert response.json() == [1, 2]
def test_tuple_form_invalid():
response = client.post("/tuple-form/", data={"values": ("1", "2", "3")})
assert response.status_code == 422, response.text
response = client.post("/tuple-form/", data={"values": ("1")})
assert response.status_code == 422, 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": {
"/model-with-tuple/": {
"post": {
"summary": "Post Model With Tuple",
"operationId": "post_model_with_tuple_model_with_tuple__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/ItemGroup"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/tuple-of-models/": {
"post": {
"summary": "Post Tuple Of Models",
"operationId": "post_tuple_of_models_tuple_of_models__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"title": "Square",
"maxItems": 2,
"minItems": 2,
"type": "array",
"prefixItems": [
{"$ref": "#/components/schemas/Coordinate"},
{"$ref": "#/components/schemas/Coordinate"},
],
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/tuple-form/": {
"post": {
"summary": "Hello",
"operationId": "hello_tuple_form__post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_hello_tuple_form__post"
}
}
},
"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": {
"Body_hello_tuple_form__post": {
"title": "Body_hello_tuple_form__post",
"required": ["values"],
"type": "object",
"properties": {
"values": {
"title": "Values",
"maxItems": 2,
"minItems": 2,
"type": "array",
"prefixItems": [
{"type": "integer"},
{"type": "integer"},
],
}
},
},
"Coordinate": {
"title": "Coordinate",
"required": ["x", "y"],
"type": "object",
"properties": {
"x": {"title": "X", "type": "number"},
"y": {"title": "Y", "type": "number"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"ItemGroup": {
"title": "ItemGroup",
"required": ["items"],
"type": "object",
"properties": {
"items": {
"title": "Items",
"type": "array",
"items": {
"maxItems": 2,
"minItems": 2,
"type": "array",
"prefixItems": [
{"type": "string"},
{"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_depends_hashable.py | tests/test_depends_hashable.py | # This is more or less a workaround to make Depends and Security hashable
# as other tools that use them depend on that
# Ref: https://github.com/fastapi/fastapi/pull/14320
from fastapi import Depends, Security
def dep():
pass
def test_depends_hashable():
dep() # just for coverage
d1 = Depends(dep)
d2 = Depends(dep)
d3 = Depends(dep, scope="function")
d4 = Depends(dep, scope="function")
s1 = Security(dep)
s2 = Security(dep)
assert hash(d1) == hash(d2)
assert hash(s1) == hash(s2)
assert hash(d1) != hash(d3)
assert hash(d3) == hash(d4)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_default_response_class_router.py | tests/test_default_response_class_router.py | from fastapi import APIRouter, FastAPI
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from fastapi.testclient import TestClient
class OverrideResponse(JSONResponse):
media_type = "application/x-override"
app = FastAPI()
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)
json_type = "application/json"
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"] == json_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"] == json_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"] == json_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_return_none_stringified_annotations.py | tests/test_return_none_stringified_annotations.py | import http
from fastapi import FastAPI
from fastapi.testclient import TestClient
def test_no_content():
app = FastAPI()
@app.get("/no-content", status_code=http.HTTPStatus.NO_CONTENT)
def return_no_content() -> "None":
return
client = TestClient(app)
response = client.get("/no-content")
assert response.status_code == http.HTTPStatus.NO_CONTENT, response.text
assert not response.content
| 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.py | tests/test_security_oauth2_authorization_code_bearer.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", 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": {},
}
},
}
}
},
}
| 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.py | tests/test_response_model_data_filter.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class UserBase(BaseModel):
email: str
class UserCreate(UserBase):
password: str
class UserDB(UserBase):
hashed_password: str
class PetDB(BaseModel):
name: str
owner: UserDB
class PetOut(BaseModel):
name: str
owner: UserBase
@app.post("/users/", response_model=UserBase)
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_forms_single_param.py | tests/test_forms_single_param.py | from typing import Annotated
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/form/")
def post_form(username: Annotated[str, Form()]):
return username
client = TestClient(app)
def test_single_form_field():
response = client.post("/form/", data={"username": "Rick"})
assert response.status_code == 200, response.text
assert response.json() == "Rick"
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": {
"/form/": {
"post": {
"summary": "Post Form",
"operationId": "post_form_form__post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_post_form_form__post"
}
}
},
"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": {
"Body_post_form_form__post": {
"properties": {"username": {"type": "string", "title": "Username"}},
"type": "object",
"required": ["username"],
"title": "Body_post_form_form__post",
},
"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_dependency_after_yield_raise.py | tests/test_dependency_after_yield_raise.py | from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
class CustomError(Exception):
pass
def catching_dep() -> Any:
try:
yield "s"
except CustomError as err:
raise HTTPException(status_code=418, detail="Session error") from err
def broken_dep() -> Any:
yield "s"
raise ValueError("Broken after yield")
app = FastAPI()
@app.get("/catching")
def catching(d: Annotated[str, Depends(catching_dep)]) -> Any:
raise CustomError("Simulated error during streaming")
@app.get("/broken")
def broken(d: Annotated[str, Depends(broken_dep)]) -> Any:
return {"message": "all good?"}
client = TestClient(app)
def test_catching():
response = client.get("/catching")
assert response.status_code == 418
assert response.json() == {"detail": "Session error"}
def test_broken_raise():
with pytest.raises(ValueError, match="Broken after yield"):
client.get("/broken")
def test_broken_no_raise():
"""
When a dependency with yield raises after the yield (not in an except), the
response is already "successfully" sent back to the client, but there's still
an error in the server afterwards, an exception is raised and captured or shown
in the server logs.
"""
with TestClient(app, raise_server_exceptions=False) as client:
response = client.get("/broken")
assert response.status_code == 200
assert response.json() == {"message": "all good?"}
def test_broken_return_finishes():
client = TestClient(app, raise_server_exceptions=False)
response = client.get("/broken")
assert response.status_code == 200
assert response.json() == {"message": "all good?"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_webhooks_security.py | tests/test_webhooks_security.py | from datetime import datetime
from typing import Annotated
from fastapi import FastAPI, Security
from fastapi.security import HTTPBearer
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
bearer_scheme = HTTPBearer()
class Subscription(BaseModel):
username: str
monthly_fee: float
start_date: datetime
@app.webhooks.post("new-subscription")
def new_subscription(
body: Subscription, token: Annotated[str, Security(bearer_scheme)]
):
"""
When a new user subscribes to your service we'll send you a POST request with this
data to the URL that you register for the event `new-subscription` in the dashboard.
"""
client = TestClient(app)
def test_dummy_webhook():
# Just for coverage
new_subscription(body={}, token="Bearer 123")
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
# insert_assert(response.json())
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {},
"webhooks": {
"new-subscription": {
"post": {
"summary": "New Subscription",
"description": "When a new user subscribes to your service we'll send you a POST request with this\ndata to the URL that you register for the event `new-subscription` in the dashboard.",
"operationId": "new_subscriptionnew_subscription_post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Subscription"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"security": [{"HTTPBearer": []}],
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {"$ref": "#/components/schemas/ValidationError"},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Subscription": {
"properties": {
"username": {"type": "string", "title": "Username"},
"monthly_fee": {"type": "number", "title": "Monthly Fee"},
"start_date": {
"type": "string",
"format": "date-time",
"title": "Start Date",
},
},
"type": "object",
"required": ["username", "monthly_fee", "start_date"],
"title": "Subscription",
},
"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",
},
},
"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_response_by_alias.py | tests/test_response_by_alias.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
app = FastAPI()
class Model(BaseModel):
name: str = Field(alias="alias")
class ModelNoAlias(BaseModel):
name: str
model_config = ConfigDict(
json_schema_extra={
"description": (
"response_model_by_alias=False is basically a quick hack, to support "
"proper OpenAPI use another model with the correct field names"
)
}
)
@app.get("/dict", response_model=Model, response_model_by_alias=False)
def read_dict():
return {"alias": "Foo"}
@app.get("/model", response_model=Model, response_model_by_alias=False)
def read_model():
return Model(alias="Foo")
@app.get("/list", response_model=list[Model], response_model_by_alias=False)
def read_list():
return [{"alias": "Foo"}, {"alias": "Bar"}]
@app.get("/by-alias/dict", response_model=Model)
def by_alias_dict():
return {"alias": "Foo"}
@app.get("/by-alias/model", response_model=Model)
def by_alias_model():
return Model(alias="Foo")
@app.get("/by-alias/list", response_model=list[Model])
def by_alias_list():
return [{"alias": "Foo"}, {"alias": "Bar"}]
@app.get("/no-alias/dict", response_model=ModelNoAlias)
def no_alias_dict():
return {"name": "Foo"}
@app.get("/no-alias/model", response_model=ModelNoAlias)
def no_alias_model():
return ModelNoAlias(name="Foo")
@app.get("/no-alias/list", response_model=list[ModelNoAlias])
def no_alias_list():
return [{"name": "Foo"}, {"name": "Bar"}]
client = TestClient(app)
def test_read_dict():
response = client.get("/dict")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Foo"}
def test_read_model():
response = client.get("/model")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Foo"}
def test_read_list():
response = client.get("/list")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Foo"},
{"name": "Bar"},
]
def test_read_dict_by_alias():
response = client.get("/by-alias/dict")
assert response.status_code == 200, response.text
assert response.json() == {"alias": "Foo"}
def test_read_model_by_alias():
response = client.get("/by-alias/model")
assert response.status_code == 200, response.text
assert response.json() == {"alias": "Foo"}
def test_read_list_by_alias():
response = client.get("/by-alias/list")
assert response.status_code == 200, response.text
assert response.json() == [
{"alias": "Foo"},
{"alias": "Bar"},
]
def test_read_dict_no_alias():
response = client.get("/no-alias/dict")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Foo"}
def test_read_model_no_alias():
response = client.get("/no-alias/model")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Foo"}
def test_read_list_no_alias():
response = client.get("/no-alias/list")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Foo"},
{"name": "Bar"},
]
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": {
"/dict": {
"get": {
"summary": "Read Dict",
"operationId": "read_dict_dict_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Model"}
}
},
}
},
}
},
"/model": {
"get": {
"summary": "Read Model",
"operationId": "read_model_model_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Model"}
}
},
}
},
}
},
"/list": {
"get": {
"summary": "Read List",
"operationId": "read_list_list_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Read List List Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Model"},
}
}
},
}
},
}
},
"/by-alias/dict": {
"get": {
"summary": "By Alias Dict",
"operationId": "by_alias_dict_by_alias_dict_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Model"}
}
},
}
},
}
},
"/by-alias/model": {
"get": {
"summary": "By Alias Model",
"operationId": "by_alias_model_by_alias_model_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Model"}
}
},
}
},
}
},
"/by-alias/list": {
"get": {
"summary": "By Alias List",
"operationId": "by_alias_list_by_alias_list_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response By Alias List By Alias List Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Model"},
}
}
},
}
},
}
},
"/no-alias/dict": {
"get": {
"summary": "No Alias Dict",
"operationId": "no_alias_dict_no_alias_dict_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModelNoAlias"
}
}
},
}
},
}
},
"/no-alias/model": {
"get": {
"summary": "No Alias Model",
"operationId": "no_alias_model_no_alias_model_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModelNoAlias"
}
}
},
}
},
}
},
"/no-alias/list": {
"get": {
"summary": "No Alias List",
"operationId": "no_alias_list_no_alias_list_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response No Alias List No Alias List Get",
"type": "array",
"items": {
"$ref": "#/components/schemas/ModelNoAlias"
},
}
}
},
}
},
}
},
},
"components": {
"schemas": {
"Model": {
"title": "Model",
"required": ["alias"],
"type": "object",
"properties": {"alias": {"title": "Alias", "type": "string"}},
},
"ModelNoAlias": {
"title": "ModelNoAlias",
"required": ["name"],
"type": "object",
"properties": {"name": {"title": "Name", "type": "string"}},
"description": "response_model_by_alias=False is basically a quick hack, to support proper OpenAPI use another model with the correct field names",
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_stringified_annotation_dependency.py | tests/test_stringified_annotation_dependency.py | from __future__ import annotations
from typing import TYPE_CHECKING, Annotated
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
if TYPE_CHECKING: # pragma: no cover
from collections.abc import AsyncGenerator
class DummyClient:
async def get_people(self) -> list:
return ["John Doe", "Jane Doe"]
async def close(self) -> None:
pass
async def get_client() -> AsyncGenerator[DummyClient, None]:
client = DummyClient()
yield client
await client.close()
Client = Annotated[DummyClient, Depends(get_client)]
@pytest.fixture(name="client")
def client_fixture() -> TestClient:
app = FastAPI()
@app.get("/")
async def get_people(client: Client) -> list:
return await client.get_people()
client = TestClient(app)
return client
def test_get(client: TestClient):
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == ["John Doe", "Jane Doe"]
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": {
"/": {
"get": {
"summary": "Get People",
"operationId": "get_people__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {},
"type": "array",
"title": "Response Get People Get",
}
}
},
}
},
}
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_exception_handlers.py | tests/test_exception_handlers.py | import pytest
from fastapi import Depends, FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.testclient import TestClient
from starlette.responses import JSONResponse
def http_exception_handler(request, exception):
return JSONResponse({"exception": "http-exception"})
def request_validation_exception_handler(request, exception):
return JSONResponse({"exception": "request-validation"})
def server_error_exception_handler(request, exception):
return JSONResponse(status_code=500, content={"exception": "server-error"})
app = FastAPI(
exception_handlers={
HTTPException: http_exception_handler,
RequestValidationError: request_validation_exception_handler,
Exception: server_error_exception_handler,
}
)
client = TestClient(app)
def raise_value_error():
raise ValueError()
def dependency_with_yield():
yield raise_value_error()
@app.get("/dependency-with-yield", dependencies=[Depends(dependency_with_yield)])
def with_yield(): ...
@app.get("/http-exception")
def route_with_http_exception():
raise HTTPException(status_code=400)
@app.get("/request-validation/{param}/")
def route_with_request_validation_exception(param: int):
pass # pragma: no cover
@app.get("/server-error")
def route_with_server_error():
raise RuntimeError("Oops!")
def test_override_http_exception():
response = client.get("/http-exception")
assert response.status_code == 200
assert response.json() == {"exception": "http-exception"}
def test_override_request_validation_exception():
response = client.get("/request-validation/invalid")
assert response.status_code == 200
assert response.json() == {"exception": "request-validation"}
def test_override_server_error_exception_raises():
with pytest.raises(RuntimeError):
client.get("/server-error")
def test_override_server_error_exception_response():
client = TestClient(app, raise_server_exceptions=False)
response = client.get("/server-error")
assert response.status_code == 500
assert response.json() == {"exception": "server-error"}
def test_traceback_for_dependency_with_yield():
client = TestClient(app, raise_server_exceptions=True)
with pytest.raises(ValueError) as exc_info:
client.get("/dependency-with-yield")
last_frame = exc_info.traceback[-1]
assert str(last_frame.path) == __file__
assert last_frame.lineno == raise_value_error.__code__.co_firstlineno
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_repeated_cookie_headers.py | tests/test_repeated_cookie_headers.py | from fastapi import Depends, FastAPI, Response
from fastapi.testclient import TestClient
app = FastAPI()
def set_cookie(*, response: Response):
response.set_cookie("cookie-name", "cookie-value")
return {}
def set_indirect_cookie(*, dep: str = Depends(set_cookie)):
return dep
@app.get("/directCookie")
def get_direct_cookie(dep: str = Depends(set_cookie)):
return {"dep": dep}
@app.get("/indirectCookie")
def get_indirect_cookie(dep: str = Depends(set_indirect_cookie)):
return {"dep": dep}
client = TestClient(app)
def test_cookie_is_set_once():
direct_response = client.get("/directCookie")
indirect_response = client.get("/indirectCookie")
assert (
direct_response.headers["set-cookie"] == indirect_response.headers["set-cookie"]
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_after_yield_streaming.py | tests/test_dependency_after_yield_streaming.py | from collections.abc import Generator
from contextlib import contextmanager
from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
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.get("/data")
def get_data(session: SessionDep) -> Any:
data = list(session)
return data
@app.get("/stream-simple")
def get_stream_simple(session: SessionDep) -> Any:
def iter_data():
yield from ["x", "y", "z"]
return StreamingResponse(iter_data())
@app.get("/stream-session")
def get_stream_session(session: SessionDep) -> Any:
def iter_data():
yield from session
return StreamingResponse(iter_data())
@app.get("/broken-session-data")
def get_broken_session_data(session: BrokenSessionDep) -> Any:
return list(session)
@app.get("/broken-session-stream")
def get_broken_session_stream(session: BrokenSessionDep) -> Any:
def iter_data():
yield from session
return StreamingResponse(iter_data())
client = TestClient(app)
def test_regular_no_stream():
response = client.get("/data")
assert response.json() == ["foo", "bar", "baz"]
def test_stream_simple():
response = client.get("/stream-simple")
assert response.text == "xyz"
def test_stream_session():
response = client.get("/stream-session")
assert response.text == "foobarbaz"
def test_broken_session_data():
with pytest.raises(ValueError, match="Session closed"):
client.get("/broken-session-data")
def test_broken_session_data_no_raise():
client = TestClient(app, raise_server_exceptions=False)
response = client.get("/broken-session-data")
assert response.status_code == 500
assert response.text == "Internal Server Error"
def test_broken_session_stream_raise():
# Can raise ValueError on Pydantic v2 and ExceptionGroup on Pydantic v1
with pytest.raises((ValueError, Exception)):
client.get("/broken-session-stream")
def test_broken_session_stream_no_raise():
"""
When a dependency with yield raises after the streaming response already started
the 200 status code is already sent, but there's still an error in the server
afterwards, an exception is raised and captured or shown in the server logs.
"""
with TestClient(app, raise_server_exceptions=False) as client:
response = client.get("/broken-session-stream")
assert response.status_code == 200
assert response.text == ""
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_digest_optional.py | tests/test_security_http_digest_optional.py | from typing import Optional
from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
from fastapi.testclient import TestClient
app = FastAPI()
security = HTTPDigest(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_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 == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_security_http_digest_incorrect_scheme_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Other invalidauthorization"}
)
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": [{"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_regex_deprecated_params.py | tests/test_regex_deprecated_params.py | from typing import Annotated
import pytest
from fastapi import FastAPI, Query
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
from .utils import needs_py310
def get_client():
app = FastAPI()
with pytest.warns(FastAPIDeprecationWarning):
@app.get("/items/")
async def read_items(
q: Annotated[str | None, Query(regex="^fixedquery$")] = None,
):
if q:
return f"Hello {q}"
else:
return "Hello World"
client = TestClient(app)
return client
@needs_py310
def test_query_params_str_validations_no_query():
client = get_client()
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == "Hello World"
@needs_py310
def test_query_params_str_validations_q_fixedquery():
client = get_client()
response = client.get("/items/", params={"q": "fixedquery"})
assert response.status_code == 200
assert response.json() == "Hello fixedquery"
@needs_py310
def test_query_params_str_validations_item_query_nonregexquery():
client = get_client()
response = client.get("/items/", params={"q": "nonregexquery"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_pattern_mismatch",
"loc": ["query", "q"],
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
}
]
}
@needs_py310
def test_openapi_schema():
client = get_client()
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
# insert_assert(response.json())
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",
"parameters": [
{
"name": "q",
"in": "query",
"required": False,
"schema": {
"anyOf": [
{"type": "string", "pattern": "^fixedquery$"},
{"type": "null"},
],
"title": "Q",
},
}
],
"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",
},
"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_route_scope.py | tests/test_route_scope.py | import pytest
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.routing import APIRoute, APIWebSocketRoute
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: str, request: Request):
route: APIRoute = request.scope["route"]
return {"user_id": user_id, "path": route.path}
@app.websocket("/items/{item_id}")
async def websocket_item(item_id: str, websocket: WebSocket):
route: APIWebSocketRoute = websocket.scope["route"]
await websocket.accept()
await websocket.send_json({"item_id": item_id, "path": route.path})
client = TestClient(app)
def test_get():
response = client.get("/users/rick")
assert response.status_code == 200, response.text
assert response.json() == {"user_id": "rick", "path": "/users/{user_id}"}
def test_invalid_method_doesnt_match():
response = client.post("/users/rick")
assert response.status_code == 405, response.text
def test_invalid_path_doesnt_match():
response = client.post("/usersx/rick")
assert response.status_code == 404, response.text
def test_websocket():
with client.websocket_connect("/items/portal-gun") as websocket:
data = websocket.receive_json()
assert data == {"item_id": "portal-gun", "path": "/items/{item_id}"}
def test_websocket_invalid_path_doesnt_match():
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/itemsx/portal-gun"):
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_custom_schema_fields.py | tests/test_custom_schema_fields.py | from typing import Annotated, Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, WithJsonSchema
app = FastAPI()
class Item(BaseModel):
name: str
description: Annotated[
Optional[str], WithJsonSchema({"type": ["string", "null"]})
] = None
model_config = {
"json_schema_extra": {
"x-something-internal": {"level": 4},
}
}
@app.get("/foo", response_model=Item)
def foo():
return {"name": "Foo item"}
client = TestClient(app)
item_schema = {
"title": "Item",
"required": ["name"],
"type": "object",
"x-something-internal": {
"level": 4,
},
"properties": {
"name": {
"title": "Name",
"type": "string",
},
"description": {
"title": "Description",
"type": ["string", "null"],
},
},
}
def test_custom_response_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json()["components"]["schemas"]["Item"] == item_schema
def test_response():
# For coverage
response = client.get("/foo")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Foo item", "description": None}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_model_description_trim_on_formfeed.py | tests/test_openapi_model_description_trim_on_formfeed.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class MyModel(BaseModel):
"""
A model with a form feed character in the title.
\f
Text after form feed character.
"""
@app.get("/foo")
def foo(v: MyModel): # pragma: no cover
pass
client = TestClient(app)
def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
openapi_schema = response.json()
assert openapi_schema["components"]["schemas"]["MyModel"]["description"] == (
"A model with a form feed character in the title.\n"
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_yield_scope.py | tests/test_dependency_yield_scope.py | import json
from typing import Annotated, Any
import pytest
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from fastapi.exceptions import FastAPIError
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
class Session:
def __init__(self) -> None:
self.open = True
def dep_session() -> Any:
s = Session()
yield s
s.open = False
def raise_after_yield() -> Any:
yield
raise HTTPException(status_code=503, detail="Exception after yield")
SessionFuncDep = Annotated[Session, Depends(dep_session, scope="function")]
SessionRequestDep = Annotated[Session, Depends(dep_session, scope="request")]
SessionDefaultDep = Annotated[Session, Depends(dep_session)]
class NamedSession:
def __init__(self, name: str = "default") -> None:
self.name = name
self.open = True
def get_named_session(session: SessionRequestDep, session_b: SessionDefaultDep) -> Any:
assert session is session_b
named_session = NamedSession(name="named")
yield named_session, session_b
named_session.open = False
NamedSessionsDep = Annotated[tuple[NamedSession, Session], Depends(get_named_session)]
def get_named_func_session(session: SessionFuncDep) -> Any:
named_session = NamedSession(name="named")
yield named_session, session
named_session.open = False
def get_named_regular_func_session(session: SessionFuncDep) -> Any:
named_session = NamedSession(name="named")
return named_session, session
BrokenSessionsDep = Annotated[
tuple[NamedSession, Session], Depends(get_named_func_session)
]
NamedSessionsFuncDep = Annotated[
tuple[NamedSession, Session], Depends(get_named_func_session, scope="function")
]
RegularSessionsDep = Annotated[
tuple[NamedSession, Session], Depends(get_named_regular_func_session)
]
app = FastAPI()
router = APIRouter()
@router.get("/")
def get_index():
return {"status": "ok"}
@app.get("/function-scope")
def function_scope(session: SessionFuncDep) -> Any:
def iter_data():
yield json.dumps({"is_open": session.open})
return StreamingResponse(iter_data())
@app.get("/request-scope")
def request_scope(session: SessionRequestDep) -> Any:
def iter_data():
yield json.dumps({"is_open": session.open})
return StreamingResponse(iter_data())
@app.get("/two-scopes")
def get_stream_session(
function_session: SessionFuncDep, request_session: SessionRequestDep
) -> Any:
def iter_data():
yield json.dumps(
{"func_is_open": function_session.open, "req_is_open": request_session.open}
)
return StreamingResponse(iter_data())
@app.get("/sub")
def get_sub(sessions: NamedSessionsDep) -> Any:
def iter_data():
yield json.dumps(
{"named_session_open": sessions[0].open, "session_open": sessions[1].open}
)
return StreamingResponse(iter_data())
@app.get("/named-function-scope")
def get_named_function_scope(sessions: NamedSessionsFuncDep) -> Any:
def iter_data():
yield json.dumps(
{"named_session_open": sessions[0].open, "session_open": sessions[1].open}
)
return StreamingResponse(iter_data())
@app.get("/regular-function-scope")
def get_regular_function_scope(sessions: RegularSessionsDep) -> Any:
def iter_data():
yield json.dumps(
{"named_session_open": sessions[0].open, "session_open": sessions[1].open}
)
return StreamingResponse(iter_data())
app.include_router(
prefix="/router-scope-function",
router=router,
dependencies=[Depends(raise_after_yield, scope="function")],
)
app.include_router(
prefix="/router-scope-request",
router=router,
dependencies=[Depends(raise_after_yield, scope="request")],
)
client = TestClient(app)
def test_function_scope() -> None:
response = client.get("/function-scope")
assert response.status_code == 200
data = response.json()
assert data["is_open"] is False
def test_request_scope() -> None:
response = client.get("/request-scope")
assert response.status_code == 200
data = response.json()
assert data["is_open"] is True
def test_two_scopes() -> None:
response = client.get("/two-scopes")
assert response.status_code == 200
data = response.json()
assert data["func_is_open"] is False
assert data["req_is_open"] is True
def test_sub() -> None:
response = client.get("/sub")
assert response.status_code == 200
data = response.json()
assert data["named_session_open"] is True
assert data["session_open"] is True
def test_broken_scope() -> None:
with pytest.raises(
FastAPIError,
match='The dependency "get_named_func_session" has a scope of "request", it cannot depend on dependencies with scope "function"',
):
@app.get("/broken-scope")
def get_broken(sessions: BrokenSessionsDep) -> Any: # pragma: no cover
pass
def test_named_function_scope() -> None:
response = client.get("/named-function-scope")
assert response.status_code == 200
data = response.json()
assert data["named_session_open"] is False
assert data["session_open"] is False
def test_regular_function_scope() -> None:
response = client.get("/regular-function-scope")
assert response.status_code == 200
data = response.json()
assert data["named_session_open"] is True
assert data["session_open"] is False
def test_router_level_dep_scope_function() -> None:
response = client.get("/router-scope-function/")
assert response.status_code == 503
assert response.json() == {"detail": "Exception after yield"}
def test_router_level_dep_scope_request() -> None:
with TestClient(app, raise_server_exceptions=False) as client:
response = client.get("/router-scope-request/")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
def test_app_level_dep_scope_function() -> None:
app = FastAPI(dependencies=[Depends(raise_after_yield, scope="function")])
@app.get("/app-scope-function")
def get_app_scope_function():
return {"status": "ok"}
with TestClient(app) as client:
response = client.get("/app-scope-function")
assert response.status_code == 503
assert response.json() == {"detail": "Exception after yield"}
def test_app_level_dep_scope_request() -> None:
app = FastAPI(dependencies=[Depends(raise_after_yield, scope="request")])
@app.get("/app-scope-request")
def get_app_scope_request():
return {"status": "ok"}
with TestClient(app, raise_server_exceptions=False) as client:
response = client.get("/app-scope-request")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_allow_inf_nan_in_enforcing.py | tests/test_allow_inf_nan_in_enforcing.py | from typing import Annotated
import pytest
from fastapi import Body, FastAPI, Query
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/")
async def get(
x: Annotated[float, Query(allow_inf_nan=True)] = 0,
y: Annotated[float, Query(allow_inf_nan=False)] = 0,
z: Annotated[float, Query()] = 0,
b: Annotated[float, Body(allow_inf_nan=False)] = 0,
) -> str:
return "OK"
client = TestClient(app)
@pytest.mark.parametrize(
"value,code",
[
("-1", 200),
("inf", 200),
("-inf", 200),
("nan", 200),
("0", 200),
("342", 200),
],
)
def test_allow_inf_nan_param_true(value: str, code: int):
response = client.post(f"/?x={value}")
assert response.status_code == code, response.text
@pytest.mark.parametrize(
"value,code",
[
("-1", 200),
("inf", 422),
("-inf", 422),
("nan", 422),
("0", 200),
("342", 200),
],
)
def test_allow_inf_nan_param_false(value: str, code: int):
response = client.post(f"/?y={value}")
assert response.status_code == code, response.text
@pytest.mark.parametrize(
"value,code",
[
("-1", 200),
("inf", 200),
("-inf", 200),
("nan", 200),
("0", 200),
("342", 200),
],
)
def test_allow_inf_nan_param_default(value: str, code: int):
response = client.post(f"/?z={value}")
assert response.status_code == code, response.text
@pytest.mark.parametrize(
"value,code",
[
("-1", 200),
("inf", 422),
("-inf", 422),
("nan", 422),
("0", 200),
("342", 200),
],
)
def test_allow_inf_nan_body(value: str, code: int):
response = client.post("/", json=value)
assert response.status_code == code, response.text
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_schema_compat_pydantic_v2.py | tests/test_schema_compat_pydantic_v2.py | import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
from tests.utils import needs_py310
@pytest.fixture(name="client")
def get_client():
from enum import Enum
app = FastAPI()
class PlatformRole(str, Enum):
admin = "admin"
user = "user"
class OtherRole(str, Enum): ...
class User(BaseModel):
username: str
role: PlatformRole | OtherRole
@app.get("/users")
async def get_user() -> User:
return {"username": "alice", "role": "admin"}
client = TestClient(app)
return client
@needs_py310
def test_get(client: TestClient):
response = client.get("/users")
assert response.json() == {"username": "alice", "role": "admin"}
@needs_py310
def test_openapi_schema(client: TestClient):
response = client.get("openapi.json")
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users": {
"get": {
"summary": "Get User",
"operationId": "get_user_users_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
}
},
}
}
},
"components": {
"schemas": {
"PlatformRole": {
"type": "string",
"enum": ["admin", "user"],
"title": "PlatformRole",
},
"User": {
"properties": {
"username": {"type": "string", "title": "Username"},
"role": {
"anyOf": [
{"$ref": "#/components/schemas/PlatformRole"},
{"enum": [], "title": "OtherRole"},
],
"title": "Role",
},
},
"type": "object",
"required": ["username", "role"],
"title": "User",
},
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_computed_fields.py | tests/test_computed_fields.py | import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
@pytest.fixture(name="client")
def get_client(request):
separate_input_output_schemas = request.param
app = FastAPI(separate_input_output_schemas=separate_input_output_schemas)
from pydantic import BaseModel, computed_field
class Rectangle(BaseModel):
width: int
length: int
@computed_field
@property
def area(self) -> int:
return self.width * self.length
@app.get("/")
def read_root() -> Rectangle:
return Rectangle(width=3, length=4)
@app.get("/responses", responses={200: {"model": Rectangle}})
def read_responses() -> Rectangle:
return Rectangle(width=3, length=4)
client = TestClient(app)
return client
@pytest.mark.parametrize("client", [True, False], indirect=True)
@pytest.mark.parametrize("path", ["/", "/responses"])
def test_get(client: TestClient, path: str):
response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() == {"width": 3, "length": 4, "area": 12}
@pytest.mark.parametrize("client", [True, False], indirect=True)
def test_openapi_schema(client: TestClient):
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": "Read Root",
"operationId": "read_root__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Rectangle"}
}
},
}
},
}
},
"/responses": {
"get": {
"summary": "Read Responses",
"operationId": "read_responses_responses_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Rectangle"}
}
},
}
},
}
},
},
"components": {
"schemas": {
"Rectangle": {
"properties": {
"width": {"type": "integer", "title": "Width"},
"length": {"type": "integer", "title": "Length"},
"area": {"type": "integer", "title": "Area", "readOnly": True},
},
"type": "object",
"required": ["width", "length", "area"],
"title": "Rectangle",
}
}
},
}
| 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_description.py | tests/test_security_api_key_header_description.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", description="An API Key Header")
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",
"description": "An API Key Header",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_regex_deprecated_body.py | tests/test_regex_deprecated_body.py | from typing import Annotated
import pytest
from fastapi import FastAPI, Form
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from .utils import needs_py310
def get_client():
app = FastAPI()
with pytest.warns(FastAPIDeprecationWarning):
@app.post("/items/")
async def read_items(
q: Annotated[str | None, Form(regex="^fixedquery$")] = None,
):
if q:
return f"Hello {q}"
else:
return "Hello World"
client = TestClient(app)
return client
@needs_py310
def test_no_query():
client = get_client()
response = client.post("/items/")
assert response.status_code == 200
assert response.json() == "Hello World"
@needs_py310
def test_q_fixedquery():
client = get_client()
response = client.post("/items/", data={"q": "fixedquery"})
assert response.status_code == 200
assert response.json() == "Hello fixedquery"
@needs_py310
def test_query_nonregexquery():
client = get_client()
response = client.post("/items/", data={"q": "nonregexquery"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_pattern_mismatch",
"loc": ["body", "q"],
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
}
]
}
@needs_py310
def test_openapi_schema():
client = get_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/": {
"post": {
"summary": "Read Items",
"operationId": "read_items_items__post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_read_items_items__post"
}
}
}
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"Body_read_items_items__post": {
"properties": {
"q": {
"anyOf": [
{"type": "string", "pattern": "^fixedquery$"},
{"type": "null"},
],
"title": "Q",
}
},
"type": "object",
"title": "Body_read_items_items__post",
},
"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_bearer_description.py | tests/test_security_http_bearer_description.py | from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
app = FastAPI()
security = HTTPBearer(description="HTTP Bearer token scheme")
@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",
"description": "HTTP Bearer token scheme",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_extra_routes.py | tests/test_extra_routes.py | from typing import Optional
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: Optional[float] = None
@app.api_route("/items/{item_id}", methods=["GET"])
def get_items(item_id: str):
return {"item_id": item_id}
def get_not_decorated(item_id: str):
return {"item_id": item_id}
app.add_api_route("/items-not-decorated/{item_id}", get_not_decorated)
@app.delete("/items/{item_id}")
def delete_item(item_id: str, item: Item):
return {"item_id": item_id, "item": item}
@app.head("/items/{item_id}")
def head_item(item_id: str):
return JSONResponse(None, headers={"x-fastapi-item-id": item_id})
@app.options("/items/{item_id}")
def options_item(item_id: str):
return JSONResponse(None, headers={"x-fastapi-item-id": item_id})
@app.patch("/items/{item_id}")
def patch_item(item_id: str, item: Item):
return {"item_id": item_id, "item": item}
@app.trace("/items/{item_id}")
def trace_item(item_id: str):
return JSONResponse(None, media_type="message/http")
client = TestClient(app)
def test_get_api_route():
response = client.get("/items/foo")
assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
def test_get_api_route_not_decorated():
response = client.get("/items-not-decorated/foo")
assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
def test_delete():
response = client.request("DELETE", "/items/foo", json={"name": "Foo"})
assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "item": {"name": "Foo", "price": None}}
def test_head():
response = client.head("/items/foo")
assert response.status_code == 200, response.text
assert response.headers["x-fastapi-item-id"] == "foo"
def test_options():
response = client.options("/items/foo")
assert response.status_code == 200, response.text
assert response.headers["x-fastapi-item-id"] == "foo"
def test_patch():
response = client.patch("/items/foo", json={"name": "Foo"})
assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "item": {"name": "Foo", "price": None}}
def test_trace():
response = client.request("trace", "/items/foo")
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "message/http"
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}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Items",
"operationId": "get_items_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
},
"delete": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Delete Item",
"operationId": "delete_item_items__item_id__delete",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
},
"options": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Options Item",
"operationId": "options_item_items__item_id__options",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
},
"head": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Head Item",
"operationId": "head_item_items__item_id__head",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
},
"patch": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Patch Item",
"operationId": "patch_item_items__item_id__patch",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
},
"trace": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Trace Item",
"operationId": "trace_item_items__item_id__trace",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
},
},
"/items-not-decorated/{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": "Get Not Decorated",
"operationId": "get_not_decorated_items_not_decorated__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
}
},
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {
"title": "Price",
"anyOf": [{"type": "number"}, {"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"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_orjson_response_class.py | tests/test_orjson_response_class.py | from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from fastapi.testclient import TestClient
from sqlalchemy.sql.elements import quoted_name
app = FastAPI(default_response_class=ORJSONResponse)
@app.get("/orjson_non_str_keys")
def get_orjson_non_str_keys():
key = quoted_name(value="msg", quote=False)
return {key: "Hello World", 1: 1}
client = TestClient(app)
def test_orjson_non_str_keys():
with client:
response = client.get("/orjson_non_str_keys")
assert response.json() == {"msg": "Hello World", "1": 1}
| 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_optional.py | tests/test_security_api_key_header_optional.py | from typing import Optional
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", 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: 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_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 == 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": [{"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_tutorial/__init__.py | tests/test_tutorial/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_params/test_tutorial002.py | tests/test_tutorial/test_path_params/test_tutorial002.py | from fastapi.testclient import TestClient
from docs_src.path_params.tutorial002_py39 import app
client = TestClient(app)
def test_get_items():
response = client.get("/items/1")
assert response.status_code == 200, response.text
assert response.json() == {"item_id": 1}
def test_get_items_invalid_id():
response = client.get("/items/item1")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"input": "item1",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"type": "int_parsing",
}
]
}
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}": {
"get": {
"operationId": "read_item_items__item_id__get",
"parameters": [
{
"in": "path",
"name": "item_id",
"required": True,
"schema": {
"title": "Item Id",
"type": "integer",
},
},
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {},
},
},
"description": "Successful Response",
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError",
},
},
},
"description": "Validation Error",
},
},
"summary": "Read Item",
},
},
},
"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",
},
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_params/test_tutorial001.py | tests/test_tutorial/test_path_params/test_tutorial001.py | import pytest
from fastapi.testclient import TestClient
from docs_src.path_params.tutorial001_py39 import app
client = TestClient(app)
@pytest.mark.parametrize(
("item_id", "expected_response"),
[
(1, {"item_id": "1"}),
("alice", {"item_id": "alice"}),
],
)
def test_get_items(item_id, expected_response):
response = client.get(f"/items/{item_id}")
assert response.status_code == 200, response.text
assert response.json() == expected_response
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}": {
"get": {
"operationId": "read_item_items__item_id__get",
"parameters": [
{
"in": "path",
"name": "item_id",
"required": True,
"schema": {
"title": "Item Id",
},
},
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {},
},
},
"description": "Successful Response",
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError",
},
},
},
"description": "Validation Error",
},
},
"summary": "Read Item",
},
},
},
"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",
},
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_params/test_tutorial005.py | tests/test_tutorial/test_path_params/test_tutorial005.py | from fastapi.testclient import TestClient
from docs_src.path_params.tutorial005_py39 import app
client = TestClient(app)
def test_get_enums_alexnet():
response = client.get("/models/alexnet")
assert response.status_code == 200
assert response.json() == {"model_name": "alexnet", "message": "Deep Learning FTW!"}
def test_get_enums_lenet():
response = client.get("/models/lenet")
assert response.status_code == 200
assert response.json() == {"model_name": "lenet", "message": "LeCNN all the images"}
def test_get_enums_resnet():
response = client.get("/models/resnet")
assert response.status_code == 200
assert response.json() == {"model_name": "resnet", "message": "Have some residuals"}
def test_get_enums_invalid():
response = client.get("/models/foo")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "enum",
"loc": ["path", "model_name"],
"msg": "Input should be 'alexnet', 'resnet' or 'lenet'",
"input": "foo",
"ctx": {"expected": "'alexnet', 'resnet' or 'lenet'"},
}
]
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
data = response.json()
assert data == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/models/{model_name}": {
"get": {
"summary": "Get Model",
"operationId": "get_model_models__model_name__get",
"parameters": [
{
"required": True,
"schema": {"$ref": "#/components/schemas/ModelName"},
"name": "model_name",
"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"},
}
},
},
"ModelName": {
"title": "ModelName",
"enum": ["alexnet", "resnet", "lenet"],
"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_tutorial/test_path_params/__init__.py | tests/test_tutorial/test_path_params/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_params/test_tutorial004.py | tests/test_tutorial/test_path_params/test_tutorial004.py | from fastapi.testclient import TestClient
from docs_src.path_params.tutorial004_py39 import app
client = TestClient(app)
def test_file_path():
response = client.get("/files/home/johndoe/myfile.txt")
print(response.content)
assert response.status_code == 200, response.text
assert response.json() == {"file_path": "home/johndoe/myfile.txt"}
def test_root_file_path():
response = client.get("/files//home/johndoe/myfile.txt")
print(response.content)
assert response.status_code == 200, response.text
assert response.json() == {"file_path": "/home/johndoe/myfile.txt"}
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": {
"/files/{file_path}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read File",
"operationId": "read_file_files__file_path__get",
"parameters": [
{
"required": True,
"schema": {"title": "File Path", "type": "string"},
"name": "file_path",
"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_tutorial/test_path_params/test_tutorial003.py | tests/test_tutorial/test_path_params/test_tutorial003.py | import pytest
from fastapi.testclient import TestClient
from docs_src.path_params.tutorial003_py39 import app
client = TestClient(app)
@pytest.mark.parametrize(
("user_id", "expected_response"),
[
("me", {"user_id": "the current user"}),
("alice", {"user_id": "alice"}),
],
)
def test_get_users(user_id: str, expected_response: dict):
response = client.get(f"/users/{user_id}")
assert response.status_code == 200, response.text
assert response.json() == expected_response
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": {
"operationId": "read_user_me_users_me_get",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {},
},
},
"description": "Successful Response",
},
},
"summary": "Read User Me",
},
},
"/users/{user_id}": {
"get": {
"operationId": "read_user_users__user_id__get",
"parameters": [
{
"in": "path",
"name": "user_id",
"required": True,
"schema": {
"title": "User 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": "Read User",
},
},
},
"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",
},
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_params/test_tutorial003b.py | tests/test_tutorial/test_path_params/test_tutorial003b.py | import asyncio
from fastapi.testclient import TestClient
from docs_src.path_params.tutorial003b_py39 import app, read_users2
client = TestClient(app)
def test_get_users():
response = client.get("/users")
assert response.status_code == 200, response.text
assert response.json() == ["Rick", "Morty"]
def test_read_users2(): # Just for coverage
assert asyncio.run(read_users2()) == ["Bean", "Elfo"]
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": {
"operationId": "read_users2_users_get",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {},
},
},
"description": "Successful Response",
},
},
"summary": "Read Users2",
},
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py | tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py | import importlib
import pytest
from dirty_equals import IsList
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_post(client: TestClient):
response = client.post(
"/user/",
json={
"username": "johndoe",
"password": "secret",
"email": "johndoe@example.com",
"full_name": "John Doe",
},
)
assert response.status_code == 200, response.text
assert response.json() == {
"username": "johndoe",
"email": "johndoe@example.com",
"full_name": "John Doe",
}
def test_openapi_schema(client: TestClient):
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": {
"/user/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserOut",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create User",
"operationId": "create_user_user__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/UserIn"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"UserIn": {
"title": "UserIn",
"required": IsList(
"username", "password", "email", check_order=False
),
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
"email": {
"title": "Email",
"type": "string",
"format": "email",
},
"full_name": {
"title": "Full Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
},
},
"UserOut": {
"title": "UserOut",
"required": ["username", "email"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"email": {
"title": "Email",
"type": "string",
"format": "email",
},
"full_name": {
"title": "Full Name",
"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"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_extra_models/test_tutorial005.py | tests/test_tutorial/test_extra_models/test_tutorial005.py | import importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial005_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_get_items(client: TestClient):
response = client.get("/keyword-weights/")
assert response.status_code == 200, response.text
assert response.json() == {"foo": 2.3, "bar": 3.4}
def test_openapi_schema(client: TestClient):
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": {
"/keyword-weights/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Read Keyword Weights Keyword Weights Get",
"type": "object",
"additionalProperties": {"type": "number"},
}
}
},
}
},
"summary": "Read Keyword Weights",
"operationId": "read_keyword_weights_keyword_weights__get",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_extra_models/__init__.py | tests/test_tutorial/test_extra_models/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_extra_models/test_tutorial004.py | tests/test_tutorial/test_extra_models/test_tutorial004.py | import importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial004_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_get_items(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Foo", "description": "There comes my hero"},
{"name": "Red", "description": "It's my aeroplane"},
]
def test_openapi_schema(client: TestClient):
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": {
"title": "Response Read Items Items Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
}
},
"summary": "Read Items",
"operationId": "read_items_items__get",
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "description"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {"title": "Description", "type": "string"},
},
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_extra_models/test_tutorial003.py | tests/test_tutorial/test_extra_models/test_tutorial003.py | import importlib
import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_get_car(client: TestClient):
response = client.get("/items/item1")
assert response.status_code == 200, response.text
assert response.json() == {
"description": "All my friends drive a low rider",
"type": "car",
}
def test_get_plane(client: TestClient):
response = client.get("/items/item2")
assert response.status_code == 200, response.text
assert response.json() == {
"description": "Music is my aeroplane, it's my aeroplane",
"type": "plane",
"size": 5,
}
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": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Read Item Items Item Id Get",
"anyOf": [
{
"$ref": "#/components/schemas/PlaneItem"
},
{
"$ref": "#/components/schemas/CarItem"
},
],
}
}
},
},
"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",
}
],
}
}
},
"components": {
"schemas": {
"PlaneItem": {
"title": "PlaneItem",
"required": ["description", "size"],
"type": "object",
"properties": {
"description": {"title": "Description", "type": "string"},
"type": {
"title": "Type",
"type": "string",
"default": "plane",
},
"size": {"title": "Size", "type": "integer"},
},
},
"CarItem": {
"title": "CarItem",
"required": ["description"],
"type": "object",
"properties": {
"description": {"title": "Description", "type": "string"},
"type": {
"title": "Type",
"type": "string",
"default": "car",
},
},
},
"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_tutorial/test_metadata/test_tutorial001_1.py | tests/test_tutorial/test_metadata/test_tutorial001_1.py | from fastapi.testclient import TestClient
from docs_src.metadata.tutorial001_1_py39 import app
client = TestClient(app)
def test_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"name": "Katana"}]
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": "ChimichangApp",
"summary": "Deadpool's favorite app. Nuff said.",
"description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n",
"termsOfService": "http://example.com/terms/",
"contact": {
"name": "Deadpoolio the Amazing",
"url": "http://x-force.example.com/contact/",
"email": "dp@x-force.example.com",
},
"license": {
"name": "Apache 2.0",
"identifier": "MIT",
},
"version": "0.0.1",
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_metadata/test_tutorial002.py | tests/test_tutorial/test_metadata/test_tutorial002.py | from fastapi.testclient import TestClient
from docs_src.metadata.tutorial002_py39 import app
client = TestClient(app)
def test_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"name": "Foo"}]
def test_get_openapi_json_default_url():
response = client.get("/openapi.json")
assert response.status_code == 404, response.text
def test_openapi_schema():
response = client.get("/api/v1/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": {}}},
}
},
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_metadata/test_tutorial001.py | tests/test_tutorial/test_metadata/test_tutorial001.py | from fastapi.testclient import TestClient
from docs_src.metadata.tutorial001_py39 import app
client = TestClient(app)
def test_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"name": "Katana"}]
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": "ChimichangApp",
"summary": "Deadpool's favorite app. Nuff said.",
"description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n",
"termsOfService": "http://example.com/terms/",
"contact": {
"name": "Deadpoolio the Amazing",
"url": "http://x-force.example.com/contact/",
"email": "dp@x-force.example.com",
},
"license": {
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
"version": "0.0.1",
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_metadata/__init__.py | tests/test_tutorial/test_metadata/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_metadata/test_tutorial004.py | tests/test_tutorial/test_metadata/test_tutorial004.py | from fastapi.testclient import TestClient
from docs_src.metadata.tutorial004_py39 import app
client = TestClient(app)
def test_path_operations():
response = client.get("/items/")
assert response.status_code == 200, response.text
response = client.get("/users/")
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": {
"/users/": {
"get": {
"tags": ["users"],
"summary": "Get Users",
"operationId": "get_users_users__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
},
"/items/": {
"get": {
"tags": ["items"],
"summary": "Get Items",
"operationId": "get_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
},
},
"tags": [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
},
{
"name": "items",
"description": "Manage items. So _fancy_ they have their own docs.",
"externalDocs": {
"description": "Items external docs",
"url": "https://fastapi.tiangolo.com/",
},
},
],
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_metadata/test_tutorial003.py | tests/test_tutorial/test_metadata/test_tutorial003.py | from fastapi.testclient import TestClient
from docs_src.metadata.tutorial003_py39 import app
client = TestClient(app)
def test_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"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/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
def test_swagger_ui_default_url():
response = client.get("/docs")
assert response.status_code == 404, response.text
def test_swagger_ui_custom_url():
response = client.get("/documentation")
assert response.status_code == 200, response.text
assert "<title>FastAPI - Swagger UI</title>" in response.text
def test_redoc_ui_default_url():
response = client.get("/redoc")
assert response.status_code == 404, response.text
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_dataclasses/test_tutorial002.py | tests/test_tutorial/test_dataclasses/test_tutorial002.py | import importlib
import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dataclasses_.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
return client
def test_get_item(client: TestClient):
response = client.get("/items/next")
assert response.status_code == 200
assert response.json() == {
"name": "Island In The Moon",
"price": 12.99,
"description": "A place to be playin' and havin' fun",
"tags": ["breater"],
"tax": None,
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/next": {
"get": {
"summary": "Read Next Item",
"operationId": "read_next_item_items_next_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
}
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
},
}
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_dataclasses/test_tutorial001.py | tests/test_tutorial/test_dataclasses/test_tutorial001.py | import importlib
import pytest
from fastapi.testclient import TestClient
from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dataclasses_.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
return client
def test_post_item(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": 3})
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 3,
"description": None,
"tax": None,
}
def test_post_invalid_item(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "invalid price"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "float_parsing",
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "invalid price",
}
]
}
def test_openapi_schema(client: TestClient):
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": {
"/items/": {
"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": {}}},
},
"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": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"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"},
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_dataclasses/__init__.py | tests/test_tutorial/test_dataclasses/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_dataclasses/test_tutorial003.py | tests/test_tutorial/test_dataclasses/test_tutorial003.py | import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dataclasses_.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
return client
def test_post_authors_item(client: TestClient):
response = client.post(
"/authors/foo/items/",
json=[{"name": "Bar"}, {"name": "Baz", "description": "Drop the Baz"}],
)
assert response.status_code == 200
assert response.json() == {
"name": "foo",
"items": [
{"name": "Bar", "description": None},
{"name": "Baz", "description": "Drop the Baz"},
],
}
def test_get_authors(client: TestClient):
response = client.get("/authors/")
assert response.status_code == 200
assert response.json() == [
{
"name": "Breaters",
"items": [
{
"name": "Island In The Moon",
"description": "A place to be playin' and havin' fun",
},
{"name": "Holy Buddies", "description": None},
],
},
{
"name": "System of an Up",
"items": [
{
"name": "Salt",
"description": "The kombucha mushroom people's favorite",
},
{"name": "Pad Thai", "description": None},
{
"name": "Lonely Night",
"description": "The mostests lonliest nightiest of allest",
},
],
},
]
def test_openapi_schema(client: TestClient):
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": {
"/authors/{author_id}/items/": {
"post": {
"summary": "Create Author Items",
"operationId": "create_author_items_authors__author_id__items__post",
"parameters": [
{
"required": True,
"schema": {"title": "Author Id", "type": "string"},
"name": "author_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"title": "Items",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Author"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/authors/": {
"get": {
"summary": "Get Authors",
"operationId": "get_authors_authors__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Get Authors Authors Get",
"type": "array",
"items": {
"$ref": "#/components/schemas/Author"
},
}
}
},
}
},
}
},
},
"components": {
"schemas": {
"Author": {
"title": "Author",
"required": ["name"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"items": {
"title": "Items",
"type": "array",
"items": {"$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"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
},
},
"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_tutorial/test_cookie_params/test_tutorial001.py | tests/test_tutorial/test_cookie_params/test_tutorial001.py | import importlib
from types import ModuleType
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
"tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.cookie_params.{request.param}")
return mod
@pytest.mark.parametrize(
"path,cookies,expected_status,expected_response",
[
("/items", None, 200, {"ads_id": None}),
("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}),
(
"/items",
{"ads_id": "ads_track", "session": "cookiesession"},
200,
{"ads_id": "ads_track"},
),
("/items", {"session": "cookiesession"}, 200, {"ads_id": None}),
],
)
def test(path, cookies, expected_status, expected_response, mod: ModuleType):
client = TestClient(mod.app, cookies=cookies)
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema(mod: ModuleType):
client = TestClient(mod.app)
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": {
"/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": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Ads Id",
},
"name": "ads_id",
"in": "cookie",
}
],
}
}
},
"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_tutorial/test_cookie_params/__init__.py | tests/test_tutorial/test_cookie_params/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial007.py | tests/test_tutorial/test_python_types/test_tutorial007.py | from docs_src.python_types.tutorial007_py39 import process_items
def test_process_items():
items_t = (1, 2, "foo")
items_s = {b"a", b"b", b"c"}
assert process_items(items_t, items_s) == (items_t, items_s)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py | tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py | import runpy
from unittest.mock import patch
import pytest
@pytest.mark.parametrize(
"module_name",
[
"tutorial001_py39",
"tutorial002_py39",
],
)
def test_run_module(module_name: str):
with patch("builtins.print") as mock_print:
runpy.run_module(f"docs_src.python_types.{module_name}", run_name="__main__")
mock_print.assert_called_with("John Doe")
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial005.py | tests/test_tutorial/test_python_types/test_tutorial005.py | from docs_src.python_types.tutorial005_py39 import get_items
def test_get_items():
res = get_items(
"item_a",
"item_b",
"item_c",
"item_d",
"item_e",
)
assert res == ("item_a", "item_b", "item_c", "item_d", "item_e")
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial006.py | tests/test_tutorial/test_python_types/test_tutorial006.py | from unittest.mock import patch
from docs_src.python_types.tutorial006_py39 import process_items
def test_process_items():
with patch("builtins.print") as mock_print:
process_items(["item_a", "item_b", "item_c"])
assert mock_print.call_count == 3
call_args = [arg.args for arg in mock_print.call_args_list]
assert call_args == [
("item_a",),
("item_b",),
("item_c",),
]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial011.py | tests/test_tutorial/test_python_types/test_tutorial011.py | import runpy
from unittest.mock import patch
import pytest
from ...utils import needs_py310
@pytest.mark.parametrize(
"module_name",
[
pytest.param("tutorial011_py39"),
pytest.param("tutorial011_py310", marks=needs_py310),
],
)
def test_run_module(module_name: str):
with patch("builtins.print") as mock_print:
runpy.run_module(f"docs_src.python_types.{module_name}", run_name="__main__")
assert mock_print.call_count == 2
call_args = [str(arg.args[0]) for arg in mock_print.call_args_list]
assert call_args == [
"id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]",
"123",
]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py | tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py | import importlib
from types import ModuleType
from unittest.mock import patch
import pytest
from ...utils import needs_py310
@pytest.fixture(
name="module",
params=[
pytest.param("tutorial009_py39"),
pytest.param("tutorial009_py310", marks=needs_py310),
pytest.param("tutorial009b_py39"),
],
)
def get_module(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.python_types.{request.param}")
return mod
def test_say_hi(module: ModuleType):
with patch("builtins.print") as mock_print:
module.say_hi("FastAPI")
module.say_hi()
assert mock_print.call_count == 2
call_args = [arg.args for arg in mock_print.call_args_list]
assert call_args == [
("Hey FastAPI!",),
("Hello World",),
]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial008b.py | tests/test_tutorial/test_python_types/test_tutorial008b.py | import importlib
from types import ModuleType
from unittest.mock import patch
import pytest
from ...utils import needs_py310
@pytest.fixture(
name="module",
params=[
pytest.param("tutorial008b_py39"),
pytest.param("tutorial008b_py310", marks=needs_py310),
],
)
def get_module(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.python_types.{request.param}")
return mod
def test_process_items(module: ModuleType):
with patch("builtins.print") as mock_print:
module.process_item("a")
assert mock_print.call_count == 1
mock_print.assert_called_with("a")
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial009c.py | tests/test_tutorial/test_python_types/test_tutorial009c.py | import importlib
import re
from types import ModuleType
from unittest.mock import patch
import pytest
from ...utils import needs_py310
@pytest.fixture(
name="module",
params=[
pytest.param("tutorial009c_py39"),
pytest.param("tutorial009c_py310", marks=needs_py310),
],
)
def get_module(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.python_types.{request.param}")
return mod
def test_say_hi(module: ModuleType):
with patch("builtins.print") as mock_print:
module.say_hi("FastAPI")
mock_print.assert_called_once_with("Hey FastAPI!")
with pytest.raises(
TypeError,
match=re.escape("say_hi() missing 1 required positional argument: 'name'"),
):
module.say_hi()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial013.py | tests/test_tutorial/test_python_types/test_tutorial013.py | from docs_src.python_types.tutorial013_py39 import say_hello
def test_say_hello():
assert say_hello("FastAPI") == "Hello FastAPI"
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/__init__.py | tests/test_tutorial/test_python_types/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial010.py | tests/test_tutorial/test_python_types/test_tutorial010.py | from docs_src.python_types.tutorial010_py39 import Person, get_person_name
def test_get_person_name():
assert get_person_name(Person("John Doe")) == "John Doe"
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial004.py | tests/test_tutorial/test_python_types/test_tutorial004.py | from docs_src.python_types.tutorial004_py39 import get_name_with_age
def test_get_name_with_age_pass_int():
assert get_name_with_age("John", 30) == "John is this old: 30"
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial008.py | tests/test_tutorial/test_python_types/test_tutorial008.py | from unittest.mock import patch
from docs_src.python_types.tutorial008_py39 import process_items
def test_process_items():
with patch("builtins.print") as mock_print:
process_items({"a": 1.0, "b": 2.5})
assert mock_print.call_count == 4
call_args = [arg.args for arg in mock_print.call_args_list]
assert call_args == [
("a",),
(1.0,),
("b",),
(2.5,),
]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial003.py | tests/test_tutorial/test_python_types/test_tutorial003.py | import pytest
from docs_src.python_types.tutorial003_py39 import get_name_with_age
def test_get_name_with_age_pass_int():
with pytest.raises(TypeError):
get_name_with_age("John", 30)
def test_get_name_with_age_pass_str():
assert get_name_with_age("John", "30") == "John is this old: 30"
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_python_types/test_tutorial012.py | tests/test_tutorial/test_python_types/test_tutorial012.py | from docs_src.python_types.tutorial012_py39 import User
def test_user():
user = User(name="John Doe", age=30)
assert user.name == "John Doe"
assert user.age == 30
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py | tests/test_tutorial/test_additional_status_codes/test_tutorial001.py | import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.additional_status_codes.{request.param}")
client = TestClient(mod.app)
return client
def test_update(client: TestClient):
response = client.put("/items/foo", json={"name": "Wrestlers"})
assert response.status_code == 200, response.text
assert response.json() == {"name": "Wrestlers", "size": None}
def test_create(client: TestClient):
response = client.put("/items/red", json={"name": "Chillies"})
assert response.status_code == 201, response.text
assert response.json() == {"name": "Chillies", "size": None}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_additional_status_codes/__init__.py | tests/test_tutorial/test_additional_status_codes/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py | tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py | import importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py39"),
pytest.param("tutorial002_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.response_status_code.{request.param}")
client = TestClient(mod.app)
return client
def test_create_item(client: TestClient):
response = client.post("/items/", params={"name": "Test Item"})
assert response.status_code == 201, response.text
assert response.json() == {"name": "Test Item"}
def test_openapi_schema(client: TestClient):
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": {
"parameters": [
{
"name": "name",
"in": "query",
"required": True,
"schema": {"title": "Name", "type": "string"},
}
],
"summary": "Create Item",
"operationId": "create_item_items__post",
"responses": {
"201": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"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_tutorial/test_response_status_code/__init__.py | tests/test_tutorial/test_response_status_code/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_security/test_tutorial007.py | tests/test_tutorial/test_security/test_tutorial007.py | import importlib
from base64 import b64encode
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial007_py39"),
pytest.param("tutorial007_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
return TestClient(mod.app)
def test_security_http_basic(client: TestClient):
response = client.get("/users/me", auth=("stanleyjobson", "swordfish"))
assert response.status_code == 200, response.text
assert response.json() == {"username": "stanleyjobson"}
def test_security_http_basic_no_credentials(client: TestClient):
response = client.get("/users/me")
assert response.json() == {"detail": "Not authenticated"}
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == "Basic"
def test_security_http_basic_invalid_credentials(client: TestClient):
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(client: TestClient):
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_security_http_basic_invalid_username(client: TestClient):
response = client.get("/users/me", auth=("alice", "swordfish"))
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Incorrect username or password"}
assert response.headers["WWW-Authenticate"] == "Basic"
def test_security_http_basic_invalid_password(client: TestClient):
response = client.get("/users/me", auth=("stanleyjobson", "wrongpassword"))
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Incorrect username or password"}
assert response.headers["WWW-Authenticate"] == "Basic"
def test_openapi_schema(client: TestClient):
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_tutorial/test_security/test_tutorial002.py | tests/test_tutorial/test_security/test_tutorial002.py | import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
client = TestClient(mod.app)
return client
def test_no_token(client: TestClient):
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_token(client: TestClient):
response = client.get("/users/me", headers={"Authorization": "Bearer testtoken"})
assert response.status_code == 200, response.text
assert response.json() == {
"username": "testtokenfakedecoded",
"email": "john@example.com",
"full_name": "John Doe",
"disabled": None,
}
def test_openapi_schema(client: TestClient):
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 Users Me",
"operationId": "read_users_me_users_me_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_tutorial/test_security/test_tutorial001.py | tests/test_tutorial/test_security/test_tutorial001.py | import importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py39"),
pytest.param("tutorial001_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
client = TestClient(mod.app)
return client
def test_no_token(client: TestClient):
response = client.get("/items")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_token(client: TestClient):
response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
assert response.status_code == 200, response.text
assert response.json() == {"token": "testtoken"}
def test_incorrect_token(client: TestClient):
response = client.get("/items", headers={"Authorization": "Notexistent testtoken"})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_openapi_schema(client: TestClient):
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_tutorial/test_security/test_tutorial005.py | tests/test_tutorial/test_security/test_tutorial005.py | import importlib
from types import ModuleType
import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
return mod
def get_access_token(
*, username="johndoe", password="secret", scope=None, client: TestClient
):
data = {"username": username, "password": password}
if scope:
data["scope"] = scope
response = client.post("/token", data=data)
content = response.json()
access_token = content.get("access_token")
return access_token
def test_login(mod: ModuleType):
client = TestClient(mod.app)
response = client.post("/token", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 200, response.text
content = response.json()
assert "access_token" in content
assert content["token_type"] == "bearer"
def test_login_incorrect_password(mod: ModuleType):
client = TestClient(mod.app)
response = client.post(
"/token", data={"username": "johndoe", "password": "incorrect"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_login_incorrect_username(mod: ModuleType):
client = TestClient(mod.app)
response = client.post("/token", data={"username": "foo", "password": "secret"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_no_token(mod: ModuleType):
client = TestClient(mod.app)
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_token(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(scope="me", client=client)
response = client.get(
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 200, response.text
assert response.json() == {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"disabled": False,
}
def test_incorrect_token(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
def test_incorrect_token_type(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me", headers={"Authorization": "Notexistent testtoken"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_verify_password(mod: ModuleType):
assert mod.verify_password(
"secret", mod.fake_users_db["johndoe"]["hashed_password"]
)
def test_get_password_hash(mod: ModuleType):
assert mod.get_password_hash("secretalice")
def test_create_access_token(mod: ModuleType):
access_token = mod.create_access_token(data={"data": "foo"})
assert access_token
def test_token_no_sub(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me",
headers={
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE"
},
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
def test_token_no_username(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me",
headers={
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y"
},
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
def test_token_no_scope(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(client=client)
response = client.get(
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not enough permissions"}
assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
def test_token_nonexistent_user(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me",
headers={
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw"
},
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
def test_token_inactive_user(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(
username="alice", password="secretalice", scope="me", client=client
)
response = client.get(
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Inactive user"}
def test_read_items(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(scope="me items", client=client)
response = client.get(
"/users/me/items/", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}]
def test_read_system_status(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(client=client)
response = client.get(
"/status/", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 200, response.text
assert response.json() == {"status": "ok"}
def test_read_system_status_no_token(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/status/")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_openapi_schema(mod: ModuleType):
client = TestClient(mod.app)
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": {
"/token": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Token"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Login For Access Token",
"operationId": "login_for_access_token_token_post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_for_access_token_token_post"
}
}
},
"required": True,
},
}
},
"/users/me/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
}
},
"summary": "Read Users Me",
"operationId": "read_users_me_users_me__get",
"security": [{"OAuth2PasswordBearer": ["me"]}],
}
},
"/users/me/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Own Items",
"operationId": "read_own_items_users_me_items__get",
"security": [{"OAuth2PasswordBearer": ["items", "me"]}],
}
},
"/status/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read System Status",
"operationId": "read_system_status_status__get",
"security": [{"OAuth2PasswordBearer": []}],
}
},
},
"components": {
"schemas": {
"User": {
"title": "User",
"required": ["username"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"email": {
"title": "Email",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"full_name": {
"title": "Full Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"disabled": {
"title": "Disabled",
"anyOf": [{"type": "boolean"}, {"type": "null"}],
},
},
},
"Token": {
"title": "Token",
"required": ["access_token", "token_type"],
"type": "object",
"properties": {
"access_token": {"title": "Access Token", "type": "string"},
"token_type": {"title": "Token Type", "type": "string"},
},
},
"Body_login_for_access_token_token_post": {
"title": "Body_login_for_access_token_token_post",
"required": ["username", "password"],
"type": "object",
"properties": {
"grant_type": {
"title": "Grant Type",
"anyOf": [
{"pattern": "^password$", "type": "string"},
{"type": "null"},
],
},
"username": {"title": "Username", "type": "string"},
"password": {
"title": "Password",
"type": "string",
"format": "password",
},
"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"}],
"format": "password",
},
},
},
"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": {
"OAuth2PasswordBearer": {
"type": "oauth2",
"flows": {
"password": {
"scopes": {
"me": "Read information about the current user.",
"items": "Read items.",
},
"tokenUrl": "token",
}
},
}
},
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_security/test_tutorial006.py | tests/test_tutorial/test_security/test_tutorial006.py | import importlib
from base64 import b64encode
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial006_py39"),
pytest.param("tutorial006_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
client = TestClient(mod.app)
return client
def test_security_http_basic(client: TestClient):
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(client: TestClient):
response = client.get("/users/me")
assert response.json() == {"detail": "Not authenticated"}
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == "Basic"
def test_security_http_basic_invalid_credentials(client: TestClient):
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(client: TestClient):
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(client: TestClient):
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_tutorial/test_security/__init__.py | tests/test_tutorial/test_security/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_security/test_tutorial004.py | tests/test_tutorial/test_security/test_tutorial004.py | import importlib
from types import ModuleType
from unittest.mock import patch
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
return mod
def get_access_token(*, username="johndoe", password="secret", client: TestClient):
data = {"username": username, "password": password}
response = client.post("/token", data=data)
content = response.json()
access_token = content.get("access_token")
return access_token
def test_login(mod: ModuleType):
client = TestClient(mod.app)
response = client.post("/token", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 200, response.text
content = response.json()
assert "access_token" in content
assert content["token_type"] == "bearer"
def test_login_incorrect_password(mod: ModuleType):
client = TestClient(mod.app)
response = client.post(
"/token", data={"username": "johndoe", "password": "incorrect"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_login_incorrect_username(mod: ModuleType):
client = TestClient(mod.app)
response = client.post("/token", data={"username": "foo", "password": "secret"})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_no_token(mod: ModuleType):
client = TestClient(mod.app)
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_token(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(client=client)
response = client.get(
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 200, response.text
assert response.json() == {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"disabled": False,
}
def test_incorrect_token(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_incorrect_token_type(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me", headers={"Authorization": "Notexistent testtoken"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_verify_password(mod: ModuleType):
assert mod.verify_password(
"secret", mod.fake_users_db["johndoe"]["hashed_password"]
)
def test_get_password_hash(mod: ModuleType):
assert mod.get_password_hash("johndoe")
def test_create_access_token(mod: ModuleType):
access_token = mod.create_access_token(data={"data": "foo"})
assert access_token
def test_token_no_sub(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me",
headers={
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE"
},
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_token_no_username(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me",
headers={
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y"
},
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_token_nonexistent_user(mod: ModuleType):
client = TestClient(mod.app)
response = client.get(
"/users/me",
headers={
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw"
},
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Could not validate credentials"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_token_inactive_user(mod: ModuleType):
client = TestClient(mod.app)
alice_user_data = {
"username": "alice",
"full_name": "Alice Wonderson",
"email": "alice@example.com",
"hashed_password": mod.get_password_hash("secretalice"),
"disabled": True,
}
with patch.dict(f"{mod.__name__}.fake_users_db", {"alice": alice_user_data}):
access_token = get_access_token(
username="alice", password="secretalice", client=client
)
response = client.get(
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Inactive user"}
def test_read_items(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(client=client)
response = client.get(
"/users/me/items/", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}]
def test_openapi_schema(mod: ModuleType):
client = TestClient(mod.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": {
"/token": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Token"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Login For Access Token",
"operationId": "login_for_access_token_token_post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_for_access_token_token_post"
}
}
},
"required": True,
},
}
},
"/users/me/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
}
},
"summary": "Read Users Me",
"operationId": "read_users_me_users_me__get",
"security": [{"OAuth2PasswordBearer": []}],
}
},
"/users/me/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Own Items",
"operationId": "read_own_items_users_me_items__get",
"security": [{"OAuth2PasswordBearer": []}],
}
},
},
"components": {
"schemas": {
"User": {
"title": "User",
"required": ["username"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"email": {
"title": "Email",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"full_name": {
"title": "Full Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"disabled": {
"title": "Disabled",
"anyOf": [{"type": "boolean"}, {"type": "null"}],
},
},
},
"Token": {
"title": "Token",
"required": ["access_token", "token_type"],
"type": "object",
"properties": {
"access_token": {"title": "Access Token", "type": "string"},
"token_type": {"title": "Token Type", "type": "string"},
},
},
"Body_login_for_access_token_token_post": {
"title": "Body_login_for_access_token_token_post",
"required": ["username", "password"],
"type": "object",
"properties": {
"grant_type": {
"title": "Grant Type",
"anyOf": [
{"pattern": "^password$", "type": "string"},
{"type": "null"},
],
},
"username": {"title": "Username", "type": "string"},
"password": {
"title": "Password",
"type": "string",
"format": "password",
},
"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"}],
"format": "password",
},
},
},
"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": {
"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_tutorial/test_security/test_tutorial003.py | tests/test_tutorial/test_security/test_tutorial003.py | import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
client = TestClient(mod.app)
return client
def test_login(client: TestClient):
response = client.post("/token", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 200, response.text
assert response.json() == {"access_token": "johndoe", "token_type": "bearer"}
def test_login_incorrect_password(client: TestClient):
response = client.post(
"/token", data={"username": "johndoe", "password": "incorrect"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_login_incorrect_username(client: TestClient):
response = client.post("/token", data={"username": "foo", "password": "secret"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_no_token(client: TestClient):
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_token(client: TestClient):
response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"})
assert response.status_code == 200, response.text
assert response.json() == {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"hashed_password": "fakehashedsecret",
"disabled": False,
}
def test_incorrect_token(client: TestClient):
response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_incorrect_token_type(client: TestClient):
response = client.get(
"/users/me", headers={"Authorization": "Notexistent testtoken"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_inactive_user(client: TestClient):
response = client.get("/users/me", headers={"Authorization": "Bearer alice"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Inactive user"}
def test_openapi_schema(client: TestClient):
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": {
"/token": {
"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_token_post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_token_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": [{"OAuth2PasswordBearer": []}],
}
},
},
"components": {
"schemas": {
"Body_login_token_post": {
"title": "Body_login_token_post",
"required": ["username", "password"],
"type": "object",
"properties": {
"grant_type": {
"title": "Grant Type",
"anyOf": [
{"pattern": "^password$", "type": "string"},
{"type": "null"},
],
},
"username": {"title": "Username", "type": "string"},
"password": {
"title": "Password",
"type": "string",
"format": "password",
},
"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"}],
"format": "password",
},
},
},
"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": {
"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_tutorial/test_generate_clients/test_tutorial002.py | tests/test_tutorial/test_generate_clients/test_tutorial002.py | from fastapi.testclient import TestClient
from docs_src.generate_clients.tutorial002_py39 import app
client = TestClient(app)
def test_post_items():
response = client.post("/items/", json={"name": "Foo", "price": 5})
assert response.status_code == 200, response.text
assert response.json() == {"message": "Item received"}
def test_post_users():
response = client.post(
"/users/", json={"username": "Foo", "email": "foo@example.com"}
)
assert response.status_code == 200, response.text
assert response.json() == {"message": "User received"}
def test_get_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Plumbus", "price": 3},
{"name": "Portal Gun", "price": 9001},
]
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": {
"tags": ["items"],
"summary": "Get Items",
"operationId": "get_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Get Items Items Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
}
},
},
"post": {
"tags": ["items"],
"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/ResponseMessage"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
},
"/users/": {
"post": {
"tags": ["users"],
"summary": "Create User",
"operationId": "create_user_users__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResponseMessage"
}
}
},
},
"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": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
},
},
"ResponseMessage": {
"title": "ResponseMessage",
"required": ["message"],
"type": "object",
"properties": {"message": {"title": "Message", "type": "string"}},
},
"User": {
"title": "User",
"required": ["username", "email"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"email": {"title": "Email", "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_tutorial/test_generate_clients/test_tutorial001.py | tests/test_tutorial/test_generate_clients/test_tutorial001.py | import importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.generate_clients.{request.param}")
client = TestClient(mod.app)
return client
def test_post_items(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": 5})
assert response.status_code == 200, response.text
assert response.json() == {"message": "item received"}
def test_get_items(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Plumbus", "price": 3},
{"name": "Portal Gun", "price": 9001},
]
def test_openapi_schema(client: TestClient):
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": "Get Items",
"operationId": "get_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Get Items Items Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
}
},
},
"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/ResponseMessage"
}
}
},
},
"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": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
},
},
"ResponseMessage": {
"title": "ResponseMessage",
"required": ["message"],
"type": "object",
"properties": {"message": {"title": "Message", "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_tutorial/test_generate_clients/__init__.py | tests/test_tutorial/test_generate_clients/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_generate_clients/test_tutorial004.py | tests/test_tutorial/test_generate_clients/test_tutorial004.py | import importlib
import json
import pathlib
from unittest.mock import patch
from docs_src.generate_clients import tutorial003_py39
def test_remove_tags(tmp_path: pathlib.Path):
tmp_file = tmp_path / "openapi.json"
openapi_json = tutorial003_py39.app.openapi()
tmp_file.write_text(json.dumps(openapi_json))
with patch("pathlib.Path", return_value=tmp_file):
importlib.import_module("docs_src.generate_clients.tutorial004_py39")
modified_openapi = json.loads(tmp_file.read_text())
assert modified_openapi == {
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError",
},
"title": "Detail",
"type": "array",
},
},
"title": "HTTPValidationError",
"type": "object",
},
"Item": {
"properties": {
"name": {
"title": "Name",
"type": "string",
},
"price": {
"title": "Price",
"type": "number",
},
},
"required": [
"name",
"price",
],
"title": "Item",
"type": "object",
},
"ResponseMessage": {
"properties": {
"message": {
"title": "Message",
"type": "string",
},
},
"required": [
"message",
],
"title": "ResponseMessage",
"type": "object",
},
"User": {
"properties": {
"email": {
"title": "Email",
"type": "string",
},
"username": {
"title": "Username",
"type": "string",
},
},
"required": [
"username",
"email",
],
"title": "User",
"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": {
"/items/": {
"get": {
"operationId": "get_items",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item",
},
"title": "Response Items-Get Items",
"type": "array",
},
},
},
"description": "Successful Response",
},
},
"summary": "Get Items",
"tags": [
"items",
],
},
"post": {
"operationId": "create_item",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item",
},
},
},
"required": True,
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResponseMessage",
},
},
},
"description": "Successful Response",
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError",
},
},
},
"description": "Validation Error",
},
},
"summary": "Create Item",
"tags": [
"items",
],
},
},
"/users/": {
"post": {
"operationId": "create_user",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/User",
},
},
},
"required": True,
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResponseMessage",
},
},
},
"description": "Successful Response",
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError",
},
},
},
"description": "Validation Error",
},
},
"summary": "Create User",
"tags": [
"users",
],
},
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_generate_clients/test_tutorial003.py | tests/test_tutorial/test_generate_clients/test_tutorial003.py | from fastapi.testclient import TestClient
from docs_src.generate_clients.tutorial003_py39 import app
client = TestClient(app)
def test_post_items():
response = client.post("/items/", json={"name": "Foo", "price": 5})
assert response.status_code == 200, response.text
assert response.json() == {"message": "Item received"}
def test_post_users():
response = client.post(
"/users/", json={"username": "Foo", "email": "foo@example.com"}
)
assert response.status_code == 200, response.text
assert response.json() == {"message": "User received"}
def test_get_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Plumbus", "price": 3},
{"name": "Portal Gun", "price": 9001},
]
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": {
"tags": ["items"],
"summary": "Get Items",
"operationId": "items-get_items",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Items-Get Items",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
}
},
},
"post": {
"tags": ["items"],
"summary": "Create Item",
"operationId": "items-create_item",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResponseMessage"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
},
"/users/": {
"post": {
"tags": ["users"],
"summary": "Create User",
"operationId": "users-create_user",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResponseMessage"
}
}
},
},
"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": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
},
},
"ResponseMessage": {
"title": "ResponseMessage",
"required": ["message"],
"type": "object",
"properties": {"message": {"title": "Message", "type": "string"}},
},
"User": {
"title": "User",
"required": ["username", "email"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"email": {"title": "Email", "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_tutorial/test_configure_swagger_ui/test_tutorial002.py | tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py | from fastapi.testclient import TestClient
from docs_src.configure_swagger_ui.tutorial002_py39 import app
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert '"syntaxHighlight": false' not in response.text, (
"not used parameters should not be included"
)
assert '"syntaxHighlight": {"theme": "obsidian"}' in response.text, (
"parameters with middle dots should be included in a JSON compatible way"
)
assert '"dom_id": "#swagger-ui"' in response.text, (
"default configs should be preserved"
)
assert "presets: [" in response.text, "default configs should be preserved"
assert "SwaggerUIBundle.presets.apis," in response.text, (
"default configs should be preserved"
)
assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, (
"default configs should be preserved"
)
assert '"layout": "BaseLayout",' in response.text, (
"default configs should be preserved"
)
assert '"deepLinking": true,' in response.text, (
"default configs should be preserved"
)
assert '"showExtensions": true,' in response.text, (
"default configs should be preserved"
)
assert '"showCommonExtensions": true,' in response.text, (
"default configs should be preserved"
)
def test_get_users():
response = client.get("/users/foo")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py | tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py | from fastapi.testclient import TestClient
from docs_src.configure_swagger_ui.tutorial001_py39 import app
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert '"syntaxHighlight": false' in response.text, (
"syntaxHighlight should be included and converted to JSON"
)
assert '"dom_id": "#swagger-ui"' in response.text, (
"default configs should be preserved"
)
assert "presets: [" in response.text, "default configs should be preserved"
assert "SwaggerUIBundle.presets.apis," in response.text, (
"default configs should be preserved"
)
assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, (
"default configs should be preserved"
)
assert '"layout": "BaseLayout",' in response.text, (
"default configs should be preserved"
)
assert '"deepLinking": true,' in response.text, (
"default configs should be preserved"
)
assert '"showExtensions": true,' in response.text, (
"default configs should be preserved"
)
assert '"showCommonExtensions": true,' in response.text, (
"default configs should be preserved"
)
def test_get_users():
response = client.get("/users/foo")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_configure_swagger_ui/__init__.py | tests/test_tutorial/test_configure_swagger_ui/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py | tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py | from fastapi.testclient import TestClient
from docs_src.configure_swagger_ui.tutorial003_py39 import app
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert '"deepLinking": false,' in response.text, (
"overridden configs should be preserved"
)
assert '"deepLinking": true' not in response.text, (
"overridden configs should not include the old value"
)
assert '"syntaxHighlight": false' not in response.text, (
"not used parameters should not be included"
)
assert '"dom_id": "#swagger-ui"' in response.text, (
"default configs should be preserved"
)
assert "presets: [" in response.text, "default configs should be preserved"
assert "SwaggerUIBundle.presets.apis," in response.text, (
"default configs should be preserved"
)
assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, (
"default configs should be preserved"
)
assert '"layout": "BaseLayout",' in response.text, (
"default configs should be preserved"
)
assert '"showExtensions": true,' in response.text, (
"default configs should be preserved"
)
assert '"showCommonExtensions": true,' in response.text, (
"default configs should be preserved"
)
def test_get_users():
response = client.get("/users/foo")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_body/test_tutorial002.py | tests/test_tutorial/test_body/test_tutorial002.py | import importlib
from typing import Union
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize("price", ["50.5", 50.5])
def test_post_with_tax(client: TestClient, price: Union[str, float]):
response = client.post(
"/items/",
json={"name": "Foo", "price": price, "description": "Some Foo", "tax": 0.3},
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": 0.3,
"price_with_tax": 50.8,
}
@pytest.mark.parametrize("price", ["50.5", 50.5])
def test_post_without_tax(client: TestClient, price: Union[str, float]):
response = client.post(
"/items/", json={"name": "Foo", "price": price, "description": "Some Foo"}
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": None,
}
def test_post_with_no_data(client: TestClient):
response = client.post("/items/", json={})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
},
]
}
def test_openapi_schema(client: TestClient):
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": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"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"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_body/test_tutorial001.py | tests/test_tutorial/test_body/test_tutorial001.py | import importlib
from unittest.mock import patch
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body.{request.param}")
client = TestClient(mod.app)
return client
def test_body_float(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": 50.5})
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": None,
"tax": None,
}
def test_post_with_str_float(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "50.5"})
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": None,
"tax": None,
}
def test_post_with_str_float_description(client: TestClient):
response = client.post(
"/items/", json={"name": "Foo", "price": "50.5", "description": "Some Foo"}
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": None,
}
def test_post_with_str_float_description_tax(client: TestClient):
response = client.post(
"/items/",
json={"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3},
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": 0.3,
}
def test_post_with_only_name(client: TestClient):
response = client.post("/items/", json={"name": "Foo"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {"name": "Foo"},
}
]
}
def test_post_with_only_name_price(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "twenty"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "float_parsing",
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "twenty",
}
]
}
def test_post_with_no_data(client: TestClient):
response = client.post("/items/", json={})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
},
]
}
def test_post_with_none(client: TestClient):
response = client.post("/items/", json=None)
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body"],
"msg": "Field required",
"input": None,
}
]
}
def test_post_broken_body(client: TestClient):
response = client.post(
"/items/",
headers={"content-type": "application/json"},
content="{some broken json}",
)
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "json_invalid",
"loc": ["body", 1],
"msg": "JSON decode error",
"input": {},
"ctx": {"error": "Expecting property name enclosed in double quotes"},
}
]
}
def test_post_form_for_json(client: TestClient):
response = client.post("/items/", data={"name": "Foo", "price": 50.5})
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": "name=Foo&price=50.5",
}
]
}
def test_explicit_content_type(client: TestClient):
response = client.post(
"/items/",
content='{"name": "Foo", "price": 50.5}',
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200, response.text
def test_geo_json(client: TestClient):
response = client.post(
"/items/",
content='{"name": "Foo", "price": 50.5}',
headers={"Content-Type": "application/geo+json"},
)
assert response.status_code == 200, response.text
def test_no_content_type_is_json(client: TestClient):
response = client.post(
"/items/",
content='{"name": "Foo", "price": 50.5}',
)
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"description": None,
"price": 50.5,
"tax": None,
}
def test_wrong_headers(client: TestClient):
data = '{"name": "Foo", "price": 50.5}'
response = client.post(
"/items/", content=data, headers={"Content-Type": "text/plain"}
)
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
}
]
}
response = client.post(
"/items/", content=data, headers={"Content-Type": "application/geo+json-seq"}
)
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
}
]
}
response = client.post(
"/items/", content=data, headers={"Content-Type": "application/not-really-json"}
)
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
}
]
}
def test_other_exceptions(client: TestClient):
with patch("json.loads", side_effect=Exception):
response = client.post("/items/", json={"test": "test2"})
assert response.status_code == 400, response.text
def test_openapi_schema(client: TestClient):
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": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"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"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_body/__init__.py | tests/test_tutorial/test_body/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false | |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_body/test_tutorial004.py | tests/test_tutorial/test_body/test_tutorial004.py | import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body.{request.param}")
client = TestClient(mod.app)
return client
def test_put_all(client: TestClient):
response = client.put(
"/items/123",
json={"name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3},
params={"q": "somequery"},
)
assert response.status_code == 200
assert response.json() == {
"item_id": 123,
"name": "Foo",
"price": 50.1,
"description": "Some Foo",
"tax": 0.3,
"q": "somequery",
}
def test_put_only_required(client: TestClient):
response = client.put(
"/items/123",
json={"name": "Foo", "price": 50.1},
)
assert response.status_code == 200
assert response.json() == {
"item_id": 123,
"name": "Foo",
"price": 50.1,
"description": None,
"tax": None,
}
def test_put_with_no_data(client: TestClient):
response = client.put("/items/123", json={})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
},
]
}
def test_openapi_schema(client: TestClient):
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": {
"parameters": [
{
"in": "path",
"name": "item_id",
"required": True,
"schema": {
"title": "Item Id",
"type": "integer",
},
},
{
"required": False,
"schema": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Q",
},
"name": "q",
"in": "query",
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"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"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_body/test_tutorial003.py | tests/test_tutorial/test_body/test_tutorial003.py | import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body.{request.param}")
client = TestClient(mod.app)
return client
def test_put_all(client: TestClient):
response = client.put(
"/items/123",
json={"name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3},
)
assert response.status_code == 200
assert response.json() == {
"item_id": 123,
"name": "Foo",
"price": 50.1,
"description": "Some Foo",
"tax": 0.3,
}
def test_put_only_required(client: TestClient):
response = client.put(
"/items/123",
json={"name": "Foo", "price": 50.1},
)
assert response.status_code == 200
assert response.json() == {
"item_id": 123,
"name": "Foo",
"price": 50.1,
"description": None,
"tax": None,
}
def test_put_with_no_data(client: TestClient):
response = client.put("/items/123", json={})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
},
]
}
def test_openapi_schema(client: TestClient):
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": {
"parameters": [
{
"in": "path",
"name": "item_id",
"required": True,
"schema": {
"title": "Item Id",
"type": "integer",
},
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"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"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_additional_responses/test_tutorial002.py | tests/test_tutorial/test_additional_responses/test_tutorial002.py | import importlib
import os
import shutil
import pytest
from fastapi.testclient import TestClient
from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.additional_responses.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
return client
def test_path_operation(client: TestClient):
response = client.get("/items/foo")
assert response.status_code == 200, response.text
assert response.json() == {"id": "foo", "value": "there goes my hero"}
def test_path_operation_img(client: TestClient):
shutil.copy("./docs/en/docs/img/favicon.png", "./image.png")
response = client.get("/items/foo?img=1")
assert response.status_code == 200, response.text
assert response.headers["Content-Type"] == "image/png"
assert len(response.content)
os.remove("./image.png")
def test_openapi_schema(client: TestClient):
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}": {
"get": {
"responses": {
"200": {
"description": "Return the JSON item or an image.",
"content": {
"image/png": {},
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
},
},
},
"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",
},
{
"required": False,
"schema": {
"anyOf": [{"type": "boolean"}, {"type": "null"}],
"title": "Img",
},
"name": "img",
"in": "query",
},
],
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["id", "value"],
"type": "object",
"properties": {
"id": {"title": "Id", "type": "string"},
"value": {"title": "Value", "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"},
},
},
"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_tutorial/test_additional_responses/test_tutorial001.py | tests/test_tutorial/test_additional_responses/test_tutorial001.py | from fastapi.testclient import TestClient
from docs_src.additional_responses.tutorial001_py39 import app
client = TestClient(app)
def test_path_operation():
response = client.get("/items/foo")
assert response.status_code == 200, response.text
assert response.json() == {"id": "foo", "value": "there goes my hero"}
def test_path_operation_not_found():
response = client.get("/items/bar")
assert response.status_code == 404, response.text
assert response.json() == {"message": "Item not found"}
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}": {
"get": {
"responses": {
"404": {
"description": "Not Found",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Message"}
}
},
},
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"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",
}
],
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["id", "value"],
"type": "object",
"properties": {
"id": {"title": "Id", "type": "string"},
"value": {"title": "Value", "type": "string"},
},
},
"Message": {
"title": "Message",
"required": ["message"],
"type": "object",
"properties": {"message": {"title": "Message", "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"},
},
},
"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_tutorial/test_additional_responses/__init__.py | tests/test_tutorial/test_additional_responses/__init__.py | python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.