| 1 |
from fastapi import FastAPI, Path, Query |
| 2 |
from fastapi.testclient import TestClient |
| 3 |
|
| 4 |
app = FastAPI() |
| 5 |
|
| 6 |
|
| 7 |
@app.get("/int/{param:int}") |
| 8 |
def int_convertor(param: int = Path()): |
| 9 |
return {"int": param} |
| 10 |
|
| 11 |
|
| 12 |
@app.get("/float/{param:float}") |
| 13 |
def float_convertor(param: float = Path()): |
| 14 |
return {"float": param} |
| 15 |
|
| 16 |
|
| 17 |
@app.get("/path/{param:path}") |
| 18 |
def path_convertor(param: str = Path()): |
| 19 |
return {"path": param} |
| 20 |
|
| 21 |
|
| 22 |
@app.get("/query/") |
| 23 |
def query_convertor(param: str = Query()): |
| 24 |
return {"query": param} |
| 25 |
|
| 26 |
|
| 27 |
client = TestClient(app) |
| 28 |
|
| 29 |
|
| 30 |
def test_route_converters_int(): |
| 31 |
# Test integer conversion |
| 32 |
response = client.get("/int/5") |
| 33 |
assert response.status_code == 200, response.text |
| 34 |
assert response.json() == {"int": 5} |
| 35 |
assert app.url_path_for("int_convertor", param=5) == "/int/5" |
| 36 |
|
| 37 |
|
| 38 |
def test_route_converters_float(): |
| 39 |
# Test float conversion |
| 40 |
response = client.get("/float/25.5") |
| 41 |
assert response.status_code == 200, response.text |
| 42 |
assert response.json() == {"float": 25.5} |
| 43 |
assert app.url_path_for("float_convertor", param=25.5) == "/float/25.5" |
| 44 |
|
| 45 |
|
| 46 |
def test_route_converters_path(): |
| 47 |
# Test path conversion |
| 48 |
response = client.get("/path/some/example") |
| 49 |
assert response.status_code == 200, response.text |
| 50 |
assert response.json() == {"path": "some/example"} |
| 51 |
|
| 52 |
|
| 53 |
def test_route_converters_query(): |
| 54 |
# Test query conversion |
| 55 |
response = client.get("/query", params={"param": "Qué tal!"}) |
| 56 |
assert response.status_code == 200, response.text |
| 57 |
assert response.json() == {"query": "Qué tal!"} |
| 58 |
|
| 59 |
|
| 60 |
def test_url_path_for_path_convertor(): |
| 61 |
assert ( |
| 62 |
app.url_path_for("path_convertor", param="some/example") == "/path/some/example" |
| 63 |
) |