sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
fastapi/fastapi:docs_src/path_operation_advanced_configuration/tutorial005_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/", openapi_extra={"x-aperture-labs-portal": "blue"}) async def read_items(): return [{"item_id": "portal-gun"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_advanced_configuration/tutorial005_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_operation_advanced_configuration/tutorial006_py310.py
from fastapi import FastAPI, Request app = FastAPI() def magic_data_reader(raw_body: bytes): return { "size": len(raw_body), "content": { "name": "Maaaagic", "price": 42, "description": "Just kiddin', no magic here. ✨", }, } @app.post( "/items/", openapi_extra={ "requestBody": { "content": { "application/json": { "schema": { "required": ["name", "price"], "type": "object", "properties": { "name": {"type": "string"}, "price": {"type": "number"}, "description": {"type": "string"}, }, } } }, "required": True, }, }, ) async def create_item(request: Request): raw_body = await request.body() data = magic_data_reader(raw_body) return data
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_advanced_configuration/tutorial006_py310.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_operation_configuration/tutorial002b_py310.py
from enum import Enum from fastapi import FastAPI app = FastAPI() class Tags(Enum): items = "items" users = "users" @app.get("/items/", tags=[Tags.items]) async def get_items(): return ["Portal gun", "Plumbus"] @app.get("/users/", tags=[Tags.users]) async def read_users(): return ["Rick", "Morty"]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_configuration/tutorial002b_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_operation_configuration/tutorial006_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/", tags=["items"]) async def read_items(): return [{"name": "Foo", "price": 42}] @app.get("/users/", tags=["users"]) async def read_users(): return [{"username": "johndoe"}] @app.get("/elements/", tags=["items"], deprecated=True) async def read_elements(): return [{"item_id": "Foo"}]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_operation_configuration/tutorial006_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id): return {"item_id": item_id}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params/tutorial002_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params/tutorial002_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params/tutorial003_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/users/me") async def read_user_me(): return {"user_id": "the current user"} @app.get("/users/{user_id}") async def read_user(user_id: str): return {"user_id": user_id}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params/tutorial003_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params/tutorial003b_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/users") async def read_users(): return ["Rick", "Morty"] @app.get("/users") async def read_users2(): return ["Bean", "Elfo"]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params/tutorial003b_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params/tutorial004_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/files/{file_path:path}") async def read_file(file_path: str): return {"file_path": file_path}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params/tutorial004_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params/tutorial005_py310.py
from enum import Enum from fastapi import FastAPI class ModelName(str, Enum): alexnet = "alexnet" resnet = "resnet" lenet = "lenet" app = FastAPI() @app.get("/models/{model_name}") async def get_model(model_name: ModelName): if model_name is ModelName.alexnet: return {"model_name": model_name, "message": "Deep Learning FTW!"} if model_name.value == "lenet": return {"model_name": model_name, "message": "LeCNN all the images"} return {"model_name": model_name, "message": "Have some residuals"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params/tutorial005_py310.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial002_an_py310.py
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial002_an_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial002_py310.py
from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial002_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial003_an_py310.py
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial003_an_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial003_py310.py
from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial003_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial004_an_py310.py
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial004_an_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial004_py310.py
from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( *, item_id: int = Path(title="The ID of the item to get", ge=1), q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial004_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial005_an_py310.py
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)], q: str, ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial005_an_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/path_params_numeric_validations/tutorial005_py310.py
from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( *, item_id: int = Path(title="The ID of the item to get", gt=0, le=1000), q: str, ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/path_params_numeric_validations/tutorial005_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/python_types/tutorial010_py310.py
class Person: def __init__(self, name: str): self.name = name def get_person_name(one_person: Person): return one_person.name
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/python_types/tutorial010_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/query_params/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] @app.get("/items/") async def read_item(skip: int = 0, limit: int = 10): return fake_items_db[skip : skip + limit]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/query_params/tutorial001_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/query_params/tutorial005_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_user_item(item_id: str, needy: str): item = {"item_id": item_id, "needy": needy} return item
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/query_params/tutorial005_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/query_params_str_validations/tutorial012_py310.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: list[str] = Query(default=["foo", "bar"])): query_items = {"q": q} return query_items
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/query_params_str_validations/tutorial012_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/query_params_str_validations/tutorial013_py310.py
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: list = Query(default=[])): query_items = {"q": q} return query_items
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/query_params_str_validations/tutorial013_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_files/tutorial001_03_an_py310.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file( file: Annotated[UploadFile, File(description="A file read as UploadFile")], ): return {"filename": file.filename}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial001_03_an_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_files/tutorial001_03_py310.py
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: bytes = File(description="A file read as bytes")): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file( file: UploadFile = File(description="A file read as UploadFile"), ): return {"filename": file.filename}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial001_03_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_files/tutorial001_an_py310.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File()]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial001_an_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_files/tutorial001_py310.py
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: bytes = File()): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial001_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_files/tutorial002_an_py310.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files(files: Annotated[list[bytes], File()]): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files(files: list[UploadFile]): return {"filenames": [file.filename for file in files]} @app.get("/") async def main(): content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial002_an_py310.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/request_files/tutorial002_py310.py
from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files(files: list[bytes] = File()): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files(files: list[UploadFile]): return {"filenames": [file.filename for file in files]} @app.get("/") async def main(): content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial002_py310.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/request_files/tutorial003_an_py310.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files( files: Annotated[list[bytes], File(description="Multiple files as bytes")], ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( files: Annotated[ list[UploadFile], File(description="Multiple files as UploadFile") ], ): return {"filenames": [file.filename for file in files]} @app.get("/") async def main(): content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial003_an_py310.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_files/tutorial003_py310.py
from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files( files: list[bytes] = File(description="Multiple files as bytes"), ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( files: list[UploadFile] = File(description="Multiple files as UploadFile"), ): return {"filenames": [file.filename for file in files]} @app.get("/") async def main(): content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_files/tutorial003_py310.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/request_form_models/tutorial001_an_py310.py
from typing import Annotated from fastapi import FastAPI, Form from pydantic import BaseModel app = FastAPI() class FormData(BaseModel): username: str password: str @app.post("/login/") async def login(data: Annotated[FormData, Form()]): return data
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_form_models/tutorial001_an_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_form_models/tutorial001_py310.py
from fastapi import FastAPI, Form from pydantic import BaseModel app = FastAPI() class FormData(BaseModel): username: str password: str @app.post("/login/") async def login(data: FormData = Form()): return data
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_form_models/tutorial001_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_form_models/tutorial002_an_py310.py
from typing import Annotated from fastapi import FastAPI, Form from pydantic import BaseModel app = FastAPI() class FormData(BaseModel): username: str password: str model_config = {"extra": "forbid"} @app.post("/login/") async def login(data: Annotated[FormData, Form()]): return data
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_form_models/tutorial002_an_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_form_models/tutorial002_py310.py
from fastapi import FastAPI, Form from pydantic import BaseModel app = FastAPI() class FormData(BaseModel): username: str password: str model_config = {"extra": "forbid"} @app.post("/login/") async def login(data: FormData = Form()): return data
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_form_models/tutorial002_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_forms/tutorial001_an_py310.py
from typing import Annotated from fastapi import FastAPI, Form app = FastAPI() @app.post("/login/") async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]): return {"username": username}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_forms/tutorial001_an_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_forms/tutorial001_py310.py
from fastapi import FastAPI, Form app = FastAPI() @app.post("/login/") async def login(username: str = Form(), password: str = Form()): return {"username": username}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_forms/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_forms_and_files/tutorial001_an_py310.py
from typing import Annotated from fastapi import FastAPI, File, Form, UploadFile app = FastAPI() @app.post("/files/") async def create_file( file: Annotated[bytes, File()], fileb: Annotated[UploadFile, File()], token: Annotated[str, Form()], ): return { "file_size": len(file), "token": token, "fileb_content_type": fileb.content_type, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_forms_and_files/tutorial001_an_py310.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/request_forms_and_files/tutorial001_py310.py
from fastapi import FastAPI, File, Form, UploadFile app = FastAPI() @app.post("/files/") async def create_file( file: bytes = File(), fileb: UploadFile = File(), token: str = Form() ): return { "file_size": len(file), "token": token, "fileb_content_type": fileb.content_type, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/request_forms_and_files/tutorial001_py310.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_change_status_code/tutorial001_py310.py
from fastapi import FastAPI, Response, status app = FastAPI() tasks = {"foo": "Listen to the Bar Fighters"} @app.put("/get-or-create-task/{task_id}", status_code=200) def get_or_create_task(task_id: str, response: Response): if task_id not in tasks: tasks[task_id] = "This didn't exist before" response.status_code = status.HTTP_201_CREATED return tasks[task_id]
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_change_status_code/tutorial001_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_cookies/tutorial001_py310.py
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.post("/cookie/") def create_cookie(): content = {"message": "Come to the dark side, we have cookies"} response = JSONResponse(content=content) response.set_cookie(key="fakesession", value="fake-cookie-session-value") return response
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_cookies/tutorial001_py310.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_cookies/tutorial002_py310.py
from fastapi import FastAPI, Response app = FastAPI() @app.post("/cookie-and-object/") def create_cookie(response: Response): response.set_cookie(key="fakesession", value="fake-cookie-session-value") return {"message": "Come to the dark side, we have cookies"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_cookies/tutorial002_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_directly/tutorial002_py310.py
from fastapi import FastAPI, Response app = FastAPI() @app.get("/legacy/") def get_legacy_data(): data = """<?xml version="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body> </shampoo> """ return Response(content=data, media_type="application/xml")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_directly/tutorial002_py310.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
fastapi/fastapi:docs_src/response_headers/tutorial001_py310.py
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.get("/headers/") def get_headers(): content = {"message": "Hello World"} headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"} return JSONResponse(content=content, headers=headers)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_headers/tutorial001_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_headers/tutorial002_py310.py
from fastapi import FastAPI, Response app = FastAPI() @app.get("/headers-and-object/") def get_headers(response: Response): response.headers["X-Cat-Dog"] = "alone in the world" return {"message": "Hello World"}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_headers/tutorial002_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_model/tutorial003_02_py310.py
from fastapi import FastAPI, Response from fastapi.responses import JSONResponse, RedirectResponse app = FastAPI() @app.get("/portal") async def get_portal(teleport: bool = False) -> Response: if teleport: return RedirectResponse(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ") return JSONResponse(content={"message": "Here's your interdimensional portal."})
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_model/tutorial003_02_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_model/tutorial003_03_py310.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/teleport") async def get_teleport() -> RedirectResponse: return RedirectResponse(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_model/tutorial003_03_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_status_code/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() @app.post("/items/", status_code=201) async def create_item(name: str): return {"name": name}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_status_code/tutorial001_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/response_status_code/tutorial002_py310.py
from fastapi import FastAPI, status app = FastAPI() @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(name: str): return {"name": name}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/response_status_code/tutorial002_py310.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/security/tutorial001_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/items/") async def read_items(token: Annotated[str, Depends(oauth2_scheme)]): return {"token": token}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/security/tutorial001_an_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/security/tutorial001_py310.py
from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/items/") async def read_items(token: str = Depends(oauth2_scheme)): return {"token": token}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/security/tutorial001_py310.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/security/tutorial006_an_py310.py
from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() @app.get("/users/me") def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): return {"username": credentials.username, "password": credentials.password}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/security/tutorial006_an_py310.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/security/tutorial006_py310.py
from fastapi import Depends, FastAPI from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() @app.get("/users/me") def read_current_user(credentials: HTTPBasicCredentials = Depends(security)): return {"username": credentials.username, "password": credentials.password}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/security/tutorial006_py310.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/security/tutorial007_an_py310.py
import secrets from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() def get_current_username( credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" is_correct_username = secrets.compare_digest( current_username_bytes, correct_username_bytes ) current_password_bytes = credentials.password.encode("utf8") correct_password_bytes = b"swordfish" is_correct_password = secrets.compare_digest( current_password_bytes, correct_password_bytes ) if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username @app.get("/users/me") def read_current_user(username: Annotated[str, Depends(get_current_username)]): return {"username": username}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/security/tutorial007_an_py310.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/security/tutorial007_py310.py
import secrets from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" is_correct_username = secrets.compare_digest( current_username_bytes, correct_username_bytes ) current_password_bytes = credentials.password.encode("utf8") correct_password_bytes = b"swordfish" is_correct_password = secrets.compare_digest( current_password_bytes, correct_password_bytes ) if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username @app.get("/users/me") def read_current_user(username: str = Depends(get_current_username)): return {"username": username}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/security/tutorial007_py310.py", "license": "MIT License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app01_py310/main.py
from fastapi import FastAPI from .config import settings app = FastAPI() @app.get("/info") async def info(): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app01_py310/main.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app02_an_py310/main.py
from functools import lru_cache from typing import Annotated from fastapi import Depends, FastAPI from .config import Settings app = FastAPI() @lru_cache def get_settings(): return Settings() @app.get("/info") async def info(settings: Annotated[Settings, Depends(get_settings)]): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app02_an_py310/main.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app02_an_py310/test_main.py
from fastapi.testclient import TestClient from .config import Settings from .main import app, get_settings client = TestClient(app) def get_settings_override(): return Settings(admin_email="testing_admin@example.com") app.dependency_overrides[get_settings] = get_settings_override def test_app(): response = client.get("/info") data = response.json() assert data == { "app_name": "Awesome API", "admin_email": "testing_admin@example.com", "items_per_user": 50, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app02_an_py310/test_main.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:docs_src/settings/app02_py310/config.py
from pydantic_settings import BaseSettings class Settings(BaseSettings): app_name: str = "Awesome API" admin_email: str items_per_user: int = 50
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app02_py310/config.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app02_py310/main.py
from functools import lru_cache from fastapi import Depends, FastAPI from .config import Settings app = FastAPI() @lru_cache def get_settings(): return Settings() @app.get("/info") async def info(settings: Settings = Depends(get_settings)): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app02_py310/main.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app03_an_py310/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): app_name: str = "Awesome API" admin_email: str items_per_user: int = 50 model_config = SettingsConfigDict(env_file=".env")
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app03_an_py310/config.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app03_an_py310/main.py
from functools import lru_cache from typing import Annotated from fastapi import Depends, FastAPI from . import config app = FastAPI() @lru_cache def get_settings(): return config.Settings() @app.get("/info") async def info(settings: Annotated[config.Settings, Depends(get_settings)]): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app03_an_py310/main.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/settings/app03_py310/main.py
from functools import lru_cache from fastapi import Depends, FastAPI from . import config app = FastAPI() @lru_cache def get_settings(): return config.Settings() @app.get("/info") async def info(settings: config.Settings = Depends(get_settings)): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/settings/app03_py310/main.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/sub_applications/tutorial001_py310.py
from fastapi import FastAPI app = FastAPI() @app.get("/app") def read_main(): return {"message": "Hello World from main app"} subapi = FastAPI() @subapi.get("/sub") def read_sub(): return {"message": "Hello World from sub API"} app.mount("/subapi", subapi)
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/sub_applications/tutorial001_py310.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/templates/tutorial001_py310.py
from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") @app.get("/items/{id}", response_class=HTMLResponse) async def read_item(request: Request, id: str): return templates.TemplateResponse( request=request, name="item.html", context={"id": id} )
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/templates/tutorial001_py310.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/using_request_directly/tutorial001_py310.py
from fastapi import FastAPI, Request app = FastAPI() @app.get("/items/{item_id}") def read_root(item_id: str, request: Request): client_host = request.client.host return {"client_host": client_host, "item_id": item_id}
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/using_request_directly/tutorial001_py310.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:docs_src/wsgi/tutorial001_py310.py
from a2wsgi import WSGIMiddleware from fastapi import FastAPI from flask import Flask, request from markupsafe import escape flask_app = Flask(__name__) @flask_app.route("/") def flask_main(): name = request.args.get("name", "World") return f"Hello, {escape(name)} from Flask!" app = FastAPI() @app.get("/v2") def read_main(): return {"message": "Hello World"} app.mount("/v1", WSGIMiddleware(flask_app))
{ "repo_id": "fastapi/fastapi", "file_path": "docs_src/wsgi/tutorial001_py310.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
fastapi/fastapi:tests/test_dependencies_utils.py
from fastapi.dependencies.utils import get_typed_annotation def test_get_typed_annotation(): # For coverage annotation = "None" typed_annotation = get_typed_annotation(annotation, globals()) assert typed_annotation is None
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_dependencies_utils.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_list_bytes_file_order_preserved_issue_14811.py
""" Regression 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 starlette.datastructures import UploadFile as StarletteUploadFile def test_list_bytes_file_preserves_order( monkeypatch: pytest.MonkeyPatch, ) -> None: app = FastAPI() @app.post("/upload") 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_read(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.setattr(StarletteUploadFile, "read", patched_read) client = TestClient(app) files = [ ("files", ("slow.txt", b"A" * 10, "text/plain")), ("files", ("fast.txt", b"B" * 10, "text/plain")), ] r = client.post("/upload", files=files) assert r.status_code == 200, r.text # Must preserve request order: slow first, fast second assert r.json() == [ord("A"), ord("B")]
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_list_bytes_file_order_preserved_issue_14811.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_router_circular_import.py
import pytest from fastapi import APIRouter def test_router_circular_import(): router = APIRouter() with pytest.raises( AssertionError, match="Cannot include the same APIRouter instance into itself. Did you mean to include a different router?", ): router.include_router(router)
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_router_circular_import.py", "license": "MIT License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_json_type.py
import json from typing import 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 query_json_list(items: Annotated[Json[list[str]], Query()]) -> list[str]: return items @app.get("/header-json-list") def header_json_list(x_items: Annotated[Json[list[str]], Header()]) -> 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 = 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( "/query-json-list", params={"items": json.dumps(["abc", "def"])} ) assert response.status_code == 200, response.text assert response.json() == ["abc", "def"] def test_header_json_list(): response = client.get( "/header-json-list", headers={"x-items": json.dumps(["abc", "def"])} ) assert response.status_code == 200, response.text assert response.json() == ["abc", "def"] def test_cookie_json_list(): client.cookies.set("items", json.dumps(["abc", "def"])) response = client.get("/cookie-json-list") assert response.status_code == 200, response.text assert response.json() == ["abc", "def"] client.cookies.clear()
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_json_type.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_dependency_pep695.py
from typing import Annotated from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import TypeAliasType async def some_value() -> int: return 123 DependedValue = TypeAliasType( "DependedValue", Annotated[int, Depends(some_value)], type_params=() ) def test_pep695_type_dependencies(): app = FastAPI() @app.get("/") async def get_with_dep(value: DependedValue) -> str: # noqa return f"value: {value}" client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.text == '"value: 123"'
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_dependency_pep695.py", "license": "MIT License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_response_dependency.py
"""Test using special types (Response, Request, BackgroundTasks) as dependency annotations. These tests verify that special FastAPI types can be used with Depends() annotations and that the dependency injection 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 Annotated[Response, Depends(...)].""" app = FastAPI() def modify_response(response: Response) -> Response: response.headers["X-Custom"] = "modified" return response @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 resp.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: Response) -> Response: response.headers["X-Custom"] = "modified" return response @app.get("/") def endpoint(response: Response = Depends(modify_response)): return {"status": "ok"} client = TestClient(app) resp = client.get("/") assert resp.status_code == 200 assert resp.json() == {"status": "ok"} assert resp.headers.get("X-Custom") == "modified" def test_response_without_depends(): """Regular Response injection should still work.""" app = FastAPI() @app.get("/") def endpoint(response: Response): response.headers["X-Direct"] = "set" return {"status": "ok"} client = TestClient(app) resp = client.get("/") assert resp.status_code == 200 assert resp.json() == {"status": "ok"} assert resp.headers.get("X-Direct") == "set" def test_response_dependency_chain(): """Response dependency should work in a chain of dependencies.""" app = FastAPI() def first_modifier(response: Response) -> Response: response.headers["X-First"] = "1" return response def second_modifier( response: Annotated[Response, Depends(first_modifier)], ) -> Response: response.headers["X-Second"] = "2" return response @app.get("/") def endpoint(response: Annotated[Response, Depends(second_modifier)]): return {"status": "ok"} client = TestClient(app) resp = client.get("/") assert resp.status_code == 200 assert resp.headers.get("X-First") == "1" assert resp.headers.get("X-Second") == "2" def test_response_dependency_returns_different_response_instance(): """Dependency that returns a different Response instance should work. When a dependency returns a new Response object (e.g., JSONResponse) instead of modifying the injected one, the returned response should be used and any modifications to it in the endpoint should be preserved. """ app = FastAPI() def default_response() -> Response: response = JSONResponse(content={"status": "ok"}) response.headers["X-Custom"] = "initial" return response @app.get("/") def endpoint(response: Annotated[Response, Depends(default_response)]): response.headers["X-Custom"] = "modified" return response client = TestClient(app) resp = client.get("/") assert resp.status_code == 200 assert resp.json() == {"status": "ok"} assert resp.headers.get("X-Custom") == "modified" # Tests for Request type hint with Depends def test_request_with_depends_annotated(): """Request type hint should work in dependency chain.""" app = FastAPI() def extract_request_info(request: Request) -> dict: return { "path": request.url.path, "user_agent": request.headers.get("user-agent", "unknown"), } @app.get("/") def endpoint( info: Annotated[dict, Depends(extract_request_info)], ): return info client = TestClient(app) resp = client.get("/", headers={"user-agent": "test-agent"}) assert resp.status_code == 200 assert resp.json() == {"path": "/", "user_agent": "test-agent"} # Tests for BackgroundTasks type hint with Depends def test_background_tasks_with_depends_annotated(): """BackgroundTasks type hint should work with Annotated[BackgroundTasks, Depends(...)].""" app = FastAPI() task_results = [] def background_task(message: str): task_results.append(message) def add_background_task(background_tasks: BackgroundTasks) -> BackgroundTasks: background_tasks.add_task(background_task, "from dependency") return background_tasks @app.get("/") def endpoint( background_tasks: Annotated[BackgroundTasks, Depends(add_background_task)], ): background_tasks.add_task(background_task, "from endpoint") return {"status": "ok"} client = TestClient(app) resp = client.get("/") assert resp.status_code == 200 assert "from dependency" in task_results assert "from endpoint" in task_results
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_response_dependency.py", "license": "MIT License", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_stringified_annotation_dependency_py314.py
from typing import TYPE_CHECKING, Annotated from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from .utils import needs_py314 if TYPE_CHECKING: # pragma: no cover class DummyUser: ... @needs_py314 def test_stringified_annotation(): # python3.14: Use forward reference without "from __future__ import annotations" async def get_current_user() -> DummyUser | None: return None app = FastAPI() client = TestClient(app) @app.get("/") async def get( current_user: Annotated[DummyUser | None, Depends(get_current_user)], ) -> str: return "hello world" response = client.get("/") assert response.status_code == 200
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_stringified_annotation_dependency_py314.py", "license": "MIT License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_additional_responses_union_duplicate_anyof.py
""" Regression test: Ensure app-level responses with Union models and content/examples don't accumulate duplicate $ref entries in anyOf arrays. See https://github.com/fastapi/fastapi/pull/14463 """ from fastapi import FastAPI from fastapi.testclient import TestClient from inline_snapshot import snapshot from pydantic import BaseModel class ModelA(BaseModel): a: str class ModelB(BaseModel): b: str app = FastAPI( responses={ 500: { "model": ModelA | ModelB, "content": {"application/json": {"examples": {"Case A": {"value": "a"}}}}, } } ) @app.get("/route1") async def route1(): pass # pragma: no cover @app.get("/route2") async def route2(): pass # pragma: no cover client = TestClient(app) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/route1": { "get": { "summary": "Route1", "operationId": "route1_route1_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "500": { "description": "Internal Server Error", "content": { "application/json": { "schema": { "anyOf": [ {"$ref": "#/components/schemas/ModelA"}, {"$ref": "#/components/schemas/ModelB"}, ], "title": "Response 500 Route1 Route1 Get", }, "examples": {"Case A": {"value": "a"}}, } }, }, }, } }, "/route2": { "get": { "summary": "Route2", "operationId": "route2_route2_get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "500": { "description": "Internal Server Error", "content": { "application/json": { "schema": { "anyOf": [ {"$ref": "#/components/schemas/ModelA"}, {"$ref": "#/components/schemas/ModelB"}, ], "title": "Response 500 Route2 Route2 Get", }, "examples": {"Case A": {"value": "a"}}, } }, }, }, } }, }, "components": { "schemas": { "ModelA": { "properties": {"a": {"type": "string", "title": "A"}}, "type": "object", "required": ["a"], "title": "ModelA", }, "ModelB": { "properties": {"b": {"type": "string", "title": "B"}}, "type": "object", "required": ["b"], "title": "ModelB", }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_additional_responses_union_duplicate_anyof.py", "license": "MIT License", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/doc_parsing_utils.py
import re from typing import TypedDict CODE_INCLUDE_RE = re.compile(r"^\{\*\s*(\S+)\s*(.*)\*\}$") CODE_INCLUDE_PLACEHOLDER = "<CODE_INCLUDE>" HEADER_WITH_PERMALINK_RE = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})?\s*$") HEADER_LINE_RE = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$") TIANGOLO_COM = "https://fastapi.tiangolo.com" ASSETS_URL_PREFIXES = ("/img/", "/css/", "/js/") MARKDOWN_LINK_RE = re.compile( r"(?<!\\)(?<!\!)" # not an image ![...] and not escaped \[...] r"\[(?P<text>.*?)\]" # link text (non-greedy) r"\(" r"(?P<url>[^)\s]+)" # url (no spaces and `)`) r'(?:\s+["\'](?P<title>.*?)["\'])?' # optional title in "" or '' r"\)" r"(?:\s*\{(?P<attrs>[^}]*)\})?" # optional attributes in {} ) HTML_LINK_RE = re.compile(r"<a\s+[^>]*>.*?</a>") HTML_LINK_TEXT_RE = re.compile(r"<a\b([^>]*)>(.*?)</a>") HTML_LINK_OPEN_TAG_RE = re.compile(r"<a\b([^>]*)>") HTML_ATTR_RE = re.compile(r'(\w+)\s*=\s*([\'"])(.*?)\2') CODE_BLOCK_LANG_RE = re.compile(r"^`{3,4}([\w-]*)", re.MULTILINE) SLASHES_COMMENT_RE = re.compile( r"^(?P<code>.*?)(?P<comment>(?:(?<= )// .*)|(?:^// .*))?$" ) HASH_COMMENT_RE = re.compile(r"^(?P<code>.*?)(?P<comment>(?:(?<= )# .*)|(?:^# .*))?$") class CodeIncludeInfo(TypedDict): line_no: int line: str class HeaderPermalinkInfo(TypedDict): line_no: int hashes: str title: str permalink: str class MarkdownLinkInfo(TypedDict): line_no: int url: str text: str title: str | None attributes: str | None full_match: str class HTMLLinkAttribute(TypedDict): name: str quote: str value: str class HtmlLinkInfo(TypedDict): line_no: int full_tag: str attributes: list[HTMLLinkAttribute] text: str class MultilineCodeBlockInfo(TypedDict): lang: str start_line_no: int content: list[str] # Code includes # -------------------------------------------------------------------------------------- def extract_code_includes(lines: list[str]) -> list[CodeIncludeInfo]: """ Extract lines that contain code includes. Return list of CodeIncludeInfo, where each dict contains: - `line_no` - line number (1-based) - `line` - text of the line """ includes: list[CodeIncludeInfo] = [] for line_no, line in enumerate(lines, start=1): if CODE_INCLUDE_RE.match(line): includes.append(CodeIncludeInfo(line_no=line_no, line=line)) return includes def replace_code_includes_with_placeholders(text: list[str]) -> list[str]: """ Replace code includes with placeholders. """ modified_text = text.copy() includes = extract_code_includes(text) for include in includes: modified_text[include["line_no"] - 1] = CODE_INCLUDE_PLACEHOLDER return modified_text def replace_placeholders_with_code_includes( text: list[str], original_includes: list[CodeIncludeInfo] ) -> list[str]: """ Replace code includes placeholders with actual code includes from the original (English) document. Fail if the number of placeholders does not match the number of original includes. """ code_include_lines = [ line_no for line_no, line in enumerate(text) if line.strip() == CODE_INCLUDE_PLACEHOLDER ] if len(code_include_lines) != len(original_includes): raise ValueError( "Number of code include placeholders does not match the number of code includes " "in the original document " f"({len(code_include_lines)} vs {len(original_includes)})" ) modified_text = text.copy() for i, line_no in enumerate(code_include_lines): modified_text[line_no] = original_includes[i]["line"] return modified_text # Header permalinks # -------------------------------------------------------------------------------------- def extract_header_permalinks(lines: list[str]) -> list[HeaderPermalinkInfo]: """ Extract list of header permalinks from the given lines. Return list of HeaderPermalinkInfo, where each dict contains: - `line_no` - line number (1-based) - `hashes` - string of hashes representing header level (e.g., "###") - `permalink` - permalink string (e.g., "{#permalink}") """ headers: list[HeaderPermalinkInfo] = [] in_code_block3 = False in_code_block4 = False for line_no, line in enumerate(lines, start=1): if not (in_code_block3 or in_code_block4): if line.startswith("```"): count = len(line) - len(line.lstrip("`")) if count == 3: in_code_block3 = True continue elif count >= 4: in_code_block4 = True continue header_match = HEADER_WITH_PERMALINK_RE.match(line) if header_match: hashes, title, permalink = header_match.groups() headers.append( HeaderPermalinkInfo( hashes=hashes, line_no=line_no, permalink=permalink, title=title ) ) elif in_code_block3: if line.startswith("```"): count = len(line) - len(line.lstrip("`")) if count == 3: in_code_block3 = False continue elif in_code_block4: if line.startswith("````"): count = len(line) - len(line.lstrip("`")) if count >= 4: in_code_block4 = False continue return headers def remove_header_permalinks(lines: list[str]) -> list[str]: """ Remove permalinks from headers in the given lines. """ modified_lines: list[str] = [] for line in lines: header_match = HEADER_WITH_PERMALINK_RE.match(line) if header_match: hashes, title, _permalink = header_match.groups() modified_line = f"{hashes} {title}" modified_lines.append(modified_line) else: modified_lines.append(line) return modified_lines def replace_header_permalinks( text: list[str], header_permalinks: list[HeaderPermalinkInfo], original_header_permalinks: list[HeaderPermalinkInfo], ) -> list[str]: """ Replace permalinks in the given text with the permalinks from the original document. Fail if the number or level of headers does not match the original. """ modified_text: list[str] = text.copy() if len(header_permalinks) != len(original_header_permalinks): raise ValueError( "Number of headers with permalinks does not match the number in the " "original document " f"({len(header_permalinks)} vs {len(original_header_permalinks)})" ) for header_no in range(len(header_permalinks)): header_info = header_permalinks[header_no] original_header_info = original_header_permalinks[header_no] if header_info["hashes"] != original_header_info["hashes"]: raise ValueError( "Header levels do not match between document and original document" f" (found {header_info['hashes']}, expected {original_header_info['hashes']})" f" for header №{header_no + 1} in line {header_info['line_no']}" ) line_no = header_info["line_no"] - 1 hashes = header_info["hashes"] title = header_info["title"] permalink = original_header_info["permalink"] modified_text[line_no] = f"{hashes} {title}{permalink}" return modified_text # Markdown links # -------------------------------------------------------------------------------------- def extract_markdown_links(lines: list[str]) -> list[MarkdownLinkInfo]: """ Extract all markdown links from the given lines. Return list of MarkdownLinkInfo, where each dict contains: - `line_no` - line number (1-based) - `url` - link URL - `text` - link text - `title` - link title (if any) """ links: list[MarkdownLinkInfo] = [] for line_no, line in enumerate(lines, start=1): for m in MARKDOWN_LINK_RE.finditer(line): links.append( MarkdownLinkInfo( line_no=line_no, url=m.group("url"), text=m.group("text"), title=m.group("title"), attributes=m.group("attrs"), full_match=m.group(0), ) ) return links def _add_lang_code_to_url(url: str, lang_code: str) -> str: if url.startswith(TIANGOLO_COM): rel_url = url[len(TIANGOLO_COM) :] if not rel_url.startswith(ASSETS_URL_PREFIXES): url = url.replace(TIANGOLO_COM, f"{TIANGOLO_COM}/{lang_code}") return url def _construct_markdown_link( url: str, text: str, title: str | None, attributes: str | None, lang_code: str, ) -> str: """ Construct a markdown link, adjusting the URL for the given language code if needed. """ url = _add_lang_code_to_url(url, lang_code) if title: link = f'[{text}]({url} "{title}")' else: link = f"[{text}]({url})" if attributes: link += f"{{{attributes}}}" return link def replace_markdown_links( text: list[str], links: list[MarkdownLinkInfo], original_links: list[MarkdownLinkInfo], lang_code: str, ) -> list[str]: """ Replace markdown links in the given text with the original links. Fail if the number of links does not match the original. """ if len(links) != len(original_links): raise ValueError( "Number of markdown links does not match the number in the " "original document " f"({len(links)} vs {len(original_links)})" ) modified_text = text.copy() for i, link_info in enumerate(links): link_text = link_info["text"] link_title = link_info["title"] original_link_info = original_links[i] # Replace replacement_link = _construct_markdown_link( url=original_link_info["url"], text=link_text, title=link_title, attributes=original_link_info["attributes"], lang_code=lang_code, ) line_no = link_info["line_no"] - 1 modified_line = modified_text[line_no] modified_line = modified_line.replace( link_info["full_match"], replacement_link, 1 ) modified_text[line_no] = modified_line return modified_text # HTML links # -------------------------------------------------------------------------------------- def extract_html_links(lines: list[str]) -> list[HtmlLinkInfo]: """ Extract all HTML links from the given lines. Return list of HtmlLinkInfo, where each dict contains: - `line_no` - line number (1-based) - `full_tag` - full HTML link tag - `attributes` - list of HTMLLinkAttribute (name, quote, value) - `text` - link text """ links = [] for line_no, line in enumerate(lines, start=1): for html_link in HTML_LINK_RE.finditer(line): link_str = html_link.group(0) link_text_match = HTML_LINK_TEXT_RE.match(link_str) assert link_text_match is not None link_text = link_text_match.group(2) assert isinstance(link_text, str) link_open_tag_match = HTML_LINK_OPEN_TAG_RE.match(link_str) assert link_open_tag_match is not None link_open_tag = link_open_tag_match.group(1) assert isinstance(link_open_tag, str) attributes: list[HTMLLinkAttribute] = [] for attr_name, attr_quote, attr_value in re.findall( HTML_ATTR_RE, link_open_tag ): assert isinstance(attr_name, str) assert isinstance(attr_quote, str) assert isinstance(attr_value, str) attributes.append( HTMLLinkAttribute( name=attr_name, quote=attr_quote, value=attr_value ) ) links.append( HtmlLinkInfo( line_no=line_no, full_tag=link_str, attributes=attributes, text=link_text, ) ) return links def _construct_html_link( link_text: str, attributes: list[HTMLLinkAttribute], lang_code: str, ) -> str: """ Reconstruct HTML link, adjusting the URL for the given language code if needed. """ attributes_upd: list[HTMLLinkAttribute] = [] for attribute in attributes: if attribute["name"] == "href": original_url = attribute["value"] url = _add_lang_code_to_url(original_url, lang_code) attributes_upd.append( HTMLLinkAttribute(name="href", quote=attribute["quote"], value=url) ) else: attributes_upd.append(attribute) attrs_str = " ".join( f"{attribute['name']}={attribute['quote']}{attribute['value']}{attribute['quote']}" for attribute in attributes_upd ) return f"<a {attrs_str}>{link_text}</a>" def replace_html_links( text: list[str], links: list[HtmlLinkInfo], original_links: list[HtmlLinkInfo], lang_code: str, ) -> list[str]: """ Replace HTML links in the given text with the links from the original document. Adjust URLs for the given language code. Fail if the number of links does not match the original. """ if len(links) != len(original_links): raise ValueError( "Number of HTML links does not match the number in the " "original document " f"({len(links)} vs {len(original_links)})" ) modified_text = text.copy() for link_index, link in enumerate(links): original_link_info = original_links[link_index] # Replace in the document text replacement_link = _construct_html_link( link_text=link["text"], attributes=original_link_info["attributes"], lang_code=lang_code, ) line_no = link["line_no"] - 1 modified_text[line_no] = modified_text[line_no].replace( link["full_tag"], replacement_link, 1 ) return modified_text # Multiline code blocks # -------------------------------------------------------------------------------------- def get_code_block_lang(line: str) -> str: match = CODE_BLOCK_LANG_RE.match(line) if match: return match.group(1) return "" def extract_multiline_code_blocks(text: list[str]) -> list[MultilineCodeBlockInfo]: blocks: list[MultilineCodeBlockInfo] = [] in_code_block3 = False in_code_block4 = False current_block_lang = "" current_block_start_line = -1 current_block_lines = [] for line_no, line in enumerate(text, start=1): stripped = line.lstrip() # --- Detect opening fence --- if not (in_code_block3 or in_code_block4): if stripped.startswith("```"): current_block_start_line = line_no count = len(stripped) - len(stripped.lstrip("`")) if count == 3: in_code_block3 = True current_block_lang = get_code_block_lang(stripped) current_block_lines = [line] continue elif count >= 4: in_code_block4 = True current_block_lang = get_code_block_lang(stripped) current_block_lines = [line] continue # --- Detect closing fence --- elif in_code_block3: if stripped.startswith("```"): count = len(stripped) - len(stripped.lstrip("`")) if count == 3: current_block_lines.append(line) blocks.append( MultilineCodeBlockInfo( lang=current_block_lang, start_line_no=current_block_start_line, content=current_block_lines, ) ) in_code_block3 = False current_block_lang = "" current_block_start_line = -1 current_block_lines = [] continue current_block_lines.append(line) elif in_code_block4: if stripped.startswith("````"): count = len(stripped) - len(stripped.lstrip("`")) if count >= 4: current_block_lines.append(line) blocks.append( MultilineCodeBlockInfo( lang=current_block_lang, start_line_no=current_block_start_line, content=current_block_lines, ) ) in_code_block4 = False current_block_lang = "" current_block_start_line = -1 current_block_lines = [] continue current_block_lines.append(line) return blocks def _split_hash_comment(line: str) -> tuple[str, str | None]: match = HASH_COMMENT_RE.match(line) if match: code = match.group("code").rstrip() comment = match.group("comment") return code, comment return line.rstrip(), None def _split_slashes_comment(line: str) -> tuple[str, str | None]: match = SLASHES_COMMENT_RE.match(line) if match: code = match.group("code").rstrip() comment = match.group("comment") return code, comment return line, None def replace_multiline_code_block( block_a: MultilineCodeBlockInfo, block_b: MultilineCodeBlockInfo ) -> list[str]: """ Replace multiline code block `a` with block `b` leaving comments intact. Syntax of comments depends on the language of the code block. Raises ValueError if the blocks are not compatible (different languages or different number of lines). """ start_line = block_a["start_line_no"] end_line_no = start_line + len(block_a["content"]) - 1 if block_a["lang"] != block_b["lang"]: raise ValueError( f"Code block (lines {start_line}-{end_line_no}) " "has different language than the original block " f"('{block_a['lang']}' vs '{block_b['lang']}')" ) if len(block_a["content"]) != len(block_b["content"]): raise ValueError( f"Code block (lines {start_line}-{end_line_no}) " "has different number of lines than the original block " f"({len(block_a['content'])} vs {len(block_b['content'])})" ) block_language = block_a["lang"].lower() if block_language in {"mermaid"}: if block_a != block_b: print( f"Skipping mermaid code block replacement (lines {start_line}-{end_line_no}). " "This should be checked manually." ) return block_a["content"].copy() # We don't handle mermaid code blocks for now code_block: list[str] = [] for line_a, line_b in zip(block_a["content"], block_b["content"], strict=False): line_a_comment: str | None = None line_b_comment: str | None = None # Handle comments based on language if block_language in { "python", "py", "sh", "bash", "dockerfile", "requirements", "gitignore", "toml", "yaml", "yml", "hash-style-comments", }: _line_a_code, line_a_comment = _split_hash_comment(line_a) _line_b_code, line_b_comment = _split_hash_comment(line_b) res_line = line_b if line_b_comment: res_line = res_line.replace(line_b_comment, line_a_comment, 1) code_block.append(res_line) elif block_language in {"console", "json", "slash-style-comments"}: _line_a_code, line_a_comment = _split_slashes_comment(line_a) _line_b_code, line_b_comment = _split_slashes_comment(line_b) res_line = line_b if line_b_comment: res_line = res_line.replace(line_b_comment, line_a_comment, 1) code_block.append(res_line) else: code_block.append(line_b) return code_block def replace_multiline_code_blocks_in_text( text: list[str], code_blocks: list[MultilineCodeBlockInfo], original_code_blocks: list[MultilineCodeBlockInfo], ) -> list[str]: """ Update each code block in `text` with the corresponding code block from `original_code_blocks` with comments taken from `code_blocks`. Raises ValueError if the number, language, or shape of code blocks do not match. """ if len(code_blocks) != len(original_code_blocks): raise ValueError( "Number of code blocks does not match the number in the original document " f"({len(code_blocks)} vs {len(original_code_blocks)})" ) modified_text = text.copy() for block, original_block in zip(code_blocks, original_code_blocks, strict=True): updated_content = replace_multiline_code_block(block, original_block) start_line_index = block["start_line_no"] - 1 for i, updated_line in enumerate(updated_content): modified_text[start_line_index + i] = updated_line return modified_text # All checks # -------------------------------------------------------------------------------------- def check_translation( doc_lines: list[str], en_doc_lines: list[str], lang_code: str, auto_fix: bool, path: str, ) -> list[str]: # Fix code includes en_code_includes = extract_code_includes(en_doc_lines) doc_lines_with_placeholders = replace_code_includes_with_placeholders(doc_lines) fixed_doc_lines = replace_placeholders_with_code_includes( doc_lines_with_placeholders, en_code_includes ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing code includes in: {path}") doc_lines = fixed_doc_lines # Fix permalinks en_permalinks = extract_header_permalinks(en_doc_lines) doc_permalinks = extract_header_permalinks(doc_lines) fixed_doc_lines = replace_header_permalinks( doc_lines, doc_permalinks, en_permalinks ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing header permalinks in: {path}") doc_lines = fixed_doc_lines # Fix markdown links en_markdown_links = extract_markdown_links(en_doc_lines) doc_markdown_links = extract_markdown_links(doc_lines) fixed_doc_lines = replace_markdown_links( doc_lines, doc_markdown_links, en_markdown_links, lang_code ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing markdown links in: {path}") doc_lines = fixed_doc_lines # Fix HTML links en_html_links = extract_html_links(en_doc_lines) doc_html_links = extract_html_links(doc_lines) fixed_doc_lines = replace_html_links( doc_lines, doc_html_links, en_html_links, lang_code ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing HTML links in: {path}") doc_lines = fixed_doc_lines # Fix multiline code blocks en_code_blocks = extract_multiline_code_blocks(en_doc_lines) doc_code_blocks = extract_multiline_code_blocks(doc_lines) fixed_doc_lines = replace_multiline_code_blocks_in_text( doc_lines, doc_code_blocks, en_code_blocks ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing multiline code blocks in: {path}") doc_lines = fixed_doc_lines return doc_lines
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/doc_parsing_utils.py", "license": "MIT License", "lines": 595, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
fastapi/fastapi:scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_lines_number_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_lines_number_gt.md")], indirect=True, ) def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_lines_number_gt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Code block (lines 14-18) has different number of lines than the original block (5 vs 4)" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_lines_number_lt.md")], indirect=True, ) def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) # assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_lines_number_lt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Code block (lines 16-18) has different number of lines than the original block (3 vs 4)" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_lines_number_mismatch.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_mermaid.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_mermaid_translated.md")], indirect=True, ) def test_translated(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 0, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_mermaid_translated.md" ).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert ( "Skipping mermaid code block replacement (lines 41-44). This should be checked manually." ) in result.output @pytest.mark.parametrize( "copy_test_files", [ ( f"{data_path}/en_doc.md", f"{data_path}/translated_doc_mermaid_not_translated.md", ) ], indirect=True, ) def test_not_translated(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 0, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_mermaid_not_translated.md" ).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert ("Skipping mermaid code block replacement") not in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_mermaid.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_number_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], indirect=True, ) def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of code blocks does not match the number " "in the original document (6 vs 5)" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_lt.md")], indirect=True, ) def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) # assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_lt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of code blocks does not match the number " "in the original document (4 vs 5)" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_number_mismatch.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_wrong_lang_code.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_wrong_lang_code.md")], indirect=True, ) def test_wrong_lang_code_1(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_wrong_lang_code.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Code block (lines 16-19) has different language than the original block ('yaml' vs 'toml')" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_wrong_lang_code_2.md")], indirect=True, ) def test_wrong_lang_code_2(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_wrong_lang_code_2.md" ).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Code block (lines 16-19) has different language than the original block ('' vs 'toml')" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_wrong_lang_code.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_code_includes/test_number_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_includes/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], indirect=True, ) def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of code include placeholders does not match the number of code includes " "in the original document (4 vs 3)" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_lt.md")], indirect=True, ) def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_lt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of code include placeholders does not match the number of code includes " "in the original document (2 vs 3)" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_code_includes/test_number_mismatch.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_complex_doc/test_compex_doc.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_complex_doc/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc.md")], indirect=True, ) def test_fix(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 0, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = (data_path / "translated_doc_expected.md").read_text("utf-8") assert fixed_content == expected_content assert "Fixing multiline code blocks in" in result.output assert "Fixing markdown links in" in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_complex_doc/test_compex_doc.py", "license": "MIT License", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_header_permalinks/test_header_level_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_header_permalinks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_level_mismatch_1.md")], indirect=True, ) def test_level_mismatch_1(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_level_mismatch_1.md" ).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Header levels do not match between document and original document" " (found #, expected ##) for header №2 in line 5" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_level_mismatch_2.md")], indirect=True, ) def test_level_mismatch_2(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_level_mismatch_2.md" ).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Header levels do not match between document and original document" " (found ##, expected #) for header №4 in line 13" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_level_mismatch.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_header_permalinks/test_header_number_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_header_permalinks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], indirect=True, ) def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of headers with permalinks does not match the number " "in the original document (5 vs 4)" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_lt.md")], indirect=True, ) def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_lt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of headers with permalinks does not match the number " "in the original document (3 vs 4)" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_number_mismatch.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_html_links/test_html_links_number_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path("scripts/tests/test_translation_fixer/test_html_links/data").absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], indirect=True, ) def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of HTML links does not match the number " "in the original document (7 vs 6)" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_lt.md")], indirect=True, ) def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) # assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_lt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of HTML links does not match the number " "in the original document (5 vs 6)" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_html_links/test_html_links_number_mismatch.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_markdown_links/test_mkd_links_number_mismatch.py
from pathlib import Path import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_markdown_links/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], indirect=True, ) def test_gt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of markdown links does not match the number " "in the original document (7 vs 6)" ) in result.output @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_lt.md")], indirect=True, ) def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) # assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_lt.md").read_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of markdown links does not match the number " "in the original document (5 vs 6)" ) in result.output
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/tests/test_translation_fixer/test_markdown_links/test_mkd_links_number_mismatch.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:scripts/translation_fixer.py
import os from collections.abc import Iterable from pathlib import Path from typing import Annotated import typer from scripts.doc_parsing_utils import check_translation non_translated_sections = ( f"reference{os.sep}", "release-notes.md", "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", "management.md", "contributing.md", ) cli = typer.Typer() @cli.callback() def callback(): pass def iter_all_lang_paths(lang_path_root: Path) -> Iterable[Path]: """ Iterate on the markdown files to translate in order of priority. """ first_dirs = [ lang_path_root / "learn", lang_path_root / "tutorial", lang_path_root / "advanced", lang_path_root / "about", lang_path_root / "how-to", ] first_parent = lang_path_root yield from first_parent.glob("*.md") for dir_path in first_dirs: yield from dir_path.rglob("*.md") first_dirs_str = tuple(str(d) for d in first_dirs) for path in lang_path_root.rglob("*.md"): if str(path).startswith(first_dirs_str): continue if path.parent == first_parent: continue yield path def get_all_paths(lang: str): res: list[str] = [] lang_docs_root = Path("docs") / lang / "docs" for path in iter_all_lang_paths(lang_docs_root): relpath = path.relative_to(lang_docs_root) if not str(relpath).startswith(non_translated_sections): res.append(str(relpath)) return res def process_one_page(path: Path) -> bool: """ Fix one translated document by comparing it to the English version. Returns True if processed successfully, False otherwise. """ try: lang_code = path.parts[1] if lang_code == "en": print(f"Skipping English document: {path}") return True en_doc_path = Path("docs") / "en" / Path(*path.parts[2:]) doc_lines = path.read_text(encoding="utf-8").splitlines() en_doc_lines = en_doc_path.read_text(encoding="utf-8").splitlines() doc_lines = check_translation( doc_lines=doc_lines, en_doc_lines=en_doc_lines, lang_code=lang_code, auto_fix=True, path=str(path), ) # Write back the fixed document doc_lines.append("") # Ensure file ends with a newline path.write_text("\n".join(doc_lines), encoding="utf-8") except ValueError as e: print(f"Error processing {path}: {e}") return False return True @cli.command() def fix_all(ctx: typer.Context, language: str): docs = get_all_paths(language) all_good = True for page in docs: doc_path = Path("docs") / language / "docs" / page res = process_one_page(doc_path) all_good = all_good and res if not all_good: raise typer.Exit(code=1) @cli.command() def fix_pages( doc_paths: Annotated[ list[Path], typer.Argument(help="List of paths to documents."), ], ): all_good = True for path in doc_paths: res = process_one_page(path) all_good = all_good and res if not all_good: raise typer.Exit(code=1) if __name__ == "__main__": cli()
{ "repo_id": "fastapi/fastapi", "file_path": "scripts/translation_fixer.py", "license": "MIT License", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
fastapi/fastapi:tests/test_pydantic_v1_error.py
import sys import warnings import pytest from tests.utils import skip_module_if_py_gte_314 if sys.version_info >= (3, 14): skip_module_if_py_gte_314() from fastapi import FastAPI from fastapi.exceptions import PydanticV1NotSupportedError with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) from pydantic.v1 import BaseModel def test_raises_pydantic_v1_model_in_endpoint_param() -> None: class ParamModelV1(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.post("/param") def endpoint(data: ParamModelV1): # pragma: no cover return data def test_raises_pydantic_v1_model_in_return_type() -> None: class ReturnModelV1(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.get("/return") def endpoint() -> ReturnModelV1: # pragma: no cover return ReturnModelV1(name="test") def test_raises_pydantic_v1_model_in_response_model() -> None: class ResponseModelV1(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.get("/response-model", response_model=ResponseModelV1) def endpoint(): # pragma: no cover return {"name": "test"} def test_raises_pydantic_v1_model_in_additional_responses_model() -> None: class ErrorModelV1(BaseModel): detail: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.get( "/responses", response_model=None, responses={400: {"model": ErrorModelV1}} ) def endpoint(): # pragma: no cover return {"ok": True} def test_raises_pydantic_v1_model_in_union() -> None: class ModelV1A(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.post("/union") def endpoint(data: dict | ModelV1A): # pragma: no cover return data def test_raises_pydantic_v1_model_in_sequence() -> None: class ModelV1A(BaseModel): name: str app = FastAPI() with pytest.raises(PydanticV1NotSupportedError): @app.post("/sequence") def endpoint(data: list[ModelV1A]): # pragma: no cover return data
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_pydantic_v1_error.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body/test_tutorial002.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial002_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body.{request.param}") client = TestClient(mod.app) return client @pytest.mark.parametrize("price", ["50.5", 50.5]) def test_post_with_tax(client: TestClient, price: str | float): response = client.post( "/items/", json={"name": "Foo", "price": price, "description": "Some Foo", "tax": 0.3}, ) assert response.status_code == 200 assert response.json() == { "name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.3, "price_with_tax": 50.8, } @pytest.mark.parametrize("price", ["50.5", 50.5]) def test_post_without_tax(client: TestClient, price: str | float): response = client.post( "/items/", json={"name": "Foo", "price": price, "description": "Some Foo"} ) assert response.status_code == 200 assert response.json() == { "name": "Foo", "price": 50.5, "description": "Some Foo", "tax": None, } def test_post_with_no_data(client: TestClient): response = client.post("/items/", json={}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "name"], "msg": "Field required", "input": {}, }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body/test_tutorial002.py", "license": "MIT License", "lines": 153, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body/test_tutorial003.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial003_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body.{request.param}") client = TestClient(mod.app) return client def test_put_all(client: TestClient): response = client.put( "/items/123", json={"name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3}, ) assert response.status_code == 200 assert response.json() == { "item_id": 123, "name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3, } def test_put_only_required(client: TestClient): response = client.put( "/items/123", json={"name": "Foo", "price": 50.1}, ) assert response.status_code == 200 assert response.json() == { "item_id": 123, "name": "Foo", "price": 50.1, "description": None, "tax": None, } def test_put_with_no_data(client: TestClient): response = client.put("/items/123", json={}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "name"], "msg": "Field required", "input": {}, }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body/test_tutorial003.py", "license": "MIT License", "lines": 164, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body/test_tutorial004.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial004_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body.{request.param}") client = TestClient(mod.app) return client def test_put_all(client: TestClient): response = client.put( "/items/123", json={"name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3}, params={"q": "somequery"}, ) assert response.status_code == 200 assert response.json() == { "item_id": 123, "name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3, "q": "somequery", } def test_put_only_required(client: TestClient): response = client.put( "/items/123", json={"name": "Foo", "price": 50.1}, ) assert response.status_code == 200 assert response.json() == { "item_id": 123, "name": "Foo", "price": 50.1, "description": None, "tax": None, } def test_put_with_no_data(client: TestClient): response = client.put("/items/123", json={}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "name"], "msg": "Field required", "input": {}, }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Q", }, "name": "q", "in": "query", }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body/test_tutorial004.py", "license": "MIT License", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_multiple_params/test_tutorial002.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial002_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") client = 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, }, "user": {"username": "johndoe", "full_name": "John Doe"}, }, ) assert response.status_code == 200 assert response.json() == { "item_id": 5, "item": { "name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.1, }, "user": {"username": "johndoe", "full_name": "John Doe"}, } def test_post_required(client: TestClient): response = client.put( "/items/5", json={ "item": {"name": "Foo", "price": 50.5}, "user": {"username": "johndoe"}, }, ) assert response.status_code == 200 assert response.json() == { "item_id": 5, "item": { "name": "Foo", "price": 50.5, "description": None, "tax": None, }, "user": {"username": "johndoe", "full_name": None}, } def test_post_no_body(client: TestClient): response = client.put("/items/5", json=None) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": None, "loc": [ "body", "item", ], "msg": "Field required", "type": "missing", }, { "input": None, "loc": [ "body", "user", ], "msg": "Field required", "type": "missing", }, ], } def test_post_no_item(client: TestClient): response = client.put("/items/5", json={"user": {"username": "johndoe"}}) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": None, "loc": [ "body", "item", ], "msg": "Field required", "type": "missing", }, ], } def test_post_no_user(client: TestClient): response = client.put("/items/5", json={"item": {"name": "Foo", "price": 50.5}}) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": None, "loc": [ "body", "user", ], "msg": "Field required", "type": "missing", }, ], } def test_post_missing_required_field_in_item(client: TestClient): response = client.put( "/items/5", json={"item": {"name": "Foo"}, "user": {"username": "johndoe"}} ) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": {"name": "Foo"}, "loc": [ "body", "item", "price", ], "msg": "Field required", "type": "missing", }, ], } def test_post_missing_required_field_in_user(client: TestClient): response = client.put( "/items/5", json={"item": {"name": "Foo", "price": 50.5}, "user": {"ful_name": "John Doe"}}, ) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": {"ful_name": "John Doe"}, "loc": [ "body", "user", "username", ], "msg": "Field required", "type": "missing", }, ], } def test_post_id_foo(client: TestClient): response = client.put( "/items/foo", json={ "item": {"name": "Foo", "price": 50.5}, "user": {"username": "johndoe"}, }, ) 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": "foo", } ] } def test_openapi_schema(client: TestClient): 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", "paths": { "/items/{item_id}": { "put": { "operationId": "update_item_items__item_id__put", "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_update_item_items__item_id__put", }, }, }, "required": True, }, "responses": { "200": { "content": { "application/json": { "schema": {}, }, }, "description": "Successful Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError", }, }, }, "description": "Validation Error", }, }, "summary": "Update Item", }, }, }, "components": { "schemas": { "Body_update_item_items__item_id__put": { "properties": { "item": { "$ref": "#/components/schemas/Item", }, "user": { "$ref": "#/components/schemas/User", }, }, "required": [ "item", "user", ], "title": "Body_update_item_items__item_id__put", "type": "object", }, "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError", }, "title": "Detail", "type": "array", }, }, "title": "HTTPValidationError", "type": "object", }, "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": {"title": "Price", "type": "number"}, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "User": { "properties": { "username": { "title": "Username", "type": "string", }, "full_name": { "title": "Full Name", "anyOf": [{"type": "string"}, {"type": "null"}], }, }, "required": [ "username", ], "title": "User", "type": "object", }, "ValidationError": { "properties": { "ctx": {"title": "Context", "type": "object"}, "input": {"title": "Input"}, "loc": { "items": { "anyOf": [ { "type": "string", }, { "type": "integer", }, ], }, "title": "Location", "type": "array", }, "msg": { "title": "Message", "type": "string", }, "type": { "title": "Error Type", "type": "string", }, }, "required": [ "loc", "msg", "type", ], "title": "ValidationError", "type": "object", }, }, }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_multiple_params/test_tutorial002.py", "license": "MIT License", "lines": 342, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_multiple_params/test_tutorial004.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial004_py310", marks=needs_py310), pytest.param("tutorial004_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") client = TestClient(mod.app) return client def test_put_all(client: TestClient): response = client.put( "/items/5", json={ "importance": 2, "item": {"name": "Foo", "price": 50.5}, "user": {"username": "Dave"}, }, params={"q": "somequery"}, ) assert response.status_code == 200 assert response.json() == { "item_id": 5, "importance": 2, "item": { "name": "Foo", "price": 50.5, "description": None, "tax": None, }, "user": {"username": "Dave", "full_name": None}, "q": "somequery", } def test_put_only_required(client: TestClient): response = client.put( "/items/5", json={ "importance": 2, "item": {"name": "Foo", "price": 50.5}, "user": {"username": "Dave"}, }, ) assert response.status_code == 200 assert response.json() == { "item_id": 5, "importance": 2, "item": { "name": "Foo", "price": 50.5, "description": None, "tax": None, }, "user": {"username": "Dave", "full_name": None}, } def test_put_missing_body(client: TestClient): response = client.put("/items/5") assert response.status_code == 422 assert response.json() == { "detail": [ { "input": None, "loc": [ "body", "item", ], "msg": "Field required", "type": "missing", }, { "input": None, "loc": [ "body", "user", ], "msg": "Field required", "type": "missing", }, { "input": None, "loc": [ "body", "importance", ], "msg": "Field required", "type": "missing", }, ], } def test_put_empty_body(client: TestClient): response = client.put("/items/5", json={}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "item"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, }, ] } def test_put_invalid_importance(client: TestClient): response = client.put( "/items/5", json={ "importance": 0, "item": {"name": "Foo", "price": 50.5}, "user": {"username": "Dave"}, }, ) assert response.status_code == 422 assert response.json() == { "detail": [ { "loc": ["body", "importance"], "msg": "Input should be greater than 0", "type": "greater_than", "input": 0, "ctx": {"gt": 0}, }, ], } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "integer"}, "name": "item_id", "in": "path", }, { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Q", }, "name": "q", "in": "query", }, ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_update_item_items__item_id__put" } } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": {"title": "Price", "type": "number"}, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, }, "User": { "title": "User", "required": ["username"], "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, "full_name": { "title": "Full Name", "anyOf": [{"type": "string"}, {"type": "null"}], }, }, }, "Body_update_item_items__item_id__put": { "title": "Body_update_item_items__item_id__put", "required": ["item", "user", "importance"], "type": "object", "properties": { "item": {"$ref": "#/components/schemas/Item"}, "user": {"$ref": "#/components/schemas/User"}, "importance": { "title": "Importance", "type": "integer", "exclusiveMinimum": 0.0, }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_multiple_params/test_tutorial004.py", "license": "MIT License", "lines": 278, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_multiple_params/test_tutorial005.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial005_py310", marks=needs_py310), pytest.param("tutorial005_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") client = 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, }, }, ) assert response.status_code == 200 assert response.json() == { "item_id": 5, "item": { "name": "Foo", "price": 50.5, "description": "Some Foo", "tax": 0.1, }, } def test_post_required(client: TestClient): response = client.put( "/items/5", json={ "item": {"name": "Foo", "price": 50.5}, }, ) assert response.status_code == 200 assert response.json() == { "item_id": 5, "item": { "name": "Foo", "price": 50.5, "description": None, "tax": None, }, } def test_post_no_body(client: TestClient): response = client.put("/items/5", json=None) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": None, "loc": [ "body", "item", ], "msg": "Field required", "type": "missing", }, ], } def test_post_like_not_embeded(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "price": 50.5, }, ) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": None, "loc": [ "body", "item", ], "msg": "Field required", "type": "missing", }, ], } def test_post_missing_required_field_in_item(client: TestClient): response = client.put( "/items/5", json={"item": {"name": "Foo"}, "user": {"username": "johndoe"}} ) assert response.status_code == 422 assert response.json() == { "detail": [ { "input": {"name": "Foo"}, "loc": [ "body", "item", "price", ], "msg": "Field required", "type": "missing", }, ], } def test_openapi_schema(client: TestClient): 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", "paths": { "/items/{item_id}": { "put": { "operationId": "update_item_items__item_id__put", "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_update_item_items__item_id__put", }, }, }, "required": True, }, "responses": { "200": { "content": { "application/json": { "schema": {}, }, }, "description": "Successful Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError", }, }, }, "description": "Validation Error", }, }, "summary": "Update Item", }, }, }, "components": { "schemas": { "Body_update_item_items__item_id__put": { "properties": { "item": { "$ref": "#/components/schemas/Item", }, }, "required": ["item"], "title": "Body_update_item_items__item_id__put", "type": "object", }, "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError", }, "title": "Detail", "type": "array", }, }, "title": "HTTPValidationError", "type": "object", }, "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": {"title": "Price", "type": "number"}, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "properties": { "ctx": {"title": "Context", "type": "object"}, "input": {"title": "Input"}, "loc": { "items": { "anyOf": [ { "type": "string", }, { "type": "integer", }, ], }, "title": "Location", "type": "array", }, "msg": { "title": "Message", "type": "string", }, "type": { "title": "Error Type", "type": "string", }, }, "required": [ "loc", "msg", "type", ], "title": "ValidationError", "type": "object", }, }, }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_multiple_params/test_tutorial005.py", "license": "MIT License", "lines": 258, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py
import importlib import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from inline_snapshot import Is, snapshot from ...utils import needs_py310 UNTYPED_LIST_SCHEMA = {"type": "array", "items": {}} LIST_OF_STR_SCHEMA = {"type": "array", "items": {"type": "string"}} SET_OF_STR_SCHEMA = {"type": "array", "items": {"type": "string"}, "uniqueItems": True} @pytest.fixture( name="mod_name", params=[ pytest.param("tutorial001_py310", marks=needs_py310), pytest.param("tutorial002_py310", marks=needs_py310), pytest.param("tutorial003_py310", marks=needs_py310), ], ) def get_mod_name(request: pytest.FixtureRequest): return request.param @pytest.fixture(name="client") def get_client(mod_name: str): mod = importlib.import_module(f"docs_src.body_nested_models.{mod_name}") client = TestClient(mod.app) return client def test_put_all(client: TestClient, mod_name: str): if mod_name.startswith("tutorial003"): tags_expected = IsList("foo", "bar", check_order=False) else: tags_expected = ["foo", "bar", "foo"] response = client.put( "/items/123", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": ["foo", "bar", "foo"], }, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 123, "item": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": tags_expected, }, } def test_put_only_required(client: TestClient): response = client.put( "/items/5", json={"name": "Foo", "price": 35.4}, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 5, "item": { "name": "Foo", "description": None, "price": 35.4, "tax": None, "tags": [], }, } def test_put_empty_body(client: TestClient): response = client.put( "/items/5", json={}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required(client: TestClient): response = client.put( "/items/5", json={"description": "A very nice Item"}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {"description": "A very nice Item"}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {"description": "A very nice Item"}, "msg": "Field required", "type": "missing", }, ] } def test_openapi_schema(client: TestClient, mod_name: str): tags_schema = {"default": [], "title": "Tags"} if mod_name.startswith("tutorial001"): tags_schema.update(UNTYPED_LIST_SCHEMA) elif mod_name.startswith("tutorial002"): tags_schema.update(LIST_OF_STR_SCHEMA) elif mod_name.startswith("tutorial003"): tags_schema.update(SET_OF_STR_SCHEMA) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", } } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": { "title": "Price", "type": "number", }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, "tags": Is(tags_schema), }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py", "license": "MIT License", "lines": 233, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_nested_models/test_tutorial004.py
import importlib import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial004_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") client = TestClient(mod.app) return client def test_put_all(client: TestClient): response = client.put( "/items/123", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": ["foo", "bar", "foo"], "image": {"url": "http://example.com/image.png", "name": "example image"}, }, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 123, "item": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": IsList("foo", "bar", check_order=False), "image": {"url": "http://example.com/image.png", "name": "example image"}, }, } def test_put_only_required(client: TestClient): response = client.put( "/items/5", json={"name": "Foo", "price": 35.4}, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 5, "item": { "name": "Foo", "description": None, "price": 35.4, "tax": None, "tags": [], "image": None, }, } def test_put_empty_body(client: TestClient): response = client.put( "/items/5", json={}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required_in_item(client: TestClient): response = client.put( "/items/5", json={"description": "A very nice Item"}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {"description": "A very nice Item"}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {"description": "A very nice Item"}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required_in_image(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "price": 35.4, "image": {"url": "http://example.com/image.png"}, }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "image", "name"], "input": {"url": "http://example.com/image.png"}, "msg": "Field required", "type": "missing", }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", } } }, "required": True, }, } } }, "components": { "schemas": { "Image": { "properties": { "url": { "title": "Url", "type": "string", }, "name": { "title": "Name", "type": "string", }, }, "required": ["url", "name"], "title": "Image", "type": "object", }, "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": { "title": "Price", "type": "number", }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, "tags": { "title": "Tags", "default": [], "type": "array", "items": {"type": "string"}, "uniqueItems": True, }, "image": { "anyOf": [ {"$ref": "#/components/schemas/Image"}, {"type": "null"}, ], }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_nested_models/test_tutorial004.py", "license": "MIT License", "lines": 264, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_nested_models/test_tutorial005.py
import importlib import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial005_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") client = TestClient(mod.app) return client def test_put_all(client: TestClient): response = client.put( "/items/123", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": ["foo", "bar", "foo"], "image": {"url": "http://example.com/image.png", "name": "example image"}, }, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 123, "item": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": IsList("foo", "bar", check_order=False), "image": {"url": "http://example.com/image.png", "name": "example image"}, }, } def test_put_only_required(client: TestClient): response = client.put( "/items/5", json={"name": "Foo", "price": 35.4}, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 5, "item": { "name": "Foo", "description": None, "price": 35.4, "tax": None, "tags": [], "image": None, }, } def test_put_empty_body(client: TestClient): response = client.put( "/items/5", json={}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required_in_item(client: TestClient): response = client.put( "/items/5", json={"description": "A very nice Item"}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {"description": "A very nice Item"}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {"description": "A very nice Item"}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required_in_image(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "price": 35.4, "image": {"url": "http://example.com/image.png"}, }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "image", "name"], "input": {"url": "http://example.com/image.png"}, "msg": "Field required", "type": "missing", }, ] } def test_put_wrong_url(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "price": 35.4, "image": {"url": "not a valid url", "name": "example image"}, }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "image", "url"], "input": "not a valid url", "msg": "Input should be a valid URL, relative URL without a base", "type": "url_parsing", "ctx": {"error": "relative URL without a base"}, }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", } } }, "required": True, }, } } }, "components": { "schemas": { "Image": { "properties": { "url": { "title": "Url", "type": "string", "format": "uri", "maxLength": 2083, "minLength": 1, }, "name": { "title": "Name", "type": "string", }, }, "required": ["url", "name"], "title": "Image", "type": "object", }, "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": { "title": "Price", "type": "number", }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, "tags": { "title": "Tags", "default": [], "type": "array", "items": {"type": "string"}, "uniqueItems": True, }, "image": { "anyOf": [ {"$ref": "#/components/schemas/Image"}, {"type": "null"}, ], }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_nested_models/test_tutorial005.py", "license": "MIT License", "lines": 288, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_nested_models/test_tutorial006.py
import importlib import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial006_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") client = TestClient(mod.app) return client def test_put_all(client: TestClient): response = client.put( "/items/123", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": ["foo", "bar", "foo"], "images": [ {"url": "http://example.com/image.png", "name": "example image"} ], }, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 123, "item": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, "tags": IsList("foo", "bar", check_order=False), "images": [ {"url": "http://example.com/image.png", "name": "example image"} ], }, } def test_put_only_required(client: TestClient): response = client.put( "/items/5", json={"name": "Foo", "price": 35.4}, ) assert response.status_code == 200, response.text assert response.json() == { "item_id": 5, "item": { "name": "Foo", "description": None, "price": 35.4, "tax": None, "tags": [], "images": None, }, } def test_put_empty_body(client: TestClient): response = client.put( "/items/5", json={}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_put_images_not_list(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "price": 35.4, "images": {"url": "http://example.com/image.png", "name": "example image"}, }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "images"], "input": { "url": "http://example.com/image.png", "name": "example image", }, "msg": "Input should be a valid list", "type": "list_type", }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "parameters": [ { "in": "path", "name": "item_id", "required": True, "schema": { "title": "Item Id", "type": "integer", }, }, ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Update Item", "operationId": "update_item_items__item_id__put", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", } } }, "required": True, }, } } }, "components": { "schemas": { "Image": { "properties": { "url": { "title": "Url", "type": "string", "format": "uri", "maxLength": 2083, "minLength": 1, }, "name": { "title": "Name", "type": "string", }, }, "required": ["url", "name"], "title": "Image", "type": "object", }, "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": { "title": "Price", "type": "number", }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, "tags": { "title": "Tags", "default": [], "type": "array", "items": {"type": "string"}, "uniqueItems": True, }, "images": { "anyOf": [ { "items": { "$ref": "#/components/schemas/Image", }, "type": "array", }, { "type": "null", }, ], "title": "Images", }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_nested_models/test_tutorial006.py", "license": "MIT License", "lines": 260, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_nested_models/test_tutorial007.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial007_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") client = 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", "price": 35.4, "tax": 3.2, "tags": ["foo"], "images": [ { "url": "http://example.com/image.png", "name": "example image", } ], } ], } response = client.post( "/offers/", json=data, ) assert response.status_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, "items": [ { "name": "Foo", "price": 35.4, "images": [ { "url": "http://example.com/image.png", "name": "example image", } ], } ], }, ) assert response.status_code == 200, response.text assert response.json() == { "name": "Special Offer", "description": None, "price": 38.6, "items": [ { "name": "Foo", "description": None, "price": 35.4, "tax": None, "tags": [], "images": [ { "url": "http://example.com/image.png", "name": "example image", } ], } ], } def test_put_empty_body(client: TestClient): response = client.post( "/offers/", json={}, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "name"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "price"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "items"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required_in_items(client: TestClient): response = client.post( "/offers/", json={ "name": "Special Offer", "price": 38.6, "items": [{}], }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "items", 0, "name"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "items", 0, "price"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_put_missing_required_in_images(client: TestClient): response = client.post( "/offers/", json={ "name": "Special Offer", "price": 38.6, "items": [ {"name": "Foo", "price": 35.4, "images": [{}]}, ], }, ) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", "items", 0, "images", 0, "url"], "input": {}, "msg": "Field required", "type": "missing", }, { "loc": ["body", "items", 0, "images", 0, "name"], "input": {}, "msg": "Field required", "type": "missing", }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/offers/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Offer", "operationId": "create_offer_offers__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Offer", } } }, "required": True, }, } } }, "components": { "schemas": { "Image": { "properties": { "url": { "title": "Url", "type": "string", "format": "uri", "maxLength": 2083, "minLength": 1, }, "name": { "title": "Name", "type": "string", }, }, "required": ["url", "name"], "title": "Image", "type": "object", }, "Item": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": { "title": "Price", "type": "number", }, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, "tags": { "title": "Tags", "default": [], "type": "array", "items": {"type": "string"}, "uniqueItems": True, }, "images": { "anyOf": [ { "items": { "$ref": "#/components/schemas/Image", }, "type": "array", }, { "type": "null", }, ], "title": "Images", }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "Offer": { "properties": { "name": { "title": "Name", "type": "string", }, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": { "title": "Price", "type": "number", }, "items": { "title": "Items", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, }, }, "required": ["name", "price", "items"], "title": "Offer", "type": "object", }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_nested_models/test_tutorial007.py", "license": "MIT License", "lines": 332, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
fastapi/fastapi:tests/test_tutorial/test_body_nested_models/test_tutorial008.py
import importlib import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot @pytest.fixture( name="client", params=[ pytest.param("tutorial008_py310"), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") client = TestClient(mod.app) return client def test_post_body(client: TestClient): data = [ {"url": "http://example.com/", "name": "Example"}, {"url": "http://fastapi.tiangolo.com/", "name": "FastAPI"}, ] response = client.post("/images/multiple", json=data) assert response.status_code == 200, response.text assert response.json() == data def test_post_invalid_list_item(client: TestClient): data = [{"url": "not a valid url", "name": "Example"}] response = client.post("/images/multiple", json=data) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body", 0, "url"], "input": "not a valid url", "msg": "Input should be a valid URL, relative URL without a base", "type": "url_parsing", "ctx": {"error": "relative URL without a base"}, }, ] } def test_post_not_a_list(client: TestClient): data = {"url": "http://example.com/", "name": "Example"} response = client.post("/images/multiple", json=data) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "loc": ["body"], "input": { "name": "Example", "url": "http://example.com/", }, "msg": "Input should be a valid list", "type": "list_type", } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/images/multiple/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Multiple Images", "operationId": "create_multiple_images_images_multiple__post", "requestBody": { "content": { "application/json": { "schema": { "title": "Images", "type": "array", "items": {"$ref": "#/components/schemas/Image"}, } } }, "required": True, }, } } }, "components": { "schemas": { "Image": { "properties": { "url": { "title": "Url", "type": "string", "format": "uri", "maxLength": 2083, "minLength": 1, }, "name": { "title": "Name", "type": "string", }, }, "required": ["url", "name"], "title": "Image", "type": "object", }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, "input": {"title": "Input"}, "ctx": {"title": "Context", "type": "object"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, } }, } )
{ "repo_id": "fastapi/fastapi", "file_path": "tests/test_tutorial/test_body_nested_models/test_tutorial008.py", "license": "MIT License", "lines": 152, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test