Coverage for tests / test_json_type.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1import json 1abcd

2from typing import Annotated 1abcd

3 

4from fastapi import Cookie, FastAPI, Form, Header, Query 1abcd

5from fastapi.testclient import TestClient 1abcd

6from pydantic import Json 1abcd

7 

8app = FastAPI() 1abcd

9 

10 

11@app.post("/form-json-list") 1abcd

12def form_json_list(items: Annotated[Json[list[str]], Form()]) -> list[str]: 1abcd

13 return items 1hij

14 

15 

16@app.get("/query-json-list") 1abcd

17def query_json_list(items: Annotated[Json[list[str]], Query()]) -> list[str]: 1abcd

18 return items 1klm

19 

20 

21@app.get("/header-json-list") 1abcd

22def header_json_list(x_items: Annotated[Json[list[str]], Header()]) -> list[str]: 1abcd

23 return x_items 1nop

24 

25 

26@app.get("/cookie-json-list") 1abcd

27def cookie_json_list(items: Annotated[Json[list[str]], Cookie()]) -> list[str]: 1abcd

28 return items 1efg

29 

30 

31client = TestClient(app) 1abcd

32 

33 

34def test_form_json_list(): 1abcd

35 response = client.post( 1hij

36 "/form-json-list", data={"items": json.dumps(["abc", "def"])} 

37 ) 

38 assert response.status_code == 200, response.text 1hij

39 assert response.json() == ["abc", "def"] 1hij

40 

41 

42def test_query_json_list(): 1abcd

43 response = client.get( 1klm

44 "/query-json-list", params={"items": json.dumps(["abc", "def"])} 

45 ) 

46 assert response.status_code == 200, response.text 1klm

47 assert response.json() == ["abc", "def"] 1klm

48 

49 

50def test_header_json_list(): 1abcd

51 response = client.get( 1nop

52 "/header-json-list", headers={"x-items": json.dumps(["abc", "def"])} 

53 ) 

54 assert response.status_code == 200, response.text 1nop

55 assert response.json() == ["abc", "def"] 1nop

56 

57 

58def test_cookie_json_list(): 1abcd

59 client.cookies.set("items", json.dumps(["abc", "def"])) 1efg

60 response = client.get("/cookie-json-list") 1efg

61 assert response.status_code == 200, response.text 1efg

62 assert response.json() == ["abc", "def"] 1efg

63 client.cookies.clear() 1efg