Allow filtering of node collection

This patch adds filter method to NodeCollection
that allow filtering by ip, mac and fqdn.

Change-Id: Ida1f1fe62c4a1ab9e83443aed20e26bbf83a0e38
This commit is contained in:
Anton Studenov
2016-12-30 12:58:39 +03:00
parent d36e9fb103
commit 2086d2397c
2 changed files with 18 additions and 0 deletions

View File

@@ -114,6 +114,14 @@ class NodeCollection(object):
raise error.NodeCollectionError(msg)
return self._make_instance(random.sample(self._hosts, count))
def filter(self, criteria_fn):
hosts = list(filter(criteria_fn, self._hosts))
if hosts:
return self._make_instance(hosts)
else:
raise error.NodeCollectionError(
'No nodes found according to criterion')
def run_task(self, task, raise_on_error=True):
"""Run ansible task on node colection

View File

@@ -155,6 +155,16 @@ class NodeCollectionTestCase(test.TestCase):
self.assertEqual(1, len(one))
self.assertIn(next(iter(one.hosts)), self.hosts)
def test_filter(self):
one = self.node_collection.filter(lambda host: host.ip == '10.0.0.2')
self.assertEqual(1, len(one))
self.assertEqual(self.hosts[0], one.hosts[0])
def test_filter_error(self):
self.assertRaises(error.NodeCollectionError,
self.node_collection.filter,
lambda host: host.ip == 'foo')
def test_run_task(self):
result = self.node_collection.run_task({'foo': 'bar'},
raise_on_error=False)