Return None when getting an attr which is None when using resource.prop()

In resource.prop, __get__() will do self.type() on the value it got to
construct an object of the type. But the type could be overwritten to any
type. And the type may not be able to construct an object from None.

For example, if self.type=dict, then self.type(None) will become dict(None),
which will give "'NoneType' object is not iterable" error.

This patch fix it by returning None if the attr's value is None.

Change-Id: Ied255c52bc3f0d024ca70d1239956ba17430b13e
Closed-bug: #1527967
This commit is contained in:
Tang Chen 2015-12-21 15:17:06 +08:00
parent 6637e74fd2
commit 2574e9585a
2 changed files with 13 additions and 0 deletions

View File

@ -104,6 +104,9 @@ class prop(object):
return None
try:
value = instance[self.name]
# self.type() should not be called on None objects.
if value is None:
return None
except KeyError:
try:
value = instance[self.alias]

View File

@ -195,6 +195,16 @@ class PropTests(base.TestCase):
self.assertEqual(val, sot._attrs["something"])
self.assertEqual(val, sot.attr)
def test_property_is_none(self):
class Test(resource.Resource):
attr = resource.prop("something", type=dict)
args = {"something": None}
sot = Test(args)
self.assertIsNone(sot._attrs["something"])
self.assertIsNone(sot.attr)
class HeaderTests(base.TestCase):
class Test(resource.Resource):