Merge "Fix sqlalchemy.ModelBase.__contains__() behaviour"
This commit is contained in:
commit
239c471972
@ -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)
|
||||
|
@ -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 = {
|
||||
|
Loading…
Reference in New Issue
Block a user