Coverage for tests/test_starlette_urlconvertors.py: 100%

36 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from fastapi import FastAPI, Path, Query 1abcde

2from fastapi.testclient import TestClient 1abcde

3 

4app = FastAPI() 1abcde

5 

6 

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

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

9 return {"int": param} 1abcde

10 

11 

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

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

14 return {"float": param} 1abcde

15 

16 

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

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

19 return {"path": param} 1abcde

20 

21 

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

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

24 return {"query": param} 1abcde

25 

26 

27client = TestClient(app) 1abcde

28 

29 

30def test_route_converters_int(): 1abcde

31 # Test integer conversion 

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

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

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

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

36 

37 

38def test_route_converters_float(): 1abcde

39 # Test float conversion 

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

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

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

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

44 

45 

46def test_route_converters_path(): 1abcde

47 # Test path conversion 

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

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

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

51 

52 

53def test_route_converters_query(): 1abcde

54 # Test query conversion 

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

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

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

58 

59 

60def test_url_path_for_path_convertor(): 1abcde

61 assert ( 1abcde

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

63 )