Ensure functions have docstrings for documentation
def form_schema(app, path="/"):
1from typing import Annotated, Optional23import pytest4from fastapi import Depends, FastAPI, File, Form, UploadFile5from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE6from fastapi.testclient import TestClient7from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator8910def form_schema(app, path="/"):11 schema = app.openapi()12 body = schema["paths"][path]["post"]["requestBody"]13 content = next(iter(body["content"].values()))14 ref = content["schema"]["$ref"]15 return body, schema["components"]["schemas"][ref.rsplit("/", 1)[-1]]161718def test_optional_form_model():19 app = FastAPI()2021 class Profile(BaseModel):22 name: str23 age: int24 tags: list[str] = Field(default_factory=list)25 enabled: bool = False2627 @app.post("/")28 def submit(profile: Annotated[Profile | None, Form()] = None):29 return profile3031 client = TestClient(app)32 response = client.post("/")33 assert response.status_code == 200, response.text34 assert response.json() is None35 response = client.post("/", data={"name": "Rick", "age": "70", "tags": ["a", "b"]})36 assert response.status_code == 200, response.text37 assert response.json() == {38 "name": "Rick",39 "age": 70,40 "tags": ["a", "b"],41 "enabled": False,42 }43 response = client.post("/", data={"name": "Rick", "age": "invalid"})44 assert response.status_code == 42245 assert response.json()["detail"][0]["loc"] == ["body", "age"]46 for fields in ({"name": ""}, {"tags": "a"}, {"enabled": "false"}):47 response = client.post("/", data=fields)48 assert response.status_code == 42249 assert [error["loc"] for error in response.json()["detail"]] == [50 ["body", "name"],51 ["body", "age"],52 ]535455def test_optional_form_model_with_other_form_field():56 app = FastAPI()5758 class Profile(BaseModel):59 name: str60 age: int6162 @app.post("/")63 def submit(64 token: Annotated[str, Form()],65 profile: Annotated[Profile | None, Form()] = None,66 ):67 return profile6869 client = TestClient(app)70 response = client.post("/", data={"token": "secret"})71 assert response.status_code == 200, response.text72 assert response.json() is None73 response = client.post("/", data={"token": "secret", "name": "Rick", "age": "70"})74 assert response.status_code == 200, response.text75 assert response.json() == {"name": "Rick", "age": 70}76 response = client.post("/", data={"token": "secret", "name": "Rick"})77 assert response.status_code == 42278 assert response.json()["detail"][0]["loc"] == ["body", "age"]798081def test_optional_form_model_in_dependency():82 app = FastAPI()8384 class Profile(BaseModel):85 name: str86 age: int8788 def profile_dependency(profile: Annotated[Profile | None, Form()] = None):89 return profile9091 @app.post("/")92 def submit(93 token: Annotated[str, Form()],94 profile: Annotated[Profile | None, Depends(profile_dependency)],95 ):96 return profile9798 client = TestClient(app)99 response = client.post("/", data={"token": "secret"})100 assert response.status_code == 200, response.text101 assert response.json() is None102 response = client.post("/", data={"token": "secret", "name": "Rick", "age": "70"})103 assert response.status_code == 200, response.text104 assert response.json() == {"name": "Rick", "age": 70}105 response = client.post("/", data={"token": "secret", "name": "Rick"})106 assert response.status_code == 422107 assert response.json()["detail"][0]["loc"] == ["body", "age"]108109110def test_optional_form_model_multipart():111 app = FastAPI()112113 class Profile(BaseModel):114 name: str115 age: int116 tags: list[str] = Field(default_factory=list)117 enabled: bool = False118119 @app.post("/")120 def submit(121 token: Annotated[str, Form()],122 profile: Annotated[Profile | None, Form()] = None,123 ):124 return profile125126 client = TestClient(app)127 response = client.post("/", files={"token": (None, "secret")})128 assert response.status_code == 200, response.text129 assert response.json() is None130 response = client.post(131 "/",132 files=[133 ("token", (None, "secret")),134 ("name", (None, "Rick")),135 ("age", (None, "70")),136 ("tags", (None, "a")),137 ("tags", (None, "b")),138 ],139 )140 assert response.status_code == 200, response.text141 assert response.json() == {142 "name": "Rick",143 "age": 70,144 "tags": ["a", "b"],145 "enabled": False,146 }147 response = client.post(148 "/",149 files={150 "token": (None, "secret"),151 "name": (None, "Rick"),152 "age": (None, "invalid"),153 },154 )155 assert response.status_code == 422156 assert response.json()["detail"][0]["loc"] == ["body", "age"]157 for fields in (158 {"token": (None, "secret"), "name": (None, "")},159 {"token": (None, "secret"), "tags": (None, "a")},160 {"token": (None, "secret"), "enabled": (None, "false")},161 ):162 response = client.post("/", files=fields)163 assert response.status_code == 422164 assert [error["loc"] for error in response.json()["detail"]] == [165 ["body", "name"],166 ["body", "age"],167 ]168169170@pytest.mark.parametrize("extra", ["ignore", "allow", "forbid"])171def test_optional_form_model_schema(extra):172 app = FastAPI()173174 class Profile(BaseModel):175 model_config = ConfigDict(extra=extra)176 name: str177 age: int178 tags: list[str] = Field(default_factory=list)179 enabled: bool = False180181 @app.post("/")182 def submit(profile: Annotated[Profile | None, Form()] = None):183 return profile184185 body, schema = form_schema(app)186 assert "required" not in body187 assert "required" not in schema188 absent = (189 {"maxProperties": 0}190 if extra in ("allow", "forbid")191 else {192 "not": {193 "anyOf": [194 {"required": [name]} for name in ["age", "enabled", "name", "tags"]195 ]196 }197 }198 )199 assert schema["allOf"] == [200 {201 "anyOf": [202 absent,203 {204 "anyOf": [{"$ref": "#/components/schemas/Profile"}],205 "title": "Profile",206 },207 ]208 }209 ]210 assert app.openapi()["components"]["schemas"]["Profile"]["required"] == [211 "name",212 "age",213 ]214 response = TestClient(app).post("/", data={"name": "Rick", "age": "70"})215 assert response.status_code == 200, response.text216217218@pytest.mark.parametrize("extra", ["ignore", "allow", "forbid"])219def test_optional_form_model_with_other_form_field_schema(extra):220 app = FastAPI()221222 class Profile(BaseModel):223 model_config = ConfigDict(extra=extra)224 name: str225 age: int226 tags: list[str] = Field(default_factory=list)227 enabled: bool = False228229 @app.post("/")230 def submit(231 token: Annotated[str, Form()],232 profile: Annotated[Profile | None, Form()] = None,233 ):234 return profile235236 body, schema = form_schema(app)237 assert body["required"] is True238 assert schema["required"] == ["token"]239 absent = (240 {"maxProperties": 0}241 if extra in ("allow", "forbid")242 else {243 "not": {244 "anyOf": [245 {"required": [name]} for name in ["age", "enabled", "name", "tags"]246 ]247 }248 }249 )250 assert schema["allOf"] == [251 {252 "anyOf": [253 absent,254 {255 "anyOf": [{"$ref": "#/components/schemas/Profile"}],256 "title": "Profile",257 },258 ]259 }260 ]261 assert app.openapi()["components"]["schemas"]["Profile"]["required"] == [262 "name",263 "age",264 ]265 response = TestClient(app).post(266 "/", data={"token": "secret", "name": "Rick", "age": "70"}267 )268 assert response.status_code == (422 if extra == "forbid" else 200), response.text269270271@pytest.mark.parametrize("extra", ["ignore", "allow", "forbid"])272@pytest.mark.parametrize("required_name", [False, True])273def test_unknown_fields_and_sibling_models(extra, required_name):274 app = FastAPI()275276 class Profile(BaseModel):277 model_config = ConfigDict(extra=extra)278 name: str = Field() if required_name else Field("default")279 enabled: bool = False280281 class Credentials(BaseModel):282 token: str283284 @app.post("/")285 def submit(286 credentials: Annotated[Credentials, Form()],287 avatar: Annotated[UploadFile | None, File()] = None,288 profile: Annotated[Profile | None, Form()] = None,289 ):290 if profile is not None and avatar is not None:291 assert profile.model_extra is not None292 assert profile.model_extra["avatar"] is avatar293 return {294 **profile.model_dump(exclude={"avatar"}),295 "avatar": {"filename": avatar.filename},296 }297 return profile298299 client = TestClient(app)300 response = client.post(301 "/", data={"token": "secret"}, files={"avatar": ("image.png", b"image")}302 )303 if extra == "ignore":304 assert response.status_code == 200, response.text305 assert response.json() is None306 elif extra == "forbid":307 assert response.status_code == 422308 assert {309 error["loc"][-1]310 for error in response.json()["detail"]311 if error["type"] == "extra_forbidden"312 } == {"token", "avatar"}313 elif required_name:314 assert response.status_code == 422315 assert response.json()["detail"][0]["loc"] == ["body", "name"]316 else:317 assert response.status_code == 200, response.text318 assert response.json()["token"] == "secret"319 assert response.json()["avatar"]["filename"] == "image.png"320 response = client.post("/", data={"token": "secret", "unknown": ["", "a"]})321 if extra == "forbid":322 assert response.status_code == 422323 assert response.json()["detail"][-1]["loc"] == ["body", "unknown"]324 elif extra == "allow" and required_name:325 assert response.status_code == 422326 assert response.json()["detail"][0]["loc"] == ["body", "name"]327 else:328 assert response.status_code == 200, response.text329 assert response.json() == (330 {331 "name": "default",332 "enabled": False,333 "token": "secret",334 "unknown": ["", "a"],335 }336 if extra == "allow"337 else None338 )339 response = client.post("/", data={"token": "secret", "name": ""})340 if required_name or extra == "forbid":341 assert response.status_code == 422342 assert response.json()["detail"][0]["loc"] == [343 "body",344 "name" if required_name else "token",345 ]346 else:347 assert response.status_code == 200, response.text348 assert response.json() == {349 "name": "default",350 "enabled": False,351 **({"token": "secret"} if extra == "allow" else {}),352 }353354355@pytest.mark.parametrize("extra", ["ignore", "allow", "forbid"])356@pytest.mark.parametrize("required_field", [False, True])357def test_required_nullable_model(extra, required_field):358 app = FastAPI()359360 class Settings(BaseModel):361 model_config = ConfigDict(extra=extra)362 name: str = Field() if required_field else Field("default")363364 @app.post("/")365 def submit(settings: Annotated[Settings | None, Form()]):366 return settings367368 @app.post("/plain")369 def plain(settings: Annotated[Settings, Form()]):370 return settings371372 client = TestClient(app)373 response = client.post("/")374 assert response.status_code == 422375 assert response.json()["detail"] == [376 {"type": "missing", "loc": ["body"], "msg": "Field required", "input": None}377 ]378 response = client.post("/", data={"name": ""})379 assert response.status_code == (422 if required_field else 200)380 response = client.post("/", data={"name": "Rick"})381 assert response.status_code == 200, response.text382 assert response.json() == {"name": "Rick"}383 response = client.post("/plain")384 assert response.status_code == (422 if required_field else 200)385 response = client.post("/", data={"unknown": "x"})386 assert response.status_code == (387 200 if extra == "allow" and not required_field else 422388 )389 body, schema = form_schema(app)390 assert body["required"] is True391 assert "required" not in schema392 absent = (393 {"maxProperties": 0}394 if extra in ("allow", "forbid")395 else {"not": {"anyOf": [{"required": ["name"]}]}}396 )397 assert schema["allOf"] == [398 {"not": absent},399 {"anyOf": [{"$ref": "#/components/schemas/Settings"}], "title": "Settings"},400 ]401402403def test_defaults_factories_and_validators():404 app = FastAPI()405 calls = []406407 class Profile(BaseModel):408 name: str = "default"409 enabled: bool = True410 tags: list[str] = Field(default_factory=list)411412 @model_validator(mode="after")413 def validate_name(self):414 calls.append(self.name)415 return self416417 default = Profile(name="parameter default")418419 def factory():420 calls.append("factory")421 return Profile(name="factory default")422423 @app.post("/")424 def submit(profile: Annotated[Profile | None, Form()] = default):425 assert profile is not None426 profile.tags.append("new")427 return profile428429 @app.post("/factory")430 def from_factory(431 profile: Annotated[Profile | None, Form(default_factory=factory)],432 ):433 return profile434435 @app.post("/validated-default")436 def validated_default(437 profile: Annotated[Profile | None, Form(validate_default=True)] = default,438 ):439 return profile440441 client = TestClient(app)442 calls.clear()443 for _ in range(2):444 response = client.post("/")445 assert response.status_code == 200, response.text446 assert response.json() == {447 "name": "parameter default",448 "enabled": True,449 "tags": ["new"],450 }451 assert default.tags == []452 assert calls == []453 for _ in range(2):454 response = client.post("/factory")455 assert response.status_code == 200, response.text456 assert response.json()["enabled"] is True457 assert calls == ["factory", "factory default", "factory", "factory default"]458 calls.clear()459 response = client.post("/factory", data={"name": "submitted"})460 assert response.status_code == 200, response.text461 assert response.json()["enabled"] is True462 assert calls == ["submitted"]463 calls.clear()464 response = client.post("/validated-default")465 assert response.status_code == 200, response.text466 assert calls == ["parameter default"]467 assert "required" not in form_schema(app)[0]468 assert "required" not in form_schema(app, "/factory")[0]469470471@pytest.mark.parametrize("key", ["display_name", "nickname", "name"])472def test_aliases_and_shared_fields(key):473 app = FastAPI()474475 class Profile(BaseModel):476 model_config = ConfigDict(extra="forbid", populate_by_name=True)477 name: str = Field(validation_alias=AliasChoices("display_name", "nickname"))478479 class Other(BaseModel):480 name: str481 age: int482483 @app.post("/")484 def submit(485 profile: Annotated[Profile | None, Form()] = None,486 other: Annotated[Other | None, Form()] = None,487 ):488 return [profile, other]489490 client = TestClient(app)491 response = client.post("/", data={key: "Rick"})492 if key == "name":493 assert response.status_code == 422494 assert response.json()["detail"][0]["loc"] == ["body", "age"]495 else:496 assert response.status_code == 200, response.text497 assert response.json() == [{"name": "Rick"}, None]498 response = client.post("/", data={key: "Rick", "name": "Rick", "age": "70"})499 assert response.status_code == 422500 assert all(501 error["type"] == "extra_forbidden" for error in response.json()["detail"]502 )503 assert response.json()["detail"][-1]["loc"] == ["body", "age"]504505506@pytest.mark.parametrize("alias_choices", [False, True])507@pytest.mark.parametrize("required", [False, True])508def test_shared_alias_activates_group_in_schema(alias_choices, required):509 app = FastAPI()510511 class Profile(BaseModel):512 model_config = ConfigDict(populate_by_name=not alias_choices)513 name: str = Field(514 alias="display_name",515 validation_alias=AliasChoices("display_name", "name")516 if alias_choices517 else None,518 )519 department: str520521 class Account(BaseModel):522 name: str523524 @app.post("/")525 def submit(526 profile: Profile | None = Form(default=... if required else None),527 account: Annotated[Account | None, Form()] = None,528 ):529 return [profile, account]530531 @app.post("/json")532 def json_body(profile: Profile):533 return profile534535 client = TestClient(app)536 response = client.post("/json", json={"name": "Rick", "department": "Science"})537 assert response.status_code == 200, response.text538 assert response.json() == {"display_name": "Rick", "department": "Science"}539 response = client.post("/", data={"name": "Rick"})540 assert response.status_code == 422541 assert response.json()["detail"][0]["loc"] == ["body", "department"]542 response = client.post("/", data={"name": "Rick", "department": "Science"})543 assert response.status_code == 200, response.text544 assert response.json() == [545 {"display_name": "Rick", "department": "Science"},546 {"name": "Rick"},547 ]548 _, schema = form_schema(app)549 model_schema = app.openapi()["components"]["schemas"]["Profile"]550 assert model_schema["required"] == ["display_name", "department"]551 present = schema["allOf"][1] if required else schema["allOf"][0]["anyOf"][1]552 assert present["anyOf"][0] == {553 **model_schema,554 "required": ["department"],555 "allOf": [{"anyOf": [{"required": ["display_name"]}, {"required": ["name"]}]}],556 }557 for key in ("display_name", "name"):558 data = {key: "Rick", "department": "Science"}559 assert client.post("/", data=data).status_code == 200560 assert client.post("/", data={key: "Rick"}).status_code == 422561562563def test_standalone_optional_form_model_alias_schema():564 app = FastAPI()565566 class Profile(BaseModel):567 model_config = ConfigDict(populate_by_name=True)568 name: str = Field(alias="display_name")569570 @app.post("/")571 def submit(profile: Annotated[Profile | None, Form()] = None):572 return profile573574 client = TestClient(app)575 _, schema = form_schema(app)576 present = schema["allOf"][0]["anyOf"][1]["anyOf"][0]577 assert present["required"] == []578 assert present["allOf"] == [579 {"anyOf": [{"required": ["display_name"]}, {"required": ["name"]}]}580 ]581 for data in ({}, {"name": "Rick"}, {"display_name": "Rick"}):582 assert client.post("/", data=data).status_code == 200583584585@pytest.mark.skipif(586 PYDANTIC_VERSION_MINOR_TUPLE < (2, 11),587 reason="validate_by_alias requires Pydantic 2.11+",588)589@pytest.mark.parametrize(590 "field_info",591 [592 Field(alias="display_name"),593 Field(validation_alias=AliasChoices("display_name", "nickname")),594 ],595)596def test_form_model_schema_with_disabled_aliases(field_info):597 app = FastAPI()598599 class Profile(BaseModel):600 model_config = ConfigDict(validate_by_alias=False)601 name: str = field_info602 department: str = "Science"603604 @app.post("/optional")605 def optional(profile: Annotated[Profile | None, Form()] = None):606 return profile.name if profile is not None else None607608 @app.post("/composed")609 def composed(610 profile: Annotated[Profile, Form()], token: Annotated[str, Form()] = "secret"611 ):612 return profile.name613614 @app.post("/json")615 def json_body(profile: Profile):616 return profile617618 client = TestClient(app)619 response = client.post("/json", json={"name": "Rick"})620 assert response.status_code == 200, response.text621 assert response.json() == Profile(name="Rick").model_dump(by_alias=True)622 for path in ("/optional", "/composed"):623 response = client.post(path, data={"name": "Rick"})624 assert response.status_code == 200, response.text625 assert response.json() == "Rick"626 assert client.post("/composed", data={"display_name": "Rick"}).status_code == 422627 _, optional_schema = form_schema(app, "/optional")628 _, composed_schema = form_schema(app, "/composed")629 optional_model = optional_schema["allOf"][0]["anyOf"][1]["anyOf"][0]630 composed_model = composed_schema["allOf"][0]631 assert optional_model == composed_model632 schemas = app.openapi()["components"]["schemas"]633 ref_name = composed_model.get("$ref", "").rsplit("/", 1)[-1]634 composed_model = schemas.get(ref_name, composed_model)635 assert set(composed_model["properties"]) == {"name", "department"}636 assert composed_model["required"] == ["name"]637 assert schemas["Profile"] == Profile.model_json_schema()638639640def test_dependency_override_names():641 app = FastAPI()642643 class Profile(BaseModel):644 model_config = ConfigDict(extra="forbid")645 name: str646647 def dependency(token: Annotated[str, Form()] = "secret"):648 return token649650 def override(new_token: Annotated[str, Form()]):651 return new_token652653 @app.post("/")654 def submit(655 token: Annotated[str, Depends(dependency)],656 profile: Annotated[Profile | None, Form()] = None,657 ):658 return profile659660 client = TestClient(app)661 assert client.post("/").json() is None662 response = client.post("/", data={"token": "secret"})663 assert response.status_code == 422664 assert response.json()["detail"][-1]["loc"] == ["body", "token"]665 app.dependency_overrides[dependency] = override666 response = client.post("/", data={"new_token": "secret"})667 assert response.status_code == 422668 assert response.json()["detail"][-1]["loc"] == ["body", "new_token"]669 assert response.json()["detail"][-1]["type"] == "extra_forbidden"670671672def test_typing_optional():673 app = FastAPI()674675 class Profile(BaseModel):676 name: str677678 @app.post("/")679 def submit(profile: Annotated[Optional[Profile], Form()] = None): # noqa: UP045680 return profile681682 client = TestClient(app)683 assert client.post("/").json() is None684 response = client.post("/", data={"name": "Rick"})685 assert response.status_code == 200, response.text686 assert response.json() == {"name": "Rick"}687688689def test_file_fields_and_empty_upload():690 app = FastAPI()691692 class Attachment(BaseModel):693 content: UploadFile694695 @app.post("/")696 def submit(attachment: Annotated[Attachment | None, Form()] = None):697 if attachment is not None:698 return {699 "filename": attachment.content.filename,700 "size": attachment.content.size,701 }702 return None703704 client = TestClient(app)705 assert client.post("/").json() is None706 response = client.post("/", files={"content": ("empty.txt", b"")})707 assert response.status_code == 200, response.text708 assert response.json() == {"filename": "empty.txt", "size": 0}709 response = client.post(710 "/",711 content=(712 '--boundary\r\nContent-Disposition: form-data; name="content"; '713 'filename=""\r\nContent-Type: application/octet-stream\r\n\r\n'714 "\r\n--boundary--\r\n"715 ),716 headers={"content-type": "multipart/form-data; boundary=boundary"},717 )718 assert response.status_code == 422719 assert response.json()["detail"][0]["loc"] == ["body", "content"]720721722@pytest.mark.parametrize("required", [False, True])723@pytest.mark.parametrize("extra", ["ignore", "allow", "forbid"])724def test_model_without_declared_fields(required, extra):725 app = FastAPI()726727 class Empty(BaseModel):728 model_config = ConfigDict(extra=extra)729730 @app.post("/")731 def submit(model: Empty | None = Form(default=... if required else None)):732 return model733734 client = TestClient(app)735 response = client.post("/")736 assert response.status_code == (422 if required else 200)737 response = client.post("/", data={"unknown": "value"})738 if extra == "forbid" or (required and extra == "ignore"):739 assert response.status_code == 422740 else:741 assert response.status_code == 200, response.text742 assert response.json() == ({"unknown": "value"} if extra == "allow" else None)743 body, schema = form_schema(app)744 assert body.get("required", False) == required745 absent = {"maxProperties": 0} if extra in ("allow", "forbid") else {}746 present = {"anyOf": [{"$ref": "#/components/schemas/Empty"}], "title": "Model"}747 if required:748 assert schema["allOf"] == [{"not": absent}, present]749 else:750 assert schema["allOf"] == [{"anyOf": [absent, present]}]751 assert app.openapi()["components"]["schemas"]["Empty"]["properties"] == {}
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.
Generated by searchcode.com · powered by code_get_file + code_get_findings