    ],
)
def get_client(request: pytest.FixtureRequest):
    mod = importlib.import_module(f"docs_src.server_sent_events.{request.param}")
    client = TestClient(mod.app)
    return client

def test_stream_all_items(client: TestClient):
    response = client.get("/items/stream")
    assert response.status_code == 200, response.text

    data_lines = [
        line for line in response.text.strip().split("\n") if line.startswith("data: ")
    ]
    assert len(data_lines) == 3

    id_lines = [
        lin

ems/stream",
        headers={"last-event-id": "0"},
    )
    assert response.status_code == 200, response.text

    data_lines = [
        line for line in response.text.strip().split("\n") if line.startswith("data: ")
    ]
    assert len(data_lines) ==

e for line in response.text.strip().split("\n") if line.startswith("id: ")
    ]
    assert id_lines == ["id: 0", "id: 1", "id: 2"]

def test_resume_from_last_event_id(client: TestClient):
    response = client.get(
        "/it


.testclient import TestClient

from docs_src.configure_swagger_ui.tutorial001_py310 import app

client = TestClient(app)

def test_swagger_ui():
    response = client.get("/docs")
    assert response.status_code == 200, response.text
    assert '"syntaxHighlight": false' in response.text, (
        "syntaxHighlight should be included and converted to JSON"
    )
    assert '"dom_id": "#swagger-ui"' in response.text, (
        "default configs should be preserved"
    )
    assert "presets: [" in response.t

, (
        "default configs should be preserved"
    )
    assert '"layout": "BaseLayout",' in response.text, (
        "default configs should be preserved"
    )
    assert '"deepLinking": true,' in response.text, (
        "default configs should be pr

ext, "default configs should be preserved"
    assert "SwaggerUIBundle.presets.apis," in response.text, (
        "default configs should be preserved"
    )
    assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text


pytest.param("tutorial003_py310", marks=needs_py310),
        pytest.param("tutorial003_an_py310", marks=needs_py310),
    ],
)
def get_client(request: pytest.FixtureRequest):
    mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")

    client = TestClient(mod.app)
    return client

def test_post_body_example(client: TestClient):
    response = client.put(
        "/items/5",
        json={
            "name": "Foo",
            "description": "A very nice Item",
            "p

se.text
    assert response.json() == snapshot(
        {
            "openapi": "3.1.0",
            "info": {"title": "FastAPI", "version": "0.1.0"},
            "paths": {
                "/items/{item_id}": {
                    "put": {

rice": 35.4,
            "tax": 3.2,
        },
    )
    assert response.status_code == 200

def test_openapi_schema(client: TestClient):
    response = client.get("/openapi.json")
    assert response.status_code == 200, respon


 Any]] = [
    {
        "id": i,
        "name": f"item-{i}",
        "values": list(range(25)),
        "meta": {
            "active": True,
            "group": i % 10,
            "tag": f"t{i % 5}",
        },
    }
    for i in range(300)
]

LARGE_METADATA: dict[str, Any] = {
    "source": "benchmark",
    "version": 1,
    "flags": {"a": True, "b": False, "c": True},
    "notes": ["x" * 50, "y" * 50, "z" * 50],
}

LARGE_PAYLOAD: dict[str, Any] = {"items": LARGE_ITEMS, "metadata": LARGE_METADATA}

d

eIn(BaseModel):
    items: list[dict[str, Any]]
    metadata: dict[str, Any]

class LargeOut(BaseModel):
    items: list[dict[str, Any]]
    metadata: dict[str, Any]

app = FastAPI()

@app.post("/sync/validated", response_model=ItemOut)
def sync_validat

ef dep_a():
    return 40

def dep_b(a: Annotated[int, Depends(dep_a)]):
    return a + 2

class ItemIn(BaseModel):
    name: str
    value: int

class ItemOut(BaseModel):
    name: str
    value: int
    dep: int

class Larg


[str] | None, Header()] = None,
):
    return {"p": p}

class HeaderModelOptionalListStr(BaseModel):
    p: list[str] | None = None

@app.get("/model-optional-list-str")
async def read_model_optional_list_str(
    p: Annotated[HeaderModelOptionalListStr, Header()],
):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/optional-list-str", "/model-optional-list-str"],
)
def test_optional_list_str_schema(path: str):
    assert app.openapi()["paths"][path]["get"]["parameters"] == snapshot(

,
                    ],
                    "title": "P",
                },
                "name": "p",
                "in": "header",
            }
        ]
    )

@pytest.mark.parametrize(
    "path",
    ["/optional-list-str", "/model-optional-lis

       [
            {
                "required": False,
                "schema": {
                    "anyOf": [
                        {"items": {"type": "string"}, "type": "array"},
                        {"type": "null"}


stapi import FastAPI, Path
from fastapi.testclient import TestClient
from inline_snapshot import Is, snapshot

app = FastAPI()

@app.get("/required-str/{p}")
async def read_required_str(p: Annotated[str, Path()]):
    return {"p": p}

@app.get("/required-alias/{p_alias}")
async def read_required_alias(p: Annotated[str, Path(alias="p_alias")]):
    return {"p": p}

@app.get("/required-validation-alias/{p_val_alias}")
def read_required_validation_alias(
    p: Annotated[str, Path(validation_alias="p_val_al

turn {"p": p}

@pytest.mark.parametrize(
    ("path", "expected_name", "expected_title"),
    [
        pytest.param("/required-str/{p}", "p", "P", id="required-str"),
        pytest.param(
            "/required-alias/{p_alias}", "p_alias", "P Alias", id

ias")],
):
    return {"p": p}

@app.get("/required-alias-and-validation-alias/{p_val_alias}")
def read_required_alias_and_validation_alias(
    p: Annotated[str, Path(alias="p_alias", validation_alias="p_val_alias")],
):
    re


r")
async def read_required_str(p: Annotated[str, Form()]):
    return {"p": p}

class FormModelRequiredStr(BaseModel):
    p: str

@app.post("/model-required-str", operation_id="model_required_str")
async def read_model_required_str(p: Annotated[FormModelRequiredStr, Form()]):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],
)
def test_required_str_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_model_name(openapi, p

    "type": "object",
    }

@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],
)
def test_required_str_missing(path: str):
    client = TestClient(app)
    response = client.post(path)
    assert response.status_code == 4

ath)

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {"title": "P", "type": "string"},
        },
        "required": ["p"],
        "title": body_model_name,


ient import TestClient
from inline_snapshot import snapshot

@pytest.fixture(
    name="client",
    params=[
        pytest.param("tutorial003_py310"),
    ],
)
def get_client(request: pytest.FixtureRequest):
    mod = importlib.import_module(f"docs_src.server_sent_events.{request.param}")
    client = TestClient(mod.app)
    return client

def test_stream_logs(client: TestClient):
    response = client.get("/logs/stream")
    assert response.status_code == 200, response.text
    assert response.headers[

ut JSON encoding (no quotes around the string)
    assert data_lines[0] == "data: 2025-01-01 INFO  Application started"
    assert data_lines[1] == "data: 2025-01-01 DEBUG Connected to database"
    assert data_lines[2] == "data: 2025-01-01 WARN  High memo

"content-type"] == "text/event-stream; charset=utf-8"

    data_lines = [
        line for line in response.text.strip().split("\n") if line.startswith("data: ")
    ]
    assert len(data_lines) == 3

    # raw_data is sent witho


mport TestClient

from docs_src.configure_swagger_ui.tutorial003_py310 import app

client = TestClient(app)

def test_swagger_ui():
    response = client.get("/docs")
    assert response.status_code == 200, response.text
    assert '"deepLinking": false,' in response.text, (
        "overridden configs should be preserved"
    )
    assert '"deepLinking": true' not in response.text, (
        "overridden configs should not include the old value"
    )
    assert '"syntaxHighlight": false' not in response.t

figs should be preserved"
    assert "SwaggerUIBundle.presets.apis," in response.text, (
        "default configs should be preserved"
    )
    assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, (
        "default configs should be prese

ext, (
        "not used parameters should not be included"
    )
    assert '"dom_id": "#swagger-ui"' in response.text, (
        "default configs should be preserved"
    )
    assert "presets: [" in response.text, "default con


/compute/", "/b/compute", "/b/compute/"]
)
def test_post(path):
    data = {"a": 2, "b": "foo"}
    response = client.post(path, json=data)
    assert response.status_code == 200, response.text
    assert data == response.json()

@pytest.mark.parametrize(
    "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"]
)
def test_post_invalid(path):
    data = {"a": "bar", "b": "foo"}
    response = client.post(path, json=data)
    assert response.status_code == 422, response.text

def test_openapi_

 "version": "0.1.0"},
            "paths": {
                "/a/compute": {
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Successful Response",

schema():
    response = client.get("/openapi.json")
    assert response.status_code == 200, response.text
    assert response.json() == snapshot(
        {
            "openapi": "3.1.0",
            "info": {"title": "FastAPI",


onal_list_str(
    p: Annotated[list[str] | None, Form()] = None,
):
    return {"p": p}

class FormModelOptionalListStr(BaseModel):
    p: list[str] | None = None

@app.post("/model-optional-list-str", operation_id="model_optional_list_str")
async def read_model_optional_list_str(p: Annotated[FormModelOptionalListStr, Form()]):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/optional-list-str", "/model-optional-list-str"],
)
def test_optional_list_str_schema(path: str):
    openapi =

      {"items": {"type": "string"}, "type": "array"},
                    {"type": "null"},
                ],
                "title": "P",
            },
        },
        "title": body_model_name,
        "type": "object",
    }

@pytest.mark.parametr

 app.openapi()
    body_model_name = get_body_model_name(openapi, path)

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {
                "anyOf": [


ile()]):
    return {"file_size": len(p)}

@app.post("/required-uploadfile", operation_id="required_uploadfile")
async def read_required_uploadfile(p: Annotated[UploadFile, File()]):
    return {"file_size": p.size}

@pytest.mark.parametrize(
    "path",
    [
        "/required-bytes",
        "/required-uploadfile",
    ],
)
def test_required_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_model_name(openapi, path)

    assert app.openapi()["components"]["schemas"][body_mod

: ["p"],
        "title": body_model_name,
        "type": "object",
    }

@pytest.mark.parametrize(
    "path",
    [
        "/required-bytes",
        "/required-uploadfile",
    ],
)
def test_required_missing(path: str):
    client = TestClient(app)

el_name] == {
        "properties": {
            "p": {
                "title": "P",
                "type": "string",
                "contentMediaType": "application/octet-stream",
            },
        },
        "required"


onal_list_str(
    p: Annotated[list[str] | None, Body(embed=True)] = None,
):
    return {"p": p}

class BodyModelOptionalListStr(BaseModel):
    p: list[str] | None = None

@app.post("/model-optional-list-str", operation_id="model_optional_list_str")
async def read_model_optional_list_str(p: BodyModelOptionalListStr):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/optional-list-str", "/model-optional-list-str"],
)
def test_optional_list_str_schema(path: str):
    openapi = app.open

tems": {"type": "string"}, "type": "array"},
                    {"type": "null"},
                ],
                "title": "P",
            },
        },
        "title": body_model_name,
        "type": "object",
    }

def test_optional_list_str_mis

api()
    body_model_name = get_body_model_name(openapi, path)

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {
                "anyOf": [
                    {"i


ed_str")
async def read_required_str(p: Annotated[str, Body(embed=True)]):
    return {"p": p}

class BodyModelRequiredStr(BaseModel):
    p: str

@app.post("/model-required-str", operation_id="model_required_str")
async def read_model_required_str(p: BodyModelRequiredStr):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],
)
def test_required_str_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_model_name(openapi, path)

"type": "object",
    }

@pytest.mark.parametrize("json", [None, {}])
@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],
)
def test_required_str_missing(path: str, json: dict[str, Any] | None):
    client = TestClient(app)

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {"title": "P", "type": "string"},
        },
        "required": ["p"],
        "title": body_model_name,


tapi.testclient import TestClient

from .app import app

def test_recursive():
    client = TestClient(app)
    response = client.get("/items/recursive")
    assert response.status_code == 200, response.text
    assert response.json() == {
        "sub_items": [{"name": "subitem", "sub_items": []}],
        "name": "item",
    }

    response = client.get("/items/recursive-submodel")
    assert response.status_code == 200, response.text
    assert response.json() == {
        "name": "item",
        "sub_i

item",
                "sub_items2": [
                    {
                        "name": "subsubitem",
                        "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}],
                    }
                ],
            }
        ]

tems1": [
            {
                "name": "sub


astAPI()

# =====================================================================================
# Without aliases

@app.get("/optional-str")
async def read_optional_str(p: str | None = None):
    return {"p": p}

class QueryModelOptionalStr(BaseModel):
    p: str | None = None

@app.get("/model-optional-str")
async def read_model_optional_str(p: Annotated[QueryModelOptionalStr, Query()]):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/optional-str", "/model-optional-str"],
)
def t

type": "string"}, {"type": "null"}],
                    "title": "P",
                },
                "name": "p",
                "in": "query",
            }
        ]
    )

@pytest.mark.parametrize(
    "path",
    ["/optional-str", "/model-option

est_optional_str_schema(path: str):
    assert app.openapi()["paths"][path]["get"]["parameters"] == snapshot(
        [
            {
                "required": False,
                "schema": {
                    "anyOf": [{"


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.schema_extra_example.{request.param}")

    client = TestClient(mod.app)
    return client

def test_post_body_example(client: TestClient):
    response = client.put(
        "/items/5",
        json={
            "name": "Foo",
            "description": "A very nice Item",
            "p


None, File()] = None):
    return {"file_size": len(p) if p else None}

@app.post("/optional-uploadfile", operation_id="optional_uploadfile")
async def read_optional_uploadfile(p: Annotated[UploadFile | None, File()] = None):
    return {"file_size": p.size if p else None}

@pytest.mark.parametrize(
    "path",
    [
        "/optional-bytes",
        "/optional-uploadfile",
    ],
)
def test_optional_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_model_name(openapi, path)

                    {"type": "null"},
                ],
                "title": "P",
            }
        },
        "title": body_model_name,
        "type": "object",
    }

@pytest.mark.parametrize(
    "path",
    [
        "/optional-bytes",

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {
                "anyOf": [
                    {"type": "string", "contentMediaType": "application/octet-stream"},


(p: Annotated[str, Cookie()]):
    return {"p": p}

class CookieModelRequiredStr(BaseModel):
    p: str

@app.get("/model-required-str")
async def read_model_required_str(p: Annotated[CookieModelRequiredStr, Cookie()]):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],
)
def test_required_str_schema(path: str):
    assert app.openapi()["paths"][path]["get"]["parameters"] == snapshot(
        [
            {
                "required": True,

)
def test_required_str_missing(path: str):
    client = TestClient(app)
    response = client.get(path)
    assert response.status_code == 422
    assert response.json() == {
        "detail": [
            {
                "type": "missing",

         "schema": {"title": "P", "type": "string"},
                "name": "p",
                "in": "cookie",
            }
        ]
    )

@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],


: Annotated[str | None, Body(embed=True)] = None):
    return {"p": p}

class BodyModelOptionalStr(BaseModel):
    p: str | None = None

@app.post("/model-optional-str", operation_id="model_optional_str")
async def read_model_optional_str(p: BodyModelOptionalStr):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/optional-str", "/model-optional-str"],
)
def test_optional_str_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_model_name(openapi, path)

    asse

       "title": body_model_name,
        "type": "object",
    }

def test_optional_str_missing():
    client = TestClient(app)
    response = client.post("/optional-str")
    assert response.status_code == 200, response.text
    assert response.json() ==

rt app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {
                "anyOf": [{"type": "string"}, {"type": "null"}],
                "title": "P",
            },
        },


astapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class RecursiveItem(BaseModel):
    sub_items: list["RecursiveItem"] = []
    name: str

class RecursiveSubitemInSubmodel(BaseModel):
    sub_items2: list["RecursiveItemViaSubmodel"] = []
    name: str

class RecursiveItemViaSubmodel(BaseModel):
    sub_items1: list[RecursiveSubitemInSubmodel] = []
    name: str

RecursiveItem.model_rebuild()
RecursiveSubitemInSubmodel.model_rebuild()
RecursiveItemViaSubmodel.model_rebuild()

@app.g

model)
def get_recursive_submodel():
    return {
        "name": "item",
        "sub_items1": [
            {
                "name": "subitem",
                "sub_items2": [
                    {
                        "name": "subsubitem",

et("/items/recursive", response_model=RecursiveItem)
def get_recursive():
    return {"name": "item", "sub_items": [{"name": "subitem", "sub_items": []}]}

@app.get("/items/recursive-submodel", response_model=RecursiveItemViaSub


):
    return {"file_size": [len(file) for file in p]}

@app.post("/list-uploadfile", operation_id="list_uploadfile")
async def read_list_uploadfile(p: Annotated[list[UploadFile], File()]):
    return {"file_size": [file.size for file in p]}

@pytest.mark.parametrize(
    "path",
    [
        "/list-bytes",
        "/list-uploadfile",
    ],
)
def test_list_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_model_name(openapi, path)

    assert app.openapi()["components"]["sche

tream",
                },
                "title": "P",
            },
        },
        "required": ["p"],
        "title": body_model_name,
        "type": "object",
    }

@pytest.mark.parametrize(
    "path",
    [
        "/list-bytes",
        "/l

mas"][body_model_name] == {
        "properties": {
            "p": {
                "type": "array",
                "items": {
                    "type": "string",
                    "contentMediaType": "application/octet-s


 None):
    return {"file_size": [len(file) for file in p] if p else None}

@app.post("/optional-list-uploadfile")
async def read_optional_list_uploadfile(
    p: Annotated[list[UploadFile] | None, File()] = None,
):
    return {"file_size": [file.size for file in p] if p else None}

@pytest.mark.parametrize(
    "path",
    [
        "/optional-list-bytes",
        "/optional-list-uploadfile",
    ],
)
def test_optional_list_schema(path: str):
    openapi = app.openapi()
    body_model_name = get_body_mo

                        "items": {
                            "type": "string",
                            "contentMediaType": "application/octet-stream",
                        },
                    },
                    {"type": "null"},

del_name(openapi, path)

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {
                "anyOf": [
                    {
                        "type": "array",


ync def read_required_str(p: Annotated[str, Header()]):
    return {"p": p}

class HeaderModelRequiredStr(BaseModel):
    p: str

@app.get("/model-required-str")
async def read_model_required_str(p: Annotated[HeaderModelRequiredStr, Header()]):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/required-str", "/model-required-str"],
)
def test_required_str_schema(path: str):
    assert app.openapi()["paths"][path]["get"]["parameters"] == snapshot(
        [
            {

, "/model-required-str"],
)
def test_required_str_missing(path: str):
    client = TestClient(app)
    response = client.get(path)
    assert response.status_code == 422
    assert response.json() == {
        "detail": [
            {
                "typ

"required": True,
                "schema": {"title": "P", "type": "string"},
                "name": "p",
                "in": "header",
            }
        ]
    )

@pytest.mark.parametrize(
    "path",
    ["/required-str"


FastAPI()

# =====================================================================================
# Without aliases

@app.get("/optional-str")
async def read_optional_str(p: Annotated[str | None, Cookie()] = None):
    return {"p": p}

class CookieModelOptionalStr(BaseModel):
    p: str | None = None

@app.get("/model-optional-str")
async def read_model_optional_str(p: Annotated[CookieModelOptionalStr, Cookie()]):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/optional-str", "/mode

             "anyOf": [{"type": "string"}, {"type": "null"}],
                    "title": "P",
                },
                "name": "p",
                "in": "cookie",
            }
        ]
    )

@pytest.mark.parametrize(
    "path",
    ["/opt

l-optional-str"],
)
def test_optional_str_schema(path: str):
    assert app.openapi()["paths"][path]["get"]["parameters"] == snapshot(
        [
            {
                "required": False,
                "schema": {


tion_id="required_list_str")
async def read_required_list_str(p: Annotated[list[str], Body(embed=True)]):
    return {"p": p}

class BodyModelRequiredListStr(BaseModel):
    p: list[str]

@app.post("/model-required-list-str", operation_id="model_required_list_str")
def read_model_required_list_str(p: BodyModelRequiredListStr):
    return {"p": p.p}

@pytest.mark.parametrize(
    "path",
    ["/required-list-str", "/model-required-list-str"],
)
def test_required_list_str_schema(path: str):
    openapi = a

,
                "title": "P",
                "type": "array",
            },
        },
        "required": ["p"],
        "title": body_model_name,
        "type": "object",
    }

@pytest.mark.parametrize("json", [None, {}])
@pytest.mark.parametrize(

pp.openapi()
    body_model_name = get_body_model_name(openapi, path)

    assert app.openapi()["components"]["schemas"][body_model_name] == {
        "properties": {
            "p": {
                "items": {"type": "string"}