prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.path_operation_advanced_configuration.{request.param}"
)
client = TestClient(mod.app)
client.headers.clear()
return client
def test_quer... | sert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
| .json() == {
"name": "Foo",
"price": 42,
"description": None,
"tax": None,
"tags": [],
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
as | {
"filepath": "tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py",
"language": "python",
"file_size": 5741,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial002_py310", marks=needs_py310),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
... | esponse.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
def test_query_params_str_validations_q_query(client: TestClient):
response = client.get("/items/", params={"q": "query"})
assert response.status_code == 200
assert respons | items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
def test_query_params_str_validations_q_empty_str(client: TestClient):
response = client.get("/items/", params={"q": ""})
assert response.status_code == 200
assert r | {
"filepath": "tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py",
"language": "python",
"file_size": 5446,
"cut_index": 716,
"middle_length": 229
} |
astapi.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.path_operation_advanced_configuration.tutorial005_py310 import app
client = TestClient(app)
def test_get():
response = client.get("/items/")
assert response.status_code == 200, response.text
def test_openapi_schema():
... | "description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Items",
| nfo": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
| {
"filepath": "tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py",
"language": "python",
"file_size": 1173,
"cut_index": 518,
"middle_length": 229
} |
snapshot
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial005_py310"),
pytest.param("tutorial005_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
cli... | arams={"q": "query"})
assert response.status_code == 200
assert response.json() == {
"items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
"q": "query",
}
def test_query_params_str_validations_q_short(client: TestClient):
res | assert response.json() == {
"items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
"q": "fixedquery",
}
def test_query_params_str_validations_q_query(client: TestClient):
response = client.get("/items/", p | {
"filepath": "tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py",
"language": "python",
"file_size": 4971,
"cut_index": 614,
"middle_length": 229
} |
py310.test_main import client, test_read_main
def test_main():
test_read_main()
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": {"titl... | l Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Main",
"operationId": "read_main__get",
| "description": "Successfu | {
"filepath": "tests/test_tutorial/test_testing/test_main_a.py",
"language": "python",
"file_size": 961,
"cut_index": 582,
"middle_length": 52
} |
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",
... | ent.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,
| = {
"item_id": 123,
"name": "Foo",
"price": 50.1,
"description": "Some Foo",
"tax": 0.3,
"q": "somequery",
}
def test_put_only_required(client: TestClient):
response = cli | {
"filepath": "tests/test_tutorial/test_body/test_tutorial004.py",
"language": "python",
"file_size": 6755,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial002_py310", marks=needs_py310),
pytest.param("tutorial002_an_py310", marks=needs_py310),
pytest.param("tutorial003_py310", marks=needs_py310),
pytest.param("tutorial003_an_py310", marks=needs_py310),
pytest.param("tutorial004_py310", marks=needs_py310),
pyte... | {"item_name": "Foo"},
{"item_name": "Bar"},
{"item_name": "Baz"},
]
},
),
(
"/items?q=foo",
200,
{
"items": [
| lient = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
(
"/items",
200,
{
"items": [
| {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py",
"language": "python",
"file_size": 6477,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial006_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
def test_get_no_headers(client: TestClient):
response = client.get("/items/")
... | "input": None,
},
]
}
def test_get_invalid_one_header(client: TestClient):
response = client.get("/items/", headers={"X-Token": "invalid"})
assert response.status_code == 400, response.text
assert response | n"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
| {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial006.py",
"language": "python",
"file_size": 5436,
"cut_index": 716,
"middle_length": 229
} |
mport importlib
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial008b_py310"),
pytest.param("tutorial008b_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dep... | assert response.json() == {"detail": "Owner error: Rick"}
def test_get_item(client: TestClient):
response = client.get("/items/portal-gun")
assert response.status_code == 200, response.text
assert response.json() == {"description": "Gun to | ode == 404, response.text
assert response.json() == {"detail": "Item not found"}
def test_owner_error(client: TestClient):
response = client.get("/items/plumbus")
assert response.status_code == 400, response.text
| {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial008b.py",
"language": "python",
"file_size": 1032,
"cut_index": 513,
"middle_length": 229
} |
tlib
from types import ModuleType
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial008d_py310"),
pytest.param("tutorial008d_an_py310"),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"... |
assert response.status_code == 200, response.text
assert response.json() == "plumbus"
def test_internal_error(mod: ModuleType):
client = TestClient(mod.app)
with pytest.raises(mod.InternalError) as exc_info:
client.get("/items/po | atus_code == 404, response.text
assert response.json() == {"detail": "Item not found, there's only a plumbus here"}
def test_get(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/items/plumbus") | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial008d.py",
"language": "python",
"file_size": 1395,
"cut_index": 524,
"middle_length": 229
} |
pytest.param("tutorial012_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
def test_get_no_headers_items(client: TestClient):
response = client.get("/items/"... | ",
"input": None,
},
]
}
def test_get_no_headers_users(client: TestClient):
response = client.get("/users/")
assert response.status_code == 422, response.text
assert response.json() == {
"detail | x-token"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial012.py",
"language": "python",
"file_size": 8599,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.query_param_models.{request.param}")
client = TestClient(mod.app)
return client
def t... | "tag2"],
}
def test_query_param_model_defaults(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"limit": 100,
"offset": 0,
"order_by": "created_at | ,
"tags": ["tag1", "tag2"],
},
)
assert response.status_code == 200
assert response.json() == {
"limit": 10,
"offset": 5,
"order_by": "updated_at",
"tags": ["tag1", | {
"filepath": "tests/test_tutorial/test_query_param_models/test_tutorial001.py",
"language": "python",
"file_size": 8024,
"cut_index": 716,
"middle_length": 229
} |
om pathlib import Path
import pytest
from fastapi.testclient import TestClient
from tests.utils import workdir_lock
@pytest.fixture(scope="module")
def client():
static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True)
from docs_src.custom_docs_ui.tutorial002... | ient: TestClient):
response = client.get("/docs/oauth2-redirect")
assert response.status_code == 200, response.text
assert "window.opener.swaggerUIRedirectOauth2" in response.text
@workdir_lock
def test_redoc_html(client: TestClient):
res | s")
assert response.status_code == 200, response.text
assert "/static/swagger-ui-bundle.js" in response.text
assert "/static/swagger-ui.css" in response.text
@workdir_lock
def test_swagger_ui_oauth2_redirect_html(cl | {
"filepath": "tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py",
"language": "python",
"file_size": 1349,
"cut_index": 524,
"middle_length": 229
} |
="client",
params=[
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_operation_configuration.{request.param}"
)
return TestClient(mod.app)
def test_post_items(clie... | ce": 42.0,
"tax": 3.2,
"tags": IsList("bar", "baz", check_order=False),
}
def test_get_items(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == | "tax": 3.2,
"tags": ["bar", "baz"],
},
)
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"description": "Item description",
"pri | {
"filepath": "tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py",
"language": "python",
"file_size": 8557,
"cut_index": 716,
"middle_length": 229
} |
y310
DESCRIPTIONS = {
"tutorial003": "Create an item with all the information, name, description, price, tax and a set of unique tags",
"tutorial004": dedent("""
Create an item with all the information:
- **name**: each item must have a name
- **description**: a long description
... | eturn request.param
@pytest.fixture(name="client")
def get_client(mod_name: str) -> TestClient:
mod = importlib.import_module(f"docs_src.path_operation_configuration.{mod_name}")
return TestClient(mod.app)
def test_post_items(client: TestClient | name="mod_name",
params=[
pytest.param("tutorial003_py310", marks=needs_py310),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
def get_mod_name(request: pytest.FixtureRequest) -> str:
r | {
"filepath": "tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py",
"language": "python",
"file_size": 7878,
"cut_index": 716,
"middle_length": 229
} |
ient
from inline_snapshot import snapshot
from docs_src.path_operation_configuration.tutorial006_py310 import app
client = TestClient(app)
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/items/", 200, [{"name": "Foo", "price": 42}]),
("/users/", 200, [{"username": "j... | response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
| ert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert | {
"filepath": "tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py",
"language": "python",
"file_size": 2652,
"cut_index": 563,
"middle_length": 229
} |
snapshot
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial007_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.path_operation_advanced_configuration.{request.param}"
)
client = TestClient(mod.app)
return ... | en_yaml(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
x - x-force
x - x-men
x - x-avengers
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 422 | post("/items/", content=yaml_data)
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Deadpoolio",
"tags": ["x-force", "x-men", "x-avengers"],
}
def test_post_brok | {
"filepath": "tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py",
"language": "python",
"file_size": 3675,
"cut_index": 614,
"middle_length": 229
} |
t.get("/users/")
assert response.status_code == 200, response.text
assert response.json() == ["Rick", "Morty"]
def test_dummy_webhook():
# Just for coverage
app.webhooks.routes[0].endpoint({})
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 20... | "200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
| "/users/": {
"get": {
"summary": "Read Users",
"operationId": "read_users_users__get",
"responses": {
| {
"filepath": "tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py",
"language": "python",
"file_size": 5219,
"cut_index": 716,
"middle_length": 229
} |
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.dependencies.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.p... | ie": None},
),
],
)
def test_get(path, cookie, expected_status, expected_response, client: TestClient):
if cookie is not None:
client.cookies.set("last_query", cookie)
else:
client.cookies.clear()
response = client.g | ),
(
"/items?q=foo",
"from_cookie",
200,
{"q_or_cookie": "foo"},
),
(
"/items",
None,
200,
{"q_or_cook | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial005.py",
"language": "python",
"file_size": 5129,
"cut_index": 716,
"middle_length": 229
} |
tlib
from types import ModuleType
import pytest
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial008c_py310"),
pytest.param("tutorial008c_an_py310"),
],
)
def get_mod(request: pytest.FixtureRe... |
response = client.get("/items/plumbus")
assert response.status_code == 200, response.text
assert response.json() == "plumbus"
def test_fastapi_error(mod: ModuleType):
client = TestClient(mod.app)
with pytest.raises(FastAPIError) as e | ent.get("/items/foo")
assert response.status_code == 404, response.text
assert response.json() == {"detail": "Item not found, there's only a plumbus here"}
def test_get(mod: ModuleType):
client = TestClient(mod.app) | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial008c.py",
"language": "python",
"file_size": 1414,
"cut_index": 524,
"middle_length": 229
} |
pytest.param("tutorial002_py310", marks=[needs_py310]),
pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.query_param_models.{request.param}")
client = TestClient(mod.app)
return client
d... | 1", "tag2"],
}
def test_query_param_model_defaults(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"limit": 100,
"offset": 0,
"order_by": "create | _at",
"tags": ["tag1", "tag2"],
},
)
assert response.status_code == 200
assert response.json() == {
"limit": 10,
"offset": 5,
"order_by": "updated_at",
"tags": ["tag | {
"filepath": "tests/test_tutorial/test_query_param_models/test_tutorial002.py",
"language": "python",
"file_size": 8214,
"cut_index": 716,
"middle_length": 229
} |
="client",
params=[
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(
f"docs_src.path_operation_configuration.{request.param}"
)
return TestClient(mod.app)
def test_post_items(clie... | ce": 42.0,
"tax": 3.2,
"tags": IsList("bar", "baz", check_order=False),
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert respons | "tax": 3.2,
"tags": ["bar", "baz"],
},
)
assert response.status_code == 201, response.text
assert response.json() == {
"name": "Foo",
"description": "Item description",
"pri | {
"filepath": "tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py",
"language": "python",
"file_size": 7100,
"cut_index": 716,
"middle_length": 229
} |
mport TestClient
from inline_snapshot import snapshot
from docs_src.path_operation_configuration.tutorial002b_py310 import app
client = TestClient(app)
def test_get_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == ["Portal gun", "Plumb... | sion": "0.1.0"},
"paths": {
"/items/": {
"get": {
"tags": ["items"],
"summary": "Get Items",
"operationId": "get_items_items__get",
| a():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "ver | {
"filepath": "tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py",
"language": "python",
"file_size": 1913,
"cut_index": 537,
"middle_length": 229
} |
0
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial010_py310", marks=needs_py310),
pytest.param("tutorial010_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.... | , params={"item-query": "fixedquery"})
assert response.status_code == 200
assert response.json() == {
"items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
"q": "fixedquery",
}
def test_query_params_str_validations_q_fixedquery(c | response.status_code == 200
assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
def test_query_params_str_validations_item_query_fixedquery(client: TestClient):
response = client.get("/items/" | {
"filepath": "tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py",
"language": "python",
"file_size": 6000,
"cut_index": 716,
"middle_length": 229
} |
ys
from types import ModuleType
from typing import Annotated, Any
from unittest.mock import Mock, patch
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
@pytest.fixture(
name="module",
params=[
"tutorial008_py310",
pytest.param(
"tutoria... | FastAPI()
@app.get("/")
def read_root(c: Annotated[Any, Depends(module.dependency_c)]):
return {"c": str(c)}
client = TestClient(app)
a_mock = Mock()
b_mock = Mock()
c_mock = Mock()
with (
patch(
| ),
],
)
def get_module(request: pytest.FixtureRequest):
mod_name = f"docs_src.dependencies.{request.param}"
mod = importlib.import_module(mod_name)
return mod
def test_get_db(module: ModuleType):
app = | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial008.py",
"language": "python",
"file_size": 1525,
"cut_index": 537,
"middle_length": 229
} |
om pathlib import Path
import pytest
from fastapi.testclient import TestClient
from tests.utils import workdir_lock
@pytest.fixture(scope="module")
def client():
static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True)
from docs_src.custom_docs_ui.tutorial001... | workdir_lock
def test_swagger_ui_oauth2_redirect_html(client: TestClient):
response = client.get("/docs/oauth2-redirect")
assert response.status_code == 200, response.text
assert "window.opener.swaggerUIRedirectOauth2" in response.text
@workd | s")
assert response.status_code == 200, response.text
assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text
assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text
@ | {
"filepath": "tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py",
"language": "python",
"file_size": 1431,
"cut_index": 524,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
pytest.param("tutorial001_02_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
... | 30}),
("/users", 200, {"q": None, "skip": 0, "limit": 100}),
],
)
def test_get(path, expected_status, expected_response, client: TestClient):
response = client.get(path)
assert response.status_code == expected_status
assert response | ),
("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}),
("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}),
("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py",
"language": "python",
"file_size": 7880,
"cut_index": 716,
"middle_length": 229
} |
snapshot
@pytest.fixture(
name="client",
params=[
"tutorial011_py310",
pytest.param("tutorial011_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
... | ery": True},
),
],
)
def test_get(path, expected_status, expected_response, client: TestClient):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_opena | ),
(
"/query-checker/?q=qwerty",
200,
{"fixed_content_in_query": False},
),
(
"/query-checker/?q=foobar",
200,
{"fixed_content_in_qu | {
"filepath": "tests/test_tutorial/test_dependencies/test_tutorial011.py",
"language": "python",
"file_size": 4514,
"cut_index": 614,
"middle_length": 229
} |
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.path_operation_configuration.{request.param}"
)
client = TestClient(mod.app)
return client
def test_query_params_str_validations(client: Tes... | sponse.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
| "price": 42,
"description": None,
"tax": None,
"tags": [],
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, re | {
"filepath": "tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py",
"language": "python",
"file_size": 5702,
"cut_index": 716,
"middle_length": 229
} |
p: str):
return {"p": p}
class QueryModelRequiredStr(BaseModel):
p: str
@app.get("/model-required-str")
async def read_model_required_str(p: Annotated[QueryModelRequiredStr, Query()]):
return {"p": p.p}
@pytest.mark.parametrize(
"path",
["/required-str", "/model-required-str"],
)
def test_requ... | issing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "p" | e": "P", "type": "string"},
"name": "p",
"in": "query",
}
]
)
@pytest.mark.parametrize(
"path",
["/required-str", "/model-required-str"],
)
def test_required_str_m | {
"filepath": "tests/test_request_params/test_query/test_required_str.py",
"language": "python",
"file_size": 10401,
"cut_index": 921,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.response_directly.{request.param}")
client = TestClient(mod.app)
return client
def test_path_operation(client: TestClient):
response = client.put(
... | response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"info": {
"title": "FastAPI",
"version": "0.1.0",
},
| us_code == 200, response.text
assert response.json() == {
"description": "A test item",
"timestamp": "2023-01-01T12:00:00",
"title": "Foo",
}
def test_openapi_schema_pv2(client: TestClient):
| {
"filepath": "tests/test_tutorial/test_response_directly/test_tutorial001.py",
"language": "python",
"file_size": 5808,
"cut_index": 716,
"middle_length": 229
} |
_errors.tutorial001_py310 import app
client = TestClient(app)
def test_get_item():
response = client.get("/items/foo")
assert response.status_code == 200, response.text
assert response.json() == {"item": "The Foo Wrestlers"}
def test_get_item_not_found():
response = client.get("/items/bar")
ass... | .0"},
"paths": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
| sponse = 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 | {
"filepath": "tests/test_tutorial/test_handling_errors/test_tutorial001.py",
"language": "python",
"file_size": 3831,
"cut_index": 614,
"middle_length": 229
} |
_errors.tutorial003_py310 import app
client = TestClient(app)
def test_get():
response = client.get("/unicorns/shinny")
assert response.status_code == 200, response.text
assert response.json() == {"unicorn_name": "shinny"}
def test_get_exception():
response = client.get("/unicorns/yolo")
assert... | ,
"paths": {
"/unicorns/{name}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
| se = 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"} | {
"filepath": "tests/test_tutorial/test_handling_errors/test_tutorial003.py",
"language": "python",
"file_size": 3827,
"cut_index": 614,
"middle_length": 229
} |
_errors.tutorial005_py310 import app
client = TestClient(app)
def test_post_validation_error():
response = client.post("/items/", json={"title": "towel", "size": "XL"})
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": ... | .text
assert response.json() == data
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
| }
],
"body": {"title": "towel", "size": "XL"},
}
def test_post():
data = {"title": "towel", "size": 5}
response = client.post("/items/", json=data)
assert response.status_code == 200, response | {
"filepath": "tests/test_tutorial/test_handling_errors/test_tutorial005.py",
"language": "python",
"file_size": 4533,
"cut_index": 614,
"middle_length": 229
} |
_errors.tutorial006_py310 import app
client = TestClient(app)
def test_get_validation_error():
response = client.get("/items/foo")
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ... |
assert response.status_code == 200, response.text
assert response.json() == {"item_id": 2}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == | t_http_error():
response = client.get("/items/3")
assert response.status_code == 418, response.text
assert response.json() == {"detail": "Nope! I don't like 3."}
def test_get():
response = client.get("/items/2") | {
"filepath": "tests/test_tutorial/test_handling_errors/test_tutorial006.py",
"language": "python",
"file_size": 4196,
"cut_index": 614,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_data_types.{request.param}")
client = TestClient(mod.app)
return client
def test_e... | "duration": 176_100,
"item_id": item_id,
}
)
response = client.put(f"/items/{item_id}", json=data)
assert response.status_code == 200, response.text
assert response.json() == expected_response
def test_openapi_schema(c | 00:00+00:00",
"repeat_at": "15:30:00",
"process_after": 300,
}
expected_response = data.copy()
expected_response.update(
{
"start_process": "2018-12-22T14:05:00+00:00",
| {
"filepath": "tests/test_tutorial/test_extra_data_types/test_tutorial001.py",
"language": "python",
"file_size": 6484,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}")
client = TestClient(mod.app)
return client
def test_create_item(client: TestClient) -> None:
... | : "Device to travel through the multi-rick-verse",
},
{"name": "Plumbus", "description": None},
]
def test_openapi_schema(client: TestClient) -> None:
response = client.get("/openapi.json")
assert response.status_code == 200, | d_items(client: TestClient) -> None:
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{
"name": "Portal Gun",
"description" | {
"filepath": "tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py",
"language": "python",
"file_size": 5839,
"cut_index": 716,
"middle_length": 229
} |
astapi.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.behind_a_proxy.tutorial001_py310 import app
client = TestClient(app, root_path="/api/v1")
def test_main():
response = client.get("/app")
assert response.status_code == 200
assert response.json() == {"message": "Hello ... | "operationId": "read_main_app_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": { | "openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/app": {
"get": {
"summary": "Read Main",
| {
"filepath": "tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py",
"language": "python",
"file_size": 1192,
"cut_index": 518,
"middle_length": 229
} |
.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.behind_a_proxy.tutorial004_py310 import app
client = TestClient(app)
def test_main():
response = client.get("/app")
assert response.status_code == 200
assert response.json() == {"message": "Hello World", "root_path": "/api/... | },
{
"url": "https://prod.example.com",
"description": "Production environment",
},
],
"paths": {
"/app": {
"get" | 1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"servers": [
{
"url": "https://stag.example.com",
"description": "Staging environment",
| {
"filepath": "tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py",
"language": "python",
"file_size": 1476,
"cut_index": 524,
"middle_length": 229
} |
_errors.tutorial002_py310 import app
client = TestClient(app)
def test_get_item_header():
response = client.get("/items-header/foo")
assert response.status_code == 200, response.text
assert response.json() == {"item": "The Foo Wrestlers"}
def test_get_item_not_found_header():
response = client.get(... | "info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items-header/{item_id}": {
"get": {
"responses": {
"200": {
| t found"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
| {
"filepath": "tests/test_tutorial/test_handling_errors/test_tutorial002.py",
"language": "python",
"file_size": 3904,
"cut_index": 614,
"middle_length": 229
} |
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}")
client = TestClient(mod.app)
return client
def test_create_item(client: TestClient) -> None:
... | : "Device to travel through the multi-rick-verse",
},
{"name": "Plumbus", "description": None},
]
def test_openapi_schema(client: TestClient) -> None:
response = client.get("/openapi.json")
assert response.status_code == 200, | d_items(client: TestClient) -> None:
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{
"name": "Portal Gun",
"description" | {
"filepath": "tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py",
"language": "python",
"file_size": 5839,
"cut_index": 716,
"middle_length": 229
} |
astapi.testclient import TestClient
from inline_snapshot import snapshot
from docs_src.behind_a_proxy.tutorial002_py310 import app
client = TestClient(app)
def test_main():
response = client.get("/app")
assert response.status_code == 200
assert response.json() == {"message": "Hello World", "root_path": ... | ": "read_main_app_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
| .0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/app": {
"get": {
"summary": "Read Main",
"operationId | {
"filepath": "tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py",
"language": "python",
"file_size": 1171,
"cut_index": 518,
"middle_length": 229
} |
pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.response_directly.{request.param}")
... | ontent-type"] == "application/xml"
assert response.text == expected_content
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == sn | o here.
</Header>
<Body>
You'll have to use soap here.
</Body>
</shampoo>
"""
response = client.get("/legacy/")
assert response.status_code == 200, response.text
assert response.headers["c | {
"filepath": "tests/test_tutorial/test_response_directly/test_tutorial002.py",
"language": "python",
"file_size": 1895,
"cut_index": 537,
"middle_length": 229
} |
_errors.tutorial004_py310 import app
client = TestClient(app)
def test_get_validation_error():
response = client.get("/items/foo")
assert response.status_code == 400, response.text
assert "Validation errors:" in response.text
assert "Field: ('path', 'item_id')" in response.text
def test_get_http_er... | response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
| nt.get("/items/2")
assert response.status_code == 200, response.text
assert response.json() == {"item_id": 2}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, | {
"filepath": "tests/test_tutorial/test_handling_errors/test_tutorial004.py",
"language": "python",
"file_size": 3985,
"cut_index": 614,
"middle_length": 229
} |
mport TestClient
from inline_snapshot import snapshot
from docs_src.behind_a_proxy.tutorial003_py310 import app
client = TestClient(app)
def test_main():
response = client.get("/app")
assert response.status_code == 200
assert response.json() == {"message": "Hello World", "root_path": "/api/v1"}
def te... | ing environment",
},
{
"url": "https://prod.example.com",
"description": "Production environment",
},
],
"paths": {
"/app": {
| "info": {"title": "FastAPI", "version": "0.1.0"},
"servers": [
{"url": "/api/v1"},
{
"url": "https://stag.example.com",
"description": "Stag | {
"filepath": "tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py",
"language": "python",
"file_size": 1512,
"cut_index": 537,
"middle_length": 229
} |
mport TestClient
from inline_snapshot import snapshot
from docs_src.extending_openapi.tutorial001_py310 import app
client = TestClient(app)
def test():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"name": "Foo"}]
def test_openapi_schema... | "version": "2.5.0",
"x-logo": {
"url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
},
},
"paths": {
"/items/": {
"get": {
| "info": {
"title": "Custom title",
"summary": "This is a very custom OpenAPI schema",
"description": "Here's a longer description of the custom **OpenAPI** schema",
| {
"filepath": "tests/test_tutorial/test_extending_openapi/test_tutorial001.py",
"language": "python",
"file_size": 1712,
"cut_index": 537,
"middle_length": 229
} |
snapshot
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002_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_items(cli... | line for line in lines if line.startswith("event: ")]
assert len(event_lines) == 3
assert all(line == "event: item_update" for line in event_lines)
data_lines = [line for line in lines if line.startswith("data: ")]
assert len(data_lines) = | f-8"
lines = response.text.strip().split("\n")
# First event is a comment-only event
assert lines[0] == ": stream of item updates"
# Remaining lines contain event:, data:, id:, retry: fields
event_lines = [ | {
"filepath": "tests/test_tutorial/test_server_sent_events/test_tutorial002.py",
"language": "python",
"file_size": 3081,
"cut_index": 614,
"middle_length": 229
} |
],
)
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_chat(client: TestClient):
response = client.post(
"/chat/stream",
json={"text": "hello worl... | e.startswith("data: ")]
assert data_lines == [
'data: "hello"',
'data: "world"',
"data: [DONE]",
]
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == | )
event_lines = [line for line in lines if line.startswith("event: ")]
assert event_lines == [
"event: token",
"event: token",
"event: done",
]
data_lines = [line for line in lines if lin | {
"filepath": "tests/test_tutorial/test_server_sent_events/test_tutorial005.py",
"language": "python",
"file_size": 5456,
"cut_index": 716,
"middle_length": 229
} |
t needs_py310
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001_py310", marks=needs_py310),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.additional_status_codes.{r... | onse.json() == {"name": "Wrestlers", "size": None}
def test_create(client: TestClient):
response = client.put("/items/red", json={"name": "Chillies"})
assert response.status_code == 201, response.text
assert response.json() == {"name": "Chill | se.status_code == 200, response.text
assert resp | {
"filepath": "tests/test_tutorial/test_additional_status_codes/test_tutorial001.py",
"language": "python",
"file_size": 934,
"cut_index": 606,
"middle_length": 52
} |
mport TestClient
from docs_src.configure_swagger_ui.tutorial002_py310 import app
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert '"syntaxHighlight": false' not in response.text, (
"not used parameters should ... | esponse.text, (
"default configs should be preserved"
)
assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, (
"default configs should be preserved"
)
assert '"layout": "BaseLayout",' in response.text, (
| ert '"dom_id": "#swagger-ui"' in response.text, (
"default configs should be preserved"
)
assert "presets: [" in response.text, "default configs should be preserved"
assert "SwaggerUIBundle.presets.apis," in r | {
"filepath": "tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py",
"language": "python",
"file_size": 1573,
"cut_index": 537,
"middle_length": 229
} |
pytest.param("tutorial001_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.p... | "openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"put": {
"summary": "Update Item",
"oper | response.status_code == 200
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
| {
"filepath": "tests/test_tutorial/test_schema_extra_example/test_tutorial001.py",
"language": "python",
"file_size": 5523,
"cut_index": 716,
"middle_length": 229
} |
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")
client = TestClient(mod.app)
return client
def test_post_body_example(client: TestClient):
response = client.p... | "openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"put": {
"summary": "Update Item",
"oper | response.status_code == 200
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
| {
"filepath": "tests/test_tutorial/test_schema_extra_example/test_tutorial002.py",
"language": "python",
"file_size": 5605,
"cut_index": 716,
"middle_length": 229
} |
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.schema_extra_example.{request.param}")
client = TestClient(mod.app)
return client
def te... | , response.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) -> None:
response = client.get("/openapi.json")
assert response.status_code == 200 | {
"filepath": "tests/test_tutorial/test_schema_extra_example/test_tutorial005.py",
"language": "python",
"file_size": 6841,
"cut_index": 716,
"middle_length": 229
} |
quest_directly.tutorial001_py310 import app
client = TestClient(app)
def test_path_operation():
response = client.get("/items/foo")
assert response.status_code == 200
assert response.json() == {"client_host": "testclient", "item_id": "foo"}
def test_openapi():
response = client.get("/openapi.json")... | ameters": [
{
"in": "path",
"name": "item_id",
"required": True,
"schema": {
| },
"openapi": "3.1.0",
"paths": {
"/items/{item_id}": {
"get": {
"operationId": "read_root_items__item_id__get",
"par | {
"filepath": "tests/test_tutorial/test_using_request_directly/test_tutorial001.py",
"language": "python",
"file_size": 4496,
"cut_index": 614,
"middle_length": 229
} |
")
async def read_required_list_str(p: Annotated[list[str], Header()]):
return {"p": p}
class HeaderModelRequiredListStr(BaseModel):
p: list[str]
@app.get("/model-required-list-str")
def read_model_required_list_str(p: Annotated[HeaderModelRequiredListStr, Header()]):
return {"p": p.p}
@pytest.mark.pa... | },
"name": "p",
"in": "header",
}
]
)
@pytest.mark.parametrize(
"path",
["/required-list-str", "/model-required-list-str"],
)
def test_required_list_str_missing(path: str):
client = Te | napshot(
[
{
"required": True,
"schema": {
"title": "P",
"type": "array",
"items": {"type": "string"},
| {
"filepath": "tests/test_request_params/test_header/test_list.py",
"language": "python",
"file_size": 11614,
"cut_index": 921,
"middle_length": 229
} |
FastAPI()
# =====================================================================================
# Without aliases
@app.get("/optional-str")
async def read_optional_str(p: Annotated[str | None, Header()] = None):
return {"p": p}
class HeaderModelOptionalStr(BaseModel):
p: str | None = None
@app.get("/mo... | "anyOf": [{"type": "string"}, {"type": "null"}],
"title": "P",
},
"name": "p",
"in": "header",
}
]
)
@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": {
| {
"filepath": "tests/test_request_params/test_header/test_optional_str.py",
"language": "python",
"file_size": 8706,
"cut_index": 716,
"middle_length": 229
} |
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.server_sent_events.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path",
[
"/items/stream",
"/items/stream-no-async",
"/items/stream-... | n(data_lines) == 3
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",
| = 200, response.text
assert response.headers["content-type"] == "text/event-stream; charset=utf-8"
data_lines = [
line for line in response.text.strip().split("\n") if line.startswith("data: ")
]
assert le | {
"filepath": "tests/test_tutorial/test_server_sent_events/test_tutorial001.py",
"language": "python",
"file_size": 8566,
"cut_index": 716,
"middle_length": 229
} |
tion_id="required_list_str")
async def read_required_list_str(p: Annotated[list[str], Form()]):
return {"p": p}
class FormModelRequiredListStr(BaseModel):
p: list[str]
@app.post("/model-required-list-str", operation_id="model_required_list_str")
def read_model_required_list_str(p: Annotated[FormModelRequire... | "string"},
"title": "P",
"type": "array",
},
},
"required": ["p"],
"title": body_model_name,
"type": "object",
}
@pytest.mark.parametrize(
"path",
["/required-list-st | enapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p": {
"items": {"type": | {
"filepath": "tests/test_request_params/test_form/test_list.py",
"language": "python",
"file_size": 11973,
"cut_index": 921,
"middle_length": 229
} |
FastAPI()
# =====================================================================================
# Without aliases
@app.post("/optional-str", operation_id="optional_str")
async def read_optional_str(p: Annotated[str | None, Form()] = None):
return {"p": p}
class FormModelOptionalStr(BaseModel):
p: str | ... | )["components"]["schemas"][body_model_name] == {
"properties": {
"p": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "P",
},
},
"title": body_model_name,
" | .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)
assert app.openapi( | {
"filepath": "tests/test_request_params/test_form/test_optional_str.py",
"language": "python",
"file_size": 9087,
"cut_index": 716,
"middle_length": 229
} |
_list_str(p: Annotated[list[str], Query()]):
return {"p": p}
class QueryModelRequiredListStr(BaseModel):
p: list[str]
@app.get("/model-required-list-str")
def read_model_required_list_str(p: Annotated[QueryModelRequiredListStr, Query()]):
return {"p": p.p}
@pytest.mark.parametrize(
"path",
["/... | p",
"in": "query",
}
]
)
@pytest.mark.parametrize(
"path",
["/required-list-str", "/model-required-list-str"],
)
def test_required_list_str_missing(path: str):
client = TestClient(app)
response = cl | {
"required": True,
"schema": {
"title": "P",
"type": "array",
"items": {"type": "string"},
},
"name": " | {
"filepath": "tests/test_request_params/test_query/test_list.py",
"language": "python",
"file_size": 11469,
"cut_index": 921,
"middle_length": 229
} |
str] | None, Query()] = None,
):
return {"p": p}
class QueryModelOptionalListStr(BaseModel):
p: list[str] | None = None
@app.get("/model-optional-list-str")
async def read_model_optional_list_str(
p: Annotated[QueryModelOptionalListStr, Query()],
):
return {"p": p.p}
@pytest.mark.parametrize(
... | ],
"title": "P",
},
"name": "p",
"in": "query",
}
]
)
@pytest.mark.parametrize(
"path",
["/optional-list-str", "/model-optional-list-str" | [
{
"required": False,
"schema": {
"anyOf": [
{"items": {"type": "string"}, "type": "array"},
{"type": "null"},
| {
"filepath": "tests/test_request_params/test_query/test_optional_list.py",
"language": "python",
"file_size": 9625,
"cut_index": 921,
"middle_length": 229
} |
],
)
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 == 20... | 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 | {
"filepath": "tests/test_tutorial/test_server_sent_events/test_tutorial004.py",
"language": "python",
"file_size": 6112,
"cut_index": 716,
"middle_length": 229
} |
.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 sh... | , (
"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 | {
"filepath": "tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py",
"language": "python",
"file_size": 1421,
"cut_index": 524,
"middle_length": 229
} |
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 te... | 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 | {
"filepath": "tests/test_tutorial/test_schema_extra_example/test_tutorial003.py",
"language": "python",
"file_size": 5796,
"cut_index": 716,
"middle_length": 229
} |
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",
"vers... | 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 | {
"filepath": "tests/benchmarks/test_general_performance.py",
"language": "python",
"file_size": 11393,
"cut_index": 921,
"middle_length": 229
} |
[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(... | ,
],
"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"} | {
"filepath": "tests/test_request_params/test_header/test_optional_list.py",
"language": "python",
"file_size": 9842,
"cut_index": 921,
"middle_length": 229
} |
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[st... | 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 | {
"filepath": "tests/test_request_params/test_path/test_required_str.py",
"language": "python",
"file_size": 2492,
"cut_index": 563,
"middle_length": 229
} |
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.pa... | "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,
| {
"filepath": "tests/test_request_params/test_form/test_required_str.py",
"language": "python",
"file_size": 10904,
"cut_index": 921,
"middle_length": 229
} |
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... | 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 | {
"filepath": "tests/test_tutorial/test_server_sent_events/test_tutorial003.py",
"language": "python",
"file_size": 2753,
"cut_index": 563,
"middle_length": 229
} |
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 prese... | 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 | {
"filepath": "tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py",
"language": "python",
"file_size": 1540,
"cut_index": 537,
"middle_length": 229
} |
/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/com... | "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", | {
"filepath": "tests/test_modules_same_name_body/test_main.py",
"language": "python",
"file_size": 6366,
"cut_index": 716,
"middle_length": 229
} |
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[FormModelOptionalListSt... | {"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": [
| {
"filepath": "tests/test_request_params/test_form/test_optional_list.py",
"language": "python",
"file_size": 10103,
"cut_index": 921,
"middle_length": 229
} |
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"... | : ["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" | {
"filepath": "tests/test_request_params/test_file/test_required.py",
"language": "python",
"file_size": 11347,
"cut_index": 921,
"middle_length": 229
} |
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: BodyModelOptionalListSt... | 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 | {
"filepath": "tests/test_request_params/test_body/test_optional_list.py",
"language": "python",
"file_size": 12933,
"cut_index": 921,
"middle_length": 229
} |
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.parame... | "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,
| {
"filepath": "tests/test_request_params/test_body/test_required_str.py",
"language": "python",
"file_size": 11204,
"cut_index": 921,
"middle_length": 229
} |
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": "i... | item",
"sub_items2": [
{
"name": "subsubitem",
"sub_items1": [{"name": "subsubsubitem", "sub_items2": []}],
}
],
}
] | tems1": [
{
"name": "sub | {
"filepath": "tests/test_validate_response_recursive/test_validate_response_recursive.py",
"language": "python",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
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")
asyn... | 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": [{" | {
"filepath": "tests/test_request_params/test_query/test_optional_str.py",
"language": "python",
"file_size": 8577,
"cut_index": 716,
"middle_length": 229
} |
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 te... | 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 | {
"filepath": "tests/test_tutorial/test_schema_extra_example/test_tutorial004.py",
"language": "python",
"file_size": 6113,
"cut_index": 716,
"middle_length": 229
} |
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",
[... |
{"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"}, | {
"filepath": "tests/test_request_params/test_file/test_optional.py",
"language": "python",
"file_size": 10017,
"cut_index": 921,
"middle_length": 229
} |
(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-requir... |
)
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"], | {
"filepath": "tests/test_request_params/test_cookie/test_required_str.py",
"language": "python",
"file_size": 10642,
"cut_index": 921,
"middle_length": 229
} |
: 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(
... | "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",
},
},
| {
"filepath": "tests/test_request_params/test_body/test_optional_str.py",
"language": "python",
"file_size": 11786,
"cut_index": 921,
"middle_length": 229
} |
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):
... | 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 | {
"filepath": "tests/test_validate_response_recursive/app.py",
"language": "python",
"file_size": 1151,
"cut_index": 518,
"middle_length": 229
} |
):
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",
... | 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 | {
"filepath": "tests/test_request_params/test_file/test_list.py",
"language": "python",
"file_size": 11832,
"cut_index": 921,
"middle_length": 229
} |
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(
"pa... |
"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", | {
"filepath": "tests/test_request_params/test_file/test_optional_list.py",
"language": "python",
"file_size": 11068,
"cut_index": 921,
"middle_length": 229
} |
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",
["/requ... | , "/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" | {
"filepath": "tests/test_request_params/test_header/test_required_str.py",
"language": "python",
"file_size": 10528,
"cut_index": 921,
"middle_length": 229
} |
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("/mo... | "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": {
| {
"filepath": "tests/test_request_params/test_cookie/test_optional_str.py",
"language": "python",
"file_size": 8810,
"cut_index": 716,
"middle_length": 229
} |
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: BodyModelRequire... | ,
"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"} | {
"filepath": "tests/test_request_params/test_body/test_list.py",
"language": "python",
"file_size": 12158,
"cut_index": 921,
"middle_length": 229
} |
er.
func toFiberHandler(handler any) (Handler, bool) {
if handler == nil {
return nil, false
}
switch handler.(type) {
case Handler, func(Ctx): // (1)-(2) Fiber handlers
return adaptFiberHandler(handler)
case func(Req, Res) error, func(Req, Res), func(Req, Res, func() error) error, func(Req, Res, func() error... | r)
case fasthttp.RequestHandler, func(*fasthttp.RequestCtx) error: // (16)-(17) fasthttp handlers
return adaptFastHTTPHandler(handler)
default: // (18) unsupported handler type
return nil, false
}
}
func adaptFiberHandler(handler any) (Handler, boo | ror: // (3)-(12) Express-style request handlers
return adaptExpressHandler(handler)
case http.HandlerFunc, http.Handler, func(http.ResponseWriter, *http.Request): // (13)-(15) net/http handlers
return adaptHTTPHandler(handle | {
"filepath": "adapter.go",
"language": "go",
"file_size": 7190,
"cut_index": 716,
"middle_length": 229
} |
application.
// App is safe for concurrent use, except for route mutation methods that
// explicitly document otherwise.
type App struct {
// App config
config Config
// Indicates if the value was explicitly configured
configured Config
// Ctx pool
pool sync.Pool
// Fasthttp server
server *fasthttp.Server
// ... | age-backed)
sharedState *SharedState
// Route stack divided by HTTP methods
stack [][]*Route
// customConstraints is a list of external constraints
customConstraints []CustomConstraint
// sendfiles stores configurations for handling ctx.SendFile oper | oute *Route
// newCtxFunc
newCtxFunc func(app *App) CustomCtx
// TLS handler
tlsHandler *TLSHandler
// Mount fields
mountFields *mountFields
// state management
state *State
// shared state management (prefork-safe, stor | {
"filepath": "app.go",
"language": "go",
"file_size": 51103,
"cut_index": 2151,
"middle_length": 229
} |
or is an interface to register custom struct validator for binding.
type StructValidator interface {
Validate(out any) error
}
var bindPool = sync.Pool{
New: func() any {
return &Bind{
shouldSkipErrHandling: true,
}
},
}
// Bind provides helper methods for binding request data to Go values.
// By default (m... | BindSourceHeader = "header"
BindSourceCookie = "cookie"
BindSourceBody = "body"
BindSourceRespHeader = "respHeader"
)
// BindError wraps a binding failure with the source and field that failed.
// Use errors.As(err, &be) to extract it wh | .
type Bind struct {
ctx Ctx
shouldSkipErrHandling bool
shouldSkipValidation bool
}
// BindError source constants for BindError.Source.
const (
BindSourceURI = "uri"
BindSourceQuery = "query"
| {
"filepath": "bind.go",
"language": "go",
"file_size": 15309,
"cut_index": 921,
"middle_length": 229
} |
s.
type contextKey int
// userContextKey define the key name for storing context.Context in *fasthttp.RequestCtx
const (
userContextKey contextKey = iota // __local_user_context__
)
// DefaultCtx is the default implementation of the Ctx interface
// generation tool `go install github.com/vburenin/ifacemaker@f30b6f9b... | for the request query string, parameters, body, HTTP headers and so on."
type DefaultCtx struct {
handlerCtx CustomCtx // Active custom context implementation, if any
DefaultReq // Default request a | req.go --file res.go --struct DefaultCtx --iface Ctx --pkg fiber --promoted --output ctx_interface_gen.go --not-exported true --iface-comment "Ctx represents the Context which hold the HTTP request and response.\nIt has methods | {
"filepath": "ctx.go",
"language": "go",
"file_size": 26445,
"cut_index": 1331,
"middle_length": 229
} |
sult for a single request.
// It stores the matched domain params (if any) alongside the match status
// to avoid allocating a new domainParams struct for every handler invocation.
type domainCheckResult struct {
params *domainParams // pre-built params (nil if no params or no match)
isMatched bool
}
// domainMat... | // This prevents DoS attacks from patterns or hostnames with excessive label counts.
// RFC 1035 suggests 127 labels max, but we use a more conservative limit to prevent memory exhaustion.
const maxDomainParts = 16
// parseDomainPattern parses a domain pa | rameter parts
paramNames []string // parameter names (without ":")
numParts int // total number of parts
}
// maxDomainParts defines the maximum number of domain labels allowed (e.g., sub.domain.example.com = 4 parts).
| {
"filepath": "domain.go",
"language": "go",
"file_size": 24357,
"cut_index": 1331,
"middle_length": 229
} |
erType, "application/pdf", "application/json"))
require.Equal(t, "text/plain;a=1", getOffer([]byte("text/plain;a=1"), acceptsOfferType, "text/plain;a=1"))
require.Empty(t, getOffer([]byte("text/plain;a=1;b=2"), acceptsOfferType, "text/plain;b=2"))
// Spaces, quotes, out of order params, and case insensitivity
requ... | .Equal(t, "text/plain;b=2;a=1", getOffer([]byte("text/plain ;a=1;b=2"), acceptsOfferType, "text/plain;b=2;a=1"))
require.Equal(t, "text/plain;a=1", getOffer([]byte("text/plain; a=1 "), acceptsOfferType, "text/plain;a=1"))
require.Equal(t, `text/plain | n"))
require.Equal(t, "text/plain", getOffer([]byte("text/plain;q=0.4 ;"), acceptsOfferType, "text/plain"))
require.Equal(t, "text/plain", getOffer([]byte("text/plain;q=0.4 ; p=foo"), acceptsOfferType, "text/plain"))
require | {
"filepath": "helpers_test.go",
"language": "go",
"file_size": 50261,
"cut_index": 2151,
"middle_length": 229
} |
string]()
)
func validateRegexHandler(handler any) any {
if handler == nil {
return regexp.MustCompile
}
handlerValue := reflect.ValueOf(handler)
handlerType := handlerValue.Type()
if handlerType.Kind() != reflect.Func || handlerValue.IsNil() {
panic("fiber: Config.RegexHandler must be a non-nil function")
... | true
}
matcherValue := reflect.ValueOf(matcher)
switch matcherValue.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return matcherValue.IsNil()
default:
return false
}
}
// compileRegex | ut(0).Implements(regexMatcherType) {
panic("fiber: Config.RegexHandler return type must support MatchString(string) bool")
}
return handler
}
func isNilRegexMatcher(matcher regexMatcher) bool {
if matcher == nil {
return | {
"filepath": "path.go",
"language": "go",
"file_size": 28060,
"cut_index": 1331,
"middle_length": 229
} |
"github.com/tinylib/msgp/msgp"
)
func TestMarshalUnmarshalredirectionMsg(t *testing.T) {
v := redirectionMsg{}
bts, err := v.MarshalMsg(nil)
if err != nil {
t.Fatal(err)
}
left, err := v.UnmarshalMsg(bts)
if err != nil {
t.Fatal(err)
}
if len(left) > 0 {
t.Errorf("%d bytes left over after UnmarshalMsg... | onMsg{}
bts := make([]byte, 0, v.Msgsize())
bts, _ = v.MarshalMsg(bts[0:0])
b.SetBytes(int64(len(bts)))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
bts, _ = v.MarshalMsg(bts[0:0])
}
}
func BenchmarkUnmarshalredirectionMsg(b *testin | enchmarkMarshalMsgredirectionMsg(b *testing.B) {
v := redirectionMsg{}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
v.MarshalMsg(nil)
}
}
func BenchmarkAppendMsgredirectionMsg(b *testing.B) {
v := redirecti | {
"filepath": "redirect_msgp_test.go",
"language": "go",
"file_size": 4670,
"cut_index": 614,
"middle_length": 229
} |
handler any, handlers ...any) Router
Options(path string, handler any, handlers ...any) Router
Trace(path string, handler any, handlers ...any) Router
Patch(path string, handler any, handlers ...any) Router
Add(methods []string, path string, handler any, handlers ...any) Router
All(path string, handler any, handl... | oute struct ###
group *Group // Group instance. used for routes in groups
path string // Prettified path
// Public fields
Method string `json:"method"` // HTTP method
Name string `json:"name"` // Route's name
//nolint:revive // Having both a Pa | Router
Name(name string) Router
}
// Route is a struct that holds all metadata for each registered handler.
type Route struct {
// ### important: always keep in sync with the copy method "app.copyRoute" and all creations of R | {
"filepath": "router.go",
"language": "go",
"file_size": 24950,
"cut_index": 1331,
"middle_length": 229
} |
rect
import (
"regexp"
"strconv"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/utils/v2"
)
// New creates a new middleware handler
func New(config ...Config) fiber.Handler {
cfg := configDefault(config...)
// Initialize
cfg.rulesRegex = map[*regexp.Regexp]string{}
for k, v := range cfg.Rules ... | Ctx().QueryArgs().QueryString())
if queryString != "" {
queryString = "?" + queryString
}
return c.Redirect().Status(cfg.StatusCode).To(replacer.Replace(v) + queryString)
}
}
return c.Next()
}
}
// https://github.com/labstack/echo | ware
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
// Rewrite
for k, v := range cfg.rulesRegex {
replacer := captureTokens(k, c.Path())
if replacer != nil {
queryString := utils.UnsafeString(c.Request | {
"filepath": "middleware/redirect/redirect.go",
"language": "go",
"file_size": 1482,
"cut_index": 524,
"middle_length": 229
} |
ver //nolint:predeclared // TODO: Rename to some non-builtin
import (
"github.com/gofiber/fiber/v3"
)
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c fiber.Ctx) bool
// PanicHandler... | nableStackTrace bool
}
// ConfigDefault is the default config
var ConfigDefault = Config{
Next: nil,
EnableStackTrace: false,
StackTraceHandler: defaultStackTraceHandler,
PanicHandler: DefaultPanicHandler,
}
// Helper function to s | ndler defines a function to handle stack trace
//
// Optional. Default: defaultStackTraceHandler
StackTraceHandler func(c fiber.Ctx, e any)
// EnableStackTrace enables handling stack trace
//
// Optional. Default: false
E | {
"filepath": "middleware/recover/config.go",
"language": "go",
"file_size": 1417,
"cut_index": 524,
"middle_length": 229
} |
_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/skip"
"github.com/stretchr/testify/require"
)
// go test -run Test_Skip
func Test_Skip(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Use(skip.New(errTeapotHandler, func(fiber.... | dHandler)
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody))
require.NoError(t, err)
require.Equal(t, fiber.StatusTeapot, resp.StatusCode)
}
// go test -run Test_SkipNilFunc
func Test_SkipNilFunc(t *testing.T) {
t.Parallel( | atusOK, resp.StatusCode)
}
// go test -run Test_SkipFalse
func Test_SkipFalse(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Use(skip.New(errTeapotHandler, func(fiber.Ctx) bool { return false }))
app.Get("/", helloWorl | {
"filepath": "middleware/skip/skip_test.go",
"language": "go",
"file_size": 1427,
"cut_index": 524,
"middle_length": 229
} |
arallel()
app, ctx := newTestCtx(t)
handler := func(c Ctx) {
require.Equal(t, app, c.App())
c.Set("X-Handler", "ok")
}
converted, ok := toFiberHandler(handler)
require.True(t, ok)
require.NotNil(t, converted)
require.NoError(t, converted(ctx))
require.Equal(t, "ok", string(ctx.Response().Header.Peek("X-... | nup(func() {
app.ReleaseCtx(customCtx)
})
return app, ctx
}
func withRouteHandlers(t *testing.T, ctx *DefaultCtx, handlers ...Handler) {
t.Helper()
ctx.route = &Route{Handlers: handlers}
ctx.indexHandler = 0
t.Cleanup(func() {
ctx.route = nil
|
}
func newTestCtx(t *testing.T) (*App, *DefaultCtx) {
t.Helper()
app := New()
fasthttpCtx := &fasthttp.RequestCtx{}
customCtx := app.AcquireCtx(fasthttpCtx)
ctx, ok := customCtx.(*DefaultCtx)
require.True(t, ok)
t.Clea | {
"filepath": "adapter_test.go",
"language": "go",
"file_size": 24551,
"cut_index": 1331,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.