From d4debf9c79a68e57fb30634e547087ba73b41be0 Mon Sep 17 00:00:00 2001 From: Joseph Freeston Date: Thu, 20 Jun 2024 17:52:18 -0400 Subject: [PATCH] Better config test coverage --- core/pvhotwatercore/common/config/__init__.py | 11 +++++++- .../common/tests/test_config/test_config.py | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/core/pvhotwatercore/common/config/__init__.py b/core/pvhotwatercore/common/config/__init__.py index 2252573..97b04ce 100644 --- a/core/pvhotwatercore/common/config/__init__.py +++ b/core/pvhotwatercore/common/config/__init__.py @@ -14,6 +14,9 @@ from tomlkit.container import Container from tomlkit.items import Item +# Valid config files will end with this +VALID_CONFIG_EXTENSION = ".toml" + class Config: """Represents a single config file. @@ -74,13 +77,19 @@ def __init__(self, filename: str) -> None: filename (str): Filename of toml config file, without a path Raises: - ValueError: if filename contains a path separator + ValueError: if filename contains a path separator or does not have the + right extension """ if os.sep in filename: raise ValueError("Filename cannot contain a path. " "The config search path should be established statically" "with Config.set_config_path()") + if not filename.endswith(VALID_CONFIG_EXTENSION): + raise ValueError( + f"The filename must end in {VALID_CONFIG_EXTENSION}." + ) + Config._CONFIG_PATH_ACCESSED = True self._conf_file_path: str = os.path.join(Config._CONFIG_PATH, filename) diff --git a/core/pvhotwatercore/common/tests/test_config/test_config.py b/core/pvhotwatercore/common/tests/test_config/test_config.py index 8a6a044..474fc24 100644 --- a/core/pvhotwatercore/common/tests/test_config/test_config.py +++ b/core/pvhotwatercore/common/tests/test_config/test_config.py @@ -118,3 +118,29 @@ def test_config_load(tmp_conf_path): assert a['Test']['a'] == 2 assert a['Test']['b'] == "bumble" assert a['Test']['today']['napoleon']['plan'] == "whateverIFeelLikeGosh" + + +def test_instantiation_with_fullpath(): + with pytest.raises(ValueError): + config.Config("a" + os.sep + "b.toml") # Contains os.sep + + try: + assert config.Config("b.toml") is not None + except FileNotFoundError: + pass + + +def test_instantiation_with_badext(): + with pytest.raises(ValueError): + config.Config("test.conf") + with pytest.raises(ValueError): + config.Config("test.yaml") + with pytest.raises(ValueError): + config.Config("test.json") + with pytest.raises(ValueError): + config.Config("test.ini") + + try: + assert config.Config("test.toml") is not None + except FileNotFoundError: + pass