Copy attributes in resource constructor

It seems like it would be a lot safer to copy the attributes
in the resource constructor rather than just using them.  This
way the resource can do what it wants with them without worrying
about messing anyone else up.

Change-Id: I004a7936243d5a585303c4b0da02163d0a6ab460
This commit is contained in:
TerryHowe
2015-09-03 12:20:38 -06:00
parent ef0e934064
commit 1d6ceaa552
5 changed files with 11 additions and 13 deletions

View File

@@ -248,15 +248,11 @@ class Resource(collections.MutableMapping):
:param bool loaded: ``True`` if this Resource exists on
the server, ``False`` if it does not.
"""
if attrs is None:
attrs = {}
self._dirty = set() if loaded else set(attrs.keys())
self._attrs = {} if attrs is None else attrs.copy()
self._dirty = set() if loaded else set(self._attrs.keys())
self.update_attrs(self._attrs)
self._loaded = loaded
self._attrs = attrs
self.update_attrs(attrs)
def __repr__(self):
return "%s.%s(attrs=%s, loaded=%s)" % (self.__module__,
self.__class__.__name__,

View File

@@ -58,7 +58,9 @@ class Sample(resource.Resource):
def create(self, session):
url = self._get_url(self)
# telemetry expects a list of samples
resp = session.post(url, service=self.service, json=[self._attrs])
attrs = self._attrs.copy()
attrs.pop('meter', None)
resp = session.post(url, service=self.service, json=[attrs])
self.update_attrs(**resp.body.pop())
self._reset_dirty()
return self

View File

@@ -78,7 +78,7 @@ class TestCluster(testtools.TestCase):
def test_instantiate(self):
sot = cluster.Cluster(FAKE)
self.assertEqual(FAKE['id'], sot.id)
self.assertIsNone(sot.id)
self.assertEqual(FAKE['name'], sot.name)
self.assertEqual(FAKE['profile_id'], sot.profile_id)

View File

@@ -93,9 +93,9 @@ class TestStack(testtools.TestCase):
sot.create(sess)
url = '/stacks'
body = FAKE.copy()
body.pop('id')
body.pop('name')
body = sot._attrs.copy()
body.pop('id', None)
body.pop('name', None)
sess.post.assert_called_with(url, service=sot.service, json=body)
self.assertEqual(FAKE_ID, sot.id)
self.assertEqual(FAKE_NAME, sot.name)

View File

@@ -135,5 +135,5 @@ class TestSample(testtools.TestCase):
new_sample.create(sess)
url = '/meters/temperature'
sess.post.assert_called_with(url, service=new_sample.service,
json=[SAMPLE])
json=[data])
self.assertIsNone(new_sample.id)