Add InventoryList.find() method

Needed by following code, this patch adds a simple InventoryList.find()
method that searches for a resource class in an InventoryList and
returns the inventory record matching that resource class, or None if
that resource class is not contained in the InventoryList.

Change-Id: I64757c2115f12788eab46627b0f0a2c8a37433f4
This commit is contained in:
Jay Pipes 2016-06-06 21:43:40 -04:00 committed by Chris Dent
parent b4b13b0457
commit 56d41ae159
2 changed files with 48 additions and 0 deletions

View File

@ -10,6 +10,7 @@
# License for the specific language governing permissions and limitations
# under the License.
import six
from sqlalchemy.orm import joinedload
from nova.db.sqlalchemy import api as db_api
@ -203,6 +204,22 @@ class InventoryList(base.ObjectListBase, base.NovaObject):
'objects': fields.ListOfObjectsField('Inventory'),
}
def find(self, res_class):
"""Return the inventory record from the list of Inventory records that
matches the supplied resource class, or None.
:param res_class: An integer or string representing a resource
class. If the value is a string, the method first
looks up the resource class identifier from the
string.
"""
if isinstance(res_class, six.string_types):
res_class = fields.ResourceClass.index(res_class)
for inv_rec in self.objects:
if fields.ResourceClass.index(inv_rec.resource_class) == res_class:
return inv_rec
@staticmethod
@db_api.api_context_manager.reader
def _get_all_by_resource_provider(context, rp_uuid):

View File

@ -14,6 +14,7 @@ import mock
from nova import exception
from nova import objects
from nova.objects import fields
from nova.tests.unit.objects import test_objects
from nova.tests import uuidsentinel as uuids
@ -279,3 +280,33 @@ class TestInventory(test_objects._LocalTest):
inventory_dict.pop('id')
inventory = objects.Inventory(self.context, **inventory_dict)
self.assertRaises(exception.ObjectActionError, inventory.save)
def test_find(self):
rp = objects.ResourceProvider(uuid=uuids.rp_uuid)
inv_list = objects.InventoryList(objects=[
objects.Inventory(
resource_provider=rp,
resource_class=fields.ResourceClass.VCPU,
total=24),
objects.Inventory(
resource_provider=rp,
resource_class=fields.ResourceClass.MEMORY_MB,
total=10240),
])
found = inv_list.find(fields.ResourceClass.MEMORY_MB)
self.assertIsNotNone(found)
self.assertEqual(10240, found.total)
found = inv_list.find(fields.ResourceClass.VCPU)
self.assertIsNotNone(found)
self.assertEqual(24, found.total)
found = inv_list.find(fields.ResourceClass.DISK_GB)
self.assertIsNone(found)
# Try an integer resource class identifier...
found = inv_list.find(fields.ResourceClass.index(
fields.ResourceClass.VCPU))
self.assertIsNotNone(found)
self.assertEqual(24, found.total)