Coverage for tests / test_request_param_model_by_alias.py: 100%

51 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from dirty_equals import IsPartialDict 1abcd

2from fastapi import Cookie, FastAPI, Header, Query 1abcd

3from fastapi.testclient import TestClient 1abcd

4from pydantic import BaseModel, Field 1abcd

5 

6app = FastAPI() 1abcd

7 

8 

9class Model(BaseModel): 1abcd

10 param: str = Field(alias="param_alias") 1abcd

11 

12 

13@app.get("/query") 1abcd

14async def query_model(data: Model = Query()): 1abcd

15 return {"param": data.param} 1mnop

16 

17 

18@app.get("/header") 1abcd

19async def header_model(data: Model = Header()): 1abcd

20 return {"param": data.param} 1qrst

21 

22 

23@app.get("/cookie") 1abcd

24async def cookie_model(data: Model = Cookie()): 1abcd

25 return {"param": data.param} 1efgh

26 

27 

28def test_query_model_with_alias(): 1abcd

29 client = TestClient(app) 1mnop

30 response = client.get("/query", params={"param_alias": "value"}) 1mnop

31 assert response.status_code == 200, response.text 1mnop

32 assert response.json() == {"param": "value"} 1mnop

33 

34 

35def test_header_model_with_alias(): 1abcd

36 client = TestClient(app) 1qrst

37 response = client.get("/header", headers={"param_alias": "value"}) 1qrst

38 assert response.status_code == 200, response.text 1qrst

39 assert response.json() == {"param": "value"} 1qrst

40 

41 

42def test_cookie_model_with_alias(): 1abcd

43 client = TestClient(app) 1efgh

44 client.cookies.set("param_alias", "value") 1efgh

45 response = client.get("/cookie") 1efgh

46 assert response.status_code == 200, response.text 1efgh

47 assert response.json() == {"param": "value"} 1efgh

48 

49 

50def test_query_model_with_alias_by_name(): 1abcd

51 client = TestClient(app) 1uvwx

52 response = client.get("/query", params={"param": "value"}) 1uvwx

53 assert response.status_code == 422, response.text 1uvwx

54 details = response.json() 1uvwx

55 assert details["detail"][0]["input"] == {"param": "value"} 1uvwx

56 

57 

58def test_header_model_with_alias_by_name(): 1abcd

59 client = TestClient(app) 1yzAB

60 response = client.get("/header", headers={"param": "value"}) 1yzAB

61 assert response.status_code == 422, response.text 1yzAB

62 details = response.json() 1yzAB

63 assert details["detail"][0]["input"] == IsPartialDict({"param": "value"}) 1yzAB

64 

65 

66def test_cookie_model_with_alias_by_name(): 1abcd

67 client = TestClient(app) 1ijkl

68 client.cookies.set("param", "value") 1ijkl

69 response = client.get("/cookie") 1ijkl

70 assert response.status_code == 422, response.text 1ijkl

71 details = response.json() 1ijkl

72 assert details["detail"][0]["input"] == {"param": "value"} 1ijkl