diff options
| -rw-r--r-- | CHANGELOG.md | 22 | ||||
| -rw-r--r-- | README.md | 12 | ||||
| -rw-r--r-- | config_file/config_file.py | 18 | ||||
| -rw-r--r-- | config_file/ini_parser.py | 8 | ||||
| -rw-r--r-- | tests/test_abstract_parser.py | 35 | ||||
| -rw-r--r-- | tests/test_base_parser.py | 0 | ||||
| -rw-r--r-- | tests/test_config_file.py | 53 |
7 files changed, 127 insertions, 21 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b56903..2bba15f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Added + + - Python's built-in `in` keyword now works with a ConfigFile. + + Example: + ```python + config = ConfigFile('./pyproject.toml') + + 'tool.poetry' in config + >>> True + ``` + +### Changed + + - Depreciated `stringify()` in favor of just using the built-in `str()`. + +### Fixed + + - Addresses issue #25 (INI parser isn't converting back to string). + ## 0.11.0 - 2020-08-07 ### Added @@ -290,14 +290,16 @@ config.delete('section.list_key') config.save() ``` -### Using `stringify()` +### Stringifying our ConfigFile -`stringify()` shows us our configuration file, with any changes we've made, -as a string. `stringify()` will always show us our latest changes since it -is stringify-ing our internal representation of the configuration file, not -just the file we've read in. +To retrieve the file as a string, with any changes we've made, we can use the +built-in `str()` method on the ConfigFile. This will always show us our latest changes since it is stringify-ing our internal representation of the configuration file, not just the file we've read in. ```python +str(config) +>>> '[section]\nnum_key = 5\nstr_key = blah\nbool_key = true\nlist_key = [1, 2]\n\n[second_section]\ndict_key = { "another_num": 5 }\n\n' + +# Depreciated but also works. config.stringify() >>> '[section]\nnum_key = 5\nstr_key = blah\nbool_key = true\nlist_key = [1, 2]\n\n[second_section]\ndict_key = { "another_num": 5 }\n\n' ``` diff --git a/config_file/config_file.py b/config_file/config_file.py index 934c198..18f3e0f 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -34,15 +34,24 @@ class ConfigFile: def original_path(self) -> Path: return Path(self.__path.original_path) - def __getitem__(self, key: str): + def __getitem__(self, key: str) -> Any: return self.__parser.parsed_content[key] - def __setitem__(self, key: str, value: Any): + def __setitem__(self, key: str, value: Any) -> None: self.__parser.parsed_content[key] = value - def __delitem__(self, key: str): + def __delitem__(self, key: str) -> None: del self.__parser.parsed_content[key] + def __contains__(self, key: str) -> bool: + return self.has(key) + + def __str__(self) -> str: + return self.stringify() + + def __repr__(self) -> str: + return f"{self.path}\n\n{self.stringify()}" + def get( self, key: str, @@ -122,6 +131,9 @@ class ConfigFile: Returns: The internal representation of the file that has been read in converted to a string. + + Depreciated: + Use str() on the ConfigFile object instead. """ return self.__parser.stringify() diff --git a/config_file/ini_parser.py b/config_file/ini_parser.py index d6905a9..0048288 100644 --- a/config_file/ini_parser.py +++ b/config_file/ini_parser.py @@ -1,6 +1,6 @@ import configparser from io import StringIO -from typing import Type +from typing import Type, Any from .base_parser import BaseParser @@ -36,3 +36,9 @@ class IniParser(BaseParser): result.update({str(section): dict(items[section])}) return result + + def get(self, search_key: str) -> Any: + retrieved_value = super().get(search_key) + return ( + retrieved_value if type(retrieved_value) is dict else str(retrieved_value) + ) diff --git a/tests/test_abstract_parser.py b/tests/test_abstract_parser.py index f52ab45..1a1346a 100644 --- a/tests/test_abstract_parser.py +++ b/tests/test_abstract_parser.py @@ -1,9 +1,12 @@ +from typing import Type + import pytest from config_file.abstract_parser import AbstractParser +from config_file.base_parser import BaseParser -class ConcreteParser(AbstractParser): +class ConcreteAbstractParser(AbstractParser): """ ConcreteParser is a concrete implementation of the AbstractParser that just calls the AbstractParser's @@ -46,23 +49,35 @@ def test_that_abstract_parser_can_not_be_instantiated(): AbstractParser("") +def test_that_base_parser_can_not_be_instantiated(): + """ + config_file.base_parser.BaseParser + + Ensure the BaseParser raises a TypeError when it is + instantiated. + """ + with pytest.raises(TypeError): + BaseParser("") + + @pytest.mark.parametrize( "function, args", [ - (ConcreteParser("").get, ("",)), - (ConcreteParser("").set, ("", "")), - (ConcreteParser("").delete, ("",)), - (ConcreteParser("").stringify, None), - (ConcreteParser("").has, ("",)), - (ConcreteParser("").reset_internal_contents, ("",)), - (ConcreteParser("").parsed_content, None), + (ConcreteAbstractParser("").get, ("",)), + (ConcreteAbstractParser("").set, ("", "")), + (ConcreteAbstractParser("").delete, ("",)), + (ConcreteAbstractParser("").stringify, None), + (ConcreteAbstractParser("").has, ("",)), + (ConcreteAbstractParser("").reset_internal_contents, ("",)), + (ConcreteAbstractParser("").parsed_content, None), ], ) -def test_that_abstract_parser_raises_not_implemented_errors(function, args): +def test_that_abstract_and_base_parser_raises_not_implemented_errors(function, args): """ config_file.abstract_parser.AbstractParser + config_file.base_parser.BaseParser - Ensure the AbstractParser raises a NotImplementedError + Ensure the AbstractParser and BaseParser raises a NotImplementedError for every method in it. """ with pytest.raises(NotImplementedError): diff --git a/tests/test_base_parser.py b/tests/test_base_parser.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tests/test_base_parser.py diff --git a/tests/test_config_file.py b/tests/test_config_file.py index e120de2..74e4dd3 100644 --- a/tests/test_config_file.py +++ b/tests/test_config_file.py @@ -8,6 +8,7 @@ from config_file.abstract_parser import AbstractParser from config_file.config_file import ConfigFile from config_file.exceptions import ParsingError from config_file.ini_parser import IniParser +from config_file.config_file_path import ConfigFilePath SUPPORTED_FILE_TYPES = ["ini", "json", "yaml", "toml"] @@ -113,13 +114,32 @@ def test_config_file_raises_error_if_path_is_directory(): @pytest.mark.parametrize( - "key, value", [("header_one.list_key", "different value"), ("header_one", {})], + "key, value", + [ + ("header_one.list_key", "different value"), + ("header_one", {}), + ("header_one.number_key", 1), + ], ) def test_set_can_add_to_or_alter_the_file(templated_config_file, key, value): + """ + config_file.config_file.ConfigFile.set + + Ensure that for the keys we can, we retrieve that same value back + (with the exception of ini, which should always be a string). + """ config = templated_config_file() config.set(key, value) - assert config.get(key) == value + # configparser treats everything as a string. Make + # sure we're entering in files in the dict as a str. + if ConfigFilePath(config.path).extension == "ini": + if isinstance(value, (int, float)): + value = str(value) + + assert config.get(key) == value + else: + assert config.get(key) == value def test_config_file_can_save(template_and_config_file): @@ -213,6 +233,7 @@ def test_has_can_find_sections_and_keys(templated_config_file, key): """ config = templated_config_file() assert config.has(key) + assert key in config def test_has_returns_false_for_sections_and_keys_that_do_not_exist( @@ -229,6 +250,12 @@ def test_has_returns_false_for_sections_and_keys_that_do_not_exist( def test_has_can_search_for_a_key_anywhere(templated_config_file): + """ + config_file.config_file.ConfigFile.has + + Ensure that the wild=True keyword argument to has() + retrieves if we have the key anywhere in the file. + """ config = templated_config_file() assert config.has("list_key", wild=True) @@ -269,6 +296,12 @@ def test_get_can_retrieve_existent_keys(templated_config_file, key, value): def test_get_can_parse_all_types(templated_config_file): + """ + config_file.config_file.ConfigFile.get + + Ensure we're able to parse out all the different types that + may be used in a configuration file with the parse_types option. + """ config = templated_config_file(template_name="all_strings") output = {"list": [], "dict": {}, "num": 5, "bool": False, "float": 5.5} @@ -358,3 +391,19 @@ def test_keys_can_be_deleted_with_array_notation(templated_config_file): with pytest.raises(KeyError): config["header_one"] + + +def test_the_config_file_can_be_stringified(template_and_config_file): + """ + config_file.config_file.ConfigFile.__str__ + config_file.config_file.ConfigFile.__repr__ + config_file.config_file.ConfigFile.stringify() + + Ensure that the stringified version of the config file + is the string version of the file and that the repr also + includes the file path. + """ + template, config = template_and_config_file() + assert template.read_text() == str(config) + assert template.read_text() == config.stringify() + assert f"{str(template)}\n\n{str(config)}" == repr(config) |