From d16057d1713dfb3003c9a01302ae070e9be38236 Mon Sep 17 00:00:00 2001 From: VM Date: Sun, 28 Jul 2024 11:10:27 -0700 Subject: [PATCH] fix: config_file decorator creates config related to the script directory, not in current directory --- src/configmodel/Decorators.py | 14 ++++++++++++- tests/test_ConfigModel.py | 37 +++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/configmodel/Decorators.py b/src/configmodel/Decorators.py index 93d79ad..046e747 100644 --- a/src/configmodel/Decorators.py +++ b/src/configmodel/Decorators.py @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*- +import inspect +import os + from configmodel.Logger import Log from configmodel import ConfigModel @@ -14,7 +17,16 @@ def decorator(cls): """ :type cls: ConfigModel """ - cls._register_as_static_config(filename=filename) + # check if file path is relative + if not os.path.isabs(filename): + # file must be relative to the same directory as the script using the decorator + client_script_path = inspect.getfile(cls) + client_script_dir = os.path.dirname(client_script_path) + abs_file_path = os.path.join(client_script_dir, filename) + else: + abs_file_path = filename + + cls._register_as_static_config(filename=abs_file_path) return cls return decorator diff --git a/tests/test_ConfigModel.py b/tests/test_ConfigModel.py index b4964b0..d2cef56 100644 --- a/tests/test_ConfigModel.py +++ b/tests/test_ConfigModel.py @@ -1,3 +1,4 @@ +import os import unittest __author__ = "Vasily Maslyukov" @@ -367,6 +368,42 @@ class NestedConfig(ConfigModel): val = RootConfig.NestedConfig.nested_value mock_get_value.assert_called_with(["nested_config", "renamed_nested_value"]) + def test_decorator_filename_same_directory(self): + """ + Check that @config_file decorator creates a file in the same directory as the script + """ + # change current directory to the temp directory + import tempfile + temp_dir = tempfile.mkdtemp() + + assert temp_dir is not None + assert os.path.isdir(temp_dir) + + current_dir = os.getcwd() + + # add cleanup action + def _cleanup_action(): + # change current directory back to the original directory + os.chdir(current_dir) + # remove temp directory + os.rmdir(temp_dir) + self.addCleanup(_cleanup_action) + + # change current directory to the temp directory + os.chdir(temp_dir) + + @config_file(TEST_CONFIG_FILE) + class StaticConfig(ConfigModel): + product_key = "1234" + secret = "abcd" + + # check that file was created in the same directory as the script + config_filename = StaticConfig._get_instance()._serializer.filename + script_dir = os.path.dirname(os.path.realpath(__file__)) + expected_file_path = os.path.join(script_dir, TEST_CONFIG_FILE) + + self.assertEqual(expected_file_path, config_filename, "Config file was not created in the same directory as the script") + if __name__ == '__main__': unittest.main()