Skip to content

Commit

Permalink
Add support for "const" keyword in JSON schema
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexPetul committed May 22, 2024
1 parent f124e60 commit 03d05af
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions django_custom_jsonfield/rest_framework/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ def build_basic_schema(self, schema: dict):
def map_serializer_field(self, auto_schema, direction):
schema = self.target.schema

if "const" in schema:
if schema["const"] is None:
return None

return {"enum": [schema["const"]]}

try:
if schema["type"] == "object":
return self.build_object_schema(schema)
Expand Down
21 changes: 21 additions & 0 deletions tests/test_openapi_schema.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Any
from unittest.mock import Mock

import pytest
Expand Down Expand Up @@ -50,6 +51,26 @@ def test_map_serializer_field_ok(schema: dict):
assert data == schema


@pytest.mark.parametrize(
"schema,expected",
[
({"const": 10}, {"enum": [10]}), # integer
({"const": 10.00}, {"enum": [10.00]}), # float
({"const": 10.00}, {"enum": [10.00]}), # bytes
({"const": "string"}, {"enum": ["string"]}), # string
({"const": True}, {"enum": [True]}), # bool
({"const": None}, None), # none
],
)
def test_map_serializer_field_const(schema: dict, expected: Any):
"""Test basic types declared as const in JSON schema."""

json_field = CustomJSONField(schema=schema)
extension = CustomJSONFieldSerializerExtension(json_field)
data = extension.map_serializer_field(Mock(), "response")
assert data == expected


@pytest.mark.parametrize(
"schema",
[
Expand Down

0 comments on commit 03d05af

Please sign in to comment.