Skip to content

Commit

Permalink
added method to ParentsGroup to add a group easily (#624)
Browse files Browse the repository at this point in the history
  • Loading branch information
kpeterson-sf committed Dec 27, 2020
1 parent 2859f89 commit 492f5e6
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
12 changes: 12 additions & 0 deletions nornir/core/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@ def __contains__(self, value: object) -> bool:
else:
return any([value == g for g in self])

def add(self, group: "Group") -> None:
"""
Add the ParentGroup. The group will only be appended
if it does not exist.
:param group: Parent Group object to add
:return: None
"""
# only add the group if it doesn't exist
if not self.__contains__(group):
self.append(group)


class InventoryElement(BaseAttributes):
__slots__ = ("groups", "data", "connection_options")
Expand Down
47 changes: 47 additions & 0 deletions tests/core/test_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,3 +530,50 @@ def test_get_hosts_dict(self, inv):
assert "group_1" in dev1_groups
assert dev2_paramiko_opts["username"] == "root"
assert "dev3.group_2" in hosts_dict

def test_add_group_to_host_runtime(self):
orig_data = {"var1": "val1"}
data = {"var3": "val3"}
g1 = inventory.Group(name="g1", data=orig_data)
g2 = inventory.Group(name="g2", groups=inventory.ParentGroups([g1]))
g3 = inventory.Group(name="g3", groups=inventory.ParentGroups([g2]), data=data)
h1 = inventory.Host(name="h1", groups=inventory.ParentGroups([g1, g2]))
h2 = inventory.Host(name="h2")
hosts = {"h1": h1, "h2": h2}
groups = {"g1": g1, "g2": g2}
inv = inventory.Inventory(hosts=hosts, groups=groups)

assert "h1" in inv.hosts
assert g3 not in inv.hosts["h1"].groups
assert h1.get("var3", None) is None

h1.groups.add(g3)
assert g3 in h1.groups
assert h1.get("var3", None) == "val3"

def test_remove_group_from_host(self):
data = {"var3": "val3"}
orig_data = {"var1": "val1"}
g1 = inventory.Group(name="g1", data=orig_data)
g2 = inventory.Group(name="g2", groups=inventory.ParentGroups([g1]))
g3 = inventory.Group(name="g3", groups=inventory.ParentGroups([g2]), data=data)
h1 = inventory.Host(name="h1", groups=inventory.ParentGroups([g1, g2, g3]))
h2 = inventory.Host(name="h2")
hosts = {"h1": h1, "h2": h2}
groups = {"g1": g1, "g2": g2}
inv = inventory.Inventory(hosts=hosts, groups=groups)

assert "h1" in inv.hosts
assert g3 in inv.hosts["h1"].groups
assert h1.get("var3") == "val3"

g3.data["var3"] = "newval3"
assert h1.get("var3", None) == "newval3"

h1.groups.remove(g3)
assert g3 not in h1.groups
assert h1.get("var3", None) is None
assert h1.get("var1", None) == "val1"

with pytest.raises(ValueError):
h1.groups.remove(g3)

0 comments on commit 492f5e6

Please sign in to comment.