Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make filter objects F, NOT_F, AND and OR comparable #854

Merged
merged 1 commit into from
Aug 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions nornir/core/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ def __or__(self, other: F_BASE) -> "OR":
def __repr__(self) -> str:
return "( {} {} {} )".format(self.op1, self.__class__.__name__, self.op2)

def __eq__(self, other: object) -> bool:
if not isinstance(other, F_OP_BASE):
# don't compare against unrelated types
return NotImplemented
return self.__class__ == other.__class__ and (
(self.op1 == other.op1 and self.op2 == other.op2)
or (self.op1 == other.op2 and self.op2 == other.op1)
)


class AND(F_OP_BASE):
def __call__(self, host: Host) -> bool:
Expand Down Expand Up @@ -54,6 +63,12 @@ def __invert__(self) -> "F":
def __repr__(self) -> str:
return "<Filter ({})>".format(self.filters)

def __eq__(self, other: object) -> bool:
if not isinstance(other, F):
# don't compare against unrelated types
return NotImplemented
return self.__class__ == other.__class__ and self.filters == other.filters

@staticmethod
def _verify_rules(data: Any, rule: List[str], value: Any) -> bool:
if len(rule) > 1:
Expand Down
27 changes: 26 additions & 1 deletion tests/core/test_filter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from nornir.core.filter import F
import pytest
from nornir.core.filter import F, AND, OR


class Test(object):
Expand Down Expand Up @@ -170,3 +171,27 @@ def test_eq__on_not_existing_key(self, nornir):
filtered = sorted(list((nornir.inventory.filter(f).hosts.keys())))

assert filtered == []

@pytest.mark.parametrize(
"filter_a,filter_b",
[
(F(), F()),
(F(site="site1") & F(role="www"), AND(F(site="site1"), F(role="www"))),
(F(site="site1") & F(role="www"), AND(F(role="www"), F(site="site1"))),
(F(site="site1") | F(role="www"), OR(F(site="site1"), F(role="www"))),
(F(site="site1") | F(role="www"), OR(F(role="www"), F(site="site1"))),
],
)
def test_compare_filter_equal(self, filter_a, filter_b):
assert filter_a == filter_b

@pytest.mark.parametrize(
"filter_a,filter_b",
[
(OR(F(site="site1"), F(role="www")), AND(F(site="site1"), F(role="www"))),
(F(site="site1"), F(role="www")),
(F(site="site1"), ~F(site="site1")),
],
)
def test_compare_filter_not_equal(self, filter_a, filter_b):
assert filter_a != filter_b
Loading