Skip to content

Commit

Permalink
add validate_schema to schemaSerializer
Browse files Browse the repository at this point in the history
  • Loading branch information
Floris272 committed Jan 29, 2025
1 parent c07f640 commit b024b5a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/open_producten/producttypen/serializers/jsonschema.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
from django_json_schema.models import JsonSchema
from jsonschema import Draft202012Validator
from jsonschema.exceptions import SchemaError
from rest_framework import serializers


class JsonSchemaSerializer(serializers.ModelSerializer):

schema = serializers.DictField()

def validate_schema(self, schema):
try:
Draft202012Validator.check_schema(schema)
except SchemaError as e:
raise serializers.ValidationError(e.message)

return schema

class Meta:
model = JsonSchema
fields = "__all__"
17 changes: 17 additions & 0 deletions src/open_producten/producttypen/tests/api/test_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,23 @@ def test_create_schema(self):
response.data.pop("id")
self.assertEqual(response.data, self.data)

def test_create_invalid_schema(self):
data = self.data | {"schema": {"type": []}}
response = self.client.post(self.path, data)

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data,
{
"schema": [
ErrorDetail(
string="[] is not valid under any of the given schemas",
code="invalid",
)
]
},
)

def test_update_schema(self):
data = self.data | {"name": "update"}
response = self.client.put(self.detail_path, data)
Expand Down

0 comments on commit b024b5a

Please sign in to comment.