Debian Codegraph @

tests/test_body.py

raw symbols SCIP
1 from typing import Any, Dict, List
2
3 import pytest
4 from pydantic import field_validator
5
6 from ninja import Body, Form, NinjaAPI, Schema
7 from ninja.errors import ConfigError, ValidationError, ValidationErrorContext
8 from ninja.testing import TestClient
9
10 api = NinjaAPI()
11
12 # testing Body marker:
13
14
15 @api.post("/task")
16 def create_task(request, start: int = Body(...), end: int = Body(...)):
17 return [start, end]
18
19
20 @api.post("/task2")
21 def create_task2(request, start: int = Body(2), end: int = Form(1)):
22 return [start, end]
23
24
25 class UserIn(Schema):
26 # for testing validation errors context
27 email: str
28
29 @field_validator("email")
30 @classmethod
31 def validate_email(cls, v):
32 if "@" not in v:
33 raise ValueError("invalid email")
34 return v
35
36
37 @api.post("/users")
38 def create_user(request, payload: UserIn):
39 return payload.dict()
40
41
42 client = TestClient(api)
43
44
45 def test_body():
46 assert client.post("/task", json={"start": 1, "end": 2}).json() == [1, 2]
47 assert client.post("/task", json={"start": 1}).json() == {
48 "detail": [{"type": "missing", "loc": ["body", "end"], "msg": "Field required"}]
49 }
50
51
52 def test_body_form():
53 data = client.post("/task2", POST={"start": "1", "end": "2"}).json()
54 print(data)
55 assert client.post("/task2", POST={"start": "1", "end": "2"}).json() == [1, 2]
56 assert client.post("/task2").json() == [2, 1]
57
58
59 def test_body_validation_error():
60 resp = client.post("/users", json={"email": "[email protected]"})
61 assert resp.status_code == 200
62
63 resp = client.post("/users", json={"email": "invalid.com"})
64 assert resp.status_code == 422
65 assert resp.json()["detail"] == [
66 {
67 "type": "value_error",
68 "loc": ["body", "payload", "email"],
69 "msg": "Value error, invalid email",
70 "ctx": {"error": "invalid email"},
71 }
72 ]
73
74
75 def test_incorrect_annotation():
76 api = NinjaAPI()
77
78 class Some(Schema):
79 a: int
80
81 with pytest.raises(ConfigError):
82
83 @api.post("/some")
84 def some(request, payload=Some):
85 # ................. ^------ invalid usage assigning class instead of annotation
86 return 42
87
88
89 class CustomErrorAPI(NinjaAPI):
90 def validation_error_from_error_contexts(
91 self,
92 error_contexts: List[ValidationErrorContext],
93 ) -> ValidationError:
94 errors: List[Dict[str, Any]] = []
95 for context in error_contexts:
96 model = context.model
97 for e in context.pydantic_validation_error.errors(
98 include_url=False, include_context=False, include_input=False
99 ):
100 errors.append({
101 "source": model.__ninja_param_source__,
102 "message": e["msg"],
103 })
104 return ValidationError(errors)
105
106
107 custom_error_api = CustomErrorAPI()
108
109
110 @custom_error_api.post("/users")
111 def create_user2(request, payload: UserIn):
112 return payload.dict()
113
114
115 custom_error_client = TestClient(custom_error_api)
116
117
118 def test_body_custom_validation_error():
119 resp = custom_error_client.post("/users", json={"email": "[email protected]"})
120 assert resp.status_code == 200
121
122 resp = custom_error_client.post("/users", json={"email": "invalid.com"})
123 assert resp.status_code == 422
124 assert resp.json()["detail"] == [
125 {
126 "source": "body",
127 "message": "Value error, invalid email",
128 }
129 ]