Skip to content

Commit

Permalink
Fix #92: Exctract value from choice object for validation
Browse files Browse the repository at this point in the history
  • Loading branch information
bhch committed Mar 18, 2023
1 parent 6266cf2 commit c89f6b6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
15 changes: 14 additions & 1 deletion django_jsonform/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,18 @@ def get_datetime(self, value):
except ValueError:
return None

def get_choice_values(self, choices):
"""Returns values for given choices.
Useful for extracting choice values for object choices.
"""
values = []
for choice in choices:
if isinstance(choice, dict):
choice = choice.get('value', '')
values.append(choice)
return values

def validate_array(self, schema, data, coords):
if not isinstance(data, list):
data_type = type(data).__name__
Expand Down Expand Up @@ -134,8 +146,9 @@ def validate_array(self, schema, data, coords):
self.add_error(coords, 'All items in this list must be unique.')

if choices:
choice_values = self.get_choice_values(choices)
for item in data:
if item not in choices:
if item not in choice_values:
self.add_error(coords, 'Invalid choice %s' % item)
break

Expand Down
10 changes: 10 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def test_validate_array_uniqueItems(self):
validator(data_2) # must pass

def test_validate_array_choices(self):
# 1. plain choices
schema = {
'type': 'array',
'items': {'type': 'string', 'choices': ['1', '2', '3']}
Expand All @@ -150,6 +151,15 @@ def test_validate_array_choices(self):
self.assertRaises(JSONSchemaValidationError, validator, wrong_data)
validator(data) # must pass

# 2. choices with labels
schema = {
'type': 'array',
'items': {'type': 'string', 'choices': [{'label': '1', 'value': '1'}]}
}
validator = JSONSchemaValidator(schema)
self.assertRaises(JSONSchemaValidationError, validator, wrong_data)
validator(data) # must pass

def test_validate_object_type(self):
"""Data must be object if schema type is object"""
# top level object
Expand Down

0 comments on commit c89f6b6

Please sign in to comment.