Coverage for tests/test_starlette_urlconvertors.py: 100%

36 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from fastapi import FastAPI, Path, Query 1abcdef

2from fastapi.testclient import TestClient 1abcdef

3 

4app = FastAPI() 1abcdef

5 

6 

7@app.get("/int/{param:int}") 1abcdef

8def int_convertor(param: int = Path()): 1abcdef

9 return {"int": param} 1ghijkl

10 

11 

12@app.get("/float/{param:float}") 1abcdef

13def float_convertor(param: float = Path()): 1abcdef

14 return {"float": param} 1mnopqr

15 

16 

17@app.get("/path/{param:path}") 1abcdef

18def path_convertor(param: str = Path()): 1abcdef

19 return {"path": param} 1stuvwx

20 

21 

22@app.get("/query/") 1abcdef

23def query_convertor(param: str = Query()): 1abcdef

24 return {"query": param} 1yzABCD

25 

26 

27client = TestClient(app) 1abcdef

28 

29 

30def test_route_converters_int(): 1abcdef

31 # Test integer conversion 

32 response = client.get("/int/5") 1ghijkl

33 assert response.status_code == 200, response.text 1ghijkl

34 assert response.json() == {"int": 5} 1ghijkl

35 assert app.url_path_for("int_convertor", param=5) == "/int/5" # type: ignore 1ghijkl

36 

37 

38def test_route_converters_float(): 1abcdef

39 # Test float conversion 

40 response = client.get("/float/25.5") 1mnopqr

41 assert response.status_code == 200, response.text 1mnopqr

42 assert response.json() == {"float": 25.5} 1mnopqr

43 assert app.url_path_for("float_convertor", param=25.5) == "/float/25.5" # type: ignore 1mnopqr

44 

45 

46def test_route_converters_path(): 1abcdef

47 # Test path conversion 

48 response = client.get("/path/some/example") 1stuvwx

49 assert response.status_code == 200, response.text 1stuvwx

50 assert response.json() == {"path": "some/example"} 1stuvwx

51 

52 

53def test_route_converters_query(): 1abcdef

54 # Test query conversion 

55 response = client.get("/query", params={"param": "Qué tal!"}) 1yzABCD

56 assert response.status_code == 200, response.text 1yzABCD

57 assert response.json() == {"query": "Qué tal!"} 1yzABCD

58 

59 

60def test_url_path_for_path_convertor(): 1abcdef

61 assert ( 1EFGHIJ

62 app.url_path_for("path_convertor", param="some/example") == "/path/some/example" 

63 )