| 1 |
from fastapi import Body, FastAPI, Query |
| 2 |
from fastapi.testclient import TestClient |
| 3 |
|
| 4 |
app = FastAPI() |
| 5 |
|
| 6 |
|
| 7 |
@app.get("/query") |
| 8 |
def read_query(q: str | None): |
| 9 |
return q |
| 10 |
|
| 11 |
|
| 12 |
@app.get("/explicit-query") |
| 13 |
def read_explicit_query(q: str | None = Query()): |
| 14 |
return q |
| 15 |
|
| 16 |
|
| 17 |
@app.post("/body-embed") |
| 18 |
def send_body_embed(b: str | None = Body(embed=True)): |
| 19 |
return b |
| 20 |
|
| 21 |
|
| 22 |
client = TestClient(app) |
| 23 |
|
| 24 |
|
| 25 |
def test_required_nonable_query_invalid(): |
| 26 |
response = client.get("/query") |
| 27 |
assert response.status_code == 422 |
| 28 |
|
| 29 |
|
| 30 |
def test_required_noneable_query_value(): |
| 31 |
response = client.get("/query", params={"q": "foo"}) |
| 32 |
assert response.status_code == 200 |
| 33 |
assert response.json() == "foo" |
| 34 |
|
| 35 |
|
| 36 |
def test_required_nonable_explicit_query_invalid(): |
| 37 |
response = client.get("/explicit-query") |
| 38 |
assert response.status_code == 422 |
| 39 |
|
| 40 |
|
| 41 |
def test_required_nonable_explicit_query_value(): |
| 42 |
response = client.get("/explicit-query", params={"q": "foo"}) |
| 43 |
assert response.status_code == 200 |
| 44 |
assert response.json() == "foo" |
| 45 |
|
| 46 |
|
| 47 |
def test_required_nonable_body_embed_no_content(): |
| 48 |
response = client.post("/body-embed") |
| 49 |
assert response.status_code == 422 |
| 50 |
|
| 51 |
|
| 52 |
def test_required_nonable_body_embed_invalid(): |
| 53 |
response = client.post("/body-embed", json={"invalid": "invalid"}) |
| 54 |
assert response.status_code == 422 |
| 55 |
|
| 56 |
|
| 57 |
def test_required_noneable_body_embed_value(): |
| 58 |
response = client.post("/body-embed", json={"b": "foo"}) |
| 59 |
assert response.status_code == 200 |
| 60 |
assert response.json() == "foo" |