Skip to content

Commit 4967eb1

Browse files
authored
Add support for "const" keyword in JSON schema (#1)
* Add support for "const" keyword in JSON schema * Add tests for const list and dict
1 parent b6dac30 commit 4967eb1

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

django_custom_jsonfield/rest_framework/openapi.py

+6
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ def build_basic_schema(self, schema: dict):
4848
def map_serializer_field(self, auto_schema, direction):
4949
schema = self.target.schema
5050

51+
if "const" in schema:
52+
if schema["const"] is None:
53+
return None
54+
55+
return {"enum": [schema["const"]]}
56+
5157
try:
5258
if schema["type"] == "object":
5359
return self.build_object_schema(schema)

tests/test_openapi_schema.py

+23
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from typing import Any
12
from unittest.mock import Mock
23

34
import pytest
@@ -50,6 +51,28 @@ def test_map_serializer_field_ok(schema: dict):
5051
assert data == schema
5152

5253

54+
@pytest.mark.parametrize(
55+
"schema,expected",
56+
[
57+
({"const": 10}, {"enum": [10]}), # integer
58+
({"const": 10.00}, {"enum": [10.00]}), # float
59+
({"const": 10.00}, {"enum": [10.00]}), # bytes
60+
({"const": "string"}, {"enum": ["string"]}), # string
61+
({"const": True}, {"enum": [True]}), # bool
62+
({"const": None}, None), # none
63+
({"const": {"k": "v", "k2": 10}}, {"enum": [{"k": "v", "k2": 10}]}), # dict
64+
({"const": [10, 20]}, {"enum": [[10, 20]]}), # list
65+
],
66+
)
67+
def test_map_serializer_field_const(schema: dict, expected: Any):
68+
"""Test basic types declared as const in JSON schema."""
69+
70+
json_field = CustomJSONField(schema=schema)
71+
extension = CustomJSONFieldSerializerExtension(json_field)
72+
data = extension.map_serializer_field(Mock(), "response")
73+
assert data == expected
74+
75+
5376
@pytest.mark.parametrize(
5477
"schema",
5578
[

0 commit comments

Comments
 (0)