-
-
Notifications
You must be signed in to change notification settings - Fork 422
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
46 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
from ninja import Body, Form, NinjaAPI | ||
from pydantic import field_validator | ||
|
||
from ninja import Body, Form, NinjaAPI, Schema | ||
from ninja.testing import TestClient | ||
|
||
api = NinjaAPI() | ||
|
@@ -16,17 +18,51 @@ def create_task2(request, start: int = Body(2), end: int = Form(1)): | |
return [start, end] | ||
|
||
|
||
class UserIn(Schema): | ||
# for testing validation errors context | ||
email: str | ||
|
||
@field_validator("email") | ||
@classmethod | ||
def validate_email(cls, v): | ||
if "@" not in v: | ||
raise ValueError("invalid email") | ||
return v | ||
|
||
|
||
@api.post("/users") | ||
def create_user(request, payload: UserIn): | ||
return payload.dict() | ||
|
||
|
||
client = TestClient(api) | ||
|
||
|
||
def test_body(): | ||
client = TestClient(api) | ||
assert client.post("/task", json={"start": 1, "end": 2}).json() == [1, 2] | ||
assert client.post("/task", json={"start": 1}).json() == { | ||
"detail": [{"type": "missing", "loc": ["body", "end"], "msg": "Field required"}] | ||
} | ||
|
||
|
||
def test_body_form(): | ||
client = TestClient(api) | ||
data = client.post("/task2", POST={"start": "1", "end": "2"}).json() | ||
print(data) | ||
assert client.post("/task2", POST={"start": "1", "end": "2"}).json() == [1, 2] | ||
assert client.post("/task2").json() == [2, 1] | ||
|
||
|
||
def test_body_validation_error(): | ||
resp = client.post("/users", json={"email": "[email protected]"}) | ||
assert resp.status_code == 200 | ||
|
||
resp = client.post("/users", json={"email": "invalid.com"}) | ||
assert resp.status_code == 422 | ||
assert resp.json()["detail"] == [ | ||
{ | ||
"type": "value_error", | ||
"loc": ["body", "payload", "email"], | ||
"msg": "Value error, invalid email", | ||
"ctx": {"error": "invalid email"}, | ||
} | ||
] |