Skip to content

Commit

Permalink
Add setters for first-level Nornir inventory attributes (#229)
Browse files Browse the repository at this point in the history
* Add support for setters

* black

* Minor cleanup
  • Loading branch information
ktbyers authored and dbarrosop committed Aug 14, 2018
1 parent a412666 commit f489808
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
20 changes: 20 additions & 0 deletions nornir/core/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,26 +201,46 @@ def hostname(self):
"""String used to connect to the device. Either ``hostname`` or ``self.name``"""
return self.get("hostname", self.name)

@hostname.setter
def hostname(self, value):
self.data["hostname"] = value

@property
def port(self):
"""Either ``port`` or ``None``."""
return self.get("port")

@port.setter
def port(self, value):
self.data["port"] = value

@property
def username(self):
"""Either ``username`` or user running the script."""
return self.get("username", getpass.getuser())

@username.setter
def username(self, value):
self.data["username"] = value

@property
def password(self):
"""Either ``password`` or empty string."""
return self.get("password", "")

@password.setter
def password(self, value):
self.data["password"] = value

@property
def platform(self):
"""OS the device is running. Defaults to ``platform``."""
return self.get("platform")

@platform.setter
def platform(self, value):
self.data["platform"] = value

def get_connection_parameters(
self, connection: Optional[str] = None
) -> Dict[str, Any]:
Expand Down
28 changes: 28 additions & 0 deletions tests/core/test_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,31 @@ def test_to_dict(self):
},
}
assert inventory.filter(role="www").to_dict() == expected

def test_setters(self):
"""Test explicit setters specified in inventory."""
defaults = {}
g1 = Group(name="g1")
h1 = Host(name="host1", groups=[g1], defaults=defaults)

g1.hostname = "group_hostname"
assert h1.hostname == "group_hostname"
g1.platform = "group_platform"
assert h1.platform == "group_platform"
g1.username = "group_username"
assert h1.username == "group_username"
g1.password = "group_password"
assert h1.password == "group_password"
g1.port = 9999
assert h1.port == 9999

h1.hostname = "alt_hostname"
assert h1.hostname == "alt_hostname"
h1.platform = "alt_platform"
assert h1.platform == "alt_platform"
h1.username = "alt_username"
assert h1.username == "alt_username"
h1.password = "alt_password"
assert h1.password == "alt_password"
h1.port = 9998
assert h1.port == 9998

0 comments on commit f489808

Please sign in to comment.