diff --git a/charmhelpers/core/sysctl.py b/charmhelpers/core/sysctl.py index 6e413e314..1f188d8c6 100644 --- a/charmhelpers/core/sysctl.py +++ b/charmhelpers/core/sysctl.py @@ -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(): diff --git a/tests/core/test_sysctl.py b/tests/core/test_sysctl.py index fe2c09d76..056874ef0 100644 --- a/tests/core/test_sysctl.py +++ b/tests/core/test_sysctl.py @@ -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"""