| 1 |
from typing import Annotated |
| 2 |
|
| 3 |
from fastapi import FastAPI, File, Form |
| 4 |
from starlette.testclient import TestClient |
| 5 |
|
| 6 |
app = FastAPI() |
| 7 |
|
| 8 |
|
| 9 |
@app.post("/urlencoded") |
| 10 |
async def post_url_encoded(age: Annotated[int | None, Form()] = None): |
| 11 |
return age |
| 12 |
|
| 13 |
|
| 14 |
@app.post("/multipart") |
| 15 |
async def post_multi_part( |
| 16 |
age: Annotated[int | None, Form()] = None, |
| 17 |
file: Annotated[bytes | None, File()] = None, |
| 18 |
): |
| 19 |
return {"file": file, "age": age} |
| 20 |
|
| 21 |
|
| 22 |
client = TestClient(app) |
| 23 |
|
| 24 |
|
| 25 |
def test_form_default_url_encoded(): |
| 26 |
response = client.post("/urlencoded", data={"age": ""}) |
| 27 |
assert response.status_code == 200 |
| 28 |
assert response.text == "null" |
| 29 |
|
| 30 |
|
| 31 |
def test_form_default_multi_part(): |
| 32 |
response = client.post("/multipart", data={"age": ""}) |
| 33 |
assert response.status_code == 200 |
| 34 |
assert response.json() == {"file": None, "age": None} |