diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-07 20:25:00 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-08-07 20:25:00 -0500 |
| commit | 05dba35cab34c2524b945da0164327b7b8a1159d (patch) | |
| tree | e1f263a316839c0d32a413c120a3c92426f36817 /tests/test_config_file.py | |
| parent | Create python-package-ci.yml (diff) | |
| parent | Fix ConfigFile default (diff) | |
| download | config-file-05dba35cab34c2524b945da0164327b7b8a1159d.zip | |
Merge pull request #24 from eugenetriguba/dev
v0.11.0
Diffstat (limited to 'tests/test_config_file.py')
| -rw-r--r-- | tests/test_config_file.py | 504 |
1 files changed, 308 insertions, 196 deletions
diff --git a/tests/test_config_file.py b/tests/test_config_file.py index f083538..e120de2 100644 --- a/tests/test_config_file.py +++ b/tests/test_config_file.py @@ -1,248 +1,360 @@ import json from pathlib import Path +from typing import Callable, Tuple import pytest +from config_file.abstract_parser import AbstractParser from config_file.config_file import ConfigFile -from config_file.parsers.base_parser import BaseParser +from config_file.exceptions import ParsingError +from config_file.ini_parser import IniParser +SUPPORTED_FILE_TYPES = ["ini", "json", "yaml", "toml"] -@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.fixture(params=SUPPORTED_FILE_TYPES) +def template_and_config_file( + request, template_file +) -> Callable[[str], Tuple[Path, ConfigFile]]: + """ + Fixture that is a wrapper around the template_file + fixture. Using the function returned, we can retrieve + a temporary file that has the contents of the specified + template file as well as a ConfigFile with the template + already passed in. + + This fixture will make the test function run once for every + supported file type, each with the corresponding template + in the different file type. + """ + + def func(template_name: str = "default"): + template = template_file(request.param, template_name) + return template, ConfigFile(template) + + return func + + +@pytest.fixture(params=SUPPORTED_FILE_TYPES) +def templated_config_file(template_and_config_file) -> Callable[[str], ConfigFile]: + """ + Wrapper around template_and_config_file for when we + only need the ConfigFile and not the template. + """ + + def func(template_name: str = "default"): + return template_and_config_file(template_name)[1] + + return func + + +def test_config_file_init_has_correct_path_and_parser(template_and_config_file): + """ + config_file.config_file.ConfigFile.__init__ + + Ensure that an initialized ConfigFile has the + correct file path and has a parser that is a AbstractParser. + """ + template_file, config = template_and_config_file() + + assert config.path == template_file + assert isinstance(config._ConfigFile__parser, AbstractParser) + + +@pytest.mark.parametrize("file_type", SUPPORTED_FILE_TYPES) +def test_config_file_raises_error_on_malformed_file(template_file, file_type): + """ + config_file.config_file.ConfigFile.__init__ + + Ensure that a ParsingError is raised on a malformed file. + """ + with pytest.raises(ParsingError): + ConfigFile(template_file(file_type, template_name="invalid")) + + +def test_config_file_expands_home_tildes_in_path(): + """ + config_file.config_file.ConfigFile.__init__ + + Ensure that a home tilde (~) in a file path passed + to ConfigFile is expanded to the full path. + """ + config_name = "temp.ini" + config_path = "~/" + config_name + + try: + Path(config_path).expanduser().touch() + assert ConfigFile(config_path).path == Path.home() / config_name + finally: + Path(config_path).expanduser().unlink() + + +@pytest.mark.parametrize("path", ["invalid", "invalid.conf"]) +def test_config_file_raises_error_on_non_existent_path(path): + """ + config_file.config_file.ConfigFile.__init__ + + Ensure that when a path to a file that does not exist + that is passed into the constructor, it raises a FileNotFoundError. + """ + with pytest.raises(FileNotFoundError): + ConfigFile(path) + + +def test_config_file_raises_error_if_path_is_directory(): + """ + config_file.config_file.ConfigFile.__init__ + + Ensure when a path to a directory is passed into + the constructor, it raises a ValueError. + """ + with pytest.raises(ValueError): + ConfigFile(".") @pytest.mark.parametrize( - "file_contents, file_name, original_file_name", - [("[calendar]\nsunday_index = 0\n\n", "config.ini", "config.original.ini")], + "key, value", [("header_one.list_key", "different value"), ("header_one", {})], ) -def test_that_config_file_can_restore_the_original( - tmpdir, file_contents, file_name, original_file_name +def test_set_can_add_to_or_alter_the_file(templated_config_file, key, value): + config = templated_config_file() + config.set(key, value) + + assert config.get(key) == value + + +def test_config_file_can_save(template_and_config_file): + """ + config_file.config_file.ConfigFile.save + + Ensure that altering the configuration file and saving it + writes those changes out to the filesystem. + """ + template_file, config = template_and_config_file() + + config.set("header_one.number_key", 25) + config.save() + + assert config.stringify() == template_file.read_text() + + +def test_restore_original_can_restore_with_calculated_in_path( + templated_config_file, template_original_file ): - config_path = tmpdir / file_name - config_path.write_text(file_contents, encoding="utf-8") + """ + config_file.config_file.ConfigFile.restore_original - original_config_path = tmpdir / original_file_name - original_config_path.write_text(file_contents, encoding="utf-8") + Ensure that we can restore the "original" configuration + file, using the *calculated* path, after altering the + internal config contents. - config = ConfigFile(str(config_path)) - config.set("calendar.sunday_index", 0) + Those internal contents and file should be reset to the + original file. + """ + config = templated_config_file() + original_file = template_original_file(config.path) + + config.set("header_one.number_key", 5) config.restore_original() - 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" - ) + assert config.stringify() == original_file.read_text() + assert config.path.read_text() == original_file.read_text() -@pytest.mark.parametrize( - "file_extension, specify_original_config_path", [("ini", False), ("ini", True)] -) -def test_missing_config_files_during_restore( - tmpdir, file_extension, specify_original_config_path + +@pytest.mark.parametrize("file_type", SUPPORTED_FILE_TYPES) +def test_restore_original_can_restore_with_passed_in_path( + template_file, tmp_file, file_type ): - with pytest.raises(OSError): - temp_path = tmpdir / f"config.{file_extension}" - temp_path.write("") - config = ConfigFile(str(temp_path)) + """ + config_file.config_file.ConfigFile.restore_original - if specify_original_config_path: - specify_original_config_path = f"does_not_exist.{file_extension}" - else: - config.path = f"does_not_exist.{file_extension}" - specify_original_config_path = None + Ensure that we can restore the "original" configuration + file, using the *passed* in path, after altering the + internal config contents. + """ + config_file = template_file(file_type) + config = ConfigFile(config_file) - config.restore_original(original_file_path=specify_original_config_path) + original_file = tmp_file(f"file.{file_type}", config_file.read_text()) + original_config = ConfigFile(original_file) + original_config.set("some_new_section.some_new_key", 5) + original_config.save() + config.restore_original(original_path=original_file) -@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") + assert config.stringify() == original_config.stringify() + assert config.path.read_text() == original_file.read_text() - config = ConfigFile(str(config_path)) - config.set("calendar.sunday_index", 1) - config.save() - assert config.stringify() == Path(config_path).read_text(encoding="utf-8") +def test_restore_original_raises_error_on_missing_file(templated_config_file): + """ + config_file.config_file.ConfigFile.restore_original -@pytest.mark.parametrize( - "section_key, value, parse_type, return_type, default, file_name, file_contents", - [ - ( - "calendar.sunday_index", - 0, - True, - None, - False, - "config.ini", - "[calendar]\nsunday_index = 0\n\n", - ), - ( - "calendar.sunday_index", - "0", - False, - None, - False, - "config.ini", - "[calendar]\nsunday_index = 0\n\n", - ), - ( - "calendar.sunday_index", - 0, - False, - None, - False, - "config.json", - json.dumps({"calendar": {"sunday_index": 0}}), - ), - ( - "calendar.missing", - "my default value", - False, - None, - "my default value", - "config.json", - json.dumps({"calendar": 5}), - ), - ( - "calendar.sunday_index", - 0, - False, - int, - False, - "config.ini", - "[calendar]\nsunday_index = 0\n\n", - ), - ], -) -def test_that_config_file_can_get( - tmpdir, - section_key, - value, - return_type, - parse_type, - file_name, - file_contents, - default, -): - config_path = tmpdir / file_name - config_path.write_text(file_contents, encoding="utf-8") - config = ConfigFile(str(config_path)) + Ensure that if we try to restore_original without using + the optional original_path argument but we do not + have a file at the calculated default path, a FileNotFoundError + is raised. + """ + config = templated_config_file() - ret_val = config.get(section_key, parse_types=parse_type, default=default) - if return_type is not None: - assert return_type(ret_val) == value - else: - assert ret_val == value + with pytest.raises(FileNotFoundError) as error: + config.restore_original() + assert "The specified config file" in str(error) + assert "does not exist" in str(error) -@pytest.mark.parametrize( - "file_extension, file_contents, section_key, expected_result", - [ - ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar.sunday_index", True), - ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar.blah", False), - ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar", True), - ("json", json.dumps({"calendar": {"sunday_index": 0}}), "calendar", True), - ("json", json.dumps({"calendar": {"sunday_index": 0}}), "blah", False), - ("json", json.dumps({"calendar": {"sunday_index": 0}}), "sunday_index", True), - ], -) -def test_that_config_file_can_find_sections_and_keys( - tmpdir, file_extension, file_contents, section_key, expected_result + +@pytest.mark.parametrize("key", ["header_one", "header_one.number_key"]) +def test_has_can_find_sections_and_keys(templated_config_file, key): + """ + config_file.config_file.ConfigFile.has + + Ensure that when a section or key that exists + is passed to has(), it can find it and returns True. + """ + config = templated_config_file() + assert config.has(key) + + +def test_has_returns_false_for_sections_and_keys_that_do_not_exist( + templated_config_file, ): - config_path = tmpdir / f"config.{file_extension}" - config_path.write_text(file_contents, encoding="utf-8") - config = ConfigFile(str(config_path)) - assert config.has(section_key) == expected_result + """ + config_file.config_file.ConfigFile.has + + Ensure that when a section or key that does not exist + is passed to has(), it can't find it and returns False. + """ + config = templated_config_file() + assert not config.has("header_one.blah") + + +def test_has_can_search_for_a_key_anywhere(templated_config_file): + config = templated_config_file() + assert config.has("list_key", wild=True) @pytest.mark.parametrize( - "section_key, file_name, file_contents, deleted_file_contents", + "key, value", [ - ( - "calendar.sunday_index", - "config.ini", - "[calendar]\nsunday_index = 0\n\n", - "[calendar]\n\n", - ), - ( - "calendar.sunday_index", - "config.json", - json.dumps({"calendar": {"sunday_index": 0}}), - json.dumps({"calendar": {}}), - ), + ("header_one.number_key", 0), + ("header_two.list_key", [1, 2, 3]), + ("header_one", {"number_key": 0}), ], ) -def test_that_config_file_can_delete( - tmpdir, section_key, file_name, file_contents, deleted_file_contents +def test_get_can_retrieve_existent_keys(templated_config_file, key, value): + """ + config_file.config_file.ConfigFile.get + + Ensure that we can retrieve a section or key + and that it is in its native type (the type that + it was set to). + + The one caveat here is the IniParser. The IniParser + uses configparser under the hood which simply always + returns back a string. However, that is not the case + for JsonParser, YamlParser, or TomlParser. + """ + config = templated_config_file() + + if isinstance(config._ConfigFile__parser, IniParser): + if type(value) is not dict: + # not a section being retrieved + value = str(value) + else: + # section is being retrieved so it should be a dict + # but the values inside should be strings. + value = json.loads(json.dumps(value), parse_int=str) + + assert config.get(key) == value + + +def test_get_can_parse_all_types(templated_config_file): + config = templated_config_file(template_name="all_strings") + output = {"list": [], "dict": {}, "num": 5, "bool": False, "float": 5.5} + + assert config.get("header", parse_types=True) == output + + +def test_get_can_use_a_default(templated_config_file): + config = templated_config_file() + assert config.get("does_not_exist", default="default!") == "default!" + + +def test_get_raises_a_key_error_on_invalid_key(templated_config_file): + config = templated_config_file() + + with pytest.raises(KeyError): + config.get("does_not_exist") + + +@pytest.mark.parametrize("key", ["header_one.number_key", "header_one"]) +def test_delete_can_remove_sections_and_keys(templated_config_file, key): + """ + config_file.config_file.ConfigFile.delete + + Ensure that we can delete keys and that they are removed + from the internal contents of the ConfigFile. + """ + config = templated_config_file() + + config.delete(key) + + assert config.has(key) is False + + +@pytest.mark.parametrize("key", ["", 0, False, {}, "header_one.does_not_exist"]) +def test_delete_raises_key_error_on_invalid_input_or_missing_key( + templated_config_file, key ): - config_path = tmpdir / file_name - config_path.write_text(file_contents, encoding="utf-8") - config = ConfigFile(str(config_path)) - config.delete(section_key) - assert config.stringify() == deleted_file_contents + """ + config_file.config_file.ConfigFile.delete + Ensure that a KeyError is raised if we + tried to provide a value that is not valid + (like the wrong type so it is an invalid key) + or one that does not exist. + """ + config = templated_config_file() -@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)) + with pytest.raises(KeyError): + config.delete(key) -def test_that_custom_parser_can_be_used(tmpdir): - class CustomParser(BaseParser): - def __init__(self, file_contents): - super().__init__(file_contents) +def test_keys_can_be_set_with_array_notation(template_and_config_file): + """ + config_file.config_file.ConfigFile.__setitem__ - def get(self, key, parse_types=True): - return key + Ensure that the ConfigFile exposes its parsed contents + using an array notation so we can set keys that way. + """ + template_file, config = template_and_config_file() - def set(self, key, value): - return key, value + config["header_one"] = {} + config.save() - def delete(self, section_key): - return section_key + assert config.stringify() == template_file.read_text() - def has(self, section_key: str) -> bool: - return True - def stringify(self) -> str: - return str(self.parsed_content) +def test_keys_can_be_retrieved_with_array_notation(templated_config_file): + """ + config_file.config_file.ConfigFile.__getitem__ - def parse(self, file_contents: str): - return file_contents + Ensure that the ConfigFile exposes its parsed contents + using an array notation so we can retrieve keys that way. + """ + config = templated_config_file() + assert int(config["header_one"]["number_key"]) == 0 - config_path = tmpdir / "config.conf" - config_path.write_text("", encoding="utf-8") - config = ConfigFile(str(config_path), parser=CustomParser) - assert isinstance(config.parser, CustomParser) - assert config.get("key") == "key" - assert config.set("key", "value") == ("key", "value") - assert config.delete("section_key") == "section_key" - assert config.has("blah") - assert config.stringify() == "" +def test_keys_can_be_deleted_with_array_notation(templated_config_file): + """ + config_file.config_file.ConfigFile.__delitem__ -def test_that_a_tidle_in_the_config_path_expands_to_the_absolute_path(): - config_name = "fjlajbkfdajfdioanfks.ini" - config_path = "~/" + config_name + Ensure that the ConfigFile exposes its parsed contents + using an array notation so we can delete keys that way. + """ + config = templated_config_file() + del config["header_one"] - try: - Path(config_path).expanduser().touch() - assert ConfigFile(config_path).path == str(Path.home() / config_name) - finally: - Path(config_path).expanduser().unlink() + with pytest.raises(KeyError): + config["header_one"] |