Coverage for tests/test_required_noneable.py: 100%

38 statements  

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

1from typing import Union 1abcde

2 

3from fastapi import Body, FastAPI, Query 1abcde

4from fastapi.testclient import TestClient 1abcde

5 

6app = FastAPI() 1abcde

7 

8 

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

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

11 return q 1abcde

12 

13 

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

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

16 return q 1abcde

17 

18 

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

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

21 return b 1abcde

22 

23 

24client = TestClient(app) 1abcde

25 

26 

27def test_required_nonable_query_invalid(): 1abcde

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

29 assert response.status_code == 422 1abcde

30 

31 

32def test_required_noneable_query_value(): 1abcde

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

34 assert response.status_code == 200 1abcde

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

36 

37 

38def test_required_nonable_explicit_query_invalid(): 1abcde

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

40 assert response.status_code == 422 1abcde

41 

42 

43def test_required_nonable_explicit_query_value(): 1abcde

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

45 assert response.status_code == 200 1abcde

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

47 

48 

49def test_required_nonable_body_embed_no_content(): 1abcde

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

51 assert response.status_code == 422 1abcde

52 

53 

54def test_required_nonable_body_embed_invalid(): 1abcde

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

56 assert response.status_code == 422 1abcde

57 

58 

59def test_required_noneable_body_embed_value(): 1abcde

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

61 assert response.status_code == 200 1abcde

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