Coverage for tests/test_ambiguous_params.py: 100%

34 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1import pytest 1hijklmn

2from fastapi import Depends, FastAPI, Path 1hijklmn

3from fastapi.param_functions import Query 1hijklmn

4from fastapi.testclient import TestClient 1hijklmn

5from fastapi.utils import PYDANTIC_V2 1hijklmn

6from typing_extensions import Annotated 1hijklmn

7 

8app = FastAPI() 1hijklmn

9 

10 

11def test_no_annotated_defaults(): 1hijklmn

12 with pytest.raises( 1opqrstu

13 AssertionError, match="Path parameters cannot have a default value" 

14 ): 

15 

16 @app.get("/items/{item_id}/") 1opqrstu

17 async def get_item(item_id: Annotated[int, Path(default=1)]): 1opqrstu

18 pass # pragma: nocover 

19 

20 with pytest.raises( 1opqrstu

21 AssertionError, 

22 match=( 

23 "`Query` default value cannot be set in `Annotated` for 'item_id'. Set the" 

24 " default value with `=` instead." 

25 ), 

26 ): 

27 

28 @app.get("/") 1opqrstu

29 async def get(item_id: Annotated[int, Query(default=1)]): 1opqrstu

30 pass # pragma: nocover 

31 

32 

33def test_multiple_annotations(): 1hijklmn

34 async def dep(): 1abcdefg

35 pass # pragma: nocover 

36 

37 @app.get("/multi-query") 1abcdefg

38 async def get(foo: Annotated[int, Query(gt=2), Query(lt=10)]): 1abcdefg

39 return foo 1abcdefg

40 

41 with pytest.raises( 1abcdefg

42 AssertionError, 

43 match=( 

44 "Cannot specify `Depends` in `Annotated` and default value" 

45 " together for 'foo'" 

46 ), 

47 ): 

48 

49 @app.get("/") 1abcdefg

50 async def get2(foo: Annotated[int, Depends(dep)] = Depends(dep)): 1abcdefg

51 pass # pragma: nocover 

52 

53 with pytest.raises( 1abcdefg

54 AssertionError, 

55 match=( 

56 "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a" 

57 " default value together for 'foo'" 

58 ), 

59 ): 

60 

61 @app.get("/") 1abcdefg

62 async def get3(foo: Annotated[int, Query(min_length=1)] = Depends(dep)): 1abcdefg

63 pass # pragma: nocover 

64 

65 client = TestClient(app) 1abcdefg

66 response = client.get("/multi-query", params={"foo": "5"}) 1abcdefg

67 assert response.status_code == 200 1abcdefg

68 assert response.json() == 5 1abcdefg

69 

70 response = client.get("/multi-query", params={"foo": "123"}) 1abcdefg

71 assert response.status_code == 422 1abcdefg

72 

73 if PYDANTIC_V2: 1abcdefg

74 response = client.get("/multi-query", params={"foo": "1"}) 1abcdefg

75 assert response.status_code == 422 1abcdefg