Debian Codegraph @

tests/test_forms.py

raw symbols SCIP
1 import pytest
2
3 from ninja import Form, NinjaAPI, Schema
4 from ninja.errors import ConfigError
5 from ninja.testing import TestClient
6
7 api = NinjaAPI()
8
9
10 @api.post("/form")
11 def form_operation(request, s: str = Form(...), i: int = Form(None)):
12 return {"s": s, "i": i}
13
14
15 client = TestClient(api)
16
17
18 def test_form():
19 response = client.post("/form") # invalid
20 assert response.status_code == 422
21
22 response = client.post("/form", POST={"s": "text"})
23 assert response.status_code == 200
24 assert response.json() == {"i": None, "s": "text"}
25
26 response = client.post("/form", POST={"s": "text", "i": None})
27 assert response.status_code == 200
28 assert response.json() == {"i": None, "s": "text"}
29
30 response = client.post("/form", POST={"s": "text", "i": 2})
31 assert response.status_code == 200
32 assert response.json() == {"i": 2, "s": "text"}
33
34
35 def test_schema():
36 schema = api.get_openapi_schema()
37 method = schema["paths"]["/api/form"]["post"]
38 print(method["requestBody"])
39 assert method["requestBody"] == {
40 "content": {
41 "application/x-www-form-urlencoded": {
42 "schema": {
43 "properties": {
44 "i": {"type": "integer", "title": "I"},
45 "s": {"type": "string", "title": "S"},
46 },
47 "required": ["s"],
48 "title": "FormParams",
49 "type": "object",
50 }
51 }
52 },
53 "required": True,
54 }
55
56
57 def test_duplicate_names():
58 # Create separate APIs for error testing to avoid frozen router issues
59 class TestData(Schema):
60 p1: str
61
62 api1 = NinjaAPI(urls_namespace="test_dup1")
63 match = "Duplicated name: 'p1' in params: 'p1' & 'data'"
64 with pytest.raises(ConfigError, match=match):
65
66 @api1.post("/broken1")
67 def broken1(request, p1: int = Form(...), data: TestData = Form(...)):
68 pass
69
70 api2 = NinjaAPI(urls_namespace="test_dup2")
71 match = "Duplicated name: 'p1' also in 'data'"
72 with pytest.raises(ConfigError, match=match):
73
74 @api2.post("/broken2")
75 def broken2(request, data: TestData = Form(...), p1: int = Form(...)):
76 pass
77
78
79 # TODO: Fix schema for this case:
80 # class Credentials(Schema):
81 # username: str
82 # password: str
83
84
85 # @api.post("/login")
86 # def login(request, credentials: Credentials = Form(...)):
87 # return {'username': credentials.username}