prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
astAPI, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBasic(auto_error=False)
@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials | None = Security(security... | est_security_http_basic_no_credentials():
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_security_http_basic_invalid_credentials():
| ef test_security_http_basic():
response = client.get("/users/me", auth=("john", "secret"))
assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
def t | {
"filepath": "tests/test_security_http_basic_optional.py",
"language": "python",
"file_size": 2751,
"cut_index": 563,
"middle_length": 229
} |
astAPI, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBasic(realm="simple")
@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
r... | sert response.json() == {"detail": "Not authenticated"}
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
def test_security_http_basic_invalid_credentials():
response = cli | cret"))
assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
def test_security_http_basic_no_credentials():
response = client.get("/users/me")
as | {
"filepath": "tests/test_security_http_basic_realm.py",
"language": "python",
"file_size": 2765,
"cut_index": 563,
"middle_length": 229
} |
security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBearer()
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return {"scheme": credentia... | sert 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. | "})
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")
as | {
"filepath": "tests/test_security_http_bearer.py",
"language": "python",
"file_size": 2313,
"cut_index": 563,
"middle_length": 229
} |
security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBearer(auto_error=False)
@app.get("/users/me")
def read_current_user(
credentials: HTTPAuthorizationCredentials | None = Security(security),
):
... | ": "foobar"}
def test_security_http_bearer_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_bearer_inc | 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 | {
"filepath": "tests/test_security_http_bearer_optional.py",
"language": "python",
"file_size": 2307,
"cut_index": 563,
"middle_length": 229
} |
security import HTTPAuthorizationCredentials, HTTPDigest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPDigest(description="HTTPDigest scheme")
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
... | client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Digest"
def test_security_http_digest_incorrect_scheme_creden | "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 = | {
"filepath": "tests/test_security_http_digest_description.py",
"language": "python",
"file_size": 2538,
"cut_index": 563,
"middle_length": 229
} |
ite:users": "Create users"},
}
}
)
class User(BaseModel):
username: str
# Here we use string annotations to test them
def get_current_user(oauth_header: "str" = Security(reusable_oauth2)):
user = User(username=oauth_header)
return user
@app.post("/login")
# Here we use string annotations t... | ert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
a | r(current_user: "User" = Depends(get_current_user)):
return current_user
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
ass | {
"filepath": "tests/test_security_oauth2.py",
"language": "python",
"file_size": 10042,
"cut_index": 921,
"middle_length": 229
} |
security import OAuth2AuthorizationCodeBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="authorize",
tokenUrl="token",
description="OAuth2 Code Bearer",
auto_error=True,
)
@app.get("/... | "})
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 = | 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 | {
"filepath": "tests/test_security_oauth2_authorization_code_bearer_description.py",
"language": "python",
"file_size": 2603,
"cut_index": 563,
"middle_length": 229
} |
454
from typing import Annotated
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="api/oauth/authorize",
toke... | _admin():
response = client.get("/admin", headers={"Authorization": "Bearer faketoken"})
assert response.status_code == 200, response.text
assert response.json() == {"message": "Admin Access"}
def test_openapi_schema():
response = client. | stAPI(dependencies=[Depends(get_token)])
@app.get("/admin", dependencies=[Security(get_token, scopes=["read", "write"])])
async def read_admin():
return {"message": "Admin Access"}
client = TestClient(app)
def test_read | {
"filepath": "tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py",
"language": "python",
"file_size": 2658,
"cut_index": 563,
"middle_length": 229
} |
ite:users": "Create users"},
}
},
description="OAuth2 security scheme",
auto_error=False,
)
class User(BaseModel):
username: str
def get_current_user(oauth_header: str | None = Security(reusable_oauth2)):
if oauth_header is None:
return None
user = User(username=oauth_header)... | ", headers={"Authorization": "Bearer footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users | ne = Depends(get_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me | {
"filepath": "tests/test_security_oauth2_optional_description.py",
"language": "python",
"file_size": 10132,
"cut_index": 921,
"middle_length": 229
} |
security import OAuth2PasswordBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="/token",
description="OAuth2PasswordBearer security scheme",
auto_error=False,
)
@app.get("/items/")
async def read_items(to... | ization": "Bearer testtoken"})
assert response.status_code == 200, response.text
assert response.json() == {"token": "testtoken"}
def test_incorrect_token():
response = client.get("/items", headers={"Authorization": "Notexistent testtoken"})
| :
response = client.get("/items")
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_token():
response = client.get("/items", headers={"Author | {
"filepath": "tests/test_security_oauth2_password_bearer_optional_description.py",
"language": "python",
"file_size": 2426,
"cut_index": 563,
"middle_length": 229
} |
fastapi.security.open_id_connect_url import OpenIdConnect
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
oid = OpenIdConnect(
openIdConnectUrl="/openid", description="OpenIdConnect security scheme"
)
class User(BaseModel):
usern... | 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
assert response.status_code | pends(get_current_user)):
return current_user
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
assert response.status_code == | {
"filepath": "tests/test_security_openid_connect_description.py",
"language": "python",
"file_size": 2638,
"cut_index": 563,
"middle_length": 229
} |
astAPI, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBasic(realm="simple", description="HTTPBasic scheme")
@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredenti... | = client.get("/users/me")
assert response.json() == {"detail": "Not authenticated"}
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
def test_security_http_basic_invalid_c | t("/users/me", auth=("john", "secret"))
assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
def test_security_http_basic_no_credentials():
response | {
"filepath": "tests/test_security_http_basic_realm_description.py",
"language": "python",
"file_size": 2965,
"cut_index": 563,
"middle_length": 229
} |
security import HTTPAuthorizationCredentials, HTTPDigest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPDigest()
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return {"scheme": credentia... | sert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Digest"
def test_security_http_digest_incorrect_scheme_credentials():
response = client. | "})
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")
as | {
"filepath": "tests/test_security_http_digest.py",
"language": "python",
"file_size": 2338,
"cut_index": 563,
"middle_length": 229
} |
security import OAuth2AuthorizationCodeBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="authorize", tokenUrl="token", auto_error=True
)
@app.get("/items/")
async def read_items(token: str | None... | ponse.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() | 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, res | {
"filepath": "tests/test_security_oauth2_authorization_code_bearer.py",
"language": "python",
"file_size": 2724,
"cut_index": 563,
"middle_length": 229
} |
ite:users": "Create users"},
}
},
auto_error=False,
)
class User(BaseModel):
username: str
def get_current_user(oauth_header: str | None = Security(reusable_oauth2)):
if oauth_header is None:
return None
user = User(username=oauth_header)
return user
@app.post("/login")
def... | kenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other foo | rrent_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footo | {
"filepath": "tests/test_security_oauth2_optional.py",
"language": "python",
"file_size": 9988,
"cut_index": 921,
"middle_length": 229
} |
fastapi.security.open_id_connect_url import OpenIdConnect
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
oid = OpenIdConnect(openIdConnectUrl="/openid")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str =... | "username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == |
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == { | {
"filepath": "tests/test_security_openid_connect.py",
"language": "python",
"file_size": 2515,
"cut_index": 563,
"middle_length": 229
} |
security import HTTPAuthorizationCredentials, HTTPDigest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPDigest(auto_error=False)
@app.get("/users/me")
def read_current_user(
credentials: HTTPAuthorizationCredentials | None = Security(security),
):
... | ": "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_inc | 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 | {
"filepath": "tests/test_security_http_digest_optional.py",
"language": "python",
"file_size": 2332,
"cut_index": 563,
"middle_length": 229
} |
security import OAuth2PasswordBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token", auto_error=False)
@app.get("/items/")
async def read_items(token: str | None = Security(oauth2_scheme)):
if token is None:
... | 00, response.text
assert response.json() == {"token": "testtoken"}
def test_incorrect_token():
response = client.get("/items", headers={"Authorization": "Notexistent testtoken"})
assert response.status_code == 200, response.text
assert re | de == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_token():
response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
assert response.status_code == 2 | {
"filepath": "tests/test_security_oauth2_password_bearer_optional.py",
"language": "python",
"file_size": 2280,
"cut_index": 563,
"middle_length": 229
} |
security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI()
security = HTTPBearer(description="HTTP Bearer token scheme")
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(secur... | ponse = 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 | aders={"Authorization": "Bearer foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Bearer", "credentials": "foobar"}
def test_security_http_bearer_no_credentials():
res | {
"filepath": "tests/test_security_http_bearer_description.py",
"language": "python",
"file_size": 2527,
"cut_index": 563,
"middle_length": 229
} |
ns/6024#discussioncomment-8541913
from typing import Annotated
import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
@pytest.fixture(name="call_counts")
def call_counts_fixture():
return {
"get_db_session": 0,
... | on)],
):
call_counts["get_current_user"] += 1
return {
"user": f"user_{call_counts['get_current_user']}",
"scopes": security_scopes.scopes,
"db_session": db_session,
}
def get_user_me(
| :
call_counts["get_db_session"] += 1
return f"db_session_{call_counts['get_db_session']}"
def get_current_user(
security_scopes: SecurityScopes,
db_session: Annotated[str, Depends(get_db_sessi | {
"filepath": "tests/test_security_scopes_sub_dependency.py",
"language": "python",
"file_size": 2956,
"cut_index": 563,
"middle_length": 229
} |
api.testclient import TestClient
app = FastAPI()
@dataclass
class Item:
name: str
date: datetime
price: float | None = None
owner_ids: list[int] | None = None
@app.get("/items/valid", response_model=Item)
def get_valid():
return {"name": "valid", "date": datetime(2021, 7, 26), "price": 1.0}
@... | {"name": "foo", "date": datetime(2021, 7, 26)},
{"name": "bar", "date": datetime(2021, 7, 26), "price": 1.0},
{
"name": "baz",
"date": datetime(2021, 7, 26),
"price": 2.0,
"owner_ids": [1, | ce", response_model=Item)
def get_coerce():
return {"name": "coerce", "date": datetime(2021, 7, 26).isoformat(), "price": "1.0"}
@app.get("/items/validlist", response_model=list[Item])
def get_validlist():
return [
| {
"filepath": "tests/test_serialize_response_dataclass.py",
"language": "python",
"file_size": 4958,
"cut_index": 614,
"middle_length": 229
} |
import TestClient
from pydantic import BaseModel
app = FastAPI()
class SubModel(BaseModel):
a: str | None = "foo"
class Model(BaseModel):
x: int | None = None
sub: SubModel
class ModelSubclass(Model):
y: int
z: int = 0
w: int | None = None
class ModelDefaults(BaseModel):
w: str | N... | clude_defaults",
response_model=ModelDefaults,
response_model_exclude_defaults=True,
)
def get_exclude_defaults() -> ModelDefaults:
return ModelDefaults(x=None, y="y")
@app.get(
"/exclude_none", response_model=ModelDefaults, response_mode | Subclass(sub={}, y=1, z=0)
@app.get(
"/exclude_unset", response_model=ModelDefaults, response_model_exclude_unset=True
)
def get_exclude_unset() -> ModelDefaults:
return ModelDefaults(x=None, y="y")
@app.get(
"/ex | {
"filepath": "tests/test_skip_defaults.py",
"language": "python",
"file_size": 2027,
"cut_index": 563,
"middle_length": 229
} |
stAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(
status_code=404,
detail="Item not found",
headers={"X-Error": "Some custom header"},
)
return {"item":... | str):
if item_id not in items:
raise StarletteHTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
client = TestClient(app)
def test_get_item():
response = client.get("/items/foo")
assert resp | detail-exception")
async def no_body_status_code_with_detail_exception():
raise HTTPException(status_code=204, detail="I should just disappear!")
@app.get("/starlette-items/{item_id}")
async def read_starlette_item(item_id: | {
"filepath": "tests/test_starlette_exception.py",
"language": "python",
"file_size": 8293,
"cut_index": 716,
"middle_length": 229
} |
ort json
from typing import AsyncIterable, Iterable # noqa: UP035 to test coverage
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Item(BaseModel):
name: str
app = FastAPI()
@app.get("/items/stream-bare-async")
async def stream_bare_async() -> Async... | trip().splitlines()]
assert lines == [{"name": "foo"}]
def test_stream_bare_sync_iterable():
response = client.get("/items/stream-bare-sync")
assert response.status_code == 200
assert response.headers["content-type"] == "application/jsonl | iterable():
response = client.get("/items/stream-bare-async")
assert response.status_code == 200
assert response.headers["content-type"] == "application/jsonl"
lines = [json.loads(line) for line in response.text.s | {
"filepath": "tests/test_stream_bare_type.py",
"language": "python",
"file_size": 1118,
"cut_index": 515,
"middle_length": 229
} |
m fastapi import FastAPI
from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
app = FastAPI()
@app.get("/items/stream-invalid")
async def stream_items_invalid() -> AsyncIterable[Item]:
... | ame": "invalid", "price": "not-a-number"}
client = TestClient(app)
def test_stream_json_validation_error_async():
with pytest.raises(ResponseValidationError):
client.get("/items/stream-invalid")
def test_stream_json_validation_error_sync( | yield {"name": "valid", "price": 1.0}
yield {"n | {
"filepath": "tests/test_stream_json_validation_error.py",
"language": "python",
"file_size": 991,
"cut_index": 582,
"middle_length": 52
} |
.testclient import TestClient
# Lax app with nested routers, inner overrides to strict
app_nested = FastAPI(strict_content_type=False) # lax app
outer_router = APIRouter(prefix="/outer") # inherits lax from app
inner_strict = APIRouter(prefix="/strict", strict_content_type=True)
inner_default = APIRouter(prefix="/d... | response = client_nested.post("/outer/strict/items/", content='{"key": "value"}')
assert response.status_code == 422
def test_default_inner_inherits_lax_from_app():
response = client_nested.post("/outer/default/items/", content='{"key": "value"} | uter_router.include_router(inner_strict)
outer_router.include_router(inner_default)
app_nested.include_router(outer_router)
client_nested = TestClient(app_nested)
def test_strict_inner_on_lax_app_rejects_no_content_type():
| {
"filepath": "tests/test_strict_content_type_nested.py",
"language": "python",
"file_size": 2776,
"cut_index": 563,
"middle_length": 229
} |
ort 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:
retur... | 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", "Ja | 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:
| {
"filepath": "tests/test_stringified_annotation_dependency.py",
"language": "python",
"file_size": 2270,
"cut_index": 563,
"middle_length": 229
} |
rom fastapi.testclient import TestClient
from inline_snapshot import snapshot
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="authorize",
tokenUrl="token",
auto_error=True,
scopes={"read": "Read access", "write": "Write access"},
)
async def get_token(token: Annotated[str, Depends(oa... | opes=["read", "write"])]
)
async def read_with_get_token():
return {"message": "Admin Access"}
router = APIRouter(dependencies=[Security(oauth2_scheme, scopes=["read"])])
@router.get("/items/")
async def read_items(token: str | None = Depends(oauth | -scheme",
dependencies=[Security(oauth2_scheme, scopes=["read", "write"])],
)
async def read_with_oauth2_scheme():
return {"message": "Admin Access"}
@app.get(
"/with-get-token", dependencies=[Security(get_token, sc | {
"filepath": "tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py",
"language": "python",
"file_size": 6759,
"cut_index": 716,
"middle_length": 229
} |
fastapi.security.open_id_connect_url import OpenIdConnect
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
app = FastAPI()
oid = OpenIdConnect(openIdConnectUrl="/openid", auto_error=False)
class User(BaseModel):
username: str
def get_current_user(o... | = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
respon | current_user: User | None = Depends(get_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
def test_security_oauth2():
response | {
"filepath": "tests/test_security_openid_connect_optional.py",
"language": "python",
"file_size": 2618,
"cut_index": 563,
"middle_length": 229
} |
tClient
app = FastAPI()
class Item(BaseModel):
name: str = Field(alias="aliased_name")
price: float | None = None
owner_ids: list[int] | None = None
@app.get("/items/valid", response_model=Item)
def get_valid():
return Item(aliased_name="valid", price=1.0)
@app.get("/items/coerce", response_model... | "k1": Item(aliased_name="foo"),
"k2": Item(aliased_name="bar", price=1.0),
"k3": Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]),
}
@app.get(
"/items/valid-exclude-unset", response_model=Item, response_model_exclude_u | me="foo"),
Item(aliased_name="bar", price=1.0),
Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]),
]
@app.get("/items/validdict", response_model=dict[str, Item])
def get_validdict():
return {
| {
"filepath": "tests/test_serialize_response_model.py",
"language": "python",
"file_size": 4229,
"cut_index": 614,
"middle_length": 229
} |
PI, Path, Query
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/int/{param:int}")
def int_convertor(param: int = Path()):
return {"int": param}
@app.get("/float/{param:float}")
def float_convertor(param: float = Path()):
return {"float": param}
@app.get("/path/{param:path}")
def path... | param=5) == "/int/5" # type: ignore
def test_route_converters_float():
# Test float conversion
response = client.get("/float/25.5")
assert response.status_code == 200, response.text
assert response.json() == {"float": 25.5}
assert ap | oute_converters_int():
# Test integer conversion
response = client.get("/int/5")
assert response.status_code == 200, response.text
assert response.json() == {"int": 5}
assert app.url_path_for("int_convertor", | {
"filepath": "tests/test_starlette_urlconvertors.py",
"language": "python",
"file_size": 1710,
"cut_index": 537,
"middle_length": 229
} |
elled without hanging.
Ref: https://github.com/fastapi/fastapi/issues/14680
"""
from collections.abc import AsyncIterable
import anyio
import pytest
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
pytestmark = [
pytest.mark.anyio,
pytest.mark.filterwarnings("ignore::pytest.Pytest... | nternal await."""
i = 0
while True:
yield i
i += 1
async def _run_asgi_and_cancel(app: FastAPI, path: str, timeout: float) -> bool:
"""Call the ASGI app for *path* and cancel after *timeout* seconds.
Returns `True` if the | nal await - would hang without checkpoint."""
i = 0
while True:
yield f"item {i}\n"
i += 1
@app.get("/stream-jsonl")
async def stream_jsonl() -> AsyncIterable[int]:
"""JSONL async generator with no i | {
"filepath": "tests/test_stream_cancellation.py",
"language": "python",
"file_size": 2771,
"cut_index": 563,
"middle_length": 229
} |
ces_callback_router = APIRouter()
@invoices_callback_router.post(
"{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived
)
def invoice_notification(body: InvoiceEvent):
pass # pragma: nocover
class Event(BaseModel):
name: str
total: float
events_callback_router = APIRo... | loper) create an
invoice.
And this path operation will:
* Send the invoice to the client.
* Collect the money from the client.
* Send a notification back to the API user (the external developer), as a callback.
* At this point | /invoices/", callbacks=invoices_callback_router.routes)
def create_invoice(invoice: Invoice, callback_url: HttpUrl | None = None):
"""
Create an invoice.
This will (let's imagine) let the API user (some external deve | {
"filepath": "tests/test_sub_callbacks.py",
"language": "python",
"file_size": 14598,
"cut_index": 921,
"middle_length": 229
} |
s_src.path_params.tutorial001_py310 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}")... | item_id}": {
"get": {
"operationId": "read_item_items__item_id__get",
"parameters": [
{
"in": "path",
| se.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{ | {
"filepath": "tests/test_tutorial/test_path_params/test_tutorial001.py",
"language": "python",
"file_size": 4584,
"cut_index": 614,
"middle_length": 229
} |
Item(name="Plumbus", description="A multi-purpose household device."),
Item(name="Portal Gun", description="A portal opening device."),
Item(name="Meeseeks Box", description="A box that summons a Meeseeks."),
]
app = FastAPI()
@app.get("/items/stream", response_class=EventSourceResponse)
async def sse_items... | ntSourceResponse)
def sse_items_sync_no_annotation():
yield from items
@app.get("/items/stream-dict", response_class=EventSourceResponse)
async def sse_items_dict():
for item in items:
yield {"name": item.name, "description": item.descrip | items
@app.get("/items/stream-no-annotation", response_class=EventSourceResponse)
async def sse_items_no_annotation():
for item in items:
yield item
@app.get("/items/stream-sync-no-annotation", response_class=Eve | {
"filepath": "tests/test_sse.py",
"language": "python",
"file_size": 10386,
"cut_index": 921,
"middle_length": 229
} |
uter, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
router_lax = APIRouter(prefix="/lax", strict_content_type=False)
router_strict = APIRouter(prefix="/strict", strict_content_type=True)
router_default = APIRouter(prefix="/default")
@router_lax.post("/items/")
async def router_lax_post(data: dic... | ("/lax/items/", content='{"key": "value"}')
assert response.status_code == 200
assert response.json() == {"key": "value"}
def test_strict_router_on_strict_app_rejects_no_content_type():
response = client.post("/strict/items/", content='{"key" | return data
app.include_router(router_lax)
app.include_router(router_strict)
app.include_router(router_default)
client = TestClient(app)
def test_lax_router_on_strict_app_accepts_no_content_type():
response = client.post | {
"filepath": "tests/test_strict_content_type_router_level.py",
"language": "python",
"file_size": 1720,
"cut_index": 537,
"middle_length": 229
} |
import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float | None = None
owner_ids: list[int] | None = None
@app.get("/items/valid", response_model=Item)
def get_valid():
return {"name": "valid", "price": 1.... | /valid")
response.raise_for_status()
assert response.json() == {"name": "valid", "price": 1.0, "owner_ids": None}
def test_coerce():
response = client.get("/items/coerce")
response.raise_for_status()
assert response.json() == {"name": | ):
return [
{"name": "foo"},
{"name": "bar", "price": 1.0},
{"name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]},
]
client = TestClient(app)
def test_valid():
response = client.get("/items | {
"filepath": "tests/test_serialize_response.py",
"language": "python",
"file_size": 1373,
"cut_index": 524,
"middle_length": 229
} |
-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"]]}
respons... | sponse = 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)
| ems": [["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"]]}
re | {
"filepath": "tests/test_tuples.py",
"language": "python",
"file_size": 11030,
"cut_index": 921,
"middle_length": 229
} |
shot
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str | None = None
class OtherItem(BaseModel):
price: int
@app.post("/items/")
def save_union_body(item: OtherItem | Item):
return {"item": item}
client = TestClient(app)
def test_post_other_item():
response = cli... | ssert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
| ent.post("/items/", json={"name": "Foo"})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"name": "Foo"}}
def test_openapi_schema():
response = client.get("/openapi.json")
a | {
"filepath": "tests/test_union_body.py",
"language": "python",
"file_size": 5022,
"cut_index": 614,
"middle_length": 229
} |
orm(BaseModel):
name: str
email: str
class CompanyForm(BaseModel):
company_name: str
industry: str
@app.post("/form-union/")
def post_union_form(data: Annotated[UserForm | CompanyForm, Form()]):
return {"received": data}
client = TestClient(app)
def test_post_user_form():
response = clie... | ponse.status_code == 200, response.text
assert response.json() == {
"received": {"company_name": "Tech Corp", "industry": "Technology"}
}
def test_invalid_form_data():
response = client.post(
"/form-union/",
data={"nam | eived": {"name": "John Doe", "email": "john@example.com"}
}
def test_post_company_form():
response = client.post(
"/form-union/", data={"company_name": "Tech Corp", "industry": "Technology"}
)
assert res | {
"filepath": "tests/test_union_forms.py",
"language": "python",
"file_size": 5993,
"cut_index": 716,
"middle_length": 229
} |
i import FastAPI
from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float | None = None
owner_ids: list[int] | None = None
@app.get("/items/invalid", response_model=Item)... | get_innerinvalid():
return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
@app.get("/items/invalidlist", response_model=list[Item])
def get_invalidlist():
return [
{"name": "foo"},
{"name": "bar", "price": | response_model=Item | None)
def get_valid_none(send_none: bool = False):
if send_none:
return None
else:
return {"name": "invalid", "price": 3.2}
@app.get("/items/innerinvalid", response_model=Item)
def | {
"filepath": "tests/test_validate_response.py",
"language": "python",
"file_size": 1977,
"cut_index": 537,
"middle_length": 229
} |
Error,
ResponseValidationError,
WebSocketRequestValidationError,
)
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
class ExceptionCapture:
def __init__(self):
self.exception = None
def capture(self, exc):
self... | lidationError)
@sub_app.exception_handler(ResponseValidationError)
async def response_validation_handler(_: Request, exc: ResponseValidationError):
captured_exception.capture(exc)
raise exc
@app.exception_handler(WebSocketRequestValidationError)
| nError)
@sub_app.exception_handler(RequestValidationError)
async def request_validation_handler(request: Request, exc: RequestValidationError):
captured_exception.capture(exc)
raise exc
@app.exception_handler(ResponseVa | {
"filepath": "tests/test_validation_error_context.py",
"language": "python",
"file_size": 4809,
"cut_index": 614,
"middle_length": 229
} |
import functools
from fastapi import FastAPI
from fastapi.testclient import TestClient
from .forward_reference_type import forwardref_method
def passthrough(f):
@functools.wraps(f)
def method(*args, **kwargs):
return f(*args, **kwargs)
return method
def test_wrapped_method_type_inference():
... | ough(passthrough(forwardref_method)))
with client:
response = client.post("/endpoint", json={"input": {"x": 0}})
response2 = client.post("/endpoint2", json={"input": {"x": 0}})
assert response.json() == response2.json() == {"x": 1}
| e still processed correctly, including dereferencing of forward
references.
"""
app = FastAPI()
client = TestClient(app)
app.post("/endpoint")(passthrough(forwardref_method))
app.post("/endpoint2")(passthr | {
"filepath": "tests/test_wrapped_method_forward_reference.py",
"language": "python",
"file_size": 997,
"cut_index": 512,
"middle_length": 229
} |
api import APIRouter, Depends, FastAPI, WebSocket
from fastapi.testclient import TestClient
def dependency_list() -> list[str]:
return []
DepList = Annotated[list[str], Depends(dependency_list)]
def create_dependency(name: str):
def fun(deps: DepList):
deps.append(name)
return Depends(fun)
... | @router.websocket("/router", dependencies=[create_dependency("routerindex")])
async def routerindex(websocket: WebSocket, deps: DepList):
await websocket.accept()
await websocket.send_text(json.dumps(deps))
await websocket.close()
@prefix_rou | ])
@app.websocket("/", dependencies=[create_dependency("index")])
async def index(websocket: WebSocket, deps: DepList):
await websocket.accept()
await websocket.send_text(json.dumps(deps))
await websocket.close()
| {
"filepath": "tests/test_ws_dependencies.py",
"language": "python",
"file_size": 2164,
"cut_index": 563,
"middle_length": 229
} |
m fastapi.testclient import TestClient
from tests.utils import needs_py310, workdir_lock
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py310", marks=needs_py310),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureReque... | move(log) # pragma: no cover
response = client.post("/send-notification/foo@example.com?q=some-query")
assert response.status_code == 200, response.text
assert response.json() == {"message": "Message sent"}
with open("./log.txt") as f:
| Path("log.txt")
if log.is_file():
os.re | {
"filepath": "tests/test_tutorial/test_background_tasks/test_tutorial002.py",
"language": "python",
"file_size": 968,
"cut_index": 582,
"middle_length": 52
} |
ient import TestClient
from inline_snapshot import snapshot
from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dataclas... | ": 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": | rt 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 | {
"filepath": "tests/test_tutorial/test_dataclasses/test_tutorial002.py",
"language": "python",
"file_size": 2961,
"cut_index": 563,
"middle_length": 229
} |
astapi import FastAPI
from fastapi.testclient import TestClient
app_default = FastAPI()
@app_default.post("/items/")
async def app_default_post(data: dict):
return data
app_lax = FastAPI(strict_content_type=False)
@app_lax.post("/items/")
async def app_lax_post(data: dict):
return data
client_default =... | y": "value"}
def test_lax_accepts_no_content_type():
response = client_lax.post("/items/", content='{"key": "value"}')
assert response.status_code == 200
assert response.json() == {"key": "value"}
def test_lax_accepts_json_content_type():
| ert response.status_code == 422
def test_default_strict_accepts_json_content_type():
response = client_default.post("/items/", json={"key": "value"})
assert response.status_code == 200
assert response.json() == {"ke | {
"filepath": "tests/test_strict_content_type_app_level.py",
"language": "python",
"file_size": 1153,
"cut_index": 518,
"middle_length": 229
} |
the top level, including OpenAPI
# Ref: https://github.com/fastapi/fastapi/discussions/14263
# Ref: https://github.com/fastapi/fastapi/issues/14271
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI(... | response = client.get("/")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, | oot():
response = client.get("/", headers={"Authorization": "Bearer token"})
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello, World!"}
def test_get_root_no_token():
| {
"filepath": "tests/test_top_level_security_scheme_in_openapi.py",
"language": "python",
"file_size": 1902,
"cut_index": 537,
"middle_length": 229
} |
napshot
from pydantic import BaseModel
@pytest.fixture(name="client")
def client_fixture() -> TestClient:
from fastapi import Body
from pydantic import Discriminator, Tag
class Cat(BaseModel):
pet_type: str = "cat"
meows: int
class Dog(BaseModel):
pet_type: str = "dog"
... | reate_pet_annotated(pet: Annotated[Pet, Body()]):
return pet
client = TestClient(app)
return client
def test_union_body_discriminator_assignment(client: TestClient) -> None:
response = client.post("/pet/assignment", json={"pet_type": | dog")],
Discriminator(get_pet_type),
]
app = FastAPI()
@app.post("/pet/assignment")
async def create_pet_assignment(pet: Pet = Body()):
return pet
@app.post("/pet/annotated")
async def c | {
"filepath": "tests/test_union_body_discriminator_annotated.py",
"language": "python",
"file_size": 8043,
"cut_index": 716,
"middle_length": 229
} |
pytest
from fastapi import FastAPI
from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
from pydantic.dataclasses import dataclass
app = FastAPI()
@dataclass
class Item:
name: str
price: float | None = None
owner_ids: list[int] | None = None
@app.get("/items... |
{"name": "baz", "price": "baz"},
]
client = TestClient(app)
def test_invalid():
with pytest.raises(ResponseValidationError):
client.get("/items/invalid")
def test_double_invalid():
with pytest.raises(ResponseValidationErr | me": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
@app.get("/items/invalidlist", response_model=list[Item])
def get_invalidlist():
return [
{"name": "foo"},
{"name": "bar", "price": "bar"}, | {
"filepath": "tests/test_validate_response_dataclass.py",
"language": "python",
"file_size": 1167,
"cut_index": 518,
"middle_length": 229
} |
rom fastapi.testclient import TestClient
router = APIRouter()
prefix_router = APIRouter()
native_prefix_route = APIRouter(prefix="/native")
app = FastAPI()
@app.websocket_route("/")
async def index(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello, world!")
await websocket.... | "/router2")
async def routerindex2(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello, router!")
await websocket.close()
@router.websocket("/router/{pathparam:path}")
async def routerindexparams(websocket: WebSoc | ()
@prefix_router.websocket_route("/")
async def routerprefixindex(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello, router with prefix!")
await websocket.close()
@router.websocket( | {
"filepath": "tests/test_ws_router.py",
"language": "python",
"file_size": 7651,
"cut_index": 716,
"middle_length": 229
} |
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):
... | t):
response = client.get("/authors/")
assert response.status_code == 200
assert response.json() == [
{
"name": "Breaters",
"items": [
{
"name": "Island In The Moon",
| esponse.json() == {
"name": "foo",
"items": [
{"name": "Bar", "description": None},
{"name": "Baz", "description": "Drop the Baz"},
],
}
def test_get_authors(client: TestClien | {
"filepath": "tests/test_tutorial/test_dataclasses/test_tutorial003.py",
"language": "python",
"file_size": 8128,
"cut_index": 716,
"middle_length": 229
} |
port Annotated, Any
from fastapi import FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
async def security1(scopes: SecurityScopes):
return scopes.scopes
async def security2(scopes: SecurityScopes):
return scopes.scopes
async def dep3(
dep1: Ann... | tated[dict[str, Any], Security(dep3, scopes=["scope3"])],
):
return dep3
client = TestClient(app)
def test_security_scopes_dont_propagate():
response = client.get("/scopes")
assert response.status_code == 200
assert response.json() == { |
@app.get("/scopes")
def get_scopes(
dep3: Anno | {
"filepath": "tests/test_security_scopes_dont_propagate.py",
"language": "python",
"file_size": 973,
"cut_index": 582,
"middle_length": 52
} |
one
class ExtendedItem(Item):
age: int
@app.post("/items/")
def save_union_different_body(item: ExtendedItem | Item):
return {"item": item}
client = TestClient(app)
def test_post_extended_item():
response = client.post("/items/", json={"name": "Foo", "age": 5})
assert response.status_code == 200... | .json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"responses": {
| _code == 200, response.text
assert response.json() == {"item": {"name": "Foo"}}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response | {
"filepath": "tests/test_union_inherited_body.py",
"language": "python",
"file_size": 5427,
"cut_index": 716,
"middle_length": 229
} |
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):
respo... | sponse.json() == {
"detail": [
{
"type": "float_parsing",
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "i | ption": 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 re | {
"filepath": "tests/test_tutorial/test_dataclasses/test_tutorial001.py",
"language": "python",
"file_size": 5307,
"cut_index": 716,
"middle_length": 229
} |
ort snapshot
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_schem... | tatus_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {},
"webhooks": {
"new-subscri | """
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.s | {
"filepath": "tests/test_webhooks_security.py",
"language": "python",
"file_size": 5296,
"cut_index": 716,
"middle_length": 229
} |
BaseModel, Field
def test_discriminator_pydantic_v2() -> None:
from pydantic import Tag
app = FastAPI()
class FirstItem(BaseModel):
value: Literal["first"]
price: int
class OtherItem(BaseModel):
value: Literal["other"]
price: float
Item = Annotated[
Ann... |
assert response.status_code == 200, response.text
assert response.json() == {"item": {"value": "first", "price": 100}}
response = client.post("/items/?q=other", json={"value": "other", "price": 100.5})
assert response.status_code == 200, | Item, q: Annotated[str, Field(description="Query string")]
) -> dict[str, Any]:
return {"item": item}
client = TestClient(app)
response = client.post("/items/?q=first", json={"value": "first", "price": 100}) | {
"filepath": "tests/test_union_body_discriminator.py",
"language": "python",
"file_size": 8964,
"cut_index": 716,
"middle_length": 229
} |
snapshot
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_s... | st(path, headers, expected_status, expected_response, client: TestClient):
response = client.get(path, headers=headers)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema(client: | , None, 200, {"User-Agent": "testclient"}),
("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}),
("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}),
],
)
def te | {
"filepath": "tests/test_tutorial/test_header_params/test_tutorial001.py",
"language": "python",
"file_size": 4452,
"cut_index": 614,
"middle_length": 229
} |
pytest.param("tutorial004_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_params_numeric_validations.{request.param}"
)
return TestClient(mod.app)
@pytest.mark.parametrize(
"path,expected_response",
... | d_id?q=somequery")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"loc": ["path", "item_id"],
"input": "invalid_id",
"msg": "Input shou | response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() == expected_response
def test_read_items_non_int_item_id(client: TestClient):
response = client.get("/items/invali | {
"filepath": "tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py",
"language": "python",
"file_size": 6793,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial006_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_params_numeric_validations.{request.param}"
)
return TestClient(mod.app)
@pytest.mark.parametrize(
"path,expected_response",
... | == expected_response
def test_read_items_item_id_less_than_zero(client: TestClient):
response = client.get("/items/-1?q=somequery&size=5")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
| : "somequery", "size": 10.4},
),
],
)
def test_read_items(client: TestClient, path, expected_response):
response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() | {
"filepath": "tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py",
"language": "python",
"file_size": 8076,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_params_numeric_validations.{request.param}"
)
return TestClient... | tems_invalid_item_id(client: TestClient):
response = client.get("/items/invalid_id")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"loc": ["path", "item_id"],
| ),
],
)
def test_read_items(client: TestClient, path, expected_response):
response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() == expected_response
def test_read_i | {
"filepath": "tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py",
"language": "python",
"file_size": 6280,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial002_an_py310"),
pytest.param("tutorial003_py310"),
pytest.param("tutorial003_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_params_numeric_validations.{request.param}"
)
... | test_read_items_invalid_item_id(client: TestClient):
response = client.get("/items/invalid_id?q=somequery")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"loc": [ | somequery"}),
],
)
def test_read_items(client: TestClient, path, expected_response):
response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() == expected_response
def | {
"filepath": "tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py",
"language": "python",
"file_size": 6348,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial005_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_params_numeric_validations.{request.param}"
)
return TestClient(mod.app)
@pytest.mark.parametrize(
"path,expected_response",
... | valid_id?q=somequery")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"loc": ["path", "item_id"],
"input": "invalid_id",
"msg": "Input | response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() == expected_response
def test_read_items_non_int_item_id(client: TestClient):
response = client.get("/items/in | {
"filepath": "tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py",
"language": "python",
"file_size": 7347,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body_fields.{request.param}")
client = TestClient(mod.app)
return client
def test_items_... | "name": "Bar",
"price": 0.2,
"description": "Some bar",
"tax": "5.4",
}
},
)
assert response.status_code == 200
assert response.json() == {
"item_id": 6,
| id": 5,
"item": {"name": "Foo", "price": 3.0, "description": None, "tax": None},
}
def test_items_6(client: TestClient):
response = client.put(
"/items/6",
json={
"item": {
| {
"filepath": "tests/test_tutorial/test_body_fields/test_tutorial001.py",
"language": "python",
"file_size": 7095,
"cut_index": 716,
"middle_length": 229
} |
= TestClient(mod.app)
return client
def test_post_all(client: TestClient):
data = {
"name": "Special Offer",
"description": "This is a special offer",
"price": 38.6,
"items": [
{
"name": "Foo",
"description": "A very nice Item",
... | _code == 200, response.text
assert response.json() == data
def test_put_only_required(client: TestClient):
response = client.post(
"/offers/",
json={
"name": "Special Offer",
"price": 38.6,
"ite | e.png",
"name": "example image",
}
],
}
],
}
response = client.post(
"/offers/",
json=data,
)
assert response.status | {
"filepath": "tests/test_tutorial/test_body_nested_models/test_tutorial007.py",
"language": "python",
"file_size": 11912,
"cut_index": 921,
"middle_length": 229
} |
snapshot
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py310", marks=needs_py310),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_s... | trange_header": "FastAPI test"},
),
(
"/items",
{"strange-header": "Not really underscore"},
200,
{"strange_header": None},
),
],
)
def test(path, headers, expected_status, expecte | , None, 200, {"strange_header": None}),
("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}),
(
"/items",
{"strange_header": "FastAPI test"},
200,
{"s | {
"filepath": "tests/test_tutorial/test_header_params/test_tutorial002.py",
"language": "python",
"file_size": 4674,
"cut_index": 614,
"middle_length": 229
} |
pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
"tutorial001_py310",
"tutorial003_py310",
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.first_steps.{request.pa... | sert response.json() == expected_response
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == snapshot(
{
"openapi": "3.1.0",
| ("/nonexistent", 404, {"detail": "Not Found"}),
],
)
def test_get_path(client: TestClient, path, expected_status, expected_response):
response = client.get(path)
assert response.status_code == expected_status
as | {
"filepath": "tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py",
"language": "python",
"file_size": 1606,
"cut_index": 537,
"middle_length": 229
} |
= 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 respon... | esponse.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
| 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 r | {
"filepath": "tests/test_tutorial/test_generate_clients/test_tutorial002.py",
"language": "python",
"file_size": 8298,
"cut_index": 716,
"middle_length": 229
} |
= 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 respon... | esponse.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
| 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 r | {
"filepath": "tests/test_tutorial/test_generate_clients/test_tutorial003.py",
"language": "python",
"file_size": 8276,
"cut_index": 716,
"middle_length": 229
} |
name="client",
params=[
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... | 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.statu | ere goes my hero"}
@workdir_lock
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 == | {
"filepath": "tests/test_tutorial/test_additional_responses/test_tutorial002.py",
"language": "python",
"file_size": 5431,
"cut_index": 716,
"middle_length": 229
} |
esponse = 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.jso... | "responses": {
"404": {
"description": "The item was not found",
"content": {
"application/json": {
| snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
| {
"filepath": "tests/test_tutorial/test_additional_responses/test_tutorial003.py",
"language": "python",
"file_size": 5453,
"cut_index": 716,
"middle_length": 229
} |
od",
params=[
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_module(request: pytest.FixtureRequest):
module = importlib.import_module(f"docs_src.encoder.{request.param}")
return module
@pytest.fixture(name="client")
def get_client(mod: ModuleType):
client = TestClient(m... | "title": "Foo",
"timestamp": "2023-01-01T12:00:00",
"description": "An optional description",
}
def test_put_invalid_data(client: TestClient, mod: ModuleType):
fake_db = mod.fake_db
response = client.put(
"/items/34 | Foo",
"timestamp": "2023-01-01T12:00:00",
"description": "An optional description",
},
)
assert response.status_code == 200
assert "123" in fake_db
assert fake_db["123"] == {
| {
"filepath": "tests/test_tutorial/test_encoder/test_tutorial001.py",
"language": "python",
"file_size": 7533,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body_updates.{request.param}")
client = TestClient(mod.app)
return client
def test_get(client: TestClient):
response = client.get("/items/baz")
a... | "tax": 10.5,
"tags": ["tag1", "tag2"],
},
)
assert response.json() == {
"name": "Fooz",
"description": "Item description",
"price": 3,
"tax": 10.5,
"tags": ["tag1", "tag2"],
}
def t | [],
}
def test_patch_all(client: TestClient):
response = client.patch(
"/items/foo",
json={
"name": "Fooz",
"description": "Item description",
"price": 3,
| {
"filepath": "tests/test_tutorial/test_body_updates/test_tutorial002.py",
"language": "python",
"file_size": 7985,
"cut_index": 716,
"middle_length": 229
} |
mport TestClient
from inline_snapshot import snapshot
from docs_src.metadata.tutorial001_py310 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... | ead 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": " | "info": {
"title": "ChimichangApp",
"summary": "Deadpool's favorite app. Nuff said.",
"description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **r | {
"filepath": "tests/test_tutorial/test_metadata/test_tutorial001.py",
"language": "python",
"file_size": 1959,
"cut_index": 537,
"middle_length": 229
} |
.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.metadata.tutorial002_py310 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_... | n": "0.1.0",
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses | napi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {
"title": "FastAPI",
"versio | {
"filepath": "tests/test_tutorial/test_metadata/test_tutorial002.py",
"language": "python",
"file_size": 1330,
"cut_index": 524,
"middle_length": 229
} |
mport TestClient
from inline_snapshot import snapshot
from docs_src.metadata.tutorial003_py310 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():... | "operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"app | "info": {
"title": "FastAPI",
"version": "0.1.0",
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
| {
"filepath": "tests/test_tutorial/test_metadata/test_tutorial003.py",
"language": "python",
"file_size": 1634,
"cut_index": 537,
"middle_length": 229
} |
from fastapi.websockets import WebSocketDisconnect
from ...utils import needs_py310
@pytest.fixture(
name="app",
params=[
pytest.param("tutorial002_py310", marks=needs_py310),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_app(request: pytest.FixtureRequest):
mo... | ebSocketDisconnect):
with client.websocket_connect("/items/foo/ws") as websocket:
message = "Message one"
websocket.send_text(message)
data = websocket.receive_text()
assert data == "Session cookie or | esponse.status_code == 200, response.text
assert b"<!DOCTYPE html>" in response.content
def test_websocket_with_cookie(app: FastAPI):
client = TestClient(app, cookies={"session": "fakesession"})
with pytest.raises(W | {
"filepath": "tests/test_tutorial/test_websockets/test_tutorial002.py",
"language": "python",
"file_size": 4110,
"cut_index": 614,
"middle_length": 229
} |
snapshot
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py310"),
pytest.param("tutorial002_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.response_status_code.{request.param}")
client = TestClient(mod.app)... | {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"parameters": [
{
| ert 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() == snapshot(
| {
"filepath": "tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py",
"language": "python",
"file_size": 3912,
"cut_index": 614,
"middle_length": 229
} |
snapshot
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial003_py310", marks=needs_py310),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_s... | {"X-Token values": ["foo", "bar"]},
),
],
)
def test(path, headers, expected_status, expected_response, client: TestClient):
response = client.get(path, headers=headers)
assert response.status_code == expected_status
assert response | , None, 200, {"X-Token values": None}),
("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}),
(
"/items",
[("x-token", "foo"), ("x-token", "bar")],
200,
| {
"filepath": "tests/test_tutorial/test_header_params/test_tutorial003.py",
"language": "python",
"file_size": 4655,
"cut_index": 614,
"middle_length": 229
} |
],
)
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 respo... | 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"},
"paths": {
| nse.status_code == 200, response.text
assert response.json() == [
{"name": "Plumbus", "price": 3},
{"name": "Portal Gun", "price": 9001},
]
def test_openapi_schema(client: TestClient):
response = cli | {
"filepath": "tests/test_tutorial/test_generate_clients/test_tutorial001.py",
"language": "python",
"file_size": 6149,
"cut_index": 716,
"middle_length": 229
} |
esponse = 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.jso... | "responses": {
"404": {
"description": "Not Found",
"content": {
"application/json": {
" | snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
| {
"filepath": "tests/test_tutorial/test_additional_responses/test_tutorial001.py",
"language": "python",
"file_size": 5213,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body_updates.{request.param}")
client = TestClient(mod.app)
return client
def test_get(client: TestClient):
response = client.get("/items/baz")
a... | tion": None,
"price": 3,
"tax": 10.5,
"tags": [],
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == sn | [],
}
def test_put(client: TestClient):
response = client.put(
"/items/bar", json={"name": "Barz", "price": 3, "description": None}
)
assert response.json() == {
"name": "Barz",
"descrip | {
"filepath": "tests/test_tutorial/test_body_updates/test_tutorial001.py",
"language": "python",
"file_size": 7516,
"cut_index": 716,
"middle_length": 229
} |
.testclient import TestClient
from docs_src.cors.tutorial001_py310 import app
def test_cors():
client = TestClient(app)
# Test pre-flight response
headers = {
"Origin": "https://localhost.tiangolo.com",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-E... | .tiangolo.com"}
response = client.get("/", headers=headers)
assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert (
response.headers["access-control-allow-origin"]
== " | "access-control-allow-origin"]
== "https://localhost.tiangolo.com"
)
assert response.headers["access-control-allow-headers"] == "X-Example"
# Test standard response
headers = {"Origin": "https://localhost | {
"filepath": "tests/test_tutorial/test_cors/test_tutorial001.py",
"language": "python",
"file_size": 1284,
"cut_index": 524,
"middle_length": 229
} |
rt pytest
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocketDisconnect
from docs_src.websockets_.tutorial001_py310 import app
client = TestClient(app)
def test_main():
response = client.get("/")
assert response.status_code == 200, response.text
assert b"<!DOCTYPE html>" i... | ebsocket.receive_text()
assert data == f"Message text was: {message}"
message = "Message two"
websocket.send_text(message)
data = websocket.receive_text()
assert data == f"Message text was: {messa | websocket.send_text(message)
data = w | {
"filepath": "tests/test_tutorial/test_websockets/test_tutorial001.py",
"language": "python",
"file_size": 829,
"cut_index": 516,
"middle_length": 52
} |
_file):
importlib.import_module("docs_src.generate_clients.tutorial004_py310")
modified_openapi = json.loads(tmp_file.read_text())
assert modified_openapi == snapshot(
{
"components": {
"schemas": {
"HTTPValidationError": {
... | tionError",
"type": "object",
},
"Item": {
"properties": {
"name": {
"title": "Name",
| },
"title": "Detail",
"type": "array",
},
},
"title": "HTTPValida | {
"filepath": "tests/test_tutorial/test_generate_clients/test_tutorial004.py",
"language": "python",
"file_size": 9511,
"cut_index": 921,
"middle_length": 229
} |
("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 respons... | "read_user_me_users_me_get",
"responses": {
"200": {
"content": {
"application/json": {
"schema | ot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"operationId": | {
"filepath": "tests/test_tutorial/test_path_params/test_tutorial003.py",
"language": "python",
"file_size": 5323,
"cut_index": 716,
"middle_length": 229
} |
ams.tutorial004_py310 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_pat... | .1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/files/{file_path}": {
"get": {
"responses": {
"200": {
| "/home/johndoe/myfile.txt"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3 | {
"filepath": "tests/test_tutorial/test_path_params/test_tutorial004.py",
"language": "python",
"file_size": 3902,
"cut_index": 614,
"middle_length": 229
} |
pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
pytest.importorskip("orjson")
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.custom_... | DeprecationWarning")
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",
| (client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
@pytest.mark.filterwarnings("ignore::fastapi.exceptions.FastAPI | {
"filepath": "tests/test_tutorial/test_custom_response/test_tutorial001.py",
"language": "python",
"file_size": 1622,
"cut_index": 537,
"middle_length": 229
} |
pytest
from fastapi.testclient import TestClient
from inline_snapshot import Is, snapshot
@pytest.fixture(
name="mod_name",
params=[
pytest.param("tutorial002_py310"),
pytest.param("tutorial003_py310"),
pytest.param("tutorial004_py310"),
],
)
def get_mod_name(request: pytest.Fixtur... |
def test_get_custom_response(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.text == html_contents
def test_openapi_schema(client: TestClient, mod_name: str):
if m | ")
return TestClient(mod.app)
html_contents = """
<html>
<head>
<title>Some HTML in here</title>
</head>
<body>
<h1>Look ma! HTML!</h1>
</body>
</html>
""" | {
"filepath": "tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py",
"language": "python",
"file_size": 1979,
"cut_index": 537,
"middle_length": 229
} |
name="client",
params=[
pytest.param("tutorial004_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... | 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.statu | ere goes my hero"}
@workdir_lock
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 == | {
"filepath": "tests/test_tutorial/test_additional_responses/test_tutorial004.py",
"language": "python",
"file_size": 5638,
"cut_index": 716,
"middle_length": 229
} |
mport TestClient
from inline_snapshot import snapshot
from docs_src.metadata.tutorial001_1_py310 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_sche... | *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": | "info": {
"title": "ChimichangApp",
"summary": "Deadpool's favorite app. Nuff said.",
"description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can * | {
"filepath": "tests/test_tutorial/test_metadata/test_tutorial001_1.py",
"language": "python",
"file_size": 1930,
"cut_index": 537,
"middle_length": 229
} |
ams.tutorial002_py310 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.sta... | t 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}": {
| 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")
asser | {
"filepath": "tests/test_tutorial/test_path_params/test_tutorial002.py",
"language": "python",
"file_size": 4876,
"cut_index": 614,
"middle_length": 229
} |
io
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.path_params.tutorial003b_py310 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() ... | "/users": {
"get": {
"operationId": "read_users2_users_get",
"responses": {
"200": {
"content": {
| son")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
| {
"filepath": "tests/test_tutorial/test_path_params/test_tutorial003b.py",
"language": "python",
"file_size": 1430,
"cut_index": 524,
"middle_length": 229
} |
ytest
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
with warnings.catch_warnings():
warnings.simplefilter("ignore", FastAPIDeprecationWarning)
from docs_src.custom_response.tutorial001b_py310 import app
client = TestClie... | nse = 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": {
| )
assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
@pytest.mark.filterwarnings("ignore::fastapi.exceptions.FastAPIDeprecationWarning")
def test_openapi_schema():
respo | {
"filepath": "tests/test_tutorial/test_custom_response/test_tutorial001b.py",
"language": "python",
"file_size": 1547,
"cut_index": 537,
"middle_length": 229
} |
ne_snapshot import snapshot
from docs_src.metadata.tutorial004_py310 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
... | mary": "Get Users",
"operationId": "get_users_users__get",
"responses": {
"200": {
"description": "Successful Response",
| api": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/": {
"get": {
"tags": ["users"],
"sum | {
"filepath": "tests/test_tutorial/test_metadata/test_tutorial004.py",
"language": "python",
"file_size": 2324,
"cut_index": 563,
"middle_length": 229
} |
tlib
import time
from types import ModuleType
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial003_py310"),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.websockets_.{request.param}... | bsocket_connect("/ws/1234") as connection,
client.websocket_connect("/ws/5678") as connection_two,
):
connection.send_text("Hello from 1234")
data1 = connection.receive_text()
assert data1 == "You wrote: Hello from 1234" | od.app)
return client
def test_get(client: TestClient, html: str):
response = client.get("/")
assert response.text == html
def test_websocket_handle_disconnection(client: TestClient):
with (
client.we | {
"filepath": "tests/test_tutorial/test_websockets/test_tutorial003.py",
"language": "python",
"file_size": 1490,
"cut_index": 524,
"middle_length": 229
} |
ams.tutorial005_py310 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(... | assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "enum",
"loc": ["path", "model_name"],
"msg": "Input should be 'alexnet', 'resnet' or 'lenet'", | lient.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")
| {
"filepath": "tests/test_tutorial/test_path_params/test_tutorial005.py",
"language": "python",
"file_size": 4710,
"cut_index": 614,
"middle_length": 229
} |
t = TestClient(mod.app)
return client
def test_post_all(client: TestClient):
response = client.put(
"/items/5",
json={
"item": {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": 0.1,
},
... | ent: TestClient):
response = client.put(
"/items/5",
json={
"item": {"name": "Foo", "price": 50.5},
"user": {"username": "johndoe"},
},
)
assert response.status_code == 200
assert response.jso |
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": 0.1,
},
"user": {"username": "johndoe", "full_name": "John Doe"},
}
def test_post_required(cli | {
"filepath": "tests/test_tutorial/test_body_multiple_params/test_tutorial002.py",
"language": "python",
"file_size": 12060,
"cut_index": 921,
"middle_length": 229
} |
astapi.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.custom_response.tutorial005_py310 import app
client = TestClient(app)
def test_get():
response = client.get("/")
assert response.status_code == 200, response.text
assert response.text == "Hello World"
def test_opena... | ",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"text/plain": {"schema": { | "info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"summary": "Main",
"operationId": "main__get | {
"filepath": "tests/test_tutorial/test_custom_response/test_tutorial005.py",
"language": "python",
"file_size": 1185,
"cut_index": 518,
"middle_length": 229
} |
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.custom_response.tutorial006b_py310 import app
client = TestClient(app)
def test_redirect_response_class():
response = client.get("/fastapi", follow_redirects=False)
assert response.status_code == 307
assert resp... | "summary": "Redirect Fastapi",
"operationId": "redirect_fastapi_fastapi_get",
"responses": {"307": {"description": "Successful Response"}},
}
}
}, | ert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/fastapi": {
"get": {
| {
"filepath": "tests/test_tutorial/test_custom_response/test_tutorial006b.py",
"language": "python",
"file_size": 1014,
"cut_index": 512,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.