Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
23 changes: 23 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,28 @@ 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
({"const": {"k": "v", "k2": 10}}, {"enum": [{"k": "v", "k2": 10}]}), # dict
({"const": [10, 20]}, {"enum": [[10, 20]]}), # list
],
)
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