prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
import Depends, FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
app = FastAPI()
def get_user(required_scopes: SecurityScopes):
return "john", required_scopes.scopes
def get_user_override(required_scopes: SecurityScopes):
return "alice", required_scop... | rt response.json() == {
"user": "john",
"scopes": ["foo", "bar"],
"data": [1, 2, 3],
}
def test_override_data():
app.dependency_overrides[get_data] = get_data_override
response = client.get("/user")
assert response | opes=["foo", "bar"]),
data: list[int] = Depends(get_data),
):
return {"user": user_data[0], "scopes": user_data[1], "data": data}
client = TestClient(app)
def test_normal():
response = client.get("/user")
asse | {
"filepath": "tests/test_dependency_security_overrides.py",
"language": "python",
"file_size": 1431,
"cut_index": 524,
"middle_length": 229
} |
ingResponse
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"... | ltDep) -> 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 g | ion, 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: SessionDefau | {
"filepath": "tests/test_dependency_yield_scope.py",
"language": "python",
"file_size": 6837,
"cut_index": 716,
"middle_length": 229
} |
import FastAPI, Request
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI(openapi_prefix="/api/v1")
@app.get("/app")
def read_main(request: Request):
return {"message": "Hello World", "root_path": request.scope.get("root_path")}
client = TestClient(app)
def test_ma... | paths": {
"/app": {
"get": {
"summary": "Read Main",
"operationId": "read_main_app_get",
"responses": {
"200": {
| se = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
" | {
"filepath": "tests/test_deprecated_openapi_prefix.py",
"language": "python",
"file_size": 1326,
"cut_index": 524,
"middle_length": 229
} |
FastAPI
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.responses import ORJSONResponse, UJSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
from tests.utils import needs_orjson, needs_ujson
class Item(BaseModel):
name: str
price: float
# ORJSON
de... | estClient(app)
with warnings.catch_warnings():
warnings.simplefilter("ignore", FastAPIDeprecationWarning)
response = client.get("/items")
assert response.status_code == 200
assert response.json() == {"name": "widget", "price": 9 | nse)
@app.get("/items")
def get_items() -> Item:
return Item(name="widget", price=9.99)
return app
@needs_orjson
def test_orjson_response_returns_correct_data():
app = _make_orjson_app()
client = T | {
"filepath": "tests/test_deprecated_responses.py",
"language": "python",
"file_size": 2158,
"cut_index": 563,
"middle_length": 229
} |
import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
class Model(BaseModel):
pass
class Model2(BaseModel):
a: Model
class Model3(BaseModel):
c: Model
d: Model2
@app.get("/", response_model=Model3)
def f():
return {"c": {}, "d": {"a": {}}}
... | {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"summary": "F",
"operationId": "f__get",
"responses": {
| }
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": | {
"filepath": "tests/test_duplicate_models_openapi.py",
"language": "python",
"file_size": 2470,
"cut_index": 563,
"middle_length": 229
} |
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, excep... |
)
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 | rver-error"})
app = FastAPI(
exception_handlers={
HTTPException: http_exception_handler,
RequestValidationError: request_validation_exception_handler,
Exception: server_error_exception_handler,
} | {
"filepath": "tests/test_exception_handlers.py",
"language": "python",
"file_size": 2504,
"cut_index": 563,
"middle_length": 229
} |
em_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 JSONRes... | e/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():
res | 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="messag | {
"filepath": "tests/test_extra_routes.py",
"language": "python",
"file_size": 15071,
"cut_index": 921,
"middle_length": 229
} |
shot import snapshot
app = FastAPI()
def _get_client_key(client_id: str = Query(...)) -> str:
return f"{client_id}_key"
def _get_client_tag(client_id: str | None = Query(None)) -> str | None:
if client_id is None:
return None
return f"{client_id}_tag"
@app.get("/foo")
def foo_handler(
cli... | ert response.json() == {"client_id": "bar_key", "client_tag": "bar_tag"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
| ef test_get_invalid():
response = client.get("/foo")
assert response.status_code == 422
def test_get_valid():
response = client.get("/foo", params={"client_id": "bar"})
assert response.status_code == 200
ass | {
"filepath": "tests/test_enforce_once_required_parameter.py",
"language": "python",
"file_size": 4154,
"cut_index": 614,
"middle_length": 229
} |
nt
app = FastAPI()
def function_dependency(value: str) -> str:
return value
async def async_function_dependency(value: str) -> str:
return value
def gen_dependency(value: str) -> Generator[str, None, None]:
yield value
async def async_gen_dependency(value: str) -> AsyncGenerator[str, None]:
yie... | 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, | one]:
yield value
class AsyncCallableDependency:
async def __call__(self, value: str) -> str:
return value
class AsyncCallableGenDependency:
async def __call__(self, value: str) -> AsyncGenerator[str, | {
"filepath": "tests/test_dependency_partial.py",
"language": "python",
"file_size": 6493,
"cut_index": 716,
"middle_length": 229
} |
rt TestClient
global_context: ContextVar[dict[str, Any]] = ContextVar("global_context", default={}) # noqa: B039
class Session:
def __init__(self) -> None:
self.open = True
async def dep_session() -> Any:
s = Session()
yield s
s.open = False
global_state = global_context.get()
glob... | uestDep, session_b: SessionDefaultDep) -> Any:
assert session is session_b
named_session = NamedSession(name="named")
yield named_session, session_b
named_session.open = False
global_state = global_context.get()
global_state["named_ | ssionDefaultDep = 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: SessionReq | {
"filepath": "tests/test_dependency_yield_scope_websockets.py",
"language": "python",
"file_size": 6177,
"cut_index": 716,
"middle_length": 229
} |
t.mock import patch
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
app = FastAPI()
@app.get("/default")
def get_default() -> Item:
return Item(name="widget", ... | wraps=__import__("json").dumps
) as mock_dumps:
response = client.get("/default")
assert response.status_code == 200
assert response.json() == {"name": "widget", "price": 9.99}
mock_dumps.assert_not_called()
def test_explicit_resp | lass_skips_json_dumps():
"""When no response_class is set, the fast path serializes directly to
JSON bytes via Pydantic's dump_json and never calls json.dumps."""
with patch(
"starlette.responses.json.dumps", | {
"filepath": "tests/test_dump_json_fast_path.py",
"language": "python",
"file_size": 1476,
"cut_index": 524,
"middle_length": 229
} |
i import Body, Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
initial_fake_database = {"rick": "Rick Sanchez"}
fake_database = initial_fake_database.copy()
initial_state = {"except": False, "finally": False}
state = initial_state.copy()
app = FastAPI()
async def get_database():
tem... | de=400, detail="Invalid user")
@app.put("/user/{user_id}")
def put_user(user_id: str, name: str = Body(), db: dict = Depends(get_database)):
db[user_id] = name
return {"message": "OK"}
@pytest.fixture(autouse=True)
def reset_state_and_db():
| nally:
state["finally"] = True
@app.put("/invalid-user/{user_id}")
def put_invalid_user(
user_id: str, name: str = Body(), db: dict = Depends(get_database)
):
db[user_id] = name
raise HTTPException(status_co | {
"filepath": "tests/test_dependency_yield_except_httpexception.py",
"language": "python",
"file_size": 1961,
"cut_index": 537,
"middle_length": 229
} |
mons}
@app.get("/decorator-depends/", dependencies=[Depends(common_parameters)])
async def decorator_depends():
return {"in": "decorator-depends"}
@router.get("/router-depends/")
async def router_depends(commons: dict = Depends(common_parameters)):
return {"in": "router-depends", "params": commons}
@route... | cy_with_sub(msg: dict = Depends(overrider_sub_dependency)):
return msg
def test_main_depends():
response = client.get("/main-depends/")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
|
client = TestClient(app)
async def overrider_dependency_simple(q: str | None = None):
return {"q": q, "skip": 5, "limit": 10}
async def overrider_sub_dependency(k: str):
return {"k": k}
async def overrider_dependen | {
"filepath": "tests/test_dependency_overrides.py",
"language": "python",
"file_size": 11457,
"cut_index": 921,
"middle_length": 229
} |
yncio import iscoroutinefunction
def noop_wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def noop_wrap_async(func):
if inspect.isgeneratorfunction(func):
@wraps(func)
async def gen_wrapper(*args, **kwargs):
asy... | spect.isroutine(func) and iscoroutinefunction(func):
return await func(*args, **kwargs)
if inspect.isclass(func):
return await run_in_threadpool(func, *args, **kwargs)
dunder_call = getattr(func, "__call__", None) # | ync def async_gen_wrapper(*args, **kwargs):
async for item in func(*args, **kwargs):
yield item
return async_gen_wrapper
@wraps(func)
async def wrapper(*args, **kwargs):
if in | {
"filepath": "tests/test_dependency_wrapped.py",
"language": "python",
"file_size": 11487,
"cut_index": 921,
"middle_length": 229
} |
t pytest
from fastapi import APIRouter, FastAPI
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
app = FastAPI()
router = APIRouter()
@router.get("")
def get_empty():
return ["OK"]
app.include_router(router, prefix="/prefix")
client = TestClient(app)
def test_use_empty... | assert response.status_code == 200, response.text
assert response.json() == ["OK"]
def test_include_empty():
# if both include and router.path are empty - it should raise exception
with pytest.raises(FastAPIError):
app.inclu | "/prefix/")
| {
"filepath": "tests/test_empty_router.py",
"language": "python",
"file_size": 805,
"cut_index": 517,
"middle_length": 14
} |
port snapshot
@pytest.fixture(name="client")
def get_client():
from pydantic import BaseModel, ValidationInfo, field_validator
app = FastAPI()
class ModelB(BaseModel):
username: str
class ModelC(ModelB):
password: str
class ModelA(BaseModel):
name: str
descripti... | odel/{name}", response_model=ModelA)
async def get_model_a(name: str, model_c=Depends(get_model_c)):
return {
"name": name,
"description": "model-a-desc",
"foo": model_c,
"tags": {"key1": "value1" | ot name.endswith("A"):
raise ValueError("name must end in A")
return name
async def get_model_c() -> ModelC:
return ModelC(username="test-user", password="test-password")
@app.get("/m | {
"filepath": "tests/test_filter_pydantic_sub_model_pv2.py",
"language": "python",
"file_size": 6849,
"cut_index": 716,
"middle_length": 229
} |
astapi import FastAPI, Form
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/form/python-list")
def post_form_param_list(items: list = Form()):
return items
@app.post("/form/python-set")
def post_form_param_set(items: set = Form()):
return items
@app.post("/form/python-tuple")
def po... | "/form/python-set", data={"items": ["first", "second", "third"]}
)
assert response.status_code == 200, response.text
assert set(response.json()) == {"first", "second", "third"}
def test_python_tuple_param_as_form():
response = client.p | items": ["first", "second", "third"]}
)
assert response.status_code == 200, response.text
assert response.json() == ["first", "second", "third"]
def test_python_set_param_as_form():
response = client.post(
| {
"filepath": "tests/test_forms_from_non_typing_sequences.py",
"language": "python",
"file_size": 1202,
"cut_index": 518,
"middle_length": 229
} |
ent
from inline_snapshot import snapshot
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... | mmary": "Post Form",
"operationId": "post_form_form__post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
| n() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/form/": {
"post": {
"su | {
"filepath": "tests/test_forms_single_param.py",
"language": "python",
"file_size": 4192,
"cut_index": 614,
"middle_length": 229
} |
import Depends, FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
T = TypeVar("T")
Dep = Annotated[T, Depends()]
class A:
pass
class B:
pass
@app.get("/a")
async def a(dep: Dep[A]):
return {"cls": dep.__class__.__name__}
@app.get("/b")
async d... | response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"info": {"title": "FastAPI", "version": "0.1.0"},
"openapi": "3.1.0",
"pa | code == 200, response.text
assert response.json() == {"cls": "A"}
response = client.get("/b")
assert response.status_code == 200, response.text
assert response.json() == {"cls": "B"}
def test_openapi_schema():
| {
"filepath": "tests/test_generic_parameterless_depends.py",
"language": "python",
"file_size": 2023,
"cut_index": 563,
"middle_length": 229
} |
shot
from pydantic import BaseModel
app = FastAPI()
class Product(BaseModel):
name: str
description: str = None # type: ignore
price: float
@app.get("/product")
async def create_item(product: Product):
return product
client = TestClient(app)
def test_get_with_body():
body = {"name": "Foo",... | "paths": {
"/product": {
"get": {
"summary": "Create Item",
"operationId": "create_item_product_get",
"requestBody": {
| ent.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"},
| {
"filepath": "tests/test_get_request_body.py",
"language": "python",
"file_size": 4311,
"cut_index": 614,
"middle_length": 229
} |
"500": {"description": "Server error level 0"},
"501": {"description": "Server error level 1"},
},
"callbacks": {
"callback0": {
"/": {
... | "required": True,
"schema": {
"title": "Level0",
"type": "string",
| "parameters": [
{
"name": "level0",
"in": "query",
| {
"filepath": "tests/test_include_router_defaults_overrides.py",
"language": "python",
"file_size": 394863,
"cut_index": 13624,
"middle_length": 229
} |
s(user_id: str | None = None):
if user_id is None:
return [{"item_id": "i1", "user_id": "u1"}, {"item_id": "i2", "user_id": "u2"}]
else:
return [{"item_id": "i2", "user_id": user_id}]
@item_router.get("/{item_id}")
def get_item(item_id: str, user_id: str | None = None):
if user_id is None:... | onse.status_code == 200, response.text
assert response.json() == [{"user_id": "u1"}, {"user_id": "u2"}]
def test_get_user():
"""Check that /users/{user_id} returns expected data"""
response = client.get("/users/abc123")
assert response.st | ="/items")
app.include_router(item_router, prefix="/users/{user_id}/items")
client = TestClient(app)
def test_get_users():
"""Check that /users returns expected data"""
response = client.get("/users")
assert resp | {
"filepath": "tests/test_infer_param_optionality.py",
"language": "python",
"file_size": 13515,
"cut_index": 921,
"middle_length": 229
} |
before File
See https://github.com/tiangolo/fastapi/discussions/9116
"""
from pathlib import Path
from typing import Annotated
import pytest
from fastapi import FastAPI, File, Form
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/file_before_form")
def file_before_form(
file: bytes = File(... | city}
@app.post("/file_list_after_form")
def file_list_after_form(
city: Annotated[str, Form()],
files: Annotated[list[bytes], File()],
):
return {"file_contents": files, "city": city}
client = TestClient(app)
@pytest.fixture
def tmp_file | rn {"file_content": file, "city": city}
@app.post("/file_list_before_form")
def file_list_before_form(
files: Annotated[list[bytes], File()],
city: Annotated[str, Form()],
):
return {"file_contents": files, "city": | {
"filepath": "tests/test_file_and_form_order_issue_9116.py",
"language": "python",
"file_size": 2304,
"cut_index": 563,
"middle_length": 229
} |
ent
from pydantic import BaseModel, Field
app = FastAPI()
class FormModel(BaseModel):
username: str
lastname: str
age: int | None = None
tags: list[str] = ["foo", "bar"]
alias_with: str = Field(alias="with", default="nothing")
class FormModelExtraAllow(BaseModel):
param: str
model_conf... | ,
"age": "70",
"tags": ["plumbus", "citadel"],
"with": "something",
},
)
assert response.status_code == 200, response.text
assert response.json() == {
"username": "Rick",
"lastname": " | ormModelExtraAllow, Form()]):
return params
client = TestClient(app)
def test_send_all_data():
response = client.post(
"/form/",
data={
"username": "Rick",
"lastname": "Sanchez" | {
"filepath": "tests/test_forms_single_model.py",
"language": "python",
"file_size": 3452,
"cut_index": 614,
"middle_length": 229
} |
tic import BaseModel
class Address(BaseModel):
"""
This is a public description of an Address
\f
You can't see this part of the docstring, it's private!
"""
line_1: str
city: str
state_province: str
class Facility(BaseModel):
id: str
... | assert response.status_code == 200, response.text
assert response.json() == {
"id": "42",
"address": {
"line_1": "123 Main St",
"city": "Anytown",
"state_province": "CA",
},
}
def test_o | address=Address(line_1="123 Main St", city="Anytown", state_province="CA"),
)
client = TestClient(app)
return client
def test_get(client: TestClient):
response = client.get("/facilities/42")
| {
"filepath": "tests/test_get_model_definitions_formfeed_escape.py",
"language": "python",
"file_size": 6103,
"cut_index": 716,
"middle_length": 229
} |
t
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class MyUuid:
def __init__(self, uuid_string: str):
self.uuid = uuid_string
def __str__(self):
return self.uuid
@property # type: ignore
def __class__(self):
return uuid.UU... | 984-a26f-d3ab460bdb51")
assert isinstance(asyncpg_uuid, uuid.UUID)
assert type(asyncpg_uuid) is not uuid.UUID
with pytest.raises(TypeError):
vars(asyncpg_uuid)
return {"fast_uuid": asyncpg_uuid}
class SomeCu | rgument must have __dict__ attribute")
def test_pydanticv2():
from pydantic import field_serializer
app = FastAPI()
@app.get("/fast_uuid")
def return_fast_uuid():
asyncpg_uuid = MyUuid("a10ff360-3b1e-4 | {
"filepath": "tests/test_inherited_custom_class.py",
"language": "python",
"file_size": 1813,
"cut_index": 537,
"middle_length": 229
} |
typing import Annotated
from fastapi import FastAPI, File, Form
from starlette.testclient import TestClient
app = FastAPI()
@app.post("/urlencoded")
async def post_url_encoded(age: Annotated[int | None, Form()] = None):
return age
@app.post("/multipart")
async def post_multi_part(
age: Annotated[int | No... | ert response.status_code == 200
assert response.text == "null"
def test_form_default_multi_part():
response = client.post("/multipart", data={"age": ""})
assert response.status_code == 200
assert response.json() == {"file": None, "age": N | client.post("/urlencoded", data={"age": ""})
ass | {
"filepath": "tests/test_form_default.py",
"language": "python",
"file_size": 829,
"cut_index": 516,
"middle_length": 52
} |
Message"
},
}
}
},
},
"422": {
"description": "Validation Error",
... | }
},
"/router": {
"post": {
"summary": "Post Router",
"operationId": "foo_post_router",
"requestBody": {
| "#/components/schemas/HTTPValidationError"
}
}
},
},
},
| {
"filepath": "tests/test_generate_unique_id_function.py",
"language": "python",
"file_size": 76760,
"cut_index": 3790,
"middle_length": 229
} |
i import FastAPI
from pydantic import BaseModel
def test_invalid_sequence():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/{id}")
def read_items(id: list[Item]):
pass # pragma: no cover
def test_i... | ms/{id}")
def read_items(id: dict[str, Item]):
pass # pragma: no cover
def test_invalid_simple_list():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: list): | d: tuple[Item, Item]):
pass # pragma: no cover
def test_invalid_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/ite | {
"filepath": "tests/test_invalid_path_param.py",
"language": "python",
"file_size": 1666,
"cut_index": 537,
"middle_length": 229
} |
Connection
from fastapi.testclient import TestClient
from starlette.websockets import WebSocket
app = FastAPI()
app.state.value = 42
async def extract_value_from_http_connection(conn: HTTPConnection):
return conn.app.state.value
@app.get("/http")
async def get_value_by_http(value: int = Depends(extract_value_f... | await websocket.close()
client = TestClient(app)
def test_value_extracting_by_http():
response = client.get("/http")
assert response.status_code == 200
assert response.json() == 42
def test_value_extracting_by_ws():
with client.web | cket.accept()
await websocket.send_json(value)
| {
"filepath": "tests/test_http_connection_injection.py",
"language": "python",
"file_size": 972,
"cut_index": 582,
"middle_length": 52
} |
est.importorskip("orjson")
from fastapi import FastAPI
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.responses import ORJSONResponse
from fastapi.testclient import TestClient
from sqlalchemy.sql.elements import quoted_name
with warnings.catch_warnings():
warnings.simplefilter("ignore", Fas... | TestClient(app)
def test_orjson_non_str_keys():
with warnings.catch_warnings():
warnings.simplefilter("ignore", FastAPIDeprecationWarning)
with client:
response = client.get("/orjson_non_str_keys")
assert response.json | e)
return {key: "Hello World", 1: 1}
client = | {
"filepath": "tests/test_orjson_response_class.py",
"language": "python",
"file_size": 892,
"cut_index": 547,
"middle_length": 52
} |
_snapshot import snapshot
app = FastAPI()
@app.get("/{repeated_alias}")
def get_parameters_with_repeated_aliases(
path: str = Path(..., alias="repeated_alias"),
query: str = Query(..., alias="repeated_alias"),
):
return {"path": path, "query": query}
client = TestClient(app)
def test_get_parameters()... | "schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schema | ery": "test_query"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == status.HTTP_200_OK
assert response.json() == snapshot(
{
"components": {
| {
"filepath": "tests/test_repeated_parameter_alias.py",
"language": "python",
"file_size": 4262,
"cut_index": 614,
"middle_length": 229
} |
ort 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... |
@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"},
| "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"}
| {
"filepath": "tests/test_schema_compat_pydantic_v2.py",
"language": "python",
"file_size": 4245,
"cut_index": 614,
"middle_length": 229
} |
ons import PydanticV1NotSupportedError
from pydantic import BaseModel, Field, ValidationError
class Person:
def __init__(self, name: str):
self.name = name
class Pet:
def __init__(self, owner: Person, name: str):
self.owner = owner
self.name = name
@dataclass
class Item:
name: ... | ):
admin = "admin"
normal = "normal"
class ModelWithConfig(BaseModel):
role: RoleEnum | None = None
model_config = {"use_enum_values": True}
class ModelWithAlias(BaseModel):
foo: str = Field(alias="Foo")
class ModelWithDefault(Ba | eturn ((k, v) for k, v in self.__dict__.items())
class Unserializable:
def __iter__(self):
raise NotImplementedError()
@property
def __dict__(self):
raise NotImplementedError()
class RoleEnum(Enum | {
"filepath": "tests/test_jsonable_encoder.py",
"language": "python",
"file_size": 9883,
"cut_index": 921,
"middle_length": 229
} |
on test: preserve order when using list[bytes] + File()
See https://github.com/fastapi/fastapi/discussions/14811
Fixed in PR: https://github.com/fastapi/fastapi/pull/14884
"""
from typing import Annotated
import anyio
import pytest
from fastapi import FastAPI, File
from fastapi.testclient import TestClient
from starl... | d(self: StarletteUploadFile, size: int = -1) -> bytes:
# Make the FIRST file slower *deterministically*
if self.filename == "slow.txt":
await anyio.sleep(0.05)
return await original_read(self, size)
monkeypatch.seta | load")
async def upload(files: Annotated[list[bytes], File()]):
# return something that makes order obvious
return [b[0] for b in files]
original_read = StarletteUploadFile.read
async def patched_rea | {
"filepath": "tests/test_list_bytes_file_order_preserved_issue_14811.py",
"language": "python",
"file_size": 1411,
"cut_index": 524,
"middle_length": 229
} |
decimal
app = FastAPI()
class Item(BaseModel):
name: str
age: condecimal(gt=Decimal(0.0)) # type: ignore
@app.post("/items/")
def save_item_no_body(item: list[Item]):
return {"item": item}
client = TestClient(app)
def test_put_correct_body():
response = client.post("/items/", json=[{"name": "F... | tus_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["body", 0, "age"],
"msg": "Input should be greater than 0",
"in | o",
"age": "5",
}
]
}
)
def test_jsonable_encoder_requiring_error():
response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}])
assert response.sta | {
"filepath": "tests/test_multi_body_errors.py",
"language": "python",
"file_size": 6875,
"cut_index": 716,
"middle_length": 229
} |
rt snapshot
app = FastAPI()
@app.get("/items/")
def read_items(q: list[int] = Query(default=None)):
return {"q": q}
client = TestClient(app)
def test_multi_query():
response = client.get("/items/?q=5&q=6")
assert response.status_code == 200, response.text
assert response.json() == {"q": [5, 6]}
... | },
{
"type": "int_parsing",
"loc": ["query", "q", 1],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "six",
},
] | {
"type": "int_parsing",
"loc": ["query", "q", 0],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "five",
| {
"filepath": "tests/test_multi_query_errors.py",
"language": "python",
"file_size": 4504,
"cut_index": 614,
"middle_length": 229
} |
rom fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI(swagger_ui_oauth2_redirect_url=None)
@app.get("/items/")
async def read_items():
return {"id": "foo"}
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, r... | .text
def test_swagger_ui_no_oauth2_redirect():
response = client.get("/docs/oauth2-redirect")
assert response.status_code == 404, response.text
def test_response():
response = client.get("/items/")
assert response.json() == {"id": "foo | ot in response | {
"filepath": "tests/test_no_swagger_ui_redirect.py",
"language": "python",
"file_size": 786,
"cut_index": 513,
"middle_length": 14
} |
"Example One": {
"summary": "Example One Summary",
"description": "Example One Description",
"value": {"data": "Data in Body examples, example1"},
},
"Example Two": {
"value": {"data": "Data in Body examples, example2"},
... | },
"Path Two": {
"value": "item_2",
},
},
),
):
return item_id
@app.get("/query_examples/")
def query_examples(
data: str | None = Query(
default=None,
examples=[
| "json_schema_item_2",
],
openapi_examples={
"Path One": {
"summary": "Path One Summary",
"description": "Path One Description",
"value": "item_1",
| {
"filepath": "tests/test_openapi_examples.py",
"language": "python",
"file_size": 16749,
"cut_index": 921,
"middle_length": 229
} |
shot
app = FastAPI()
@app.get(
"/",
openapi_extra={
"parameters": [
{
"required": False,
"schema": {"title": "Extra Param 1"},
"name": "extra_param_1",
"in": "query",
},
{
"required": T... | = {}
def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version" | parameters(standard_query_param: int | None = 50):
return {}
client = TestClient(app)
def test_get_route():
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() = | {
"filepath": "tests/test_openapi_query_parameter_extension.py",
"language": "python",
"file_size": 4901,
"cut_index": 614,
"middle_length": 229
} |
PI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI(
servers=[
{"url": "/", "description": "Default, relative server"},
{
"url": "http://staging.localhost.tiangolo.com:8000",
"description": "Staging but actually localhost still",
... | napshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"servers": [
{"url": "/", "description": "Default, relative server"},
{
"url": | lient.get("/foo")
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() == s | {
"filepath": "tests/test_openapi_servers.py",
"language": "python",
"file_size": 1759,
"cut_index": 537,
"middle_length": 229
} |
i import FastAPI, Query
from pydantic import BaseModel
def test_invalid_sequence():
with pytest.raises(
AssertionError,
match="Query parameter 'q' must be one of the supported types",
):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")... | =None)):
pass # pragma: no cover
def test_invalid_dict():
with pytest.raises(
AssertionError,
match="Query parameter 'q' must be one of the supported types",
):
app = FastAPI()
class Item(BaseModel):
| ery parameter 'q' must be one of the supported types",
):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: tuple[Item, Item] = Query(default | {
"filepath": "tests/test_invalid_sequence_param.py",
"language": "python",
"file_size": 1545,
"cut_index": 537,
"middle_length": 229
} |
mport Annotated
from fastapi import Cookie, FastAPI, Form, Header, Query
from fastapi.testclient import TestClient
from pydantic import Json
app = FastAPI()
@app.post("/form-json-list")
def form_json_list(items: Annotated[Json[list[str]], Form()]) -> list[str]:
return items
@app.get("/query-json-list")
def qu... | client.post(
"/form-json-list", data={"items": json.dumps(["abc", "def"])}
)
assert response.status_code == 200, response.text
assert response.json() == ["abc", "def"]
def test_query_json_list():
response = client.get(
"/ | list[str]:
return x_items
@app.get("/cookie-json-list")
def cookie_json_list(items: Annotated[Json[list[str]], Cookie()]) -> list[str]:
return items
client = TestClient(app)
def test_form_json_list():
response = | {
"filepath": "tests/test_json_type.py",
"language": "python",
"file_size": 1694,
"cut_index": 537,
"middle_length": 229
} |
t_redoc_html, get_swagger_ui_html
def test_strings_in_generated_swagger():
sig = inspect.signature(get_swagger_ui_html)
swagger_js_url = sig.parameters.get("swagger_js_url").default # type: ignore
swagger_css_url = sig.parameters.get("swagger_css_url").default # type: ignore
swagger_favicon_url = si... | file.css"
swagger_favicon_url = "swagger_fake_file.png"
html = get_swagger_ui_html(
openapi_url="/docs",
title="title",
swagger_js_url=swagger_js_url,
swagger_css_url=swagger_css_url,
swagger_favicon_url=swag | rl in body_content
assert swagger_css_url in body_content
assert swagger_favicon_url in body_content
def test_strings_in_custom_swagger():
swagger_js_url = "swagger_fake_file.js"
swagger_css_url = "swagger_fake_ | {
"filepath": "tests/test_local_docs.py",
"language": "python",
"file_size": 2506,
"cut_index": 563,
"middle_length": 229
} |
m fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, Field
class MessageEventType(str, Enum):
alpha = "alpha"
beta = "beta"
class MessageEvent(BaseModel):
event_type: MessageEventType = Field(default=MessageEventType.alph... | t(body=f"Processed: {input_message}"),
)
client = TestClient(app)
def test_create_message():
response = client.post("/messages", params={"input_message": "Hello"})
assert response.status_code == 200, response.text
assert response.json() | (title="Minimal FastAPI App", version="1.0.0")
@app.post("/messages", response_model=Message)
async def create_message(input_message: str) -> Message:
return Message(
input=input_message,
output=MessageOutpu | {
"filepath": "tests/test_no_schema_split.py",
"language": "python",
"file_size": 6653,
"cut_index": 716,
"middle_length": 229
} |
import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
@app.get("/", openapi_extra={"x-custom-extension": "value"})
def route_with_extras():
return {}
client = TestClient(app)
def test_get_route():
response = client.get("/")
assert response.stat... | "responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
| assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
| {
"filepath": "tests/test_openapi_route_extensions.py",
"language": "python",
"file_size": 1273,
"cut_index": 524,
"middle_length": 229
} |
"delete", "options", "head", "patch", "trace"]
def test_signatures_consistency():
base_sig = inspect.signature(APIRouter.get)
for method_name in method_names:
router_method = getattr(APIRouter, method_name)
app_method = getattr(FastAPI, method_name)
router_sig = inspect.signature(route... | spect.Parameter = app_sig.parameters[key]
assert param.annotation == router_param.annotation
assert param.annotation == app_param.annotation
assert param.default == router_param.default
assert param.default = | router_sig.parameters[key]
app_param: in | {
"filepath": "tests/test_operations_signatures.py",
"language": "python",
"file_size": 934,
"cut_index": 606,
"middle_length": 52
} |
f test_incorrect_multipart_installed_form(monkeypatch):
monkeypatch.setattr("python_multipart.__version__", "0.0.12")
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False)
with pytest.raises(R... | monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False)
with pytest.raises(RuntimeError, match=multipart_incorrect_install_error):
app = FastAPI()
@app.post("/")
async def root(f: UploadFile = File() | cover
def test_incorrect_multipart_installed_file_upload(monkeypatch):
monkeypatch.setattr("python_multipart.__version__", "0.0.12")
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
| {
"filepath": "tests/test_multipart_installation.py",
"language": "python",
"file_size": 5809,
"cut_index": 716,
"middle_length": 229
} |
_output_schemas)
@app.post("/items/", responses={402: {"model": Item}})
def create_item(item: Item) -> Item:
return item
@app.post("/items-list/")
def create_item_list(item: list[Item]):
return item
@app.get("/items/")
def read_items() -> list[Item]:
return [
... | lient = TestClient(app)
return client
def test_create_item():
client = get_app_client()
client_no = get_app_client(separate_input_output_schemas=False)
response = client.post("/items/", json={"name": "Plumbus"})
response2 = client_no. | Item(name="Plumbus"),
]
@app.post("/with-computed-field/")
def create_with_computed_field(
with_computed_field: WithComputedField,
) -> WithComputedField:
return with_computed_field
c | {
"filepath": "tests/test_openapi_separate_input_output_schemas.py",
"language": "python",
"file_size": 28494,
"cut_index": 1331,
"middle_length": 229
} |
port snapshot
app = FastAPI()
async def user_exists(user_id: int):
return True
@app.get("/users/{user_id}", dependencies=[Depends(user_exists)])
async def read_users(user_id: int):
pass
client = TestClient(app)
def test_read_users():
response = client.get("/users/42")
assert response.status_cod... | ad_users_users__user_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "User Id", "type": "integer"},
| nfo": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/{user_id}": {
"get": {
"summary": "Read Users",
"operationId": "re | {
"filepath": "tests/test_param_in_path_and_dependency.py",
"language": "python",
"file_size": 3648,
"cut_index": 614,
"middle_length": 229
} |
Body, Cookie, Header, Param, Path, Query
test_data: list[Any] = ["teststr", None, ..., 1, []]
def get_user():
return {} # pragma: no cover
def test_param_repr_str():
assert repr(Param("teststr")) == "Param(teststr)"
def test_param_repr_none():
assert repr(Param(None)) == "Param(None)"
def test_par... | "Query(teststr)"
def test_query_repr_none():
assert repr(Query(None)) == "Query(None)"
def test_query_repr_ellipsis():
assert repr(Query(...)) == "Query(PydanticUndefined)"
def test_query_repr_number():
assert repr(Query(1)) == "Query(1)" | epr(Param([])) == "Param([])"
def test_path_repr():
assert repr(Path()) == "Path(PydanticUndefined)"
assert repr(Path(...)) == "Path(PydanticUndefined)"
def test_query_repr_str():
assert repr(Query("teststr")) == | {
"filepath": "tests/test_params_repr.py",
"language": "python",
"file_size": 2321,
"cut_index": 563,
"middle_length": 229
} |
shot
app = FastAPI()
@app.put("/items/{item_id}")
def save_item_no_body(item_id: str):
return {"item_id": item_id}
client = TestClient(app)
def test_put_no_body():
response = client.put("/items/foo")
assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
... | nfo": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"put": {
"responses": {
"200": {
"descripti | "foo"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"i | {
"filepath": "tests/test_put_no_body.py",
"language": "python",
"file_size": 3889,
"cut_index": 614,
"middle_length": 229
} |
_future__ import annotations
import uuid
from dataclasses import dataclass, field
from dirty_equals import IsUUID
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
@dataclass
class Item:
id: uuid.UUID
name: str
price: float
tags: list[str] = f... | ns():
response = client.get("/item")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"id": IsUUID(),
"name": "Island In The Moon",
"price": 12.99,
" | "id": uuid.uuid4(),
"name": "Island In The Moon",
"price": 12.99,
"description": "A place to be playin' and havin' fun",
"tags": ["breater"],
}
client = TestClient(app)
def test_annotatio | {
"filepath": "tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py",
"language": "python",
"file_size": 1131,
"cut_index": 518,
"middle_length": 229
} |
ntic import BaseModel
app = FastAPI()
class Model(BaseModel):
param: str
model_config = {"extra": "allow"}
class AuthHeaders(BaseModel):
x_user_id: str
@app.get("/query")
async def query_model_with_extra(data: Model = Query()):
return data
@app.get("/header")
async def header_model_with_extra(... | "param2": ["456", "789"], # Pass a list of values as extra parameter
},
)
assert resp.status_code == 200
assert resp.json() == {
"param": "123",
"param2": ["456", "789"],
}
def test_query_pass_extra_single(): | r_model_requires_hyphen(data: AuthHeaders = Header()):
return data
def test_query_pass_extra_list():
client = TestClient(app)
resp = client.get(
"/query",
params={
"param": "123",
| {
"filepath": "tests/test_query_cookie_header_model_extra_params.py",
"language": "python",
"file_size": 3282,
"cut_index": 614,
"middle_length": 229
} |
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"H... | y"})
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.sta | ient.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": "fixedquer | {
"filepath": "tests/test_regex_deprecated_body.py",
"language": "python",
"file_size": 5490,
"cut_index": 716,
"middle_length": 229
} |
om 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")
d... | = 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" | dep}
client | {
"filepath": "tests/test_repeated_cookie_headers.py",
"language": "python",
"file_size": 792,
"cut_index": 514,
"middle_length": 14
} |
import TestClient
def test_root_path_does_not_persist_across_requests():
app = FastAPI()
@app.get("/")
def read_root(): # pragma: no cover
return {"ok": True}
# Attacker request with a spoofed root_path
attacker_client = TestClient(app, root_path="/evil-api")
response1 = attacker_c... | le_different_root_paths_do_not_accumulate():
app = FastAPI()
@app.get("/")
def read_root(): # pragma: no cover
return {"ok": True}
for prefix in ["/path-a", "/path-b", "/path-c"]:
c = TestClient(app, root_path=prefix)
| clean_client = TestClient(app)
response2 = clean_client.get("/openapi.json")
data2 = response2.json()
servers = [s.get("url") for s in data2.get("servers", [])]
assert "/evil-api" not in servers
def test_multip | {
"filepath": "tests/test_openapi_cache_root_path.py",
"language": "python",
"file_size": 2348,
"cut_index": 563,
"middle_length": 229
} |
om fastapi import FastAPI, File
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/files")
async def upload_files(files: list[bytes] | None = File(None)):
if files is None:
return {"files_count": 0}
return {"files_count": len(files), "sizes": [len(f) for f in files]}
def test_opt... | assert response.json() == {"files_count": 2, "sizes": [8, 8]}
def test_optional_bytes_list_no_files():
client = TestClient(app)
response = client.post("/files")
assert response.status_code == 200
assert response.json() == {"files_count" | code == 200
| {
"filepath": "tests/test_optional_file_list.py",
"language": "python",
"file_size": 789,
"cut_index": 514,
"middle_length": 14
} |
f hidden_cookie(
hidden_cookie: str | None = Cookie(default=None, include_in_schema=False),
):
return {"hidden_cookie": hidden_cookie}
@app.get("/hidden_header")
async def hidden_header(
hidden_header: str | None = Header(default=None, include_in_schema=False),
):
return {"hidden_header": hidden_heade... | (
"/hidden_cookie",
{},
200,
{"hidden_cookie": None},
),
(
"/hidden_cookie",
{"hidden_cookie": "somevalue"},
200,
{"hidden_cookie": "somev | ef hidden_query(
hidden_query: str | None = Query(default=None, include_in_schema=False),
):
return {"hidden_query": hidden_query}
@pytest.mark.parametrize(
"path,cookies,expected_status,expected_response",
[
| {
"filepath": "tests/test_param_include_in_schema.py",
"language": "python",
"file_size": 8848,
"cut_index": 716,
"middle_length": 229
} |
e.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_query_baz():
response = client.get("/query?query=baz")
assert respo... | }
]
}
def test_query_optional():
response = client.get("/query/optional")
assert response.status_code == 200
assert response.json() == "foo bar"
def test_query_optional_query_baz():
response = client.get("/query/optional? | 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
| {
"filepath": "tests/test_query.py",
"language": "python",
"file_size": 7548,
"cut_index": 716,
"middle_length": 229
} |
t snapshot
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"... | 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 | 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()
| {
"filepath": "tests/test_regex_deprecated_params.py",
"language": "python",
"file_size": 5209,
"cut_index": 716,
"middle_length": 229
} |
ode == 200
assert response.json() == "42"
def test_path_str_True():
response = client.get("/path/str/True")
assert response.status_code == 200
assert response.json() == "True"
def test_path_int_foobar():
response = client.get("/path/int/foobar")
assert response.status_code == 422
assert ... | response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input | r, unable to parse string as an integer",
"input": "foobar",
}
]
}
def test_path_int_True():
response = client.get("/path/int/True")
assert response.status_code == 422
assert | {
"filepath": "tests/test_path.py",
"language": "python",
"file_size": 21003,
"cut_index": 1331,
"middle_length": 229
} |
yping import Any
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
def test_read_with_orm_mode() -> None:
class PersonBase(BaseModel):
name: str
lastname: str
class Person(PersonBase):
@property
def full_name(self... | Person.model_validate(person)
return db_person
client = TestClient(app)
person_data = {"name": "Dive", "lastname": "Wilson"}
response = client.post("/people/", json=person_data)
data = response.json()
assert response.status_c | sonBase):
full_name: str
model_config = {"from_attributes": True}
app = FastAPI()
@app.post("/people/", response_model=PersonRead)
def create_person(person: PersonCreate) -> Any:
db_person = | {
"filepath": "tests/test_read_with_orm_mode.py",
"language": "python",
"file_size": 1215,
"cut_index": 518,
"middle_length": 229
} |
line_snapshot import snapshot
app = FastAPI()
def get_header(*, someheader: str = Header()):
return someheader
def get_something_else(*, someheader: str = Depends(get_header)):
return f"{someheader}123"
@app.get("/")
def get_deps(dep1: str = Depends(get_header), dep2: str = Depends(get_something_else)):
... | response.json()
assert (
len(actual_schema["paths"]["/"]["get"]["parameters"]) == 1
) # primary goal of this test
assert actual_schema == snapshot(
{
"components": {
"schemas": {
| tus.HTTP_200_OK
assert response.json() == {"dep1": "hello", "dep2": "hello123"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == status.HTTP_200_OK
actual_schema = | {
"filepath": "tests/test_repeated_dependency_schema.py",
"language": "python",
"file_size": 4075,
"cut_index": 614,
"middle_length": 229
} |
# NOTE: These are not valid JSON:API resources
# but they are fine for testing requestBody with custom media_type
class Product(BaseModel):
name: str
price: float
class Shop(BaseModel):
name: str
@app.post("/products")
async def create_product(data: Product = Body(media_type=media_type, embed=True)):
... | {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/products": {
"post": {
"summary": "Create Product",
| pass # pragma: no cover
client = TestClient(app)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
| {
"filepath": "tests/test_request_body_parameters_media_type.py",
"language": "python",
"file_size": 7344,
"cut_index": 716,
"middle_length": 229
} |
import Cookie, FastAPI, Header, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Model(BaseModel):
param: str = Field(alias="param_alias")
@app.get("/query")
async def query_model(data: Model = Query()):
return {"param": data.param}
@app.get("/h... | "value"}
def test_header_model_with_alias():
client = TestClient(app)
response = client.get("/header", headers={"param_alias": "value"})
assert response.status_code == 200, response.text
assert response.json() == {"param": "value"}
def |
def test_query_model_with_alias():
client = TestClient(app)
response = client.get("/query", params={"param_alias": "value"})
assert response.status_code == 200, response.text
assert response.json() == {"param": | {
"filepath": "tests/test_request_param_model_by_alias.py",
"language": "python",
"file_size": 2182,
"cut_index": 563,
"middle_length": 229
} |
nt import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
class JsonApiResponse(JSONResponse):
media_type = "application/vnd.api+json"
class Error(BaseModel):
status: str
title: str
class JsonApiError(BaseModel):
errors: list[Error]
@app.get(
"... | t
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/a": {
"get": {
"responses | tion": "Error", "model": Error}})
async def b():
pass # pragma: no cover
client = TestClient(app)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.tex | {
"filepath": "tests/test_response_class_no_mediatype.py",
"language": "python",
"file_size": 3730,
"cut_index": 614,
"middle_length": 229
} |
TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
class JsonApiResponse(JSONResponse):
media_type = "application/vnd.api+json"
class Error(BaseModel):
status: str
title: str
class JsonApiError(BaseModel):
errors: list[Error]
@app.get(
"/a",
s... | th" not in response.headers
assert response.content == b""
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"open | on": "No Content"}})
async def b():
pass # pragma: no cover
client = TestClient(app)
def test_get_response():
response = client.get("/a")
assert response.status_code == 204, response.text
assert "content-leng | {
"filepath": "tests/test_response_code_no_body.py",
"language": "python",
"file_size": 3602,
"cut_index": 614,
"middle_length": 229
} |
PI
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):... | =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]
| 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 | {
"filepath": "tests/test_response_model_data_filter.py",
"language": "python",
"file_size": 1701,
"cut_index": 537,
"middle_length": 229
} |
import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class ResponseModel(BaseModel):
code: int = 200
message: str = Field(default_factory=lambda: "Successful operation.")
@app.get(
"/response_model_has_default_factory_return_dict",
response... | onse_model_has_default_factory_return_dict")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] == "Successful operation."
def test_response_model_has_default_factory_re | del=ResponseModel,
)
async def response_model_has_default_factory_return_model():
return ResponseModel()
client = TestClient(app)
def test_response_model_has_default_factory_return_dict():
response = client.get("/resp | {
"filepath": "tests/test_response_model_default_factory.py",
"language": "python",
"file_size": 1264,
"cut_index": 524,
"middle_length": 229
} |
ort pytest
from fastapi import FastAPI
from fastapi.exceptions import FastAPIError
class NonPydanticModel:
pass
def test_invalid_response_model_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", response_model=NonPydanticModel)
def read_root():
pas... | model": NonPydanticModel}})
def read_root():
pass # pragma: nocover
def test_invalid_response_model_sub_type_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", responses={"500" | del])
def read_root():
pass # pragma: nocover
def test_invalid_response_model_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", responses={"500": {" | {
"filepath": "tests/test_response_model_invalid.py",
"language": "python",
"file_size": 1099,
"cut_index": 515,
"middle_length": 229
} |
t
from inline_snapshot import snapshot
app = FastAPI()
@app.delete(
"/{id}",
status_code=204,
response_model=None,
)
async def delete_deployment(
id: int,
response: Response,
) -> Any:
response.status_code = 400
return {"msg": "Status overwritten", "id": id}
client = TestClient(app)
d... | "info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/{id}": {
"delete": {
"summary": "Delete Deployment",
"operationId": "delete_deployment__id__dele | "id": 1}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
| {
"filepath": "tests/test_response_set_response_code_empty.py",
"language": "python",
"file_size": 3723,
"cut_index": 614,
"middle_length": 229
} |
TestClient
def test_redirect_slashes_enabled():
app = FastAPI()
router = APIRouter()
@router.get("/hello/")
def hello_page() -> str:
return "Hello, World!"
app.include_router(router)
client = TestClient(app)
response = client.get("/hello/", follow_redirects=False)
assert re... | r.get("/hello/")
def hello_page() -> str:
return "Hello, World!"
app.include_router(router)
client = TestClient(app)
response = client.get("/hello/", follow_redirects=False)
assert response.status_code == 200
response = | _slashes=False)
router = APIRouter()
@route | {
"filepath": "tests/test_router_redirect_slashes.py",
"language": "python",
"file_size": 974,
"cut_index": 582,
"middle_length": 52
} |
ts.utils import skip_module_if_py_gte_314
if sys.version_info >= (3, 14):
skip_module_if_py_gte_314()
from fastapi import FastAPI
from fastapi.exceptions import PydanticV1NotSupportedError
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
from pydantic.v1 import BaseModel
def... | app = FastAPI()
with pytest.raises(PydanticV1NotSupportedError):
@app.get("/return")
def endpoint() -> ReturnModelV1: # pragma: no cover
return ReturnModelV1(name="test")
def test_raises_pydantic_v1_model_in_response | @app.post("/param")
def endpoint(data: ParamModelV1): # pragma: no cover
return data
def test_raises_pydantic_v1_model_in_return_type() -> None:
class ReturnModelV1(BaseModel):
name: str
| {
"filepath": "tests/test_pydantic_v1_error.py",
"language": "python",
"file_size": 2347,
"cut_index": 563,
"middle_length": 229
} |
lias=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... | ="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- | lias": "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 | {
"filepath": "tests/test_response_by_alias.py",
"language": "python",
"file_size": 11945,
"cut_index": 921,
"middle_length": 229
} |
turn_dict_with_extra_data():
return {"name": "John", "surname": "Doe", "password_hash": "secret"}
@app.get(
"/response_model-no_annotation-return_submodel_with_extra_data", response_model=User
)
def response_model_no_annotation_return_submodel_with_extra_data():
return DBUser(name="John", surname="Doe", p... | t")
def no_response_model_annotation_return_invalid_dict() -> User:
return {"name": "John"}
@app.get("/no_response_model-annotation-return_invalid_model")
def no_response_model_annotation_return_invalid_model() -> User:
return Item(name="Foo", pr |
@app.get("/no_response_model-annotation-return_exact_dict")
def no_response_model_annotation_return_exact_dict() -> User:
return {"name": "John", "surname": "Doe"}
@app.get("/no_response_model-annotation-return_invalid_dic | {
"filepath": "tests/test_response_model_as_return_annotation.py",
"language": "python",
"file_size": 51514,
"cut_index": 2151,
"middle_length": 229
} |
class Model1(BaseModel):
foo: str
bar: str
class Model2(BaseModel):
ref: Model1
baz: str
class Model3(BaseModel):
name: str
age: int
ref2: Model2
app = FastAPI()
@app.get(
"/simple_include",
response_model=Model2,
response_model_include={"baz": ..., "ref": {"foo"}},
)
de... | ": "simple_include_dict model bar",
},
"baz": "simple_include_dict model2 baz",
}
@app.get(
"/simple_exclude",
response_model=Model2,
response_model_exclude={"ref": {"bar"}},
)
def simple_exclude():
return Model2(
| le_include_dict",
response_model=Model2,
response_model_include={"baz": ..., "ref": {"foo"}},
)
def simple_include_dict():
return {
"ref": {
"foo": "simple_include_dict model foo",
"bar | {
"filepath": "tests/test_response_model_include_exclude.py",
"language": "python",
"file_size": 4118,
"cut_index": 614,
"middle_length": 229
} |
lse
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("/")
... | own")
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("shutdo | own")
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("shutd | {
"filepath": "tests/test_router_events.py",
"language": "python",
"file_size": 12005,
"cut_index": 921,
"middle_length": 229
} |
from typing import Annotated
import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.testclient import TestClient
@pytest.fixture(name="call_counter")
def call_counter_fixture():
return {"count": 0}
@pytest.fixture(name="app")
def app_fixture(call_counter: dict[str, int]):
def get_db():
... | ixture(app: FastAPI):
return TestClient(app)
def test_security_scopes_dependency_called_once(
client: TestClient, call_counter: dict[str, int]
):
response = client.get("/")
assert response.status_code == 200
assert call_counter["coun | "/")
def endpoint(
db: Annotated[str, Depends(get_db)],
user: Annotated[str, Security(get_user, scopes=["read"])],
):
return {"db": db}
return app
@pytest.fixture(name="client")
def client_f | {
"filepath": "tests/test_security_scopes.py",
"language": "python",
"file_size": 1006,
"cut_index": 512,
"middle_length": 229
} |
astapi.openapi.docs import get_swagger_ui_html
def test_init_oauth_html_chars_are_escaped():
xss_payload = "Evil</script><script>alert(1)</script>"
html = get_swagger_ui_html(
openapi_url="/openapi.json",
title="Test",
init_oauth={"appName": xss_payload},
)
body = html.body.dec... | in body
assert "\\u003cimg" in body
def test_normal_init_oauth_still_works():
html = get_swagger_ui_html(
openapi_url="/openapi.json",
title="Test",
init_oauth={"clientId": "my-client", "appName": "My App"},
)
bod | er_ui_html(
openapi_url="/openapi.json",
title="Test",
swagger_ui_parameters={"customKey": "<img src=x onerror=alert(1)>"},
)
body = html.body.decode()
assert "<img src=x onerror=alert(1)>" not | {
"filepath": "tests/test_swagger_ui_escape.py",
"language": "python",
"file_size": 1146,
"cut_index": 518,
"middle_length": 229
} |
security.http import HTTPAuthorizationCredentials, HTTPBase
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBase(scheme="Other", auto_error=False)
@app.get("/users/me")
def read_current_user(
credentials: HTTPAuthorizationCredentials | None = Securit... | "credentials": "foobar"}
def test_security_http_base_no_credentials():
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_openapi_schem | lient(app)
def test_security_http_base():
response = client.get("/users/me", headers={"Authorization": "Other foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", | {
"filepath": "tests/test_security_http_base_optional.py",
"language": "python",
"file_size": 2045,
"cut_index": 563,
"middle_length": 229
} |
i 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_i... | se.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_m | 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, respon | {
"filepath": "tests/test_route_scope.py",
"language": "python",
"file_size": 1530,
"cut_index": 537,
"middle_length": 229
} |
import Body, FastAPI, Query
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/query")
def read_query(q: str | None):
return q
@app.get("/explicit-query")
def read_explicit_query(q: str | None = Query()):
return q
@app.post("/body-embed")
def send_body_embed(b: str | None = Body(embed=... | et("/explicit-query")
assert response.status_code == 422
def test_required_nonable_explicit_query_value():
response = client.get("/explicit-query", params={"q": "foo"})
assert response.status_code == 200
assert response.json() == "foo"
| able_query_value():
response = client.get("/query", params={"q": "foo"})
assert response.status_code == 200
assert response.json() == "foo"
def test_required_nonable_explicit_query_invalid():
response = client.g | {
"filepath": "tests/test_required_noneable.py",
"language": "python",
"file_size": 1486,
"cut_index": 524,
"middle_length": 229
} |
fastapi.security import APIKeyCookie
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyCookie(name="key")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str = Security(api_key)):
user = Us... | _no_key():
client = TestClient(app)
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "APIKey"
| client = TestClient(app, cookies={"key": "secret"})
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key | {
"filepath": "tests/test_security_api_key_cookie.py",
"language": "python",
"file_size": 2157,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyCookie
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyCookie(name="key", auto_error=False)
class User(BaseModel):
username: str
def get_current_user(oauth_header: str | None = Security... | sponse = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
client = TestClient(app)
response = client.get("/users/me")
assert | et_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
else:
return current_user
def test_security_api_key():
client = TestClient(app, cookies={"key": "secret"})
re | {
"filepath": "tests/test_security_api_key_cookie_optional.py",
"language": "python",
"file_size": 2267,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyHeader
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
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 = ... | t"}
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" | r
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": "secre | {
"filepath": "tests/test_security_api_key_header_description.py",
"language": "python",
"file_size": 2285,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyQuery
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyQuery(name="key")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str = Security(api_key)):
user = User... | nse = 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 | test_security_api_key():
response = client.get("/users/me?key=secret")
assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
respo | {
"filepath": "tests/test_security_api_key_query.py",
"language": "python",
"file_size": 2076,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyQuery
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyQuery(name="key", auto_error=False)
class User(BaseModel):
username: str
def get_current_user(oauth_header: str | None = Security(a... | ret")
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 r | nds(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?key=sec | {
"filepath": "tests/test_security_api_key_query_optional.py",
"language": "python",
"file_size": 2179,
"cut_index": 563,
"middle_length": 229
} |
security.http import HTTPAuthorizationCredentials, HTTPBase
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBase(scheme="Other")
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return {"sch... | me", headers={"Authorization": "Other foobar "})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", "credentials": "foobar"}
def test_security_http_base_no_credentials():
response = client.get("/u | Other foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", "credentials": "foobar"}
def test_security_http_base_with_whitespaces():
response = client.get("/users/ | {
"filepath": "tests/test_security_http_base.py",
"language": "python",
"file_size": 2254,
"cut_index": 563,
"middle_length": 229
} |
PI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
email: str
password: str
class UserDB(BaseModel):
email: str
hashed_password: str
class User(BaseModel):
email: str
class PetDB(BaseModel):
name: str
owner: UserD... | ts/", 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)
r | ponse_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("/pe | {
"filepath": "tests/test_response_model_data_filter_no_inheritance.py",
"language": "python",
"file_size": 1721,
"cut_index": 537,
"middle_length": 229
} |
ample(firstname: str = Form(example="John")):
# return firstname
# @app.post("/form_examples")
# def form_examples(
# lastname: str = Form(
# ...,
# examples={
# "example1": {"summary": "last name summary", "value": "Doe"},
# "example2": {... | },
# ),
# ):
# return lastname
with pytest.warns(FastAPIDeprecationWarning):
@app.get("/path_example/{item_id}")
def path_example(
item_id: str = Path(
example="item_1",
) | (
# ...,
# example="Doe overridden",
# examples={
# "example1": {"summary": "last name summary", "value": "Doe"},
# "example2": {"value": "Doesn't"},
# | {
"filepath": "tests/test_schema_extra_examples.py",
"language": "python",
"file_size": 35532,
"cut_index": 2151,
"middle_length": 229
} |
fastapi.security import APIKeyCookie
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyCookie(name="key", description="An API Cookie Key")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str = ... | ret"}
def test_security_api_key_no_key():
client = TestClient(app)
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers[ | r
def test_security_api_key():
client = TestClient(app, cookies={"key": "secret"})
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"username": "sec | {
"filepath": "tests/test_security_api_key_cookie_description.py",
"language": "python",
"file_size": 2345,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyHeader
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
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: str | None = Security... | ders={"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 | pends(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", hea | {
"filepath": "tests/test_security_api_key_header_optional.py",
"language": "python",
"file_size": 2200,
"cut_index": 563,
"middle_length": 229
} |
jection system properly handles them.
"""
from typing import Annotated
from fastapi import BackgroundTasks, Depends, FastAPI, Request, Response
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
def test_response_with_depends_annotated():
"""Response type hint should work with ... | esp.json() == {"status": "ok"}
assert resp.headers.get("X-Custom") == "modified"
def test_response_with_depends_default():
"""Response type hint should work with Response = Depends(...)."""
app = FastAPI()
def modify_response(response: R | @app.get("/")
def endpoint(response: Annotated[Response, Depends(modify_response)]):
return {"status": "ok"}
client = TestClient(app)
resp = client.get("/")
assert resp.status_code == 200
assert r | {
"filepath": "tests/test_response_dependency.py",
"language": "python",
"file_size": 5306,
"cut_index": 716,
"middle_length": 229
} |
et("/valid1", responses={"500": {"model": int}})
def valid1():
pass
@app.get("/valid2", responses={"500": {"model": list[int]}})
def valid2():
pass
@app.get("/valid3", responses={"500": {"model": Model}})
def valid3():
pass
@app.get("/valid4", responses={"500": {"model": list[Model]}})
def valid4():
... | se.text
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", |
assert response.status_code == 200, response.text
response = client.get("/valid3")
assert response.status_code == 200, response.text
response = client.get("/valid4")
assert response.status_code == 200, respon | {
"filepath": "tests/test_response_model_sub_types.py",
"language": "python",
"file_size": 5933,
"cut_index": 716,
"middle_length": 229
} |
import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, ConfigDict, Field
@pytest.fixture(name="client")
def get_client():
app = FastAPI()
class ModelWithRef(BaseModel):
ref: str = Field(validation_alias="$ref", serialization_alias... | :
response = client.get("openapi.json")
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"g | ref": "some-ref"}
client = TestClient(app)
return client
def test_get(client: TestClient):
response = client.get("/")
assert response.json() == {"$ref": "some-ref"}
def test_openapi_schema(client: TestClient) | {
"filepath": "tests/test_schema_ref_pydantic_v2.py",
"language": "python",
"file_size": 2164,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyQuery
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyQuery(name="key", description="API Key Query")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str = Securi... | y_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_sc | ient = TestClient(app)
def test_security_api_key():
response = client.get("/users/me?key=secret")
assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_securit | {
"filepath": "tests/test_security_api_key_query_description.py",
"language": "python",
"file_size": 2256,
"cut_index": 563,
"middle_length": 229
} |
security.http import HTTPAuthorizationCredentials, HTTPBase
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBase(scheme="Other", description="Other Security Scheme")
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = ... |
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Other"
def test_openapi_schema():
response | sers/me", headers={"Authorization": "Other foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", "credentials": "foobar"}
def test_security_http_base_no_credentials(): | {
"filepath": "tests/test_security_http_base_description.py",
"language": "python",
"file_size": 2201,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security import APIKeyHeader
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyHeader(name="key")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str = Security(api_key)):
user = Us... | o_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():
| f 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_n | {
"filepath": "tests/test_security_api_key_header.py",
"language": "python",
"file_size": 2097,
"cut_index": 563,
"middle_length": 229
} |
rt pytest
from ...utils import needs_py310
@pytest.fixture(
name="test_module",
params=[
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_test_module(request: pytest.FixtureRequest) -> ModuleType:
mod: ModuleTy... | _in_items_with_q()
def test_override_in_items_with_params_run(test_module: ModuleType):
test_override_in_items_with_params = test_module.test_override_in_items_with_params
test_override_in_items_with_params()
def test_override_in_users(test_mo | = test_module.test_override_in_items
test_override_in_items()
def test_override_in_items_with_q_run(test_module: ModuleType):
test_override_in_items_with_q = test_module.test_override_in_items_with_q
test_override | {
"filepath": "tests/test_tutorial/test_testing_dependencies/test_tutorial001.py",
"language": "python",
"file_size": 2372,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.