aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2020-01-19 13:20:57 -0600
committerEugene Triguba <eugenetriguba@gmail.com>2020-01-19 13:20:57 -0600
commit2117c36ab0953f69945275e9bc5bfece4c14a26b (patch)
treee5ae2d7773e5eae6af84e42c2ad75dd98375f75d
parentAdd TODO to ini_parser to be able to retrieve sections (diff)
downloadconfig-file-2117c36ab0953f69945275e9bc5bfece4c14a26b.zip
Add save() and reset() methods to ConfigFile
Test coverage on other files has also been increased
-rw-r--r--config_file/config_file.py90
-rw-r--r--config_file/utils.py5
-rw-r--r--tests/test_config_file.py63
-rw-r--r--tests/test_ini_parser.py15
-rw-r--r--tests/test_parse_value.py11
-rw-r--r--tests/test_utils.py19
6 files changed, 188 insertions, 15 deletions
diff --git a/config_file/config_file.py b/config_file/config_file.py
index 5a2dbb5..b090ace 100644
--- a/config_file/config_file.py
+++ b/config_file/config_file.py
@@ -1,5 +1,6 @@
import inspect
-from pathlib import Path
+from pathlib import Path, PurePath
+from shutil import copyfile
from config_file.parsers.base_parser import BaseParser
from config_file.parsers.ini_parser import IniParser
@@ -7,26 +8,49 @@ from config_file.utils import split_on_dot
class ConfigFile:
- def __init__(self, file_path: str, parser=None):
- self.path = self.__create_config_path(file_path)
+ def __init__(self, file_path, parser=None):
+ """
+ Saves the config file path and expands it if needed, reads in
+ the file contents, and determines what parser should be used for
+ the given file.
- with open(self.path, "r") as file:
- self.contents = file.read()
+ :param file_path: The path to your configuration file.
+ :param parser: A custom parser you'd like used for your config file.
+ It must be a concrete implementation of BaseParser.
+ :raises ValueError: If the specified file path does not have an extension
+ that is supported or it is a directory.
+ """
+ self.path = self.__create_config_path(file_path)
+ self.contents = self.__read_config_file()
self.parser = self.__determine_parser(file_path, parser)
@staticmethod
- def __create_config_path(file_path: str):
+ def __create_config_path(file_path, original=False) -> str:
+ if isinstance(file_path, PurePath):
+ file_path = str(file_path)
+
if len(file_path) > 1 and file_path[0] == "~":
- return Path(file_path).expanduser().resolve()
+ return str(Path(file_path).expanduser())
+
+ if original:
+ file_parts = split_on_dot(file_path, only_last_dot=True)
+ file_parts.insert(-1, "original")
+ file_path = ".".join(file_parts)
- return Path(file_path)
+ if Path(file_path).is_dir():
+ raise ValueError(f"The specified config file ({file_path}) is a directory.")
+
+ return file_path
+
+ def __determine_parser(self, file_path, parser):
+ if isinstance(file_path, PurePath):
+ file_path = str(file_path)
- def __determine_parser(self, file_path: str, parser):
if isinstance(parser, BaseParser) and not inspect.isabstract(parser):
return parser(self.contents)
- file_type = split_on_dot(file_path)[-1]
+ file_type = split_on_dot(file_path, only_last_dot=True)[-1]
if file_type == "ini":
return IniParser(self.contents)
else:
@@ -35,6 +59,10 @@ class ConfigFile:
f"unrecognized file type: {file_path}"
)
+ def __read_config_file(self):
+ with open(self.path, "r") as file:
+ return file.read()
+
def get(self, key, parse_type=True):
"""
Retrieve the value of a key in its native type.
@@ -64,6 +92,46 @@ class ConfigFile:
using a section.key format.
Some formats, like JSON, do not have sections and therefore,
- it would only be checking if the section
+ it would only be checking if the key exists.
"""
return self.parser.has(section_key)
+
+ def reset(self, original_file_path=None):
+ """
+ Resets the config file by deleting it and copying the original back
+ in its place. The contents of this config file are then set to the
+ newly reset config file.
+
+ :param original_file_path: The path to the original config file to reset it to.
+ If this is not provided and, say, your configuration file is config.json, the
+ method would look for a config.original.json in the same folder by default.
+
+ :return: True if the reset succeeded
+ :raises OSError: If the original configuration file is not present or if an
+ error occurred when trying to copy the file.
+ """
+ if original_file_path is None:
+ original_file_path = self.__create_config_path(
+ str(self.path), original=True
+ )
+
+ if not Path(original_file_path).exists():
+ raise OSError(f"The {original_file_path} file to reset to does not exist.")
+
+ Path(self.path).expanduser().unlink(missing_ok=True)
+ copyfile(original_file_path, self.path)
+
+ self.contents = self.__read_config_file()
+ self.parser.parsed_content = self.parser.parse(self.contents)
+
+ return True
+
+ def save(self):
+ """
+ Save the configuration changes by writing the file out to the specified path
+ :return: True if the save succeeded.
+ """
+ with open(self.path, "w") as config_file:
+ config_file.write(self.parser.stringify())
+
+ return True
diff --git a/config_file/utils.py b/config_file/utils.py
index 41ce2a5..61f0ae0 100644
--- a/config_file/utils.py
+++ b/config_file/utils.py
@@ -8,6 +8,11 @@ def split_on_dot(line: str, only_last_dot=False):
:raises ValueError: if the line does not have a dot.
"""
if "." not in line:
+ # TODO: This is used in the parser for section.keys where a more specific
+ # error message would be nice, but it is only used more generically to, say,
+ # split a file path. We may just have to insert some try-catches to catch the
+ # ValueError and insert a more specific error message or create a custom error
+ # for this method?
raise ValueError(
"section_key must contain the section and key separated by a dot. "
+ "e.g. 'section.key'"
diff --git a/tests/test_config_file.py b/tests/test_config_file.py
new file mode 100644
index 0000000..1daba6f
--- /dev/null
+++ b/tests/test_config_file.py
@@ -0,0 +1,63 @@
+from pathlib import Path
+
+import pytest
+
+from config_file.config_file import BaseParser, ConfigFile
+
+
+@pytest.mark.parametrize(
+ "file_contents, file_name", [("[calendar]\nsunday_index = 0\n\n", "config.ini")]
+)
+def test_that_config_file_initializes_correctly(tmp_path, file_contents, file_name):
+ temp = tmp_path / file_name
+ temp.write_text(file_contents)
+
+ config = ConfigFile(temp)
+ assert config.path == str(temp)
+ assert config.contents == temp.read_text()
+ assert isinstance(config.parser, BaseParser)
+
+
+@pytest.mark.parametrize(
+ "file_contents, file_name, original_file_name",
+ [("[calendar]\nsunday_index = 0\n\n", "config.ini", "config.original.ini")],
+)
+def test_that_config_file_can_reset(
+ tmpdir, file_contents, file_name, original_file_name
+):
+ config_path = tmpdir / file_name
+ config_path.write_text(file_contents, encoding="utf-8")
+
+ original_config_path = tmpdir / original_file_name
+ original_config_path.write_text(file_contents, encoding="utf-8")
+
+ config = ConfigFile(str(config_path))
+ config.set("calendar.sunday_index", 0)
+ config.reset()
+ assert config.stringify() == ConfigFile(str(original_config_path)).stringify()
+ assert config_path.read_text(encoding="utf-8") == original_config_path.read_text(
+ encoding="utf-8"
+ )
+
+
+@pytest.mark.parametrize(
+ "file_contents, file_name", [("[calendar]\nsunday_index = 0\n\n", "config.ini")]
+)
+def test_that_config_file_can_save(tmpdir, file_contents, file_name):
+ config_path = tmpdir / file_name
+ config_path.write_text(file_contents, encoding="utf-8")
+
+ config = ConfigFile(str(config_path))
+ config.set("calendar.sunday_index", 1)
+ config.save()
+ assert config.stringify() == Path(config_path).read_text(encoding="utf-8")
+
+
+@pytest.mark.parametrize(
+ "path, is_dir", [("invalid", False), ("invalid", True), ("invalid.conf", False)]
+)
+def test_invalid_config_paths(tmpdir, path, is_dir):
+ with pytest.raises(ValueError):
+ temp_path = tmpdir / path
+ temp_path.write("")
+ ConfigFile(str(tmpdir)) if is_dir else ConfigFile(str(temp_path))
diff --git a/tests/test_ini_parser.py b/tests/test_ini_parser.py
index 5c26b23..da1b43e 100644
--- a/tests/test_ini_parser.py
+++ b/tests/test_ini_parser.py
@@ -35,17 +35,26 @@ floatkey = 5.3
@pytest.mark.parametrize(
+ "test_input", ["invalid.invalid_key"],
+)
+def test_that_getting_unknown_sections_or_keys_throws_errors(test_input):
+ with pytest.raises(ParsingError):
+ IniParser("").get(test_input)
+
+
+@pytest.mark.parametrize(
"section_key,value,expected_value",
[
("test.key1", "different value", "[test]\nkey1 = different value\n\n"),
- ("test.key2", 5, "[test]\nkey1 = different value\nkey2 = 5\n\n"),
- ("test2.key", False, "[test]\nkey1 = value1\n[test2]\nkey = False\n\n"),
+ ("test.key2", 5, "[test]\nkey1 = value1\nkey2 = 5\n\n"),
+ ("test2.key", False, "[test]\nkey1 = value1\n\n[test2]\nkey = False\n\n"),
],
)
def test_that_ini_parser_can_set_values(section_key, value, expected_value):
ini_file = """[test]\nkey1 = value1\n\n"""
parser = IniParser(ini_file)
- assert parser.stringify() == ini_file
+ parser.set(section_key, value)
+ assert parser.stringify() == expected_value
@pytest.mark.parametrize(
diff --git a/tests/test_parse_value.py b/tests/test_parse_value.py
index 54e056b..2123337 100644
--- a/tests/test_parse_value.py
+++ b/tests/test_parse_value.py
@@ -1,6 +1,6 @@
import pytest
-from config_file.parsers.parse_value import parse_value
+from config_file.parsers.parse_value import can_be_parsed_as_bool, parse_value
@pytest.mark.parametrize(
@@ -21,3 +21,12 @@ from config_file.parsers.parse_value import parse_value
)
def test_parse_value(test_input, expected):
assert parse_value(test_input) == expected
+
+
+def test_can_be_parsed_as_bool():
+ """
+ This is the section not being covered in the parse_value.py
+ file from test_parse_value, but I don't think it's reachable
+ from using it.
+ """
+ assert can_be_parsed_as_bool(5) is False
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644
index 0000000..6779d18
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,19 @@
+import pytest
+
+from config_file.utils import split_on_dot
+
+
+@pytest.mark.parametrize(
+ "test_input, only_last_dot, expected_result",
+ [("section.key.blah", False, ["section", "key", "blah"])],
+)
+def test_that_split_on_dot_splits_the_line_correctly(
+ test_input, only_last_dot, expected_result
+):
+ assert split_on_dot(test_input, only_last_dot=only_last_dot) == expected_result
+
+
+@pytest.mark.parametrize("test_input", ["this line has no dots in it"])
+def test_that_split_on_dot_raises_error_when_there_is_no_dot(test_input):
+ with pytest.raises(ValueError):
+ split_on_dot(test_input)