Repository: cwacek/python-jsonschema-objects

Issue:
Bad handling of arrays of mixed types objects
(or at least inconsistent with `jsonschema`)

Here is a minimal test case:

```
schema_good = {
    'title': 'example',
    'type': 'array',
    'items': {
        'oneOf': [
            {
                'type': 'object',
                'properties': {
                    'a': {
                        'type': 'string',
                    }
                },
                'required': [ 'a' ],
            },
            {
                'type': 'object',
                'properties': {
                    'b': {
                        'type': 'string',
                    }
                },
                'required': [ 'b' ],
            },
        ]
    },
}

instance = [{'a': ''}, {'b': ''}]
```

`jsonschema` validates our instance but `build_classes()` crashes:

```
Traceback (most recent call last):
  File "schema.py", line 70, in <module>
    pjs.ObjectBuilder(schema_bad).build_classes()
  File ".../python_jsonschema_objects/__init__.py", line 83, in build_classes
    builder.construct(nm, self.schema)
  File ".../python_jsonschema_objects/classbuilder.py", line 418, in construct
    ret = self._construct(uri, *args, **kw)
  File ".../python_jsonschema_objects/classbuilder.py", line 474, in _construct
    **clsdata_copy)
  File ".../python-jsonschema-objects/python_jsonschema_objects/validators.py", line 317, in create
    elif isdict and item_constraint['type'] == 'array':
KeyError: 'type'
```

If we remove the `required` arrays in both objects, `build_classes()` terminates but `jsonschema` is unable to validate the instance anymore:

```
jsonschema.exceptions.ValidationError: {'a': ''} is valid under each of {'properties': {'b': {'type': 'string'}}, 'type': 'object'}, {'properties': {'a': {'type': 'string'}}, 'type': 'object'}

Failed validating 'oneOf' in schema['items']:
    {'oneOf': [{'properties': {'a': {'type': 'string'}}, 'type': 'object'},
               {'properties': {'b': {'type': 'string'}}, 'type': 'object'}]}

On instance[0]:
    {'a': ''}
```

Discussion:

Patch:
diff --git a/python_jsonschema_objects/__init__.py b/python_jsonschema_objects/__init__.py
index 04ccf1d..39aeb54 100644
--- a/python_jsonschema_objects/__init__.py
+++ b/python_jsonschema_objects/__init__.py
@@ -47,7 +47,6 @@ class ObjectBuilder(object):
                                          resolver=self.resolver)
 
         self._classes = None
-        self._resolved = None
 
     @property
     def classes(self):
@@ -55,12 +54,6 @@ class ObjectBuilder(object):
           self._classes = self.build_classes()
         return self._classes
 
-    def get_class(self, uri):
-        if self._resolved is None:
-          self._classes = self.build_classes()
-        return self._resolved.get(uri, None)
-
-
     def memory_resolver(self, uri):
         return self.mem_resolved[uri[7:]]
 
@@ -95,10 +88,8 @@ class ObjectBuilder(object):
 
         nm = self.schema['title'] if 'title' in self.schema else self.schema['id']
         nm = inflection.parameterize(six.text_type(nm), '_')
-
         kw = {"strict" : strict}
         builder.construct(nm, self.schema,**kw)
-        self._resolved = builder.resolved
 
         return (
             util.Namespace.from_mapping(dict(
diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py
index f75b039..086a5c3 100644
--- a/python_jsonschema_objects/classbuilder.py
+++ b/python_jsonschema_objects/classbuilder.py
@@ -255,8 +255,8 @@ class ProtocolBase(collections.MutableMapping):
 
         propname = lambda x: self.__prop_names__[x]
         missing = [x for x in self.__required__
-                   if propname(x) not in self._properties
-                   or self._properties[propname(x)] is None]
+                   if propname(x) not in self._properties or
+                   self._properties[propname(x)] is None]
 
         if len(missing) > 0:
             raise validators.ValidationError(
@@ -305,6 +305,7 @@ class TypeProxy(object):
                 self.__class__, klass))
             try:
                 obj = klass(*a, **kw)
+                obj.validate()
             except TypeError as e:
                 validation_errors.append((klass, e))
             except validators.ValidationError as e:
diff --git a/python_jsonschema_objects/validators.py b/python_jsonschema_objects/validators.py
index facb0c6..6aafcb3 100644
--- a/python_jsonschema_objects/validators.py
+++ b/python_jsonschema_objects/validators.py
@@ -166,6 +166,20 @@ class ArrayValidator(object):
             raise TypeError("Invalid value given to array validator: {0}"
                             .format(ary))
 
+    @classmethod
+    def from_json(cls, jsonmsg):
+        import json
+        msg = json.loads(jsonmsg)
+        obj = cls(msg)
+        obj.validate()
+        return obj
+
+    @classmethod
+    def serialize(self):
+        self.validate()
+        enc = util.ProtocolJSONEncoder()
+        return enc.encode(self)
+
     def validate(self):
         converted = self.validate_items()
         self.validate_length()
@@ -238,10 +252,12 @@ class ArrayValidator(object):
                     val = elem
                 val.validate()
                 typed_elems.append(val)
+
             elif util.safe_issubclass(typ, ArrayValidator):
                 val = typ(elem)
                 val.validate()
                 typed_elems.append(val)
+
             elif isinstance(typ, classbuilder.TypeProxy):
                 try:
                     if isinstance(elem, (six.string_types, six.integer_types, float)):
@@ -251,8 +267,9 @@ class ArrayValidator(object):
                 except TypeError as e:
                     raise ValidationError("'{0}' is not a valid value for '{1}': {2}"
                                           .format(elem, typ, e))
-                val.validate()
-                typed_elems.append(val)
+                else:
+                    val.validate()
+                    typed_elems.append(val)
 
         return typed_elems
 
@@ -314,11 +331,32 @@ class ArrayValidator(object):
 
                     item_constraint = klassbuilder.resolved[uri]
 
-                elif isdict and item_constraint['type'] == 'array':
+                elif isdict and item_constraint.get('type') == 'array':
+                    # We need to create a sub-array validator.
                     item_constraint = ArrayValidator.create(name + "#sub",
                                                             item_constraint=item_constraint[
                                                                 'items'],
                                                             addl_constraints=item_constraint)
+                elif isdict and 'oneOf' in item_constraint:
+                    # We need to create a TypeProxy validator
+                    uri = "{0}_{1}".format(name, "<anonymous_list_type>")
+                    type_array = []
+                    for i, item_detail in enumerate(item_constraint['oneOf']):
+                        if '$ref' in item_detail:
+                            subtype = klassbuilder.construct(
+                                util.resolve_ref_uri(
+                                    klassbuilder.resolver.resolution_scope,
+                                    item_detail['$ref']),
+                                item_detail)
+                        else:
+                            subtype = klassbuilder.construct(
+                                uri + "_%s" % i, item_detail)
+
+                        type_array.append(subtype)
+
+                    item_constraint = classbuilder.TypeProxy(type_array)
+
+
 
         props['__itemtype__'] = item_constraint
 


Test patch:
diff --git a/test/test_regression_49.py b/test/test_regression_49.py
new file mode 100644
index 0000000..ed110c2
--- /dev/null
+++ b/test/test_regression_49.py
@@ -0,0 +1,51 @@
+import pytest
+
+from jsonschema import validate
+import python_jsonschema_objects as pjo
+import json
+
+
+@pytest.fixture
+def bad_schema_49():
+    return {
+        'title': 'example',
+        'type': 'array',
+        'items': {
+            'oneOf': [
+                {
+                    'type': 'object',
+                    'properties': {
+                        'a': {
+                            'type': 'string',
+                        }
+                    },
+                    'required': ['a'],
+                },
+                {
+                    'type': 'object',
+                    'properties': {
+                        'b': {
+                            'type': 'string',
+                        }
+                    },
+                    'required': ['b'],
+                },
+            ]
+        },
+    }
+
+
+@pytest.fixture
+def instance():
+    return [{"a": ''}, {"b": ""}]
+
+
+def test_is_valid_jsonschema(bad_schema_49, instance):
+    validate(instance, bad_schema_49)
+
+
+def test_regression_49(bad_schema_49, instance):
+    builder = pjo.ObjectBuilder(bad_schema_49)
+    ns = builder.build_classes()
+
+    ns.Example.from_json(json.dumps(instance))