Skip to content

feat(validation): add anyOf validator for ContainsOnly #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
handle_equal,
handle_length,
handle_one_of,
handle_any_of,
handle_range,
handle_regexp,
)
Expand Down Expand Up @@ -100,6 +101,7 @@
validate.Equal: handle_equal,
validate.Length: handle_length,
validate.OneOf: handle_one_of,
validate.ContainsOnly: handle_any_of,
validate.Range: handle_range,
validate.Regexp: handle_regexp,
}
Expand Down
35 changes: 35 additions & 0 deletions marshmallow_jsonschema/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,41 @@ def handle_one_of(schema, field, validator, parent_schema):
return schema


def handle_any_of(schema, field, validator, parent_schema):
"""Adds the validation logic for ``marshmallow.validate.ContainsOnly`` by setting
the JSONSchema `anyOf` property to the allowed choices in the validator.
Args:
schema (dict): The original JSON schema we generated. This is what we
want to post-process.
field (fields.Field): The field that generated the original schema and
who this post-processor belongs to.
validator (marshmallow.validate.ContainsOnly): The validator attached to the
passed in field.
parent_schema (marshmallow.Schema): The Schema instance that the field
belongs to.
Returns:
dict: New JSON Schema that has been post processed and
altered.
"""
if schema["type"] != "array":
return schema

choices = field._serialize(validator.choices, field.name, None)
if not choices:
return schema

field_type = schema["items"].get("type", "string")

labels = validator.labels if validator.labels else choices
schema["items"]["anyOf"] = [
{"type": field_type, "title": label, "const": choice}
for choice, label in zip(choices, labels)
]
schema["uniqueItems"] = True

return schema


def handle_equal(schema, field, validator, parent_schema):
"""Adds the validation logic for ``marshmallow.validate.Equal`` by setting
the JSONSchema `enum` property to value of the validator.
Expand Down
60 changes: 59 additions & 1 deletion tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest
from marshmallow import Schema, fields, validate
from marshmallow.validate import OneOf, Range
from marshmallow.validate import OneOf, Range, ContainsOnly
from marshmallow_enum import EnumField
from marshmallow_union import Union

Expand Down Expand Up @@ -80,6 +80,64 @@ class TestSchema(Schema):
assert foo_property["enumNames"] == []


def test_any_of_validator():
class TestSchema(Schema):
foo = fields.List(
fields.String,
validate=ContainsOnly(
choices=["apple", "lime", "orange"], labels=["Apple", "Lime", "Orange"]
),
)

schema = TestSchema()

dumped = validate_and_dump(schema)

foo_property = dumped["definitions"]["TestSchema"]["properties"]["foo"]
assert foo_property["uniqueItems"] == True
assert foo_property["items"]["anyOf"] == [
{"type": "string", "title": "Apple", "const": "apple"},
{"type": "string", "title": "Lime", "const": "lime"},
{"type": "string", "title": "Orange", "const": "orange"},
]


def test_any_of_validator_empty_choice():
class TestSchema(Schema):
foo = fields.List(
fields.String,
validate=ContainsOnly(choices=[]),
)

schema = TestSchema()

dumped = validate_and_dump(schema)

foo_property = dumped["definitions"]["TestSchema"]["properties"]["foo"]
assert foo_property == {
"title": "foo",
"type": "array",
"items": {"title": "foo", "type": "string"},
}


def test_any_of_validator_with_string_field():
class TestSchema(Schema):
foo = fields.String(
validate=ContainsOnly(
choices=["apple", "lime", "orange"], labels=["Apple", "Lime", "Orange"]
)
)

schema = TestSchema()

dumped = validate_and_dump(schema)

foo_property = dumped["definitions"]["TestSchema"]["properties"]["foo"]
assert "uniqueItems" not in foo_property
assert "items" not in foo_property


def test_range():
class TestSchema(Schema):
foo = fields.Integer(
Expand Down