Skip to content

Commit 82b1fb4

Browse files
authored
Merge pull request #263 from cwacek/fix/218
bugfix: Fix #218 by serializing "null" for "null" types
2 parents d122ce8 + 3d78861 commit 82b1fb4

File tree

3 files changed

+78
-18
lines changed

3 files changed

+78
-18
lines changed

python_jsonschema_objects/classbuilder.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ def as_dict(self):
6161
out[prop] = [getattr(x, "for_json", lambda: x)() for x in propval]
6262
elif isinstance(propval, (ProtocolBase, LiteralValue)):
6363
out[prop] = propval.as_dict()
64-
elif propval is not None:
64+
elif (
65+
propval is not None
66+
or self.__propinfo__[prop].get("type", None) == "null"
67+
):
6568
out[prop] = propval
6669

6770
return out
@@ -150,9 +153,6 @@ def __new__(cls, **props):
150153
obj = None
151154
validation_errors = []
152155
for klass in valid_types:
153-
logger.debug(
154-
util.lazy_format("Attempting to instantiate {0} as {1}", cls, klass)
155-
)
156156
try:
157157
obj = klass(**props)
158158
obj.validate()
@@ -170,6 +170,7 @@ def __new__(cls, **props):
170170
return obj
171171

172172
def __init__(self, **props):
173+
logger.debug(util.lazy_format("Creating '{0}'", self.__class__))
173174
self._extended_properties = dict()
174175
self._properties = dict(
175176
zip(
@@ -648,6 +649,14 @@ def _build_object(self, nm, clsdata, parents, **kw):
648649

649650
# Set default value, even if None
650651
if "default" in detail:
652+
logger.debug(
653+
util.lazy_format(
654+
"Setting default for {0}.{1} to: {2}",
655+
nm,
656+
prop,
657+
detail["default"],
658+
)
659+
)
651660
defaults.add(prop)
652661

653662
if detail.get("type", None) == "object":

python_jsonschema_objects/util.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -52,21 +52,15 @@ class ProtocolJSONEncoder(json.JSONEncoder):
5252
def default(self, obj):
5353
from python_jsonschema_objects import classbuilder, wrapper_types
5454

55-
if isinstance(obj, classbuilder.LiteralValue):
56-
return obj._value
57-
if isinstance(obj, wrapper_types.ArrayWrapper):
55+
if isinstance(
56+
obj,
57+
(
58+
wrapper_types.ArrayWrapper,
59+
classbuilder.ProtocolBase,
60+
classbuilder.LiteralValue,
61+
),
62+
):
5863
return obj.for_json()
59-
if isinstance(obj, classbuilder.ProtocolBase):
60-
props = {}
61-
for raw, trans in six.iteritems(obj.__prop_names__):
62-
props[raw] = getattr(obj, trans)
63-
if props[raw] is None:
64-
del props[raw]
65-
for raw, data in six.iteritems(obj._extended_properties):
66-
props[raw] = data
67-
if props[raw] is None:
68-
del props[raw]
69-
return props
7064
else:
7165
return json.JSONEncoder.default(self, obj)
7266

test/test_regression_218.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import pytest
2+
import json
3+
import python_jsonschema_objects as pjo
4+
5+
import logging
6+
7+
logging.basicConfig(level=logging.DEBUG)
8+
logging.getLogger().setLevel(logging.DEBUG)
9+
10+
schema = """
11+
{
12+
"$schema": "http://json-schema.org/draft-04/schema#",
13+
"$id": "schema.json",
14+
"title":"Null Test",
15+
"type": "object",
16+
"$ref": "#/definitions/test",
17+
"definitions": {
18+
"test": {
19+
"type": "object",
20+
"properties": {
21+
"name": {
22+
"type": "string",
23+
"default": "String"
24+
},
25+
"id": {
26+
"type": "null",
27+
"default": null
28+
}
29+
}
30+
}
31+
}
32+
}
33+
"""
34+
35+
36+
@pytest.fixture
37+
def schema_json():
38+
return json.loads(schema)
39+
40+
41+
@pytest.fixture
42+
def ns(schema_json):
43+
builder = pjo.ObjectBuilder(schema_json)
44+
ns = builder.build_classes()
45+
return ns
46+
47+
48+
def test_defaults_serialize_for_nullable_types(ns):
49+
logging.basicConfig(level=logging.DEBUG)
50+
logging.getLogger().setLevel(logging.DEBUG)
51+
thing1 = ns.NullTest()
52+
53+
serialized = thing1.as_dict()
54+
print(serialized)
55+
assert json.dumps(serialized) == """{"name": "String", "id": null}"""
56+
serialized = thing1.serialize()
57+
assert serialized == """{"name": "String", "id": null}"""

0 commit comments

Comments
 (0)