Merge "Fix sqlalchemy.ModelBase.__contains__() behaviour"

This commit is contained in:
Jenkins 2015-06-27 03:20:57 +00:00 committed by Gerrit Code Review
commit 239c471972
2 changed files with 21 additions and 1 deletions

View File

@ -54,7 +54,15 @@ class ModelBase(six.Iterator):
return getattr(self, key)
def __contains__(self, key):
return hasattr(self, key)
# Don't use hasattr() because hasattr() catches any exception, not only
# AttributeError. We want to passthrough SQLAlchemy exceptions
# (ex: sqlalchemy.orm.exc.DetachedInstanceError).
try:
getattr(self, key)
except AttributeError:
return False
else:
return True
def get(self, key, default=None):
return getattr(self, key, default)

View File

@ -70,6 +70,18 @@ class ModelBaseTest(test_base.DbTestCase):
self.assertFalse('non-existent-key' in mb)
def test_modelbase_contains_exc(self):
class ErrorModel(models.ModelBase):
@property
def bug(self):
raise ValueError
model = ErrorModel()
model.update({'attr': 5})
self.assertTrue('attr' in model)
self.assertRaises(ValueError, lambda: 'bug' in model)
def test_modelbase_items_iteritems(self):
h = {'a': '1', 'b': '2'}
expected = {