Coverage for tests / test_required_noneable.py: 100%

38 statements  

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

1from typing import Union 1abcd

2 

3from fastapi import Body, FastAPI, Query 1abcd

4from fastapi.testclient import TestClient 1abcd

5 

6app = FastAPI() 1abcd

7 

8 

9@app.get("/query") 1abcd

10def read_query(q: Union[str, None]): 1abcd

11 return q 1efg

12 

13 

14@app.get("/explicit-query") 1abcd

15def read_explicit_query(q: Union[str, None] = Query()): 1abcd

16 return q 1hij

17 

18 

19@app.post("/body-embed") 1abcd

20def send_body_embed(b: Union[str, None] = Body(embed=True)): 1abcd

21 return b 1klm

22 

23 

24client = TestClient(app) 1abcd

25 

26 

27def test_required_nonable_query_invalid(): 1abcd

28 response = client.get("/query") 1nop

29 assert response.status_code == 422 1nop

30 

31 

32def test_required_noneable_query_value(): 1abcd

33 response = client.get("/query", params={"q": "foo"}) 1efg

34 assert response.status_code == 200 1efg

35 assert response.json() == "foo" 1efg

36 

37 

38def test_required_nonable_explicit_query_invalid(): 1abcd

39 response = client.get("/explicit-query") 1qrs

40 assert response.status_code == 422 1qrs

41 

42 

43def test_required_nonable_explicit_query_value(): 1abcd

44 response = client.get("/explicit-query", params={"q": "foo"}) 1hij

45 assert response.status_code == 200 1hij

46 assert response.json() == "foo" 1hij

47 

48 

49def test_required_nonable_body_embed_no_content(): 1abcd

50 response = client.post("/body-embed") 1tuv

51 assert response.status_code == 422 1tuv

52 

53 

54def test_required_nonable_body_embed_invalid(): 1abcd

55 response = client.post("/body-embed", json={"invalid": "invalid"}) 1wxy

56 assert response.status_code == 422 1wxy

57 

58 

59def test_required_noneable_body_embed_value(): 1abcd

60 response = client.post("/body-embed", json={"b": "foo"}) 1klm

61 assert response.status_code == 200 1klm

62 assert response.json() == "foo" 1klm