| 1 |
from dirty_equals import IsPartialDict |
| 2 |
from fastapi import Cookie, FastAPI, Header, Query |
| 3 |
from fastapi.testclient import TestClient |
| 4 |
from pydantic import BaseModel, Field |
| 5 |
|
| 6 |
app = FastAPI() |
| 7 |
|
| 8 |
|
| 9 |
class Model(BaseModel): |
| 10 |
param: str = Field(alias="param_alias") |
| 11 |
|
| 12 |
|
| 13 |
@app.get("/query") |
| 14 |
async def query_model(data: Model = Query()): |
| 15 |
return {"param": data.param} |
| 16 |
|
| 17 |
|
| 18 |
@app.get("/header") |
| 19 |
async def header_model(data: Model = Header()): |
| 20 |
return {"param": data.param} |
| 21 |
|
| 22 |
|
| 23 |
@app.get("/cookie") |
| 24 |
async def cookie_model(data: Model = Cookie()): |
| 25 |
return {"param": data.param} |
| 26 |
|
| 27 |
|
| 28 |
def test_query_model_with_alias(): |
| 29 |
client = TestClient(app) |
| 30 |
response = client.get("/query", params={"param_alias": "value"}) |
| 31 |
assert response.status_code == 200, response.text |
| 32 |
assert response.json() == {"param": "value"} |
| 33 |
|
| 34 |
|
| 35 |
def test_header_model_with_alias(): |
| 36 |
client = TestClient(app) |
| 37 |
response = client.get("/header", headers={"param_alias": "value"}) |
| 38 |
assert response.status_code == 200, response.text |
| 39 |
assert response.json() == {"param": "value"} |
| 40 |
|
| 41 |
|
| 42 |
def test_cookie_model_with_alias(): |
| 43 |
client = TestClient(app) |
| 44 |
client.cookies.set("param_alias", "value") |
| 45 |
response = client.get("/cookie") |
| 46 |
assert response.status_code == 200, response.text |
| 47 |
assert response.json() == {"param": "value"} |
| 48 |
|
| 49 |
|
| 50 |
def test_query_model_with_alias_by_name(): |
| 51 |
client = TestClient(app) |
| 52 |
response = client.get("/query", params={"param": "value"}) |
| 53 |
assert response.status_code == 422, response.text |
| 54 |
details = response.json() |
| 55 |
assert details["detail"][0]["input"] == {"param": "value"} |
| 56 |
|
| 57 |
|
| 58 |
def test_header_model_with_alias_by_name(): |
| 59 |
client = TestClient(app) |
| 60 |
response = client.get("/header", headers={"param": "value"}) |
| 61 |
assert response.status_code == 422, response.text |
| 62 |
details = response.json() |
| 63 |
assert details["detail"][0]["input"] == IsPartialDict({"param": "value"}) |
| 64 |
|
| 65 |
|
| 66 |
def test_cookie_model_with_alias_by_name(): |
| 67 |
client = TestClient(app) |
| 68 |
client.cookies.set("param", "value") |
| 69 |
response = client.get("/cookie") |
| 70 |
assert response.status_code == 422, response.text |
| 71 |
details = response.json() |
| 72 |
assert details["detail"][0]["input"] == {"param": "value"} |