Skip to content

Commit

Permalink
Support python dict in sysctl_create
Browse files Browse the repository at this point in the history
Add support for directly passing a python dict rather than a
YAML formatted string to sysctl_create to make it easier for
charms to set sane defaults without hopping via YAML first.
  • Loading branch information
javacruft committed Sep 27, 2017
1 parent 97ed190 commit da4b2d3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
18 changes: 11 additions & 7 deletions charmhelpers/core/sysctl.py
Expand Up @@ -31,18 +31,22 @@
def create(sysctl_dict, sysctl_file):
"""Creates a sysctl.conf file from a YAML associative array
:param sysctl_dict: a YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }"
:param sysctl_dict: a dict or YAML-formatted string of sysctl
options eg "{ 'kernel.max_pid': 1337 }"
:type sysctl_dict: str
:param sysctl_file: path to the sysctl file to be saved
:type sysctl_file: str or unicode
:returns: None
"""
try:
sysctl_dict_parsed = yaml.safe_load(sysctl_dict)
except yaml.YAMLError:
log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict),
level=ERROR)
return
if type(sysctl_dict) is not dict:
try:
sysctl_dict_parsed = yaml.safe_load(sysctl_dict)
except yaml.YAMLError:
log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict),
level=ERROR)
return
else:
sysctl_dict_parsed = sysctl_dict

with open(sysctl_file, "w") as fd:
for key, value in sysctl_dict_parsed.items():
Expand Down
19 changes: 19 additions & 0 deletions tests/core/test_sysctl.py
Expand Up @@ -53,6 +53,25 @@ def test_create(self, mock_open):
"sysctl", "-p",
"/etc/sysctl.d/test-sysctl.conf"])

@patch(builtin_open)
def test_create_with_dict(self, mock_open):
"""Test create sysctl method"""
_file = MagicMock(spec=io.FileIO)
mock_open.return_value = _file

create({"kernel.max_pid": 1337}, "/etc/sysctl.d/test-sysctl.conf")

_file.__enter__().write.assert_called_with("kernel.max_pid=1337\n")

self.log.assert_called_with(
"Updating sysctl_file: /etc/sysctl.d/test-sysctl.conf"
" values: {'kernel.max_pid': 1337}",
level='DEBUG')

self.check_call.assert_called_with([
"sysctl", "-p",
"/etc/sysctl.d/test-sysctl.conf"])

@patch(builtin_open)
def test_create_invalid_argument(self, mock_open):
"""Test create sysctl with an invalid argument"""
Expand Down

0 comments on commit da4b2d3

Please sign in to comment.