Skip to content

Commit

Permalink
Merge pull request #89 from cwacek/feature/support-top-level-arrays
Browse files Browse the repository at this point in the history
Fix #88. Properly construct wrappers for top level array constraints
  • Loading branch information
cwacek authored Oct 7, 2017
2 parents a0a560d + 5cc4599 commit dee1406
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
8 changes: 7 additions & 1 deletion python_jsonschema_objects/wrapper_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,10 +275,16 @@ def create(name, item_constraint=None, **addl_constraints):

item_constraint = classbuilder.TypeProxy(type_array)

elif isdict and item_constraint.get('type') == 'object':
""" We need to create a ProtocolBase object for this anonymous definition"""
uri = "{0}_{1}".format(name, "<anonymous_list_type>")
item_constraint = klassbuilder.construct(
uri, item_constraint)

props['__itemtype__'] = item_constraint

props.update(addl_constraints)

validator = type(str(name), (ArrayWrapper,), props)

return validator
return validator
49 changes: 49 additions & 0 deletions test/test_regression_88.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import pytest
import json

import python_jsonschema_objects as pjs


def test_nested_arrays_work_fine():
schema = {
"$schema": "http://json-schema.org/draft-04/schema",
"title": "Example1",
"type": "object",
"properties": {
"name": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"}
}
}
}
}
}

ns1 = pjs.ObjectBuilder(schema).build_classes()
j1 = ns1.Example1.from_json(json.dumps({'name': [{'value':'foo'}, {'value':'bar'}]}))
assert j1.name[0].value == 'foo'
assert j1.name[1].value == 'bar'


def test_top_level_arrays_are_converted_to_objects_properly():
schema = {
"$schema": "http://json-schema.org/draft-04/schema",
"title": "Example2",
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"}
}
}
}

ns2 = pjs.ObjectBuilder(schema).build_classes()
j2 = ns2.Example2.from_json(json.dumps([{'name': 'foo'}, {'name': 'bar'}]))
assert not isinstance(j2[0], dict) # Out[173]: {'name': 'foo'}
assert j2[0].name == 'foo'
assert j2[1].name == 'bar'

0 comments on commit dee1406

Please sign in to comment.