Skip to content

Commit

Permalink
F object can also check attributes and callables
Browse files Browse the repository at this point in the history
  • Loading branch information
dbarrosop committed Jul 17, 2018
1 parent ff298ab commit 9ff6546
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
10 changes: 5 additions & 5 deletions nornir/core/filter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
class F_OP_BASE(object):

def __init__(self, op1, op2):
self.op1 = op1
self.op2 = op2
Expand All @@ -15,19 +14,16 @@ def __repr__(self):


class AND(F_OP_BASE):

def __call__(self, host):
return self.op1(host) and self.op2(host)


class OR(F_OP_BASE):

def __call__(self, host):
return self.op1(host) or self.op2(host)


class F(object):

def __init__(self, **kwargs):
self.filters = kwargs

Expand Down Expand Up @@ -57,6 +53,11 @@ def _verify_rules(data, rule, value):
operator = "__{}__".format(rule[0])
if hasattr(data, operator):
return getattr(data, operator)(value)
elif hasattr(data, rule[0]):
if callable(getattr(data, rule[0])):
return getattr(data, rule[0])(value)
else:
return getattr(data, rule[0]) == value

else:
return data.get(rule[0]) == value
Expand All @@ -68,7 +69,6 @@ def _verify_rules(data, rule, value):


class NOT_F(F):

def __call__(self, host):
return not any(
F._verify_rules(host, k.split("__"), v) for k, v in self.filters.items()
Expand Down
6 changes: 6 additions & 0 deletions tests/core/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,9 @@ def test_nested_data_a_list_contains(self):
filtered = sorted(list((inventory.filter(f).hosts.keys())))

assert filtered == ["dev1.group_1", "dev2.group_1"]

def test_has_parent_group(self):
f = F(has_parent_group="parent_group")
filtered = sorted(list((inventory.filter(f).hosts.keys())))

assert filtered == ["dev1.group_1", "dev2.group_1"]

0 comments on commit 9ff6546

Please sign in to comment.