Debian Codegraph @

tests/test_patch_dict.py

raw symbols SCIP
1 from typing import List, Optional
2
3 import pytest
4
5 from ninja import NinjaAPI, Schema
6 from ninja.patch_dict import PatchDict
7 from ninja.testing import TestClient
8
9 api = NinjaAPI()
10
11 client = TestClient(api)
12
13
14 class SomeSchema(Schema):
15 name: str
16 age: int
17 category: Optional[str] = None
18
19
20 class OtherSchema(SomeSchema):
21 other: str
22 category: Optional[List[str]] = None
23
24
25 @api.patch("/patch")
26 def patch(request, payload: PatchDict[SomeSchema]):
27 return {"payload": payload, "type": str(type(payload))}
28
29
30 @api.patch("/patch-inherited")
31 def patch_inherited(request, payload: PatchDict[OtherSchema]):
32 return {"payload": payload, "type": str(type(payload))}
33
34
35 @pytest.mark.parametrize(
36 "input,output",
37 [
38 ({"name": "foo"}, {"name": "foo"}),
39 ({"age": "1"}, {"age": 1}),
40 ({}, {}),
41 ({"wrong_param": 1}, {}),
42 ({"age": None}, {"age": None}),
43 ],
44 )
45 def test_patch_calls(input: dict, output: dict):
46 response = client.patch("/patch", json=input)
47 assert response.json() == {"payload": output, "type": "<class 'dict'>"}
48
49
50 def test_schema():
51 "Checking that json schema properties are all optional"
52 schema = api.get_openapi_schema()
53 assert schema["components"]["schemas"]["SomeSchemaPatch"] == {
54 "title": "SomeSchemaPatch",
55 "type": "object",
56 "properties": {
57 "name": {
58 "anyOf": [{"type": "string"}, {"type": "null"}],
59 "title": "Name",
60 },
61 "age": {
62 "anyOf": [{"type": "integer"}, {"type": "null"}],
63 "title": "Age",
64 },
65 "category": {
66 "anyOf": [{"type": "string"}, {"type": "null"}],
67 "title": "Category",
68 },
69 },
70 }
71
72
73 def test_patch_inherited():
74 input = {"other": "any", "category": ["cat1", "cat2"]}
75 expected_output = {"payload": input, "type": "<class 'dict'>"}
76
77 response = client.patch("/patch-inherited", json=input)
78 assert response.json() == expected_output
79
80
81 def test_inherited_schema():
82 "Checking that json schema properties for inherithed schemas are ok"
83 schema = api.get_openapi_schema()
84 assert schema["components"]["schemas"]["OtherSchemaPatch"] == {
85 "title": "OtherSchemaPatch",
86 "type": "object",
87 "properties": {
88 "name": {
89 "anyOf": [{"type": "string"}, {"type": "null"}],
90 "title": "Name",
91 },
92 "age": {
93 "anyOf": [{"type": "integer"}, {"type": "null"}],
94 "title": "Age",
95 },
96 "other": {
97 "anyOf": [{"type": "string"}, {"type": "null"}],
98 "title": "Other",
99 },
100 "category": {
101 "anyOf": [
102 {
103 "items": {
104 "type": "string",
105 },
106 "type": "array",
107 },
108 {"type": "null"},
109 ],
110 "title": "Category",
111 },
112 },
113 }