| 1 |
import json |
| 2 |
from typing import Annotated |
| 3 |
|
| 4 |
from fastapi import Cookie, FastAPI, Form, Header, Query |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
from pydantic import Json |
| 7 |
|
| 8 |
app = FastAPI() |
| 9 |
|
| 10 |
|
| 11 |
@app.post("/form-json-list") |
| 12 |
def form_json_list(items: Annotated[Json[list[str]], Form()]) -> list[str]: |
| 13 |
return items |
| 14 |
|
| 15 |
|
| 16 |
@app.get("/query-json-list") |
| 17 |
def query_json_list(items: Annotated[Json[list[str]], Query()]) -> list[str]: |
| 18 |
return items |
| 19 |
|
| 20 |
|
| 21 |
@app.get("/header-json-list") |
| 22 |
def header_json_list(x_items: Annotated[Json[list[str]], Header()]) -> list[str]: |
| 23 |
return x_items |
| 24 |
|
| 25 |
|
| 26 |
@app.get("/cookie-json-list") |
| 27 |
def cookie_json_list(items: Annotated[Json[list[str]], Cookie()]) -> list[str]: |
| 28 |
return items |
| 29 |
|
| 30 |
|
| 31 |
client = TestClient(app) |
| 32 |
|
| 33 |
|
| 34 |
def test_form_json_list(): |
| 35 |
response = client.post( |
| 36 |
"/form-json-list", data={"items": json.dumps(["abc", "def"])} |
| 37 |
) |
| 38 |
assert response.status_code == 200, response.text |
| 39 |
assert response.json() == ["abc", "def"] |
| 40 |
|
| 41 |
|
| 42 |
def test_query_json_list(): |
| 43 |
response = client.get( |
| 44 |
"/query-json-list", params={"items": json.dumps(["abc", "def"])} |
| 45 |
) |
| 46 |
assert response.status_code == 200, response.text |
| 47 |
assert response.json() == ["abc", "def"] |
| 48 |
|
| 49 |
|
| 50 |
def test_header_json_list(): |
| 51 |
response = client.get( |
| 52 |
"/header-json-list", headers={"x-items": json.dumps(["abc", "def"])} |
| 53 |
) |
| 54 |
assert response.status_code == 200, response.text |
| 55 |
assert response.json() == ["abc", "def"] |
| 56 |
|
| 57 |
|
| 58 |
def test_cookie_json_list(): |
| 59 |
client.cookies.set("items", json.dumps(["abc", "def"])) |
| 60 |
response = client.get("/cookie-json-list") |
| 61 |
assert response.status_code == 200, response.text |
| 62 |
assert response.json() == ["abc", "def"] |
| 63 |
client.cookies.clear() |