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
feature: Permit an array to be provided for 'type'. Fixes #17
  • Loading branch information
cwacek committed Jul 16, 2016
commit 4a492dff4b3ba4f6fa85eca820b175e6db9b4883
20 changes: 18 additions & 2 deletions python_jsonschema_objects/classbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def __new__(cls, **props):
else: # We got nothing
raise validators.ValidationError(
"Unable to instantiate any valid types: \n"
"\n".join("{0}: {1}".format(k, e) for k, e in validation_errors)
"".join("{0}: {1}\n".format(k, e) for k, e in validation_errors)
)

return obj
Expand Down Expand Up @@ -314,7 +314,7 @@ def __call__(self, *a, **kw):
else: # We got nothing
raise validators.ValidationError(
"Unable to instantiate any valid types: \n"
"\n".join("{0}: {1}".format(k, e) for k, e in validation_errors)
"".join("{0}: {1}\n".format(k, e) for k, e in validation_errors)
)


Expand Down Expand Up @@ -474,6 +474,18 @@ def _construct(self, uri, clsdata, parent=(ProtocolBase,)):
**clsdata_copy)
return self.resolved[uri]

elif isinstance(clsdata.get('type'), list):
types = []
for i, item_detail in enumerate(clsdata['type']):
subdata = {k: v for k, v in six.iteritems(clsdata) if k != 'type'}
subdata['type'] = item_detail
types.append(self._build_literal(
uri + "_%s" % i,
subdata))

self.resolved[uri] = TypeProxy(types)
return self.resolved[uri]

elif (clsdata.get('type', None) == 'object' or
clsdata.get('properties', None) is not None or
clsdata.get('additionalProperties', False)):
Expand Down Expand Up @@ -770,6 +782,10 @@ def setprop(self, val):
val = info['type'](**util.coerce_for_expansion(val))

val.validate()

elif isinstance(info['type'], TypeProxy):
val = info['type'](val)

elif info['type'] is None:
# This is the null value
if val is not None:
Expand Down
33 changes: 33 additions & 0 deletions test/test_regression_17.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import pytest

import python_jsonschema_objects as pjo


@pytest.fixture
def test_class():
schema = {
'title': 'Example',
'properties': {
"claimed_by": {
"id": "claimed",
"type": ["string", "integer", "null"],
"description": "Robots Only. The human agent that has claimed this robot.",
"required": False
},
}
}

builder = pjo.ObjectBuilder(schema)
ns = builder.build_classes()
return ns


@pytest.mark.parametrize('value', [
"Hi", 4, None])
def test_properties_can_have_multiple_types(test_class, value):
test_class.Example(claimed_by=value)

@pytest.mark.parametrize('value', [2.4])
def test_multiply_typed_properties_still_validate(test_class, value):
with pytest.raises(pjo.ValidationError):
test_class.Example(claimed_by=value)